diff --git a/build.gradle.kts b/build.gradle.kts index 01f64ad2..c390d97e 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -20,8 +20,8 @@ dependencies { testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:latest.release") - implementation("com.caoccao.javet:javet-macos:2.1.2") // Mac OS (x86_64 and arm64) - implementation("com.caoccao.javet:javet:2.1.2") // Linux and Windows + implementation("com.caoccao.javet:javet-macos:3.0.0") // Mac OS (x86_64 and arm64) + implementation("com.caoccao.javet:javet:3.0.0") // Linux and Windows } tasks.withType { diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index f398c33c..309b4e18 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-all.zip networkTimeout=10000 zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 79a61d42..65dcd68d 100755 --- a/gradlew +++ b/gradlew @@ -144,7 +144,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC3045 + # shellcheck disable=SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac @@ -152,7 +152,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then '' | soft) :;; #( *) # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC3045 + # shellcheck disable=SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac diff --git a/js/.nvmrc b/js/.nvmrc index 1e24c021..aad5ebe1 100644 --- a/js/.nvmrc +++ b/js/.nvmrc @@ -1 +1 @@ -18.15.0 \ No newline at end of file +20.8.0 \ No newline at end of file diff --git a/js/build.gradle.kts b/js/build.gradle.kts index 307f1966..95a7416a 100644 --- a/js/build.gradle.kts +++ b/js/build.gradle.kts @@ -1,5 +1,5 @@ plugins { - id("com.github.node-gradle.node") version "3.5.1" + id("com.github.node-gradle.node") version "7.0.1" } apply(plugin = "base") @@ -8,8 +8,8 @@ apply(plugin = "com.github.node-gradle.node") group = "org.openrewrite" node { - version.set("18.15.0") - npmVersion.set("9.5.0") + version.set("20.8.0") + npmVersion.set("10.1.0") download.set(true) } diff --git a/js/package.json b/js/package.json index d33e50c9..ff802768 100644 --- a/js/package.json +++ b/js/package.json @@ -19,14 +19,14 @@ "format": "prettier --write ./src" }, "devDependencies": { - "@types/node": "^18.15.11", - "parcel": "^2.8.3", - "prettier": "^2.8.8", + "@types/node": "^20.8.0", + "parcel": "^2.10.0", + "prettier": "^3.0.3", "process": "^0.11.10", "ts-node": "^10.9.1" }, "dependencies": { - "@typescript/vfs": "^1.4.0", - "typescript": "^5.0.4" + "@typescript/vfs": "^1.5.0", + "typescript": "^5.2.2" } } diff --git a/js/yarn.lock b/js/yarn.lock index d1d578ce..7e6cb4ed 100644 --- a/js/yarn.lock +++ b/js/yarn.lock @@ -30,43 +30,11 @@ dependencies: "@jridgewell/trace-mapping" "0.3.9" -"@jridgewell/gen-mapping@^0.3.0": - version "0.3.3" - resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz#7e02e6eb5df901aaedb08514203b096614024098" - integrity sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ== - dependencies: - "@jridgewell/set-array" "^1.0.1" - "@jridgewell/sourcemap-codec" "^1.4.10" - "@jridgewell/trace-mapping" "^0.3.9" - -"@jridgewell/resolve-uri@3.1.0": - version "3.1.0" - resolved "https://registry.yarnpkg.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz#2203b118c157721addfe69d47b70465463066d78" - integrity sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w== - "@jridgewell/resolve-uri@^3.0.3": version "3.1.1" resolved "https://registry.yarnpkg.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz#c08679063f279615a3326583ba3a90d1d82cc721" integrity sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA== -"@jridgewell/set-array@^1.0.1": - version "1.1.2" - resolved "https://registry.yarnpkg.com/@jridgewell/set-array/-/set-array-1.1.2.tgz#7c6cf998d6d20b914c0a55a91ae928ff25965e72" - integrity sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw== - -"@jridgewell/source-map@^0.3.2": - version "0.3.3" - resolved "https://registry.yarnpkg.com/@jridgewell/source-map/-/source-map-0.3.3.tgz#8108265659d4c33e72ffe14e33d6cc5eb59f2fda" - integrity sha512-b+fsZXeLYi9fEULmfBrhxn4IrPlINf8fiNarzTof004v3lFdntdwa9PF7vFJqm3mg7s+ScJMxXaE3Acp1irZcg== - dependencies: - "@jridgewell/gen-mapping" "^0.3.0" - "@jridgewell/trace-mapping" "^0.3.9" - -"@jridgewell/sourcemap-codec@1.4.14": - version "1.4.14" - resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz#add4c98d341472a289190b424efbdb096991bb24" - integrity sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw== - "@jridgewell/sourcemap-codec@^1.4.10": version "1.4.15" resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz#d7c6e6755c78567a951e04ab52ef0fd26de59f32" @@ -80,14 +48,6 @@ "@jridgewell/resolve-uri" "^3.0.3" "@jridgewell/sourcemap-codec" "^1.4.10" -"@jridgewell/trace-mapping@^0.3.9": - version "0.3.18" - resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.18.tgz#25783b2086daf6ff1dcb53c9249ae480e4dd4cd6" - integrity sha512-w+niJYzMHdd7USdiH2U6869nqhD2nbfZXND5Yp93qIbEmnDNk7PD48o+YchRVpzMU7M6jVCbenTR7PA1FLQ9pA== - dependencies: - "@jridgewell/resolve-uri" "3.1.0" - "@jridgewell/sourcemap-codec" "1.4.14" - "@lezer/common@^0.15.0", "@lezer/common@^0.15.7": version "0.15.12" resolved "https://registry.yarnpkg.com/@lezer/common/-/common-0.15.12.tgz#2f21aec551dd5fd7d24eb069f90f54d5bc6ee5e9" @@ -100,35 +60,35 @@ dependencies: "@lezer/common" "^0.15.0" -"@lmdb/lmdb-darwin-arm64@2.5.2": - version "2.5.2" - resolved "https://registry.yarnpkg.com/@lmdb/lmdb-darwin-arm64/-/lmdb-darwin-arm64-2.5.2.tgz#bc66fa43286b5c082e8fee0eacc17995806b6fbe" - integrity sha512-+F8ioQIUN68B4UFiIBYu0QQvgb9FmlKw2ctQMSBfW2QBrZIxz9vD9jCGqTCPqZBRbPHAS/vG1zSXnKqnS2ch/A== +"@lmdb/lmdb-darwin-arm64@2.8.5": + version "2.8.5" + resolved "https://registry.yarnpkg.com/@lmdb/lmdb-darwin-arm64/-/lmdb-darwin-arm64-2.8.5.tgz#895d8cb16a9d709ce5fedd8b60022903b875e08e" + integrity sha512-KPDeVScZgA1oq0CiPBcOa3kHIqU+pTOwRFDIhxvmf8CTNvqdZQYp5cCKW0bUk69VygB2PuTiINFWbY78aR2pQw== -"@lmdb/lmdb-darwin-x64@2.5.2": - version "2.5.2" - resolved "https://registry.yarnpkg.com/@lmdb/lmdb-darwin-x64/-/lmdb-darwin-x64-2.5.2.tgz#89d8390041bce6bab24a82a20392be22faf54ffc" - integrity sha512-KvPH56KRLLx4KSfKBx0m1r7GGGUMXm0jrKmNE7plbHlesZMuPJICtn07HYgQhj1LNsK7Yqwuvnqh1QxhJnF1EA== +"@lmdb/lmdb-darwin-x64@2.8.5": + version "2.8.5" + resolved "https://registry.yarnpkg.com/@lmdb/lmdb-darwin-x64/-/lmdb-darwin-x64-2.8.5.tgz#ca243534c8b37d5516c557e4624256d18dd63184" + integrity sha512-w/sLhN4T7MW1nB3R/U8WK5BgQLz904wh+/SmA2jD8NnF7BLLoUgflCNxOeSPOWp8geP6nP/+VjWzZVip7rZ1ug== -"@lmdb/lmdb-linux-arm64@2.5.2": - version "2.5.2" - resolved "https://registry.yarnpkg.com/@lmdb/lmdb-linux-arm64/-/lmdb-linux-arm64-2.5.2.tgz#14fe4c96c2bb1285f93797f45915fa35ee047268" - integrity sha512-aLl89VHL/wjhievEOlPocoefUyWdvzVrcQ/MHQYZm2JfV1jUsrbr/ZfkPPUFvZBf+VSE+Q0clWs9l29PCX1hTQ== +"@lmdb/lmdb-linux-arm64@2.8.5": + version "2.8.5" + resolved "https://registry.yarnpkg.com/@lmdb/lmdb-linux-arm64/-/lmdb-linux-arm64-2.8.5.tgz#b44a8023057e21512eefb9f6120096843b531c1e" + integrity sha512-vtbZRHH5UDlL01TT5jB576Zox3+hdyogvpcbvVJlmU5PdL3c5V7cj1EODdh1CHPksRl+cws/58ugEHi8bcj4Ww== -"@lmdb/lmdb-linux-arm@2.5.2": - version "2.5.2" - resolved "https://registry.yarnpkg.com/@lmdb/lmdb-linux-arm/-/lmdb-linux-arm-2.5.2.tgz#05bde4573ab10cf21827339fe687148f2590cfa1" - integrity sha512-5kQAP21hAkfW5Bl+e0P57dV4dGYnkNIpR7f/GAh6QHlgXx+vp/teVj4PGRZaKAvt0GX6++N6hF8NnGElLDuIDw== +"@lmdb/lmdb-linux-arm@2.8.5": + version "2.8.5" + resolved "https://registry.yarnpkg.com/@lmdb/lmdb-linux-arm/-/lmdb-linux-arm-2.8.5.tgz#17bd54740779c3e4324e78e8f747c21416a84b3d" + integrity sha512-c0TGMbm2M55pwTDIfkDLB6BpIsgxV4PjYck2HiOX+cy/JWiBXz32lYbarPqejKs9Flm7YVAKSILUducU9g2RVg== -"@lmdb/lmdb-linux-x64@2.5.2": - version "2.5.2" - resolved "https://registry.yarnpkg.com/@lmdb/lmdb-linux-x64/-/lmdb-linux-x64-2.5.2.tgz#d2f85afd857d2c33d2caa5b057944574edafcfee" - integrity sha512-xUdUfwDJLGjOUPH3BuPBt0NlIrR7f/QHKgu3GZIXswMMIihAekj2i97oI0iWG5Bok/b+OBjHPfa8IU9velnP/Q== +"@lmdb/lmdb-linux-x64@2.8.5": + version "2.8.5" + resolved "https://registry.yarnpkg.com/@lmdb/lmdb-linux-x64/-/lmdb-linux-x64-2.8.5.tgz#6c61835b6cc58efdf79dbd5e8c72a38300a90302" + integrity sha512-Xkc8IUx9aEhP0zvgeKy7IQ3ReX2N8N1L0WPcQwnZweWmOuKfwpS3GRIYqLtK5za/w3E60zhFfNdS+3pBZPytqQ== -"@lmdb/lmdb-win32-x64@2.5.2": - version "2.5.2" - resolved "https://registry.yarnpkg.com/@lmdb/lmdb-win32-x64/-/lmdb-win32-x64-2.5.2.tgz#28f643fbc0bec30b07fbe95b137879b6b4d1c9c5" - integrity sha512-zrBczSbXKxEyK2ijtbRdICDygRqWSRPpZMN5dD1T8VMEW5RIhIbwFWw2phDRXuBQdVDpSjalCIUMWMV2h3JaZA== +"@lmdb/lmdb-win32-x64@2.8.5": + version "2.8.5" + resolved "https://registry.yarnpkg.com/@lmdb/lmdb-win32-x64/-/lmdb-win32-x64-2.8.5.tgz#8233e8762440b0f4632c47a09b1b6f23de8b934c" + integrity sha512-4wvrf5BgnR8RpogHhtpCPJMKBmvyZPhhUtEwMJbXh0ni2BucpfF07jlmyM11zRqQ2XIq6PbC2j7W7UCCcm1rRQ== "@mischnic/json-sourcemap@^0.1.0": version "0.1.0" @@ -169,97 +129,99 @@ resolved "https://registry.yarnpkg.com/@msgpackr-extract/msgpackr-extract-win32-x64/-/msgpackr-extract-win32-x64-3.0.2.tgz#0f164b726869f71da3c594171df5ebc1c4b0a407" integrity sha512-O+6Gs8UeDbyFpbSh2CPEz/UOrrdWPTBYNblZK5CxxLisYt4kGX3Sc+czffFonyjiGSq3jWLwJS/CCJc7tBr4sQ== -"@parcel/bundler-default@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/bundler-default/-/bundler-default-2.8.3.tgz#d64739dbc2dbd59d6629861bf77a8083aced5229" - integrity sha512-yJvRsNWWu5fVydsWk3O2L4yIy3UZiKWO2cPDukGOIWMgp/Vbpp+2Ct5IygVRtE22bnseW/E/oe0PV3d2IkEJGg== +"@parcel/bundler-default@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/bundler-default/-/bundler-default-2.10.0.tgz#f5a7be4610fcc62491eae4ae5377537443a3a962" + integrity sha512-pn8McDCuS02/D9jSo9QUTIv3tBQLlJl0PD4FvrndORXLAIFGoQR7jO4lxTSJB/eVBXwqKNVIR7WpB4sjsnBFyg== dependencies: - "@parcel/diagnostic" "2.8.3" - "@parcel/graph" "2.8.3" - "@parcel/hash" "2.8.3" - "@parcel/plugin" "2.8.3" - "@parcel/utils" "2.8.3" + "@parcel/diagnostic" "2.10.0" + "@parcel/graph" "3.0.0" + "@parcel/plugin" "2.10.0" + "@parcel/rust" "2.10.0" + "@parcel/utils" "2.10.0" nullthrows "^1.1.1" -"@parcel/cache@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/cache/-/cache-2.8.3.tgz#169e130cf59913c0ed9fadce1a450e68f710e16f" - integrity sha512-k7xv5vSQrJLdXuglo+Hv3yF4BCSs1tQ/8Vbd6CHTkOhf7LcGg6CPtLw053R/KdMpd/4GPn0QrAsOLdATm1ELtQ== +"@parcel/cache@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/cache/-/cache-2.10.0.tgz#c2f2b6fb1933c6fb3c763774da4bd0ea04ec9de0" + integrity sha512-4FzZpMTAAEFE65+O+Cf7f5kLLWRCiA+04IJdDYyQG5YzW1WujKXzrbh8B6tSSlw712dsQ/cUqNW4O0Q3FFKrfw== dependencies: - "@parcel/fs" "2.8.3" - "@parcel/logger" "2.8.3" - "@parcel/utils" "2.8.3" - lmdb "2.5.2" + "@parcel/fs" "2.10.0" + "@parcel/logger" "2.10.0" + "@parcel/utils" "2.10.0" + lmdb "2.8.5" -"@parcel/codeframe@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/codeframe/-/codeframe-2.8.3.tgz#84fb529ef70def7f5bc64f6c59b18d24826f5fcc" - integrity sha512-FE7sY53D6n/+2Pgg6M9iuEC6F5fvmyBkRE4d9VdnOoxhTXtkEqpqYgX7RJ12FAQwNlxKq4suBJQMgQHMF2Kjeg== +"@parcel/codeframe@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/codeframe/-/codeframe-2.10.0.tgz#03854005a55fb84fa975bc6c335cdc5f61c0519d" + integrity sha512-hHp457tddXEWrOgHHaA/NtkOhOAyt4mpBUzhnPbWDONLu5xeg1mu1Jffiu2rlw5xajhphrUFDWyJW0/xq1815g== dependencies: chalk "^4.1.0" -"@parcel/compressor-raw@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/compressor-raw/-/compressor-raw-2.8.3.tgz#301753df8c6de967553149639e8a4179b88f0c95" - integrity sha512-bVDsqleBUxRdKMakWSlWC9ZjOcqDKE60BE+Gh3JSN6WJrycJ02P5wxjTVF4CStNP/G7X17U+nkENxSlMG77ySg== - dependencies: - "@parcel/plugin" "2.8.3" - -"@parcel/config-default@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/config-default/-/config-default-2.8.3.tgz#9a43486e7c702e96c68052c37b79098d7240e35b" - integrity sha512-o/A/mbrO6X/BfGS65Sib8d6SSG45NYrNooNBkH/o7zbOBSRQxwyTlysleK1/3Wa35YpvFyLOwgfakqCtbGy4fw== - dependencies: - "@parcel/bundler-default" "2.8.3" - "@parcel/compressor-raw" "2.8.3" - "@parcel/namer-default" "2.8.3" - "@parcel/optimizer-css" "2.8.3" - "@parcel/optimizer-htmlnano" "2.8.3" - "@parcel/optimizer-image" "2.8.3" - "@parcel/optimizer-svgo" "2.8.3" - "@parcel/optimizer-terser" "2.8.3" - "@parcel/packager-css" "2.8.3" - "@parcel/packager-html" "2.8.3" - "@parcel/packager-js" "2.8.3" - "@parcel/packager-raw" "2.8.3" - "@parcel/packager-svg" "2.8.3" - "@parcel/reporter-dev-server" "2.8.3" - "@parcel/resolver-default" "2.8.3" - "@parcel/runtime-browser-hmr" "2.8.3" - "@parcel/runtime-js" "2.8.3" - "@parcel/runtime-react-refresh" "2.8.3" - "@parcel/runtime-service-worker" "2.8.3" - "@parcel/transformer-babel" "2.8.3" - "@parcel/transformer-css" "2.8.3" - "@parcel/transformer-html" "2.8.3" - "@parcel/transformer-image" "2.8.3" - "@parcel/transformer-js" "2.8.3" - "@parcel/transformer-json" "2.8.3" - "@parcel/transformer-postcss" "2.8.3" - "@parcel/transformer-posthtml" "2.8.3" - "@parcel/transformer-raw" "2.8.3" - "@parcel/transformer-react-refresh-wrap" "2.8.3" - "@parcel/transformer-svg" "2.8.3" - -"@parcel/core@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/core/-/core-2.8.3.tgz#22a69f36095d53736ab10bf42697d9aa5f4e382b" - integrity sha512-Euf/un4ZAiClnlUXqPB9phQlKbveU+2CotZv7m7i+qkgvFn5nAGnrV4h1OzQU42j9dpgOxWi7AttUDMrvkbhCQ== +"@parcel/compressor-raw@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/compressor-raw/-/compressor-raw-2.10.0.tgz#e782c73f1ccc256dffb6d9bd427d206c170e7980" + integrity sha512-TXjosh5+kNN4lxENeIZ/2ZFQKWXpXlOoHhJbW4cGPXBMHxm0eimVpnFpD8xbWxg7VCcWzbEaUTp20GQ153X+9A== + dependencies: + "@parcel/plugin" "2.10.0" + +"@parcel/config-default@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/config-default/-/config-default-2.10.0.tgz#689cd864c69560a42254804c4eabe7fdf5b872d2" + integrity sha512-7Ucd+KNEC08To2NrduC/yIHBN5ayedBoiuI5OVrDeKvyqUnI1S1HRqPF3DsrM8pC2PIdnwJgoOviRXwJemW28A== + dependencies: + "@parcel/bundler-default" "2.10.0" + "@parcel/compressor-raw" "2.10.0" + "@parcel/namer-default" "2.10.0" + "@parcel/optimizer-css" "2.10.0" + "@parcel/optimizer-htmlnano" "2.10.0" + "@parcel/optimizer-image" "2.10.0" + "@parcel/optimizer-svgo" "2.10.0" + "@parcel/optimizer-swc" "2.10.0" + "@parcel/packager-css" "2.10.0" + "@parcel/packager-html" "2.10.0" + "@parcel/packager-js" "2.10.0" + "@parcel/packager-raw" "2.10.0" + "@parcel/packager-svg" "2.10.0" + "@parcel/packager-wasm" "2.10.0" + "@parcel/reporter-dev-server" "2.10.0" + "@parcel/resolver-default" "2.10.0" + "@parcel/runtime-browser-hmr" "2.10.0" + "@parcel/runtime-js" "2.10.0" + "@parcel/runtime-react-refresh" "2.10.0" + "@parcel/runtime-service-worker" "2.10.0" + "@parcel/transformer-babel" "2.10.0" + "@parcel/transformer-css" "2.10.0" + "@parcel/transformer-html" "2.10.0" + "@parcel/transformer-image" "2.10.0" + "@parcel/transformer-js" "2.10.0" + "@parcel/transformer-json" "2.10.0" + "@parcel/transformer-postcss" "2.10.0" + "@parcel/transformer-posthtml" "2.10.0" + "@parcel/transformer-raw" "2.10.0" + "@parcel/transformer-react-refresh-wrap" "2.10.0" + "@parcel/transformer-svg" "2.10.0" + +"@parcel/core@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/core/-/core-2.10.0.tgz#ee262df3d51f64ed3f5a121e16b3d71cf62fe957" + integrity sha512-8jvLhLC2503HIBphJe/C1qL3bfiTSw6WgIDH0e7B8EL0v7v2JYnlTZ8o9myf+bMAxzwNLiZ2uEDCri9EWbi4tQ== dependencies: "@mischnic/json-sourcemap" "^0.1.0" - "@parcel/cache" "2.8.3" - "@parcel/diagnostic" "2.8.3" - "@parcel/events" "2.8.3" - "@parcel/fs" "2.8.3" - "@parcel/graph" "2.8.3" - "@parcel/hash" "2.8.3" - "@parcel/logger" "2.8.3" - "@parcel/package-manager" "2.8.3" - "@parcel/plugin" "2.8.3" + "@parcel/cache" "2.10.0" + "@parcel/diagnostic" "2.10.0" + "@parcel/events" "2.10.0" + "@parcel/fs" "2.10.0" + "@parcel/graph" "3.0.0" + "@parcel/logger" "2.10.0" + "@parcel/package-manager" "2.10.0" + "@parcel/plugin" "2.10.0" + "@parcel/profiler" "2.10.0" + "@parcel/rust" "2.10.0" "@parcel/source-map" "^2.1.1" - "@parcel/types" "2.8.3" - "@parcel/utils" "2.8.3" - "@parcel/workers" "2.8.3" + "@parcel/types" "2.10.0" + "@parcel/utils" "2.10.0" + "@parcel/workers" "2.10.0" abortcontroller-polyfill "^1.1.9" base-x "^3.0.8" browserslist "^4.6.6" @@ -269,279 +231,302 @@ json5 "^2.2.0" msgpackr "^1.5.4" nullthrows "^1.1.1" - semver "^5.7.1" + semver "^7.5.2" -"@parcel/diagnostic@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/diagnostic/-/diagnostic-2.8.3.tgz#d560276d5d2804b48beafa1feaf3fc6b2ac5e39d" - integrity sha512-u7wSzuMhLGWZjVNYJZq/SOViS3uFG0xwIcqXw12w54Uozd6BH8JlhVtVyAsq9kqnn7YFkw6pXHqAo5Tzh4FqsQ== +"@parcel/diagnostic@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/diagnostic/-/diagnostic-2.10.0.tgz#3407c2d8ffbc7e543e7e292493400ed47c8b8faf" + integrity sha512-ibr+sUZLc0MW75b+nThOa6YEi9QXTNYbUNCo067mtMIfhKNYTx24DaiGzDWgy1Yv49eucBaQ4u7gFI2Qa98uIA== dependencies: "@mischnic/json-sourcemap" "^0.1.0" nullthrows "^1.1.1" -"@parcel/events@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/events/-/events-2.8.3.tgz#205f8d874e6ecc2cbdb941bf8d54bae669e571af" - integrity sha512-hoIS4tAxWp8FJk3628bsgKxEvR7bq2scCVYHSqZ4fTi/s0+VymEATrRCUqf+12e5H47uw1/ZjoqrGtBI02pz4w== - -"@parcel/fs-search@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/fs-search/-/fs-search-2.8.3.tgz#1c7d812c110b808758f44c56e61dfffdb09e9451" - integrity sha512-DJBT2N8knfN7Na6PP2mett3spQLTqxFrvl0gv+TJRp61T8Ljc4VuUTb0hqBj+belaASIp3Q+e8+SgaFQu7wLiQ== - dependencies: - detect-libc "^1.0.3" +"@parcel/events@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/events/-/events-2.10.0.tgz#4a2c693c7154b4b6a8913d25ed9f9684b10c324b" + integrity sha512-mhykJBnP3BPMI6A9hLZmTtmNHZuE+HGzsF6vzmA2YBuU3/BGlQUmxdObsmwQ1O24eq0EfJVwTM+R/bdu+/nFrA== -"@parcel/fs@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/fs/-/fs-2.8.3.tgz#80536afe877fc8a2bd26be5576b9ba27bb4c5754" - integrity sha512-y+i+oXbT7lP0e0pJZi/YSm1vg0LDsbycFuHZIL80pNwdEppUAtibfJZCp606B7HOjMAlNZOBo48e3hPG3d8jgQ== +"@parcel/fs@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/fs/-/fs-2.10.0.tgz#f1884249e090f40a623784870da82f5d1008c165" + integrity sha512-so39KdZ4o7tDekeuuQfQdbfTUvldUtzvIsuUtJMqxVOVJRZr9VjieR9GbeFhqRmi9fM5oYdzQn4lbduKdAtANA== dependencies: - "@parcel/fs-search" "2.8.3" - "@parcel/types" "2.8.3" - "@parcel/utils" "2.8.3" + "@parcel/rust" "2.10.0" + "@parcel/types" "2.10.0" + "@parcel/utils" "2.10.0" "@parcel/watcher" "^2.0.7" - "@parcel/workers" "2.8.3" + "@parcel/workers" "2.10.0" -"@parcel/graph@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/graph/-/graph-2.8.3.tgz#00ffe8ec032e74fee57199e54529f1da7322571d" - integrity sha512-26GL8fYZPdsRhSXCZ0ZWliloK6DHlMJPWh6Z+3VVZ5mnDSbYg/rRKWmrkhnr99ZWmL9rJsv4G74ZwvDEXTMPBg== +"@parcel/graph@3.0.0": + version "3.0.0" + resolved "https://registry.yarnpkg.com/@parcel/graph/-/graph-3.0.0.tgz#0e7838e196912f011c37564a9fea40772a9d7c64" + integrity sha512-8Lussud6gWRM3Mysu+veBRsBdSlWgkM8y7PvF8AiRwEY2eiVxZ3Rgh8o9KJau3B8R8q+lyCaUElYpbnUT6Bkiw== dependencies: nullthrows "^1.1.1" -"@parcel/hash@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/hash/-/hash-2.8.3.tgz#bc2499a27395169616cad2a99e19e69b9098f6e9" - integrity sha512-FVItqzjWmnyP4ZsVgX+G00+6U2IzOvqDtdwQIWisCcVoXJFCqZJDy6oa2qDDFz96xCCCynjRjPdQx2jYBCpfYw== +"@parcel/logger@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/logger/-/logger-2.10.0.tgz#79fd4bf8b272294dfd0c67323fc7a8cff238685b" + integrity sha512-rDa48czGBZA313scvSEkuHSOQiGdoYLaWqInZBKtl0zke3qrgTFNG4b173H6IFdNq5KmKjafBxaV5jG87i4Gww== dependencies: - detect-libc "^1.0.3" - xxhash-wasm "^0.4.2" + "@parcel/diagnostic" "2.10.0" + "@parcel/events" "2.10.0" -"@parcel/logger@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/logger/-/logger-2.8.3.tgz#e14e4debafb3ca9e87c07c06780f9afc38b2712c" - integrity sha512-Kpxd3O/Vs7nYJIzkdmB6Bvp3l/85ydIxaZaPfGSGTYOfaffSOTkhcW9l6WemsxUrlts4za6CaEWcc4DOvaMOPA== - dependencies: - "@parcel/diagnostic" "2.8.3" - "@parcel/events" "2.8.3" - -"@parcel/markdown-ansi@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/markdown-ansi/-/markdown-ansi-2.8.3.tgz#1337d421bb1133ad178f386a8e1b746631bba4a1" - integrity sha512-4v+pjyoh9f5zuU/gJlNvNFGEAb6J90sOBwpKJYJhdWXLZMNFCVzSigxrYO+vCsi8G4rl6/B2c0LcwIMjGPHmFQ== +"@parcel/markdown-ansi@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/markdown-ansi/-/markdown-ansi-2.10.0.tgz#fb65d8cdcc21251c7f1e39724948278d1127c406" + integrity sha512-fuOuFglNANegE2nqVURwOJ/HzKM28O0hqy120Gl0NTbCAFbG34WCFxfkmVio8fondD4NcZcDj5GGv5P5TWcTIg== dependencies: chalk "^4.1.0" -"@parcel/namer-default@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/namer-default/-/namer-default-2.8.3.tgz#5304bee74beb4b9c1880781bdbe35be0656372f4" - integrity sha512-tJ7JehZviS5QwnxbARd8Uh63rkikZdZs1QOyivUhEvhN+DddSAVEdQLHGPzkl3YRk0tjFhbqo+Jci7TpezuAMw== +"@parcel/namer-default@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/namer-default/-/namer-default-2.10.0.tgz#4be6649b0e5e7acf1f3ede075ef029edeb1ac64a" + integrity sha512-N1IF6A8Y2fYz0BteU9IkhPQGezLA3cKkoSxoIOTiUf2LZPpUIuCGEAB1IgaUVNdAeMVsGw3UrdEYZg4xdMovEg== dependencies: - "@parcel/diagnostic" "2.8.3" - "@parcel/plugin" "2.8.3" + "@parcel/diagnostic" "2.10.0" + "@parcel/plugin" "2.10.0" nullthrows "^1.1.1" -"@parcel/node-resolver-core@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/node-resolver-core/-/node-resolver-core-2.8.3.tgz#581df074a27646400b3fed9da95297b616a7db8f" - integrity sha512-12YryWcA5Iw2WNoEVr/t2HDjYR1iEzbjEcxfh1vaVDdZ020PiGw67g5hyIE/tsnG7SRJ0xdRx1fQ2hDgED+0Ww== +"@parcel/node-resolver-core@3.1.0": + version "3.1.0" + resolved "https://registry.yarnpkg.com/@parcel/node-resolver-core/-/node-resolver-core-3.1.0.tgz#28e83952a8bf39c4529b06bfb59d92cc0a3c2b2f" + integrity sha512-0KBdWIXCpnDzjoZgc1qHhgxtNe5CZ4r4+Iht+LExacXwG1A1O5qKLQE1bBAgcjqkgv1iglVuMx0kVe9G8oob8A== dependencies: - "@parcel/diagnostic" "2.8.3" - "@parcel/utils" "2.8.3" + "@mischnic/json-sourcemap" "^0.1.0" + "@parcel/diagnostic" "2.10.0" + "@parcel/fs" "2.10.0" + "@parcel/rust" "2.10.0" + "@parcel/utils" "2.10.0" nullthrows "^1.1.1" - semver "^5.7.1" + semver "^7.5.2" -"@parcel/optimizer-css@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/optimizer-css/-/optimizer-css-2.8.3.tgz#420a333f4b78f7ff15e69217dfed34421b1143ee" - integrity sha512-JotGAWo8JhuXsQDK0UkzeQB0UR5hDAKvAviXrjqB4KM9wZNLhLleeEAW4Hk8R9smCeQFP6Xg/N/NkLDpqMwT3g== +"@parcel/optimizer-css@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/optimizer-css/-/optimizer-css-2.10.0.tgz#7502237ed0b3a7086f72102d92864dcf2f679857" + integrity sha512-D7hFYjJpudlbSgMlzwSbSguLehwGe4vJrQ4s83jj7z0UlHd74Vir9fd9LQTPuUErgs2SOQIPxFwLGqR6Hi+mOg== dependencies: - "@parcel/diagnostic" "2.8.3" - "@parcel/plugin" "2.8.3" + "@parcel/diagnostic" "2.10.0" + "@parcel/plugin" "2.10.0" "@parcel/source-map" "^2.1.1" - "@parcel/utils" "2.8.3" + "@parcel/utils" "2.10.0" browserslist "^4.6.6" lightningcss "^1.16.1" nullthrows "^1.1.1" -"@parcel/optimizer-htmlnano@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/optimizer-htmlnano/-/optimizer-htmlnano-2.8.3.tgz#a71ab6f0f24160ef9f573266064438eff65e96d0" - integrity sha512-L8/fHbEy8Id2a2E0fwR5eKGlv9VYDjrH9PwdJE9Za9v1O/vEsfl/0T/79/x129l5O0yB6EFQkFa20MiK3b+vOg== +"@parcel/optimizer-htmlnano@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/optimizer-htmlnano/-/optimizer-htmlnano-2.10.0.tgz#36f4a34ba59d916f4fb1173538b7c7549bc51188" + integrity sha512-uYmluYpyyVumY7d/aHkGnFVLzOHoGqzVF9os/PkqVOnGEQ3qQibO3Hl9neTtm2GEUgeOfq1lrXLEfpW/k3qG1w== dependencies: - "@parcel/plugin" "2.8.3" + "@parcel/plugin" "2.10.0" htmlnano "^2.0.0" nullthrows "^1.1.1" posthtml "^0.16.5" svgo "^2.4.0" -"@parcel/optimizer-image@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/optimizer-image/-/optimizer-image-2.8.3.tgz#ea49b4245b4f7d60b38c7585c6311fb21d341baa" - integrity sha512-SD71sSH27SkCDNUNx9A3jizqB/WIJr3dsfp+JZGZC42tpD/Siim6Rqy9M4To/BpMMQIIiEXa5ofwS+DgTEiEHQ== - dependencies: - "@parcel/diagnostic" "2.8.3" - "@parcel/plugin" "2.8.3" - "@parcel/utils" "2.8.3" - "@parcel/workers" "2.8.3" - detect-libc "^1.0.3" - -"@parcel/optimizer-svgo@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/optimizer-svgo/-/optimizer-svgo-2.8.3.tgz#04da4efec6b623679539a84961bff6998034ba8a" - integrity sha512-9KQed99NZnQw3/W4qBYVQ7212rzA9EqrQG019TIWJzkA9tjGBMIm2c/nXpK1tc3hQ3e7KkXkFCQ3C+ibVUnHNA== - dependencies: - "@parcel/diagnostic" "2.8.3" - "@parcel/plugin" "2.8.3" - "@parcel/utils" "2.8.3" +"@parcel/optimizer-image@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/optimizer-image/-/optimizer-image-2.10.0.tgz#8a08898d1fc591d3bb19ca21fd17f57124b12b49" + integrity sha512-uR/nd3kRxiQuPxB0nP5WLlydTUwRHcpFPAY0iV12cyjCQs+MaZHrhwoDO8kWVaT7jN7WXKYcSIHeP1kvR0HEQw== + dependencies: + "@parcel/diagnostic" "2.10.0" + "@parcel/plugin" "2.10.0" + "@parcel/rust" "2.10.0" + "@parcel/utils" "2.10.0" + "@parcel/workers" "2.10.0" + +"@parcel/optimizer-svgo@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/optimizer-svgo/-/optimizer-svgo-2.10.0.tgz#a80782132ea3961725e5ce58affb7f76c1163730" + integrity sha512-2IXClEpjlafidKAiOh/+amdDWOHGtA4Sil/3flmhLkjNFh7z2bGTYodO5xvC3Umw6N11fPNL1Wch1jn54fMO1g== + dependencies: + "@parcel/diagnostic" "2.10.0" + "@parcel/plugin" "2.10.0" + "@parcel/utils" "2.10.0" svgo "^2.4.0" -"@parcel/optimizer-terser@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/optimizer-terser/-/optimizer-terser-2.8.3.tgz#3a06d98d09386a1a0ae1be85376a8739bfba9618" - integrity sha512-9EeQlN6zIeUWwzrzu6Q2pQSaYsYGah8MtiQ/hog9KEPlYTP60hBv/+utDyYEHSQhL7y5ym08tPX5GzBvwAD/dA== +"@parcel/optimizer-swc@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/optimizer-swc/-/optimizer-swc-2.10.0.tgz#46d77c5183627291acc297dd33e466abb2aae5bb" + integrity sha512-yq17TG6uyzIbiouK57AngJa6rVwfJ8hPzgc2lqZ9LJxDX07t/5Z+k/+aq4Izy+7kQNR8kH+4asWaMXReSsXmNQ== dependencies: - "@parcel/diagnostic" "2.8.3" - "@parcel/plugin" "2.8.3" + "@parcel/diagnostic" "2.10.0" + "@parcel/plugin" "2.10.0" "@parcel/source-map" "^2.1.1" - "@parcel/utils" "2.8.3" + "@parcel/utils" "2.10.0" + "@swc/core" "^1.3.36" nullthrows "^1.1.1" - terser "^5.2.0" - -"@parcel/package-manager@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/package-manager/-/package-manager-2.8.3.tgz#ddd0d62feae3cf0fb6cc0537791b3a16296ad458" - integrity sha512-tIpY5pD2lH53p9hpi++GsODy6V3khSTX4pLEGuMpeSYbHthnOViobqIlFLsjni+QA1pfc8NNNIQwSNdGjYflVA== - dependencies: - "@parcel/diagnostic" "2.8.3" - "@parcel/fs" "2.8.3" - "@parcel/logger" "2.8.3" - "@parcel/types" "2.8.3" - "@parcel/utils" "2.8.3" - "@parcel/workers" "2.8.3" - semver "^5.7.1" - -"@parcel/packager-css@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/packager-css/-/packager-css-2.8.3.tgz#0eff34268cb4f5dfb53c1bbca85f5567aeb1835a" - integrity sha512-WyvkMmsurlHG8d8oUVm7S+D+cC/T3qGeqogb7sTI52gB6uiywU7lRCizLNqGFyFGIxcVTVHWnSHqItBcLN76lA== - dependencies: - "@parcel/plugin" "2.8.3" + +"@parcel/package-manager@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/package-manager/-/package-manager-2.10.0.tgz#be4170f832ab61dd3963de483c951baac0a8033f" + integrity sha512-BBUhwgX2Rz92SqGCyYp5Du4UEzm/bjrSSoeLtuRRevWKTVXhgHGbqcAlZmICoxb1lZGpn8x+pEivWd3w+5M7iA== + dependencies: + "@parcel/diagnostic" "2.10.0" + "@parcel/fs" "2.10.0" + "@parcel/logger" "2.10.0" + "@parcel/node-resolver-core" "3.1.0" + "@parcel/types" "2.10.0" + "@parcel/utils" "2.10.0" + "@parcel/workers" "2.10.0" + semver "^7.5.2" + +"@parcel/packager-css@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/packager-css/-/packager-css-2.10.0.tgz#212cb2b96084304e9597f4a07278dc9e4b9e65de" + integrity sha512-BY1PoPPOngiJ6gFD+mUQ6YZvwDxlth8oCU9328T8kFwhmA4qL6pfIxNPI1I53Ig5f38tf1nhFkHACDCbs4MxaQ== + dependencies: + "@parcel/diagnostic" "2.10.0" + "@parcel/plugin" "2.10.0" "@parcel/source-map" "^2.1.1" - "@parcel/utils" "2.8.3" + "@parcel/utils" "2.10.0" nullthrows "^1.1.1" -"@parcel/packager-html@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/packager-html/-/packager-html-2.8.3.tgz#f9263b891aa4dd46c6e2fa2b07025a482132fff1" - integrity sha512-OhPu1Hx1RRKJodpiu86ZqL8el2Aa4uhBHF6RAL1Pcrh2EhRRlPf70Sk0tC22zUpYL7es+iNKZ/n0Rl+OWSHWEw== +"@parcel/packager-html@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/packager-html/-/packager-html-2.10.0.tgz#2faebaa136e498fce605300a284d7078f95bda5e" + integrity sha512-EtxQwuQXQ6zrPRG9/pIdIcvuDCzBEsAnjN9kZ+XuxEYGoReX7weN4oALA6gCnw3w7U4cq6+VR1R08F6Cd8T2MQ== dependencies: - "@parcel/plugin" "2.8.3" - "@parcel/types" "2.8.3" - "@parcel/utils" "2.8.3" + "@parcel/plugin" "2.10.0" + "@parcel/types" "2.10.0" + "@parcel/utils" "2.10.0" nullthrows "^1.1.1" posthtml "^0.16.5" -"@parcel/packager-js@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/packager-js/-/packager-js-2.8.3.tgz#3ed11565915d73d12192b6901c75a6b820e4a83a" - integrity sha512-0pGKC3Ax5vFuxuZCRB+nBucRfFRz4ioie19BbDxYnvBxrd4M3FIu45njf6zbBYsI9eXqaDnL1b3DcZJfYqtIzw== +"@parcel/packager-js@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/packager-js/-/packager-js-2.10.0.tgz#3f47411a3780090941cb0bec7525d019987105d8" + integrity sha512-9r1pv8GScZzgGempexikym9d1aehTAp0DxK71LUxBT0os9Br+nJOtV4wmJWnHapt4r108d75DcgtytdVM5nuqA== dependencies: - "@parcel/diagnostic" "2.8.3" - "@parcel/hash" "2.8.3" - "@parcel/plugin" "2.8.3" + "@parcel/diagnostic" "2.10.0" + "@parcel/plugin" "2.10.0" + "@parcel/rust" "2.10.0" "@parcel/source-map" "^2.1.1" - "@parcel/utils" "2.8.3" + "@parcel/types" "2.10.0" + "@parcel/utils" "2.10.0" globals "^13.2.0" nullthrows "^1.1.1" -"@parcel/packager-raw@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/packager-raw/-/packager-raw-2.8.3.tgz#bdec826df991e186cb58691cc45d12ad5c06676e" - integrity sha512-BA6enNQo1RCnco9MhkxGrjOk59O71IZ9DPKu3lCtqqYEVd823tXff2clDKHK25i6cChmeHu6oB1Rb73hlPqhUA== +"@parcel/packager-raw@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/packager-raw/-/packager-raw-2.10.0.tgz#ad3e83c50517a050d47bea97db3104c7ea6bf5cd" + integrity sha512-fk1XGqMP38uyWC1Jqg8/Mp1x0dLxfd9GnmLHQCUZ0OSQLwF9Nqpow1WR4tC8juxYNK5haGqKyL9X5pVN4KLNYQ== dependencies: - "@parcel/plugin" "2.8.3" + "@parcel/plugin" "2.10.0" -"@parcel/packager-svg@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/packager-svg/-/packager-svg-2.8.3.tgz#7233315296001c531cb55ca96b5f2ef672343630" - integrity sha512-mvIoHpmv5yzl36OjrklTDFShLUfPFTwrmp1eIwiszGdEBuQaX7JVI3Oo2jbVQgcN4W7J6SENzGQ3Q5hPTW3pMw== +"@parcel/packager-svg@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/packager-svg/-/packager-svg-2.10.0.tgz#2f4416c91b15b94149b6cdd495ebe0c87053ede8" + integrity sha512-+vXXZwENinz/N2m04tH5BDSc8Zv7XNd/fsXZ3BAcEWmYpiTHBYMgbIy+fsdQb1tpFwku7CezthHFDsXejyNtrg== dependencies: - "@parcel/plugin" "2.8.3" - "@parcel/types" "2.8.3" - "@parcel/utils" "2.8.3" + "@parcel/plugin" "2.10.0" + "@parcel/types" "2.10.0" + "@parcel/utils" "2.10.0" posthtml "^0.16.4" -"@parcel/plugin@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/plugin/-/plugin-2.8.3.tgz#7bb30a5775eaa6473c27f002a0a3ee7308d6d669" - integrity sha512-jZ6mnsS4D9X9GaNnvrixDQwlUQJCohDX2hGyM0U0bY2NWU8Km97SjtoCpWjq+XBCx/gpC4g58+fk9VQeZq2vlw== +"@parcel/packager-wasm@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/packager-wasm/-/packager-wasm-2.10.0.tgz#d09059cabb42ebf50eecd363db0b7472ba41d04b" + integrity sha512-G/OsV9Xpyu1D/mTwazw4FkWlFotcFMaRmejmc6km3+qjaFxMubRBLCNMCvGw2lDIhA40qz/DpZS/kblB/FGSPA== + dependencies: + "@parcel/plugin" "2.10.0" + +"@parcel/plugin@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/plugin/-/plugin-2.10.0.tgz#03a963f713fa76d76469955e3a693e7c3b607138" + integrity sha512-FaWchkYJxLOohNNb3ah9R/9gckew+iGOzcGZ1bUtLGc/Dwz1mTVeaAanqOjlZ6C5FCe9lMctkH7h0eQsJ0mlVQ== dependencies: - "@parcel/types" "2.8.3" + "@parcel/types" "2.10.0" -"@parcel/reporter-cli@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/reporter-cli/-/reporter-cli-2.8.3.tgz#12a4743b51b8fe6837f53c20e01bbf1f7336e8e4" - integrity sha512-3sJkS6tFFzgIOz3u3IpD/RsmRxvOKKiQHOTkiiqRt1l44mMDGKS7zANRnJYsQzdCsgwc9SOP30XFgJwtoVlMbw== +"@parcel/profiler@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/profiler/-/profiler-2.10.0.tgz#839084002fa4323e71f65de604f7863e43a59524" + integrity sha512-SGkslseYA5TQOb8Z7gepi7YiIv3uH4BYAM9nwduMZrRZENcICbgTh1Pb+dp10y+6k9hFFH748eHtxJqSWARDBw== dependencies: - "@parcel/plugin" "2.8.3" - "@parcel/types" "2.8.3" - "@parcel/utils" "2.8.3" + "@parcel/diagnostic" "2.10.0" + "@parcel/events" "2.10.0" + chrome-trace-event "^1.0.2" + +"@parcel/reporter-cli@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/reporter-cli/-/reporter-cli-2.10.0.tgz#3c26779362a296c3e1bad91986c0907687376fef" + integrity sha512-+OtZUdmHFgNY8+w3/U7dEZKMTtIFh7EiFw5VelKIGdvJrZNa9j7vbFuZziK6zUW2uopCk4qsDinn6Rfi7M16KA== + dependencies: + "@parcel/plugin" "2.10.0" + "@parcel/types" "2.10.0" + "@parcel/utils" "2.10.0" chalk "^4.1.0" term-size "^2.2.1" -"@parcel/reporter-dev-server@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/reporter-dev-server/-/reporter-dev-server-2.8.3.tgz#a0daa5cc015642684cea561f4e0e7116bbffdc1c" - integrity sha512-Y8C8hzgzTd13IoWTj+COYXEyCkXfmVJs3//GDBsH22pbtSFMuzAZd+8J9qsCo0EWpiDow7V9f1LischvEh3FbQ== +"@parcel/reporter-dev-server@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/reporter-dev-server/-/reporter-dev-server-2.10.0.tgz#428b4784773c05c9ccd9a5849ce2f15d812165d7" + integrity sha512-1dMkVgbfx+AxRVjzX5on3LOY8Vhsr4wuwQdLhmN1kAveTNWUYBPSVzIt5ZPVj3Cmpwpaonj7tHkZ2YujaNWHQg== dependencies: - "@parcel/plugin" "2.8.3" - "@parcel/utils" "2.8.3" + "@parcel/plugin" "2.10.0" + "@parcel/utils" "2.10.0" -"@parcel/resolver-default@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/resolver-default/-/resolver-default-2.8.3.tgz#5ae41e537ae4a793c1abb47f094482b9e2ac3535" - integrity sha512-k0B5M/PJ+3rFbNj4xZSBr6d6HVIe6DH/P3dClLcgBYSXAvElNDfXgtIimbjCyItFkW9/BfcgOVKEEIZOeySH/A== +"@parcel/reporter-tracer@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/reporter-tracer/-/reporter-tracer-2.10.0.tgz#9650d2a04e0c78c516fca59ec75e9ab895b07504" + integrity sha512-mlxF3ozH6Kys4hewG1Bze1q8wHJL1ue276Qek9xPJly8ed08wU7rPGZF0vz8fJfKT8vx+nGvnKFXYiHjF+w6bg== dependencies: - "@parcel/node-resolver-core" "2.8.3" - "@parcel/plugin" "2.8.3" + "@parcel/plugin" "2.10.0" + "@parcel/utils" "2.10.0" + chrome-trace-event "^1.0.3" + nullthrows "^1.1.1" -"@parcel/runtime-browser-hmr@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/runtime-browser-hmr/-/runtime-browser-hmr-2.8.3.tgz#1fa74e1fbd1030b0a920c58afa3a9eb7dc4bcd1e" - integrity sha512-2O1PYi2j/Q0lTyGNV3JdBYwg4rKo6TEVFlYGdd5wCYU9ZIN9RRuoCnWWH2qCPj3pjIVtBeppYxzfVjPEHINWVg== +"@parcel/resolver-default@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/resolver-default/-/resolver-default-2.10.0.tgz#47a55bf6d7552cf765b54fcd52a3e024a7037da6" + integrity sha512-KWtKrmjf/CAyZkk+SSwHhMMwN6cjJJRtUSLCvwbrlevd0onRl3erUdVYrJrNB5X+N8ylCO6Vb0wCyMegOo/OwQ== dependencies: - "@parcel/plugin" "2.8.3" - "@parcel/utils" "2.8.3" + "@parcel/node-resolver-core" "3.1.0" + "@parcel/plugin" "2.10.0" -"@parcel/runtime-js@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/runtime-js/-/runtime-js-2.8.3.tgz#0baa4c8fbf77eabce05d01ccc186614968ffc0cd" - integrity sha512-IRja0vNKwvMtPgIqkBQh0QtRn0XcxNC8HU1jrgWGRckzu10qJWO+5ULgtOeR4pv9krffmMPqywGXw6l/gvJKYQ== +"@parcel/runtime-browser-hmr@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/runtime-browser-hmr/-/runtime-browser-hmr-2.10.0.tgz#dccfcef66af867100c3ad7b155aeaf7363df64e2" + integrity sha512-x22HHUAFuhycE/NGowkEaR7zeZsp8PcViHkmuNkSvLboe8PJvq4BFpnd+RUj+o8EjN31p+8K2pFqS1hYAmtdwg== dependencies: - "@parcel/plugin" "2.8.3" - "@parcel/utils" "2.8.3" + "@parcel/plugin" "2.10.0" + "@parcel/utils" "2.10.0" + +"@parcel/runtime-js@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/runtime-js/-/runtime-js-2.10.0.tgz#3c1cb3b5e8b3e6b6015e1b67a7b5d493eb3756e5" + integrity sha512-AyDY+tQ9jiip6YsDGbaw7Azj60qG4fWNniUMIRMsywKQZOySLpfMNGHUcwDkV8j1NTve87Cwr2EzMOMnQHaUsQ== + dependencies: + "@parcel/diagnostic" "2.10.0" + "@parcel/plugin" "2.10.0" + "@parcel/utils" "2.10.0" nullthrows "^1.1.1" -"@parcel/runtime-react-refresh@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/runtime-react-refresh/-/runtime-react-refresh-2.8.3.tgz#381a942fb81e8f5ac6c7e0ee1b91dbf34763c3f8" - integrity sha512-2v/qFKp00MfG0234OdOgQNAo6TLENpFYZMbVbAsPMY9ITiqG73MrEsrGXVoGbYiGTMB/Toer/lSWlJxtacOCuA== +"@parcel/runtime-react-refresh@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/runtime-react-refresh/-/runtime-react-refresh-2.10.0.tgz#4b11085f5a69065de796e1cff239237ff78a55ad" + integrity sha512-hmiK9i6iitdjfcCaI0888+pecQHA0dzf6wMKnwtJsYQxCv2TrwXPsSOMHjkKr1K3ALXi8vlauG4K0Rm7c+vfdw== dependencies: - "@parcel/plugin" "2.8.3" - "@parcel/utils" "2.8.3" + "@parcel/plugin" "2.10.0" + "@parcel/utils" "2.10.0" react-error-overlay "6.0.9" react-refresh "^0.9.0" -"@parcel/runtime-service-worker@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/runtime-service-worker/-/runtime-service-worker-2.8.3.tgz#54d92da9ff1dfbd27db0e84164a22fa59e99b348" - integrity sha512-/Skkw+EeRiwzOJso5fQtK8c9b452uWLNhQH1ISTodbmlcyB4YalAiSsyHCtMYD0c3/t5Sx4ZS7vxBAtQd0RvOw== +"@parcel/runtime-service-worker@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/runtime-service-worker/-/runtime-service-worker-2.10.0.tgz#6c10e3b24a3d5d4d565439547d8eb50acf2aae05" + integrity sha512-vi84PwAsyPI1P/5FTt1uNKjH1NGizQRdS4CmjBMz+VBT6GVuXMgZ9iQy3OYC8MsiyHlyG7mScftI74RWqw1DDg== dependencies: - "@parcel/plugin" "2.8.3" - "@parcel/utils" "2.8.3" + "@parcel/plugin" "2.10.0" + "@parcel/utils" "2.10.0" nullthrows "^1.1.1" +"@parcel/rust@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/rust/-/rust-2.10.0.tgz#fc930715a3200bb05a58007fc11cb29f444382c9" + integrity sha512-9J7riqPI8mVlFSDphK9kVUH8nFQgeMbO/95Ycf4vaEOVE1ICQo1h18WHAy2DndmL1uSd/UTimirrP6yLt/I3KA== + "@parcel/source-map@^2.1.1": version "2.1.1" resolved "https://registry.yarnpkg.com/@parcel/source-map/-/source-map-2.1.1.tgz#fb193b82dba6dd62cc7a76b326f57bb35000a782" @@ -549,165 +534,166 @@ dependencies: detect-libc "^1.0.3" -"@parcel/transformer-babel@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/transformer-babel/-/transformer-babel-2.8.3.tgz#286bc6cb9afe4c0259f0b28e0f2f47322a24b130" - integrity sha512-L6lExfpvvC7T/g3pxf3CIJRouQl+sgrSzuWQ0fD4PemUDHvHchSP4SNUVnd6gOytF3Y1KpnEZIunQGi5xVqQCQ== +"@parcel/transformer-babel@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/transformer-babel/-/transformer-babel-2.10.0.tgz#328573dd90948f3ec04646731e523cab9cde3b4e" + integrity sha512-XwlzHt7WPfueFlwl/bXItopgZ6ILSPzl5OmPeytHrM2TanymeLjJ1y3vxwY1C1BhNlrTwPHcf9U8aiuVSpE8RQ== dependencies: - "@parcel/diagnostic" "2.8.3" - "@parcel/plugin" "2.8.3" + "@parcel/diagnostic" "2.10.0" + "@parcel/plugin" "2.10.0" "@parcel/source-map" "^2.1.1" - "@parcel/utils" "2.8.3" + "@parcel/utils" "2.10.0" browserslist "^4.6.6" json5 "^2.2.0" nullthrows "^1.1.1" - semver "^5.7.0" + semver "^7.5.2" -"@parcel/transformer-css@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/transformer-css/-/transformer-css-2.8.3.tgz#d6c44100204e73841ad8e0f90472172ea8b9120c" - integrity sha512-xTqFwlSXtnaYen9ivAgz+xPW7yRl/u4QxtnDyDpz5dr8gSeOpQYRcjkd4RsYzKsWzZcGtB5EofEk8ayUbWKEUg== +"@parcel/transformer-css@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/transformer-css/-/transformer-css-2.10.0.tgz#f23b2ffd901a02b189571d6ead752b7c1f3ec871" + integrity sha512-hITticpUE/qilpsTc7HQP04qhXwyUSKGZKgcFnvf8+BJO/LoclbVK1nzbR61eYl5Jhj1XB67p3tCt5fSvPhOsQ== dependencies: - "@parcel/diagnostic" "2.8.3" - "@parcel/plugin" "2.8.3" + "@parcel/diagnostic" "2.10.0" + "@parcel/plugin" "2.10.0" "@parcel/source-map" "^2.1.1" - "@parcel/utils" "2.8.3" + "@parcel/utils" "2.10.0" browserslist "^4.6.6" lightningcss "^1.16.1" nullthrows "^1.1.1" -"@parcel/transformer-html@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/transformer-html/-/transformer-html-2.8.3.tgz#5c68b28ee6b8c7a13b8aee87f7957ad3227bd83f" - integrity sha512-kIZO3qsMYTbSnSpl9cnZog+SwL517ffWH54JeB410OSAYF1ouf4n5v9qBnALZbuCCmPwJRGs4jUtE452hxwN4g== +"@parcel/transformer-html@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/transformer-html/-/transformer-html-2.10.0.tgz#de4d95c2124656b226620a49b7ea264c2cf19239" + integrity sha512-rc8YKjB+bE7yGHOf674CSzW8ii+m5caBo4akdRIUdhEHJS4FnSwxYIZlMcfV9pZM4Tj5PFMZyrlAHad6YrO8aA== dependencies: - "@parcel/diagnostic" "2.8.3" - "@parcel/hash" "2.8.3" - "@parcel/plugin" "2.8.3" + "@parcel/diagnostic" "2.10.0" + "@parcel/plugin" "2.10.0" + "@parcel/rust" "2.10.0" nullthrows "^1.1.1" posthtml "^0.16.5" posthtml-parser "^0.10.1" posthtml-render "^3.0.0" - semver "^5.7.1" + semver "^7.5.2" srcset "4" -"@parcel/transformer-image@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/transformer-image/-/transformer-image-2.8.3.tgz#73805b2bfc3c8919d7737544e5f8be39e3f303fe" - integrity sha512-cO4uptcCGTi5H6bvTrAWEFUsTNhA4kCo8BSvRSCHA2sf/4C5tGQPHt3JhdO0GQLPwZRCh/R41EkJs5HZ8A8DAg== +"@parcel/transformer-image@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/transformer-image/-/transformer-image-2.10.0.tgz#d7502a8139aea0997d00982151115e0dde422e58" + integrity sha512-qbNyAJvzqdO/OnHhCOoPAZN5aBD/xphyXvDNI0Fb3UPEr5MQtAnzv2lS1I63s4rKpphBntWj7nEIAio6s7c5bw== dependencies: - "@parcel/plugin" "2.8.3" - "@parcel/utils" "2.8.3" - "@parcel/workers" "2.8.3" + "@parcel/plugin" "2.10.0" + "@parcel/utils" "2.10.0" + "@parcel/workers" "2.10.0" nullthrows "^1.1.1" -"@parcel/transformer-js@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/transformer-js/-/transformer-js-2.8.3.tgz#fe400df428394d1e7fe5afb6dea5c7c858e44f03" - integrity sha512-9Qd6bib+sWRcpovvzvxwy/PdFrLUXGfmSW9XcVVG8pvgXsZPFaNjnNT8stzGQj1pQiougCoxMY4aTM5p1lGHEQ== +"@parcel/transformer-js@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/transformer-js/-/transformer-js-2.10.0.tgz#142a70b77466e5359774d21939da06d5f579bb5e" + integrity sha512-39ZNnje8dlmME1ipjFyAFHyhHaGCwZZpXYN9SCTl/+AnjZLamnmVFkesgBbrRSBRQixRG1VwCvrWsjLLeLkTUg== dependencies: - "@parcel/diagnostic" "2.8.3" - "@parcel/plugin" "2.8.3" + "@parcel/diagnostic" "2.10.0" + "@parcel/plugin" "2.10.0" + "@parcel/rust" "2.10.0" "@parcel/source-map" "^2.1.1" - "@parcel/utils" "2.8.3" - "@parcel/workers" "2.8.3" - "@swc/helpers" "^0.4.12" + "@parcel/utils" "2.10.0" + "@parcel/workers" "2.10.0" + "@swc/helpers" "^0.5.0" browserslist "^4.6.6" - detect-libc "^1.0.3" nullthrows "^1.1.1" regenerator-runtime "^0.13.7" - semver "^5.7.1" + semver "^7.5.2" -"@parcel/transformer-json@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/transformer-json/-/transformer-json-2.8.3.tgz#25deb3a5138cc70a83269fc5d39d564609354d36" - integrity sha512-B7LmVq5Q7bZO4ERb6NHtRuUKWGysEeaj9H4zelnyBv+wLgpo4f5FCxSE1/rTNmP9u1qHvQ3scGdK6EdSSokGPg== +"@parcel/transformer-json@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/transformer-json/-/transformer-json-2.10.0.tgz#77a684a2e631c3058fd8d70d4b05aaf704a6b928" + integrity sha512-4G6ZIt7IYu1l3BlsL55Hi3869X6KHE0CHybWf364h5ZUmzo3Xpc5i7cziQX+IhWDo1qn1jiziOPGY85LXlo8ug== dependencies: - "@parcel/plugin" "2.8.3" + "@parcel/plugin" "2.10.0" json5 "^2.2.0" -"@parcel/transformer-postcss@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/transformer-postcss/-/transformer-postcss-2.8.3.tgz#df4fdc1c90893823445f2a8eb8e2bdd0349ccc58" - integrity sha512-e8luB/poIlz6jBsD1Izms+6ElbyzuoFVa4lFVLZnTAChI3UxPdt9p/uTsIO46HyBps/Bk8ocvt3J4YF84jzmvg== +"@parcel/transformer-postcss@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/transformer-postcss/-/transformer-postcss-2.10.0.tgz#b38a4892e14cf82a5324a01ff2d063207b1a383e" + integrity sha512-Xhz+MHr9Q31d3u3hsBOtmFGEQx7FsNbTumGpqIqaGkDDq4IIMKbEwyrpkmf7/02kyxcbwr6uaBqnMHm55j10sQ== dependencies: - "@parcel/diagnostic" "2.8.3" - "@parcel/hash" "2.8.3" - "@parcel/plugin" "2.8.3" - "@parcel/utils" "2.8.3" + "@parcel/diagnostic" "2.10.0" + "@parcel/plugin" "2.10.0" + "@parcel/rust" "2.10.0" + "@parcel/utils" "2.10.0" clone "^2.1.1" nullthrows "^1.1.1" postcss-value-parser "^4.2.0" - semver "^5.7.1" + semver "^7.5.2" -"@parcel/transformer-posthtml@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/transformer-posthtml/-/transformer-posthtml-2.8.3.tgz#7c3912a5a631cb26485f6464e0d6eeabb6f1e718" - integrity sha512-pkzf9Smyeaw4uaRLsT41RGrPLT5Aip8ZPcntawAfIo+KivBQUV0erY1IvHYjyfFzq1ld/Fo2Ith9He6mxpPifA== +"@parcel/transformer-posthtml@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/transformer-posthtml/-/transformer-posthtml-2.10.0.tgz#accca3feb46c367182a6ea56148e8b83e41733a2" + integrity sha512-kmz8Yip5hh2y3bfA76mC2QtI9VHdS7k5dV96/yjar0CkLHJnr33Jh7MTfuCN+01nVU20Tn3YMqEMQ/ErPVJwlg== dependencies: - "@parcel/plugin" "2.8.3" - "@parcel/utils" "2.8.3" + "@parcel/plugin" "2.10.0" + "@parcel/utils" "2.10.0" nullthrows "^1.1.1" posthtml "^0.16.5" posthtml-parser "^0.10.1" posthtml-render "^3.0.0" - semver "^5.7.1" + semver "^7.5.2" -"@parcel/transformer-raw@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/transformer-raw/-/transformer-raw-2.8.3.tgz#3a22213fe18a5f83fd78889cb49f06e059cfead7" - integrity sha512-G+5cXnd2/1O3nV/pgRxVKZY/HcGSseuhAe71gQdSQftb8uJEURyUHoQ9Eh0JUD3MgWh9V+nIKoyFEZdf9T0sUQ== +"@parcel/transformer-raw@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/transformer-raw/-/transformer-raw-2.10.0.tgz#4e8fa1bdffca28bc7653cdbe49ab3ca464875399" + integrity sha512-1tR58kqzTh4baLq/++bp84H2lhOoAz8cJeJykgsYImva7aRWcjlTppNKjBF6Ef8etIRMPZOozTdbS53VdQ9IbA== dependencies: - "@parcel/plugin" "2.8.3" + "@parcel/plugin" "2.10.0" -"@parcel/transformer-react-refresh-wrap@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/transformer-react-refresh-wrap/-/transformer-react-refresh-wrap-2.8.3.tgz#8b0392638405dd470a886002229f7889d5464822" - integrity sha512-q8AAoEvBnCf/nPvgOwFwKZfEl/thwq7c2duxXkhl+tTLDRN2vGmyz4355IxCkavSX+pLWSQ5MexklSEeMkgthg== +"@parcel/transformer-react-refresh-wrap@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/transformer-react-refresh-wrap/-/transformer-react-refresh-wrap-2.10.0.tgz#3cf47430a31ec2402eba87fc0db8b18f8beb89e3" + integrity sha512-4ab1tiwUA2XznTh/eb/IVKEA+Ynkbqc5sgNuobf1MLKF82FXTUT5szVshff/ODpwublvVBD3YbXlapxV5xyFvA== dependencies: - "@parcel/plugin" "2.8.3" - "@parcel/utils" "2.8.3" + "@parcel/plugin" "2.10.0" + "@parcel/utils" "2.10.0" react-refresh "^0.9.0" -"@parcel/transformer-svg@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/transformer-svg/-/transformer-svg-2.8.3.tgz#4df959cba4ebf45d7aaddd540f752e6e84df38b2" - integrity sha512-3Zr/gBzxi1ZH1fftH/+KsZU7w5GqkmxlB0ZM8ovS5E/Pl1lq1t0xvGJue9m2VuQqP8Mxfpl5qLFmsKlhaZdMIQ== +"@parcel/transformer-svg@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/transformer-svg/-/transformer-svg-2.10.0.tgz#3277d04f8b1d5ebf9bf7259da25fc0ee491e7dab" + integrity sha512-qEZFk4gxyVNhm2V8R3YLo9qCyYNVBySWmZLjmwuhLLmAE+r0qGebc9oXyo7C6ML5d/4Tfj6NriCOeX+HMhPVxw== dependencies: - "@parcel/diagnostic" "2.8.3" - "@parcel/hash" "2.8.3" - "@parcel/plugin" "2.8.3" + "@parcel/diagnostic" "2.10.0" + "@parcel/plugin" "2.10.0" + "@parcel/rust" "2.10.0" nullthrows "^1.1.1" posthtml "^0.16.5" posthtml-parser "^0.10.1" posthtml-render "^3.0.0" - semver "^5.7.1" + semver "^7.5.2" -"@parcel/types@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/types/-/types-2.8.3.tgz#3306bc5391b6913bd619914894b8cd84a24b30fa" - integrity sha512-FECA1FB7+0UpITKU0D6TgGBpGxYpVSMNEENZbSJxFSajNy3wrko+zwBKQmFOLOiPcEtnGikxNs+jkFWbPlUAtw== +"@parcel/types@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/types/-/types-2.10.0.tgz#033f35dccb95c940847a8fb5f525a0494d07106b" + integrity sha512-iDFVvgN+jK02GY++V+WY3WuNTM6CGDPToGfL31/Sgf6/1PzT7kL6uXJ6+859u8wkTIrtkWD2XyTNkKJJ8jPwgg== dependencies: - "@parcel/cache" "2.8.3" - "@parcel/diagnostic" "2.8.3" - "@parcel/fs" "2.8.3" - "@parcel/package-manager" "2.8.3" + "@parcel/cache" "2.10.0" + "@parcel/diagnostic" "2.10.0" + "@parcel/fs" "2.10.0" + "@parcel/package-manager" "2.10.0" "@parcel/source-map" "^2.1.1" - "@parcel/workers" "2.8.3" + "@parcel/workers" "2.10.0" utility-types "^3.10.0" -"@parcel/utils@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/utils/-/utils-2.8.3.tgz#0d56c9e8e22c119590a5e044a0e01031965da40e" - integrity sha512-IhVrmNiJ+LOKHcCivG5dnuLGjhPYxQ/IzbnF2DKNQXWBTsYlHkJZpmz7THoeLtLliGmSOZ3ZCsbR8/tJJKmxjA== +"@parcel/utils@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/utils/-/utils-2.10.0.tgz#5764e53200cefb8fc1055638e49d746c40fba5ef" + integrity sha512-8qx9caJTjli6UKpKlcPjdSBblkwTc+BnIsSK3/7fX7kbtHLmEkQH/RWZbbOJItHbnzlsmaDJTfS7j6rrcFw2Pw== dependencies: - "@parcel/codeframe" "2.8.3" - "@parcel/diagnostic" "2.8.3" - "@parcel/hash" "2.8.3" - "@parcel/logger" "2.8.3" - "@parcel/markdown-ansi" "2.8.3" + "@parcel/codeframe" "2.10.0" + "@parcel/diagnostic" "2.10.0" + "@parcel/logger" "2.10.0" + "@parcel/markdown-ansi" "2.10.0" + "@parcel/rust" "2.10.0" "@parcel/source-map" "^2.1.1" chalk "^4.1.0" + nullthrows "^1.1.1" "@parcel/watcher@^2.0.7": version "2.1.0" @@ -719,25 +705,104 @@ node-addon-api "^3.2.1" node-gyp-build "^4.3.0" -"@parcel/workers@2.8.3": - version "2.8.3" - resolved "https://registry.yarnpkg.com/@parcel/workers/-/workers-2.8.3.tgz#255450ccf4db234082407e4ddda5fd575f08c235" - integrity sha512-+AxBnKgjqVpUHBcHLWIHcjYgKIvHIpZjN33mG5LG9XXvrZiqdWvouEzqEXlVLq5VzzVbKIQQcmsvRy138YErkg== +"@parcel/workers@2.10.0": + version "2.10.0" + resolved "https://registry.yarnpkg.com/@parcel/workers/-/workers-2.10.0.tgz#90fdbe37e3522d11b56d38ef50611f1547c31e94" + integrity sha512-PILDag4aW7G9w2AvYvBsMHe/NRCoOt+L7HJzp6UIvy6ssbafH/8fzdGjSpA99GXzC5AXpAHVt8RXhGMXmMP6QA== dependencies: - "@parcel/diagnostic" "2.8.3" - "@parcel/logger" "2.8.3" - "@parcel/types" "2.8.3" - "@parcel/utils" "2.8.3" - chrome-trace-event "^1.0.2" + "@parcel/diagnostic" "2.10.0" + "@parcel/logger" "2.10.0" + "@parcel/profiler" "2.10.0" + "@parcel/types" "2.10.0" + "@parcel/utils" "2.10.0" nullthrows "^1.1.1" -"@swc/helpers@^0.4.12": - version "0.4.14" - resolved "https://registry.yarnpkg.com/@swc/helpers/-/helpers-0.4.14.tgz#1352ac6d95e3617ccb7c1498ff019654f1e12a74" - integrity sha512-4C7nX/dvpzB7za4Ql9K81xK3HPxCpHMgwTZVyf+9JQ6VUbn9jjZVN7/Nkdz/Ugzs2CSjqnL/UPXroiVBVHUWUw== +"@swc/core-darwin-arm64@1.3.93": + version "1.3.93" + resolved "https://registry.yarnpkg.com/@swc/core-darwin-arm64/-/core-darwin-arm64-1.3.93.tgz#aefd94625451988286bebccb1c072bae0a36bcdb" + integrity sha512-gEKgk7FVIgltnIfDO6GntyuQBBlAYg5imHpRgLxB1zSI27ijVVkksc6QwISzFZAhKYaBWIsFSVeL9AYSziAF7A== + +"@swc/core-darwin-x64@1.3.93": + version "1.3.93" + resolved "https://registry.yarnpkg.com/@swc/core-darwin-x64/-/core-darwin-x64-1.3.93.tgz#18409c6effdf508ddf1ebccfa77d35aaa6cd72f0" + integrity sha512-ZQPxm/fXdDQtn3yrYSL/gFfA8OfZ5jTi33yFQq6vcg/Y8talpZ+MgdSlYM0FkLrZdMTYYTNFiuBQuuvkA+av+Q== + +"@swc/core-linux-arm-gnueabihf@1.3.93": + version "1.3.93" + resolved "https://registry.yarnpkg.com/@swc/core-linux-arm-gnueabihf/-/core-linux-arm-gnueabihf-1.3.93.tgz#23a97bc94a8b2f23fb6cc4bc9d8936899e5eeff5" + integrity sha512-OYFMMI2yV+aNe3wMgYhODxHdqUB/jrK0SEMHHS44GZpk8MuBXEF+Mcz4qjkY5Q1EH7KVQqXb/gVWwdgTHpjM2A== + +"@swc/core-linux-arm64-gnu@1.3.93": + version "1.3.93" + resolved "https://registry.yarnpkg.com/@swc/core-linux-arm64-gnu/-/core-linux-arm64-gnu-1.3.93.tgz#7a17406a7cf76a959a617626d5ee2634ae9afa26" + integrity sha512-BT4dT78odKnJMNiq5HdjBsv29CiIdcCcImAPxeFqAeFw1LL6gh9nzI8E96oWc+0lVT5lfhoesCk4Qm7J6bty8w== + +"@swc/core-linux-arm64-musl@1.3.93": + version "1.3.93" + resolved "https://registry.yarnpkg.com/@swc/core-linux-arm64-musl/-/core-linux-arm64-musl-1.3.93.tgz#a30be7780090afefd3b8706398418cbe1d23db49" + integrity sha512-yH5fWEl1bktouC0mhh0Chuxp7HEO4uCtS/ly1Vmf18gs6wZ8DOOkgAEVv2dNKIryy+Na++ljx4Ym7C8tSJTrLw== + +"@swc/core-linux-x64-gnu@1.3.93": + version "1.3.93" + resolved "https://registry.yarnpkg.com/@swc/core-linux-x64-gnu/-/core-linux-x64-gnu-1.3.93.tgz#41e903fd82e059952d16051b442cbe65ee5b8cb3" + integrity sha512-OFUdx64qvrGJhXKEyxosHxgoUVgba2ztYh7BnMiU5hP8lbI8G13W40J0SN3CmFQwPP30+3oEbW7LWzhKEaYjlg== + +"@swc/core-linux-x64-musl@1.3.93": + version "1.3.93" + resolved "https://registry.yarnpkg.com/@swc/core-linux-x64-musl/-/core-linux-x64-musl-1.3.93.tgz#0866807545c44eac9b3254b374310ad5e1c573f9" + integrity sha512-4B8lSRwEq1XYm6xhxHhvHmKAS7pUp1Q7E33NQ2TlmFhfKvCOh86qvThcjAOo57x8DRwmpvEVrqvpXtYagMN6Ig== + +"@swc/core-win32-arm64-msvc@1.3.93": + version "1.3.93" + resolved "https://registry.yarnpkg.com/@swc/core-win32-arm64-msvc/-/core-win32-arm64-msvc-1.3.93.tgz#c72411dea2fd4f62a832f71a6e15424d849e7610" + integrity sha512-BHShlxtkven8ZjjvZ5QR6sC5fZCJ9bMujEkiha6W4cBUTY7ce7qGFyHmQd+iPC85d9kD/0cCiX/Xez8u0BhO7w== + +"@swc/core-win32-ia32-msvc@1.3.93": + version "1.3.93" + resolved "https://registry.yarnpkg.com/@swc/core-win32-ia32-msvc/-/core-win32-ia32-msvc-1.3.93.tgz#05c2b031b976af4ef81f5073ee114254678a5d5d" + integrity sha512-nEwNWnz4JzYAK6asVvb92yeylfxMYih7eMQOnT7ZVlZN5ba9WF29xJ6kcQKs9HRH6MvWhz9+wRgv3FcjlU6HYA== + +"@swc/core-win32-x64-msvc@1.3.93": + version "1.3.93" + resolved "https://registry.yarnpkg.com/@swc/core-win32-x64-msvc/-/core-win32-x64-msvc-1.3.93.tgz#f8748b3fd1879f13084b1b0814edf328c662935c" + integrity sha512-jibQ0zUr4kwJaQVwgmH+svS04bYTPnPw/ZkNInzxS+wFAtzINBYcU8s2PMWbDb2NGYiRSEeoSGyAvS9H+24JFA== + +"@swc/core@^1.3.36": + version "1.3.93" + resolved "https://registry.yarnpkg.com/@swc/core/-/core-1.3.93.tgz#be4282aa44deffb0e5081a2613bac00335600630" + integrity sha512-690GRr1wUGmGYZHk7fUduX/JUwViMF2o74mnZYIWEcJaCcd9MQfkhsxPBtjeg6tF+h266/Cf3RPYhsFBzzxXcA== + dependencies: + "@swc/counter" "^0.1.1" + "@swc/types" "^0.1.5" + optionalDependencies: + "@swc/core-darwin-arm64" "1.3.93" + "@swc/core-darwin-x64" "1.3.93" + "@swc/core-linux-arm-gnueabihf" "1.3.93" + "@swc/core-linux-arm64-gnu" "1.3.93" + "@swc/core-linux-arm64-musl" "1.3.93" + "@swc/core-linux-x64-gnu" "1.3.93" + "@swc/core-linux-x64-musl" "1.3.93" + "@swc/core-win32-arm64-msvc" "1.3.93" + "@swc/core-win32-ia32-msvc" "1.3.93" + "@swc/core-win32-x64-msvc" "1.3.93" + +"@swc/counter@^0.1.1": + version "0.1.2" + resolved "https://registry.yarnpkg.com/@swc/counter/-/counter-0.1.2.tgz#bf06d0770e47c6f1102270b744e17b934586985e" + integrity sha512-9F4ys4C74eSTEUNndnER3VJ15oru2NumfQxS8geE+f3eB5xvfxpWyqE5XlVnxb/R14uoXi6SLbBwwiDSkv+XEw== + +"@swc/helpers@^0.5.0": + version "0.5.3" + resolved "https://registry.yarnpkg.com/@swc/helpers/-/helpers-0.5.3.tgz#98c6da1e196f5f08f977658b80d6bd941b5f294f" + integrity sha512-FaruWX6KdudYloq1AHD/4nU+UsMTdNE8CKyrseXWEcgjDAbvkwJg2QGPAnfIJLIWsjZOSPLOAykK6fuYp4vp4A== dependencies: tslib "^2.4.0" +"@swc/types@^0.1.5": + version "0.1.5" + resolved "https://registry.yarnpkg.com/@swc/types/-/types-0.1.5.tgz#043b731d4f56a79b4897a3de1af35e75d56bc63a" + integrity sha512-myfUej5naTBWnqOCc/MdVOLVjXUXtIA+NpDrDBKJtLLg2shUjBu3cZmB/85RyitKc55+lUUyl7oRfLOvkr2hsw== + "@trysound/sax@0.2.0": version "0.2.0" resolved "https://registry.yarnpkg.com/@trysound/sax/-/sax-0.2.0.tgz#cccaab758af56761eb7bf37af6f03f326dd798ad" @@ -763,20 +828,22 @@ resolved "https://registry.yarnpkg.com/@tsconfig/node16/-/node16-1.0.3.tgz#472eaab5f15c1ffdd7f8628bd4c4f753995ec79e" integrity sha512-yOlFc+7UtL/89t2ZhjPvvB/DeAr3r+Dq58IgzsFkOAvVC6NMJXmCGjbptdXdR9qsX7pKcTL+s87FtYREi2dEEQ== -"@types/node@^18.15.11": - version "18.15.11" - resolved "https://registry.yarnpkg.com/@types/node/-/node-18.15.11.tgz#b3b790f09cb1696cffcec605de025b088fa4225f" - integrity sha512-E5Kwq2n4SbMzQOn6wnmBjuK9ouqlURrcZDVfbo9ftDDTFt3nk7ZKK4GMOzoYgnpQJKcxwQw+lGaBvvlMo0qN/Q== +"@types/node@^20.8.0": + version "20.8.7" + resolved "https://registry.yarnpkg.com/@types/node/-/node-20.8.7.tgz#ad23827850843de973096edfc5abc9e922492a25" + integrity sha512-21TKHHh3eUHIi2MloeptJWALuCu5H7HQTdTrWIFReA8ad+aggoX+lRes3ex7/FtpC+sVUpFMQ+QTfYr74mruiQ== + dependencies: + undici-types "~5.25.1" "@types/parse-json@^4.0.0": version "4.0.0" resolved "https://registry.yarnpkg.com/@types/parse-json/-/parse-json-4.0.0.tgz#2f8bb441434d163b35fb8ffdccd7138927ffb8c0" integrity sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA== -"@typescript/vfs@^1.4.0": - version "1.4.0" - resolved "https://registry.yarnpkg.com/@typescript/vfs/-/vfs-1.4.0.tgz#2d22985c7666c9d4ce26eb025405e6f156aa32b0" - integrity sha512-Pood7yv5YWMIX+yCHo176OnF8WUlKGImFG7XlsuH14Zb1YN5+dYD3uUtS7lqZtsH7tAveNUi2NzdpQCN0yRbaw== +"@typescript/vfs@^1.5.0": + version "1.5.0" + resolved "https://registry.yarnpkg.com/@typescript/vfs/-/vfs-1.5.0.tgz#ed942922724f9ace8c07c80b006c47e5e3833218" + integrity sha512-AJS307bPgbsZZ9ggCT3wwpg3VbTKMFNHfaY/uF0ahSkYYrPF2dSSKDNIDIQAHm9qJqbLvCsSJH7yN4Vs/CsMMg== dependencies: debug "^4.1.1" @@ -790,7 +857,7 @@ acorn-walk@^8.1.1: resolved "https://registry.yarnpkg.com/acorn-walk/-/acorn-walk-8.2.0.tgz#741210f2e2426454508853a2f44d0ab83b7f69c1" integrity sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA== -acorn@^8.4.1, acorn@^8.5.0: +acorn@^8.4.1: version "8.8.2" resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.8.2.tgz#1b2f25db02af965399b9776b0c2c391276d37c4a" integrity sha512-xjIYgE8HBrkpd/sJqOGNspf8uHG+NOHGOw6a/Urj8taM2EXfdNAH2oFcPeIFfsv3+kz/mJrS5VuMqbNLjCa2vw== @@ -843,11 +910,6 @@ browserslist@^4.6.6: node-releases "^2.0.8" update-browserslist-db "^1.0.10" -buffer-from@^1.0.0: - version "1.1.2" - resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.2.tgz#2b146a6fd72e80b4f55d255f35ed59a3a9a41bd5" - integrity sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ== - callsites@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/callsites/-/callsites-3.1.0.tgz#b3630abd8943432f54b3f0519238e33cd7df2f73" @@ -875,7 +937,7 @@ chalk@^4.1.0: ansi-styles "^4.1.0" supports-color "^7.1.0" -chrome-trace-event@^1.0.2: +chrome-trace-event@^1.0.2, chrome-trace-event@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/chrome-trace-event/-/chrome-trace-event-1.0.3.tgz#1015eced4741e15d06664a957dbbf50d041e26ac" integrity sha512-p3KULyQg4S7NIHixdwbGX+nFHkoBiA4YQmyWtjb8XngSKV124nJmRysgAeujbUVb15vh+RvFUfCPqU7rXk+hZg== @@ -909,11 +971,6 @@ color-name@~1.1.4: resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2" integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== -commander@^2.20.0: - version "2.20.3" - resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" - integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== - commander@^7.0.0, commander@^7.2.0: version "7.2.0" resolved "https://registry.yarnpkg.com/commander/-/commander-7.2.0.tgz#a36cb57d0b501ce108e4d20559a150a391d97ab7" @@ -978,6 +1035,11 @@ detect-libc@^1.0.3: resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-1.0.3.tgz#fa137c4bd698edf55cd5cd02ac559f91a4c4ba9b" integrity sha512-pGjwhsmsp4kL2RTz08wcOlGN83otlqHeD/Z5T8GXZB+/YcpQ/dgo+lbU8ZsGxV0HIvqqxo9l7mqYwyYMD9bKDg== +detect-libc@^2.0.1: + version "2.0.2" + resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-2.0.2.tgz#8ccf2ba9315350e1241b88d0ac3b0e1fbd99605d" + integrity sha512-UX6sGumvvqSaXgdKGUsgZWqcUyIXZ/vZTrlRT/iobiKhGL0zL4d3osHj3uqllWJK+i+sixDS/3COVEOFbupFyw== + diff@^4.0.1: version "4.0.2" resolved "https://registry.yarnpkg.com/diff/-/diff-4.0.2.tgz#60f3aecb89d5fae520c11aa19efc2bb982aade7d" @@ -1214,23 +1276,30 @@ lines-and-columns@^1.1.6: resolved "https://registry.yarnpkg.com/lines-and-columns/-/lines-and-columns-1.2.4.tgz#eca284f75d2965079309dc0ad9255abb2ebc1632" integrity sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg== -lmdb@2.5.2: - version "2.5.2" - resolved "https://registry.yarnpkg.com/lmdb/-/lmdb-2.5.2.tgz#37e28a9fb43405f4dc48c44cec0e13a14c4a6ff1" - integrity sha512-V5V5Xa2Hp9i2XsbDALkBTeHXnBXh/lEmk9p22zdr7jtuOIY9TGhjK6vAvTpOOx9IKU4hJkRWZxn/HsvR1ELLtA== +lmdb@2.8.5: + version "2.8.5" + resolved "https://registry.yarnpkg.com/lmdb/-/lmdb-2.8.5.tgz#ce191110c755c0951caa062722e300c703973837" + integrity sha512-9bMdFfc80S+vSldBmG3HOuLVHnxRdNTlpzR6QDnzqCQtCzGUEAGTzBKYMeIM+I/sU4oZfgbcbS7X7F65/z/oxQ== dependencies: - msgpackr "^1.5.4" - node-addon-api "^4.3.0" - node-gyp-build-optional-packages "5.0.3" - ordered-binary "^1.2.4" + msgpackr "^1.9.5" + node-addon-api "^6.1.0" + node-gyp-build-optional-packages "5.1.1" + ordered-binary "^1.4.1" weak-lru-cache "^1.2.2" optionalDependencies: - "@lmdb/lmdb-darwin-arm64" "2.5.2" - "@lmdb/lmdb-darwin-x64" "2.5.2" - "@lmdb/lmdb-linux-arm" "2.5.2" - "@lmdb/lmdb-linux-arm64" "2.5.2" - "@lmdb/lmdb-linux-x64" "2.5.2" - "@lmdb/lmdb-win32-x64" "2.5.2" + "@lmdb/lmdb-darwin-arm64" "2.8.5" + "@lmdb/lmdb-darwin-x64" "2.8.5" + "@lmdb/lmdb-linux-arm" "2.8.5" + "@lmdb/lmdb-linux-arm64" "2.8.5" + "@lmdb/lmdb-linux-x64" "2.8.5" + "@lmdb/lmdb-win32-x64" "2.8.5" + +lru-cache@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-6.0.0.tgz#6d6fe6570ebd96aaf90fcad1dafa3b2566db3a94" + integrity sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA== + dependencies: + yallist "^4.0.0" make-error@^1.1.1: version "1.3.6" @@ -1255,7 +1324,7 @@ ms@2.1.2: resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== -msgpackr-extract@^3.0.1: +msgpackr-extract@^3.0.1, msgpackr-extract@^3.0.2: version "3.0.2" resolved "https://registry.yarnpkg.com/msgpackr-extract/-/msgpackr-extract-3.0.2.tgz#e05ec1bb4453ddf020551bcd5daaf0092a2c279d" integrity sha512-SdzXp4kD/Qf8agZ9+iTu6eql0m3kWm1A2y1hkpTeVNENutaB0BwHlSvAIaMxwntmRUAUjon2V4L8Z/njd0Ct8A== @@ -1276,26 +1345,35 @@ msgpackr@^1.5.4: optionalDependencies: msgpackr-extract "^3.0.1" +msgpackr@^1.9.5: + version "1.9.9" + resolved "https://registry.yarnpkg.com/msgpackr/-/msgpackr-1.9.9.tgz#ec71e37beb8729280847f683cb0a340eb35ce70f" + integrity sha512-sbn6mioS2w0lq1O6PpGtsv6Gy8roWM+o3o4Sqjd6DudrL/nOugY+KyJUimoWzHnf9OkO0T6broHFnYE/R05t9A== + optionalDependencies: + msgpackr-extract "^3.0.2" + node-addon-api@^3.2.1: version "3.2.1" resolved "https://registry.yarnpkg.com/node-addon-api/-/node-addon-api-3.2.1.tgz#81325e0a2117789c0128dab65e7e38f07ceba161" integrity sha512-mmcei9JghVNDYydghQmeDX8KoAm0FAiYyIcUt/N4nhyAipB17pllZQDOJD2fotxABnt4Mdz+dKTO7eftLg4d0A== -node-addon-api@^4.3.0: - version "4.3.0" - resolved "https://registry.yarnpkg.com/node-addon-api/-/node-addon-api-4.3.0.tgz#52a1a0b475193e0928e98e0426a0d1254782b77f" - integrity sha512-73sE9+3UaLYYFmDsFZnqCInzPyh3MqIwZO9cw58yIqAZhONrrabrYyYe3TuIqtIiOuTXVhsGau8hcrhhwSsDIQ== - -node-gyp-build-optional-packages@5.0.3: - version "5.0.3" - resolved "https://registry.yarnpkg.com/node-gyp-build-optional-packages/-/node-gyp-build-optional-packages-5.0.3.tgz#92a89d400352c44ad3975010368072b41ad66c17" - integrity sha512-k75jcVzk5wnnc/FMxsf4udAoTEUv2jY3ycfdSd3yWu6Cnd1oee6/CfZJApyscA4FJOmdoixWwiwOyf16RzD5JA== +node-addon-api@^6.1.0: + version "6.1.0" + resolved "https://registry.yarnpkg.com/node-addon-api/-/node-addon-api-6.1.0.tgz#ac8470034e58e67d0c6f1204a18ae6995d9c0d76" + integrity sha512-+eawOlIgy680F0kBzPUNFhMZGtJ1YmqM6l4+Crf4IkImjYrO/mqPwRMh352g23uIaQKFItcQ64I7KMaJxHgAVA== node-gyp-build-optional-packages@5.0.7: version "5.0.7" resolved "https://registry.yarnpkg.com/node-gyp-build-optional-packages/-/node-gyp-build-optional-packages-5.0.7.tgz#5d2632bbde0ab2f6e22f1bbac2199b07244ae0b3" integrity sha512-YlCCc6Wffkx0kHkmam79GKvDQ6x+QZkMjFGrIMxgFNILFvGSbCp2fCBC55pGTT9gVaz8Na5CLmxt/urtzRv36w== +node-gyp-build-optional-packages@5.1.1: + version "5.1.1" + resolved "https://registry.yarnpkg.com/node-gyp-build-optional-packages/-/node-gyp-build-optional-packages-5.1.1.tgz#52b143b9dd77b7669073cbfe39e3f4118bfc603c" + integrity sha512-+P72GAjVAbTxjjwUmwjVrqrdZROD4nf8KgpBoDxqXXTiYZZt/ud60dE5yvCSr9lRO8e8yv6kgJIC0K0PfZFVQw== + dependencies: + detect-libc "^2.0.1" + node-gyp-build@^4.3.0: version "4.6.0" resolved "https://registry.yarnpkg.com/node-gyp-build/-/node-gyp-build-4.6.0.tgz#0c52e4cbf54bbd28b709820ef7b6a3c2d6209055" @@ -1318,30 +1396,30 @@ nullthrows@^1.1.1: resolved "https://registry.yarnpkg.com/nullthrows/-/nullthrows-1.1.1.tgz#7818258843856ae971eae4208ad7d7eb19a431b1" integrity sha512-2vPPEi+Z7WqML2jZYddDIfy5Dqb0r2fze2zTxNNknZaFpVHU3mFB3R+DWeJWGVx0ecvttSGlJTI+WG+8Z4cDWw== -ordered-binary@^1.2.4: - version "1.4.0" - resolved "https://registry.yarnpkg.com/ordered-binary/-/ordered-binary-1.4.0.tgz#6bb53d44925f3b8afc33d1eed0fa15693b211389" - integrity sha512-EHQ/jk4/a9hLupIKxTfUsQRej1Yd/0QLQs3vGvIqg5ZtCYSzNhkzHoZc7Zf4e4kUlDaC3Uw8Q/1opOLNN2OKRQ== - -parcel@^2.8.3: - version "2.8.3" - resolved "https://registry.yarnpkg.com/parcel/-/parcel-2.8.3.tgz#1ff71d7317274fd367379bc7310a52c6b75d30c2" - integrity sha512-5rMBpbNE72g6jZvkdR5gS2nyhwIXaJy8i65osOqs/+5b7zgf3eMKgjSsDrv6bhz3gzifsba6MBJiZdBckl+vnA== - dependencies: - "@parcel/config-default" "2.8.3" - "@parcel/core" "2.8.3" - "@parcel/diagnostic" "2.8.3" - "@parcel/events" "2.8.3" - "@parcel/fs" "2.8.3" - "@parcel/logger" "2.8.3" - "@parcel/package-manager" "2.8.3" - "@parcel/reporter-cli" "2.8.3" - "@parcel/reporter-dev-server" "2.8.3" - "@parcel/utils" "2.8.3" +ordered-binary@^1.4.1: + version "1.4.1" + resolved "https://registry.yarnpkg.com/ordered-binary/-/ordered-binary-1.4.1.tgz#205cb6efd6c27fa0ef4eced994a023e081cdc911" + integrity sha512-9LtiGlPy982CsgxZvJGNNp2/NnrgEr6EAyN3iIEP3/8vd3YLgAZQHbQ75ZrkfBRGrNg37Dk3U6tuVb+B4Xfslg== + +parcel@^2.10.0: + version "2.10.0" + resolved "https://registry.yarnpkg.com/parcel/-/parcel-2.10.0.tgz#6b1245baf771ab025769069a28901a54fdc10823" + integrity sha512-YJmWEsiv1ClpPcJiWkr3gFj40sRvfeK89GGGwJjpzQMQsBmN6h6OHrSkByx0jrsPIvdsOIccU702upYpRAypuw== + dependencies: + "@parcel/config-default" "2.10.0" + "@parcel/core" "2.10.0" + "@parcel/diagnostic" "2.10.0" + "@parcel/events" "2.10.0" + "@parcel/fs" "2.10.0" + "@parcel/logger" "2.10.0" + "@parcel/package-manager" "2.10.0" + "@parcel/reporter-cli" "2.10.0" + "@parcel/reporter-dev-server" "2.10.0" + "@parcel/reporter-tracer" "2.10.0" + "@parcel/utils" "2.10.0" chalk "^4.1.0" commander "^7.0.0" get-port "^4.2.0" - v8-compile-cache "^2.0.0" parent-module@^1.0.0: version "1.0.1" @@ -1409,10 +1487,10 @@ posthtml@^0.16.4, posthtml@^0.16.5: posthtml-parser "^0.11.0" posthtml-render "^3.0.0" -prettier@^2.8.8: - version "2.8.8" - resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.8.8.tgz#e8c5d7e98a4305ffe3de2e1fc4aca1a71c28b1da" - integrity sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q== +prettier@^3.0.3: + version "3.0.3" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.0.3.tgz#432a51f7ba422d1469096c0fdc28e235db8f9643" + integrity sha512-L/4pUDMxcNa8R/EthV08Zt42WBO4h1rarVtK0K+QJG0X187OLo7l699jWw0GKuwzkPQ//jMFA/8Xm6Fh3J/DAg== process@^0.11.10: version "0.11.10" @@ -1444,20 +1522,14 @@ safe-buffer@^5.0.1: resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== -semver@^5.7.0, semver@^5.7.1: - version "5.7.1" - resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7" - integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ== - -source-map-support@~0.5.20: - version "0.5.21" - resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.21.tgz#04fe7c7f9e1ed2d662233c28cb2b35b9f63f6e4f" - integrity sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w== +semver@^7.5.2: + version "7.5.4" + resolved "https://registry.yarnpkg.com/semver/-/semver-7.5.4.tgz#483986ec4ed38e1c6c48c34894a9182dbff68a6e" + integrity sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA== dependencies: - buffer-from "^1.0.0" - source-map "^0.6.0" + lru-cache "^6.0.0" -source-map@^0.6.0, source-map@^0.6.1: +source-map@^0.6.1: version "0.6.1" resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== @@ -1504,16 +1576,6 @@ term-size@^2.2.1: resolved "https://registry.yarnpkg.com/term-size/-/term-size-2.2.1.tgz#2a6a54840432c2fb6320fea0f415531e90189f54" integrity sha512-wK0Ri4fOGjv/XPy8SBHZChl8CM7uMc5VML7SqiQ0zG7+J5Vr+RMQDoHa2CNT6KHUnTGIXH34UDMkPzAUyapBZg== -terser@^5.2.0: - version "5.16.8" - resolved "https://registry.yarnpkg.com/terser/-/terser-5.16.8.tgz#ccde583dabe71df3f4ed02b65eb6532e0fae15d5" - integrity sha512-QI5g1E/ef7d+PsDifb+a6nnVgC4F22Bg6T0xrBrz6iloVB4PUkkunp6V8nzoOOZJIzjWVdAGqCdlKlhLq/TbIA== - dependencies: - "@jridgewell/source-map" "^0.3.2" - acorn "^8.5.0" - commander "^2.20.0" - source-map-support "~0.5.20" - timsort@^0.3.0: version "0.3.0" resolved "https://registry.yarnpkg.com/timsort/-/timsort-0.3.0.tgz#405411a8e7e6339fe64db9a234de11dc31e02bd4" @@ -1555,10 +1617,15 @@ type-fest@^0.20.2: resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.20.2.tgz#1bf207f4b28f91583666cb5fbd327887301cd5f4" integrity sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ== -typescript@^5.0.4: - version "5.0.4" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-5.0.4.tgz#b217fd20119bd61a94d4011274e0ab369058da3b" - integrity sha512-cW9T5W9xY37cc+jfEnaUvX91foxtHkza3Nw3wkoF4sSlKn0MONdkdEndig/qPBWXNkmplh3NzayQzCiHM4/hqw== +typescript@^5.2.2: + version "5.2.2" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-5.2.2.tgz#5ebb5e5a5b75f085f22bc3f8460fba308310fa78" + integrity sha512-mI4WrpHsbCIcwT9cF4FZvr80QUeKvsUsUvKDoR+X/7XHQH98xYD8YHZg7ANtz2GtZt/CBq2QJ0thkGJMHfqc1w== + +undici-types@~5.25.1: + version "5.25.3" + resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-5.25.3.tgz#e044115914c85f0bcbb229f346ab739f064998c3" + integrity sha512-Ga1jfYwRn7+cP9v8auvEXN1rX3sWqlayd4HP7OKk4mZWylEmu3KzXDUGrQUN6Ol7qo1gPvB2e5gX6udnyEPgdA== update-browserslist-db@^1.0.10: version "1.0.10" @@ -1578,20 +1645,15 @@ v8-compile-cache-lib@^3.0.1: resolved "https://registry.yarnpkg.com/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz#6336e8d71965cb3d35a1bbb7868445a7c05264bf" integrity sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg== -v8-compile-cache@^2.0.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz#2de19618c66dc247dcfb6f99338035d8245a2cee" - integrity sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA== - weak-lru-cache@^1.2.2: version "1.2.2" resolved "https://registry.yarnpkg.com/weak-lru-cache/-/weak-lru-cache-1.2.2.tgz#fdbb6741f36bae9540d12f480ce8254060dccd19" integrity sha512-DEAoo25RfSYMuTGc9vPJzZcZullwIqRDSI9LOy+fkCJPi6hykCnfKaXTuPBDuXAUcqHXyOgFtHNp/kB2FjYHbw== -xxhash-wasm@^0.4.2: - version "0.4.2" - resolved "https://registry.yarnpkg.com/xxhash-wasm/-/xxhash-wasm-0.4.2.tgz#752398c131a4dd407b5132ba62ad372029be6f79" - integrity sha512-/eyHVRJQCirEkSZ1agRSCwriMhwlyUcFkXD5TPVSLP+IPzjsqMVzZwdoczLp1SoQU0R3dxz1RpIK+4YNQbCVOA== +yallist@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72" + integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A== yaml@^1.10.0: version "1.10.2" diff --git a/settings.gradle.kts b/settings.gradle.kts index aba627fc..9423e44d 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,7 +1,7 @@ rootProject.name = "rewrite-javascript" include("js") -enableFeaturePreview("VERSION_ORDERING_V2") +//enableFeaturePreview("VERSION_ORDERING_V2") //plugins { // id("com.gradle.enterprise") version "latest.release" diff --git a/src/main/java/com/caoccao/javet/interop/JavetBridge.java b/src/main/java/com/caoccao/javet/interop/JavetBridge.java index b62ff9d1..633edaae 100644 --- a/src/main/java/com/caoccao/javet/interop/JavetBridge.java +++ b/src/main/java/com/caoccao/javet/interop/JavetBridge.java @@ -30,9 +30,7 @@ public final class JavetBridge { private JavetBridge() {} public static Map getReferenceMapSnapshot(V8Runtime runtime) { - synchronized (runtime.referenceLock) { - return new HashMap<>(runtime.referenceMap); - } + return new HashMap<>(runtime.referenceMap); } public static V8Runtime makeWrappedV8Runtime() { diff --git a/src/main/java/org/openrewrite/javascript/TypeScriptTypeGoat.ts b/src/main/java/org/openrewrite/javascript/TypeScriptTypeGoat.ts deleted file mode 100644 index dfb26493..00000000 --- a/src/main/java/org/openrewrite/javascript/TypeScriptTypeGoat.ts +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -abstract class TypeScriptTypeGoat & A> { - - protected constructor() { - } - - public static parameterizedField: PT; - - public static unionField: typeof TypeScriptTypeGoat.TypeA | typeof TypeScriptTypeGoat.TypeB - - public static TypeA = class { - } - - public static TypeB = class { - } - - ExtendsTypeScriptTypeGoat = class extends TypeScriptTypeGoat { - enumTypeA(n: EnumTypeA): void { - } - genericIntersection(n: U): U { - return undefined; - } - genericRecursive(n: TypeScriptTypeGoat): TypeScriptTypeGoat { - return undefined; - } - inheritedTypeScriptTypeGoat(n: InheritedTypeScriptTypeGoat): InheritedTypeScriptTypeGoat { - return undefined; - } - } - - clazz(n: A): void { - } - - primitive(n: number): void { - } - - array(n: A[]): void { - } - - multidimensionalArray(n: A[][]): void { - } - - parameterized(n: PT): PT { - return n - } - - parameterizedRecursive(n: PT>): PT> { - return n - } - - generic(n: PT): PT { - return n - } - - public abstract genericRecursive>(n: TypeScriptTypeGoat): TypeScriptTypeGoat; - - genericUnbounded(n: PT): PT { - return n - } - - public abstract enumTypeA(n: EnumTypeA): void; - public abstract inheritedTypeScriptTypeGoat & C>(n: InheritedTypeScriptTypeGoat): InheritedTypeScriptTypeGoat; - public abstract genericIntersection & C>(n: U): U; - - genericT(n: T): T { - return n - } - - recursiveIntersection & Intersection>(n: U): void { - } - - merged(n: B) { - n.foo() - n.bar() - n.buz() - } - - mergedGeneric(n: PT): PT { - return n - } -} - -interface A { -} - -interface B { - foo(): void -} - -interface B { - bar(): void -} - -class B { - buz(): void { - } -} - -interface C { - -} - -interface PT { -} - -interface Intersection & Intersection> { - getIntersectionType(): T -} - -abstract class Extension> { -} - -function decorator(value: boolean) { - return function (target: any, - propertyKey: string, - descriptor: PropertyDescriptor) { - descriptor.enumerable = value; - }; -} - -enum EnumTypeA { - FOO, BAR -} - -abstract class InheritedTypeScriptTypeGoat & C> extends TypeScriptTypeGoat { - protected constructor() { - super(); - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/JavetNativeBridge.java b/src/main/java/org/openrewrite/javascript/internal/JavetNativeBridge.java index 3304e28f..f61446bc 100644 --- a/src/main/java/org/openrewrite/javascript/internal/JavetNativeBridge.java +++ b/src/main/java/org/openrewrite/javascript/internal/JavetNativeBridge.java @@ -144,7 +144,7 @@ private static void actuallyInit() { try { System.err.printf(" tmp path: %s%n", tempFile.getAbsolutePath()); System.err.printf(" tmp exists: %s%n", tempFile.exists()); - System.err.printf(" tmp size: %s%n", tempFile.length()); + System.err.printf(" tmp size: %s%n", tempFile.length()); } catch (Throwable ignored) { } } diff --git a/src/main/java/org/openrewrite/javascript/internal/TypeScriptParserVisitor.java b/src/main/java/org/openrewrite/javascript/internal/TypeScriptParserVisitor.java index d09d5c27..41d6c145 100644 --- a/src/main/java/org/openrewrite/javascript/internal/TypeScriptParserVisitor.java +++ b/src/main/java/org/openrewrite/javascript/internal/TypeScriptParserVisitor.java @@ -3347,32 +3347,32 @@ private List mapModifiers(@Nullable List nodes, List comments = Collections.emptyList(); TSCSyntaxKind kind; boolean done = false; @@ -3462,7 +3462,7 @@ private Space whitespace() { case WhitespaceTrivia: case NewLineTrivia: { if (comments.isEmpty()) { - initialSpace += lastToken(); + initialSpace.append(lastToken()); } else { comments = ListUtils.mapLast( comments, @@ -3495,7 +3495,7 @@ private Space whitespace() { break; } } while (!done); - return Space.build(initialSpace, comments); + return Space.build(initialSpace.toString(), comments); } private J unknown(TSCNode node) { diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCNodeFlag.java b/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCNodeFlag.java index 601ac6a4..28006845 100644 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCNodeFlag.java +++ b/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCNodeFlag.java @@ -25,41 +25,44 @@ public enum TSCNodeFlag { None(0), Let(1), Const(2), - NestedNamespace(4), - Synthesized(8), - Namespace(16), - OptionalChain(32), - ExportContext(64), + Using(4), + /** Also includes Constant */ + AwaitUsing(6), + NestedNamespace(8), + Synthesized(16), + Namespace(32), + OptionalChain(64), + ExportContext(128), /** Also includes IdentifierHasExtendedUnicodeEscape */ - ContainsThis(128), - HasImplicitReturn(256), - HasExplicitReturn(512), - GlobalAugmentation(1024), + ContainsThis(256), + HasImplicitReturn(512), + HasExplicitReturn(1024), + GlobalAugmentation(2048), /** Also includes IdentifierIsInJSDocNamespace */ - HasAsyncFunctions(2048), - DisallowInContext(4096), - YieldContext(8192), - DecoratorContext(16384), - AwaitContext(32768), - DisallowConditionalTypesContext(65536), - ThisNodeHasError(131072), - JavaScriptFile(262144), - ThisNodeOrAnySubNodesHasError(524288), - HasAggregatedChildData(1048576), - PossiblyContainsDynamicImport(2097152), - PossiblyContainsImportMeta(4194304), - JSDoc(8388608), - Ambient(16777216), - InWithStatement(33554432), - JsonFile(67108864), - TypeCached(134217728), - Deprecated(268435456), - BlockScoped(3), - ReachabilityCheckFlags(768), - ReachabilityAndEmitFlags(2816), - ContextFlags(50720768), - TypeExcludesFlags(40960), - PermanentlySetIncrementalFlags(6291456); + HasAsyncFunctions(4096), + DisallowInContext(8192), + YieldContext(16384), + DecoratorContext(32768), + AwaitContext(65536), + DisallowConditionalTypesContext(131072), + ThisNodeHasError(262144), + JavaScriptFile(524288), + ThisNodeOrAnySubNodesHasError(1048576), + HasAggregatedChildData(2097152), + PossiblyContainsDynamicImport(4194304), + PossiblyContainsImportMeta(8388608), + JSDoc(16777216), + Ambient(33554432), + InWithStatement(67108864), + JsonFile(134217728), + TypeCached(268435456), + Deprecated(536870912), + BlockScoped(7), + ReachabilityCheckFlags(1536), + ReachabilityAndEmitFlags(5632), + ContextFlags(101441536), + TypeExcludesFlags(81920), + PermanentlySetIncrementalFlags(12582912); public final int code; @@ -77,70 +80,74 @@ public static TSCNodeFlag fromMaskExact(int code) { case 2: return TSCNodeFlag.Const; case 4: - return TSCNodeFlag.NestedNamespace; + return TSCNodeFlag.Using; + case 6: + return TSCNodeFlag.AwaitUsing; case 8: - return TSCNodeFlag.Synthesized; + return TSCNodeFlag.NestedNamespace; case 16: - return TSCNodeFlag.Namespace; + return TSCNodeFlag.Synthesized; case 32: - return TSCNodeFlag.OptionalChain; + return TSCNodeFlag.Namespace; case 64: - return TSCNodeFlag.ExportContext; + return TSCNodeFlag.OptionalChain; case 128: - return TSCNodeFlag.ContainsThis; + return TSCNodeFlag.ExportContext; case 256: - return TSCNodeFlag.HasImplicitReturn; + return TSCNodeFlag.ContainsThis; case 512: - return TSCNodeFlag.HasExplicitReturn; + return TSCNodeFlag.HasImplicitReturn; case 1024: - return TSCNodeFlag.GlobalAugmentation; + return TSCNodeFlag.HasExplicitReturn; case 2048: - return TSCNodeFlag.HasAsyncFunctions; + return TSCNodeFlag.GlobalAugmentation; case 4096: - return TSCNodeFlag.DisallowInContext; + return TSCNodeFlag.HasAsyncFunctions; case 8192: - return TSCNodeFlag.YieldContext; + return TSCNodeFlag.DisallowInContext; case 16384: - return TSCNodeFlag.DecoratorContext; + return TSCNodeFlag.YieldContext; case 32768: - return TSCNodeFlag.AwaitContext; + return TSCNodeFlag.DecoratorContext; case 65536: - return TSCNodeFlag.DisallowConditionalTypesContext; + return TSCNodeFlag.AwaitContext; case 131072: - return TSCNodeFlag.ThisNodeHasError; + return TSCNodeFlag.DisallowConditionalTypesContext; case 262144: - return TSCNodeFlag.JavaScriptFile; + return TSCNodeFlag.ThisNodeHasError; case 524288: - return TSCNodeFlag.ThisNodeOrAnySubNodesHasError; + return TSCNodeFlag.JavaScriptFile; case 1048576: - return TSCNodeFlag.HasAggregatedChildData; + return TSCNodeFlag.ThisNodeOrAnySubNodesHasError; case 2097152: - return TSCNodeFlag.PossiblyContainsDynamicImport; + return TSCNodeFlag.HasAggregatedChildData; case 4194304: - return TSCNodeFlag.PossiblyContainsImportMeta; + return TSCNodeFlag.PossiblyContainsDynamicImport; case 8388608: - return TSCNodeFlag.JSDoc; + return TSCNodeFlag.PossiblyContainsImportMeta; case 16777216: - return TSCNodeFlag.Ambient; + return TSCNodeFlag.JSDoc; case 33554432: - return TSCNodeFlag.InWithStatement; + return TSCNodeFlag.Ambient; case 67108864: - return TSCNodeFlag.JsonFile; + return TSCNodeFlag.InWithStatement; case 134217728: - return TSCNodeFlag.TypeCached; + return TSCNodeFlag.JsonFile; case 268435456: + return TSCNodeFlag.TypeCached; + case 536870912: return TSCNodeFlag.Deprecated; - case 3: + case 7: return TSCNodeFlag.BlockScoped; - case 768: + case 1536: return TSCNodeFlag.ReachabilityCheckFlags; - case 2816: + case 5632: return TSCNodeFlag.ReachabilityAndEmitFlags; - case 50720768: + case 101441536: return TSCNodeFlag.ContextFlags; - case 40960: + case 81920: return TSCNodeFlag.TypeExcludesFlags; - case 6291456: + case 12582912: return TSCNodeFlag.PermanentlySetIncrementalFlags; default: throw new IllegalArgumentException("unknown TSCNodeFlag code: " + code); diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCSyntaxKind.java b/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCSyntaxKind.java index 6e3160a4..34b24817 100644 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCSyntaxKind.java +++ b/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCSyntaxKind.java @@ -33,383 +33,385 @@ public enum TSCSyntaxKind { ShebangTrivia(6), /** Also includes LastTriviaToken */ ConflictMarkerTrivia(7), + NonTextFileMarkerTrivia(8), /** Also includes FirstLiteralToken */ - NumericLiteral(8), - BigIntLiteral(9), - StringLiteral(10), - JsxText(11), - JsxTextAllWhiteSpaces(12), - RegularExpressionLiteral(13), + NumericLiteral(9), + BigIntLiteral(10), + StringLiteral(11), + JsxText(12), + JsxTextAllWhiteSpaces(13), + RegularExpressionLiteral(14), /** Also includes LastLiteralToken, FirstTemplateToken */ - NoSubstitutionTemplateLiteral(14), - TemplateHead(15), - TemplateMiddle(16), + NoSubstitutionTemplateLiteral(15), + TemplateHead(16), + TemplateMiddle(17), /** Also includes LastTemplateToken */ - TemplateTail(17), + TemplateTail(18), /** Also includes FirstPunctuation */ - OpenBraceToken(18), - CloseBraceToken(19), - OpenParenToken(20), - CloseParenToken(21), - OpenBracketToken(22), - CloseBracketToken(23), - DotToken(24), - DotDotDotToken(25), - SemicolonToken(26), - CommaToken(27), - QuestionDotToken(28), + OpenBraceToken(19), + CloseBraceToken(20), + OpenParenToken(21), + CloseParenToken(22), + OpenBracketToken(23), + CloseBracketToken(24), + DotToken(25), + DotDotDotToken(26), + SemicolonToken(27), + CommaToken(28), + QuestionDotToken(29), /** Also includes FirstBinaryOperator */ - LessThanToken(29), - LessThanSlashToken(30), - GreaterThanToken(31), - LessThanEqualsToken(32), - GreaterThanEqualsToken(33), - EqualsEqualsToken(34), - ExclamationEqualsToken(35), - EqualsEqualsEqualsToken(36), - ExclamationEqualsEqualsToken(37), - EqualsGreaterThanToken(38), - PlusToken(39), - MinusToken(40), - AsteriskToken(41), - AsteriskAsteriskToken(42), - SlashToken(43), - PercentToken(44), - PlusPlusToken(45), - MinusMinusToken(46), - LessThanLessThanToken(47), - GreaterThanGreaterThanToken(48), - GreaterThanGreaterThanGreaterThanToken(49), - AmpersandToken(50), - BarToken(51), - CaretToken(52), - ExclamationToken(53), - TildeToken(54), - AmpersandAmpersandToken(55), - BarBarToken(56), - QuestionToken(57), - ColonToken(58), - AtToken(59), - QuestionQuestionToken(60), - BacktickToken(61), - HashToken(62), + LessThanToken(30), + LessThanSlashToken(31), + GreaterThanToken(32), + LessThanEqualsToken(33), + GreaterThanEqualsToken(34), + EqualsEqualsToken(35), + ExclamationEqualsToken(36), + EqualsEqualsEqualsToken(37), + ExclamationEqualsEqualsToken(38), + EqualsGreaterThanToken(39), + PlusToken(40), + MinusToken(41), + AsteriskToken(42), + AsteriskAsteriskToken(43), + SlashToken(44), + PercentToken(45), + PlusPlusToken(46), + MinusMinusToken(47), + LessThanLessThanToken(48), + GreaterThanGreaterThanToken(49), + GreaterThanGreaterThanGreaterThanToken(50), + AmpersandToken(51), + BarToken(52), + CaretToken(53), + ExclamationToken(54), + TildeToken(55), + AmpersandAmpersandToken(56), + BarBarToken(57), + QuestionToken(58), + ColonToken(59), + AtToken(60), + QuestionQuestionToken(61), + BacktickToken(62), + HashToken(63), /** Also includes FirstAssignment */ - EqualsToken(63), + EqualsToken(64), /** Also includes FirstCompoundAssignment */ - PlusEqualsToken(64), - MinusEqualsToken(65), - AsteriskEqualsToken(66), - AsteriskAsteriskEqualsToken(67), - SlashEqualsToken(68), - PercentEqualsToken(69), - LessThanLessThanEqualsToken(70), - GreaterThanGreaterThanEqualsToken(71), - GreaterThanGreaterThanGreaterThanEqualsToken(72), - AmpersandEqualsToken(73), - BarEqualsToken(74), - BarBarEqualsToken(75), - AmpersandAmpersandEqualsToken(76), - QuestionQuestionEqualsToken(77), + PlusEqualsToken(65), + MinusEqualsToken(66), + AsteriskEqualsToken(67), + AsteriskAsteriskEqualsToken(68), + SlashEqualsToken(69), + PercentEqualsToken(70), + LessThanLessThanEqualsToken(71), + GreaterThanGreaterThanEqualsToken(72), + GreaterThanGreaterThanGreaterThanEqualsToken(73), + AmpersandEqualsToken(74), + BarEqualsToken(75), + BarBarEqualsToken(76), + AmpersandAmpersandEqualsToken(77), + QuestionQuestionEqualsToken(78), /** Also includes LastAssignment, LastCompoundAssignment, LastPunctuation, LastBinaryOperator */ - CaretEqualsToken(78), - Identifier(79), - PrivateIdentifier(80), + CaretEqualsToken(79), + Identifier(80), + PrivateIdentifier(81), + JSDocCommentTextToken(82), /** Also includes FirstReservedWord, FirstKeyword */ - BreakKeyword(81), - CaseKeyword(82), - CatchKeyword(83), - ClassKeyword(84), - ConstKeyword(85), - ContinueKeyword(86), - DebuggerKeyword(87), - DefaultKeyword(88), - DeleteKeyword(89), - DoKeyword(90), - ElseKeyword(91), - EnumKeyword(92), - ExportKeyword(93), - ExtendsKeyword(94), - FalseKeyword(95), - FinallyKeyword(96), - ForKeyword(97), - FunctionKeyword(98), - IfKeyword(99), - ImportKeyword(100), - InKeyword(101), - InstanceOfKeyword(102), - NewKeyword(103), - NullKeyword(104), - ReturnKeyword(105), - SuperKeyword(106), - SwitchKeyword(107), - ThisKeyword(108), - ThrowKeyword(109), - TrueKeyword(110), - TryKeyword(111), - TypeOfKeyword(112), - VarKeyword(113), - VoidKeyword(114), - WhileKeyword(115), + BreakKeyword(83), + CaseKeyword(84), + CatchKeyword(85), + ClassKeyword(86), + ConstKeyword(87), + ContinueKeyword(88), + DebuggerKeyword(89), + DefaultKeyword(90), + DeleteKeyword(91), + DoKeyword(92), + ElseKeyword(93), + EnumKeyword(94), + ExportKeyword(95), + ExtendsKeyword(96), + FalseKeyword(97), + FinallyKeyword(98), + ForKeyword(99), + FunctionKeyword(100), + IfKeyword(101), + ImportKeyword(102), + InKeyword(103), + InstanceOfKeyword(104), + NewKeyword(105), + NullKeyword(106), + ReturnKeyword(107), + SuperKeyword(108), + SwitchKeyword(109), + ThisKeyword(110), + ThrowKeyword(111), + TrueKeyword(112), + TryKeyword(113), + TypeOfKeyword(114), + VarKeyword(115), + VoidKeyword(116), + WhileKeyword(117), /** Also includes LastReservedWord */ - WithKeyword(116), + WithKeyword(118), /** Also includes FirstFutureReservedWord */ - ImplementsKeyword(117), - InterfaceKeyword(118), - LetKeyword(119), - PackageKeyword(120), - PrivateKeyword(121), - ProtectedKeyword(122), - PublicKeyword(123), - StaticKeyword(124), + ImplementsKeyword(119), + InterfaceKeyword(120), + LetKeyword(121), + PackageKeyword(122), + PrivateKeyword(123), + ProtectedKeyword(124), + PublicKeyword(125), + StaticKeyword(126), /** Also includes LastFutureReservedWord */ - YieldKeyword(125), + YieldKeyword(127), /** Also includes FirstContextualKeyword */ - AbstractKeyword(126), - AccessorKeyword(127), - AsKeyword(128), - AssertsKeyword(129), - AssertKeyword(130), - AnyKeyword(131), - AsyncKeyword(132), - AwaitKeyword(133), - BooleanKeyword(134), - ConstructorKeyword(135), - DeclareKeyword(136), - GetKeyword(137), - InferKeyword(138), - IntrinsicKeyword(139), - IsKeyword(140), - KeyOfKeyword(141), - ModuleKeyword(142), - NamespaceKeyword(143), - NeverKeyword(144), - OutKeyword(145), - ReadonlyKeyword(146), - RequireKeyword(147), - NumberKeyword(148), - ObjectKeyword(149), - SatisfiesKeyword(150), - SetKeyword(151), - StringKeyword(152), - SymbolKeyword(153), - TypeKeyword(154), - UndefinedKeyword(155), - UniqueKeyword(156), - UnknownKeyword(157), - FromKeyword(158), - GlobalKeyword(159), - BigIntKeyword(160), - OverrideKeyword(161), + AbstractKeyword(128), + AccessorKeyword(129), + AsKeyword(130), + AssertsKeyword(131), + AssertKeyword(132), + AnyKeyword(133), + AsyncKeyword(134), + AwaitKeyword(135), + BooleanKeyword(136), + ConstructorKeyword(137), + DeclareKeyword(138), + GetKeyword(139), + InferKeyword(140), + IntrinsicKeyword(141), + IsKeyword(142), + KeyOfKeyword(143), + ModuleKeyword(144), + NamespaceKeyword(145), + NeverKeyword(146), + OutKeyword(147), + ReadonlyKeyword(148), + RequireKeyword(149), + NumberKeyword(150), + ObjectKeyword(151), + SatisfiesKeyword(152), + SetKeyword(153), + StringKeyword(154), + SymbolKeyword(155), + TypeKeyword(156), + UndefinedKeyword(157), + UniqueKeyword(158), + UnknownKeyword(159), + UsingKeyword(160), + FromKeyword(161), + GlobalKeyword(162), + BigIntKeyword(163), + OverrideKeyword(164), /** Also includes LastKeyword, LastToken, LastContextualKeyword */ - OfKeyword(162), + OfKeyword(165), /** Also includes FirstNode */ - QualifiedName(163), - ComputedPropertyName(164), - TypeParameter(165), - Parameter(166), - Decorator(167), - PropertySignature(168), - PropertyDeclaration(169), - MethodSignature(170), - MethodDeclaration(171), - ClassStaticBlockDeclaration(172), - Constructor(173), - GetAccessor(174), - SetAccessor(175), - CallSignature(176), - ConstructSignature(177), - IndexSignature(178), + QualifiedName(166), + ComputedPropertyName(167), + TypeParameter(168), + Parameter(169), + Decorator(170), + PropertySignature(171), + PropertyDeclaration(172), + MethodSignature(173), + MethodDeclaration(174), + ClassStaticBlockDeclaration(175), + Constructor(176), + GetAccessor(177), + SetAccessor(178), + CallSignature(179), + ConstructSignature(180), + IndexSignature(181), /** Also includes FirstTypeNode */ - TypePredicate(179), - TypeReference(180), - FunctionType(181), - ConstructorType(182), - TypeQuery(183), - TypeLiteral(184), - ArrayType(185), - TupleType(186), - OptionalType(187), - RestType(188), - UnionType(189), - IntersectionType(190), - ConditionalType(191), - InferType(192), - ParenthesizedType(193), - ThisType(194), - TypeOperator(195), - IndexedAccessType(196), - MappedType(197), - LiteralType(198), - NamedTupleMember(199), - TemplateLiteralType(200), - TemplateLiteralTypeSpan(201), + TypePredicate(182), + TypeReference(183), + FunctionType(184), + ConstructorType(185), + TypeQuery(186), + TypeLiteral(187), + ArrayType(188), + TupleType(189), + OptionalType(190), + RestType(191), + UnionType(192), + IntersectionType(193), + ConditionalType(194), + InferType(195), + ParenthesizedType(196), + ThisType(197), + TypeOperator(198), + IndexedAccessType(199), + MappedType(200), + LiteralType(201), + NamedTupleMember(202), + TemplateLiteralType(203), + TemplateLiteralTypeSpan(204), /** Also includes LastTypeNode */ - ImportType(202), - ObjectBindingPattern(203), - ArrayBindingPattern(204), - BindingElement(205), - ArrayLiteralExpression(206), - ObjectLiteralExpression(207), - PropertyAccessExpression(208), - ElementAccessExpression(209), - CallExpression(210), - NewExpression(211), - TaggedTemplateExpression(212), - TypeAssertionExpression(213), - ParenthesizedExpression(214), - FunctionExpression(215), - ArrowFunction(216), - DeleteExpression(217), - TypeOfExpression(218), - VoidExpression(219), - AwaitExpression(220), - PrefixUnaryExpression(221), - PostfixUnaryExpression(222), - BinaryExpression(223), - ConditionalExpression(224), - TemplateExpression(225), - YieldExpression(226), - SpreadElement(227), - ClassExpression(228), - OmittedExpression(229), - ExpressionWithTypeArguments(230), - AsExpression(231), - NonNullExpression(232), - MetaProperty(233), - SyntheticExpression(234), - SatisfiesExpression(235), - TemplateSpan(236), - SemicolonClassElement(237), - Block(238), - EmptyStatement(239), + ImportType(205), + ObjectBindingPattern(206), + ArrayBindingPattern(207), + BindingElement(208), + ArrayLiteralExpression(209), + ObjectLiteralExpression(210), + PropertyAccessExpression(211), + ElementAccessExpression(212), + CallExpression(213), + NewExpression(214), + TaggedTemplateExpression(215), + TypeAssertionExpression(216), + ParenthesizedExpression(217), + FunctionExpression(218), + ArrowFunction(219), + DeleteExpression(220), + TypeOfExpression(221), + VoidExpression(222), + AwaitExpression(223), + PrefixUnaryExpression(224), + PostfixUnaryExpression(225), + BinaryExpression(226), + ConditionalExpression(227), + TemplateExpression(228), + YieldExpression(229), + SpreadElement(230), + ClassExpression(231), + OmittedExpression(232), + ExpressionWithTypeArguments(233), + AsExpression(234), + NonNullExpression(235), + MetaProperty(236), + SyntheticExpression(237), + SatisfiesExpression(238), + TemplateSpan(239), + SemicolonClassElement(240), + Block(241), + EmptyStatement(242), /** Also includes FirstStatement */ - VariableStatement(240), - ExpressionStatement(241), - IfStatement(242), - DoStatement(243), - WhileStatement(244), - ForStatement(245), - ForInStatement(246), - ForOfStatement(247), - ContinueStatement(248), - BreakStatement(249), - ReturnStatement(250), - WithStatement(251), - SwitchStatement(252), - LabeledStatement(253), - ThrowStatement(254), - TryStatement(255), + VariableStatement(243), + ExpressionStatement(244), + IfStatement(245), + DoStatement(246), + WhileStatement(247), + ForStatement(248), + ForInStatement(249), + ForOfStatement(250), + ContinueStatement(251), + BreakStatement(252), + ReturnStatement(253), + WithStatement(254), + SwitchStatement(255), + LabeledStatement(256), + ThrowStatement(257), + TryStatement(258), /** Also includes LastStatement */ - DebuggerStatement(256), - VariableDeclaration(257), - VariableDeclarationList(258), - FunctionDeclaration(259), - ClassDeclaration(260), - InterfaceDeclaration(261), - TypeAliasDeclaration(262), - EnumDeclaration(263), - ModuleDeclaration(264), - ModuleBlock(265), - CaseBlock(266), - NamespaceExportDeclaration(267), - ImportEqualsDeclaration(268), - ImportDeclaration(269), - ImportClause(270), - NamespaceImport(271), - NamedImports(272), - ImportSpecifier(273), - ExportAssignment(274), - ExportDeclaration(275), - NamedExports(276), - NamespaceExport(277), - ExportSpecifier(278), - MissingDeclaration(279), - ExternalModuleReference(280), - JsxElement(281), - JsxSelfClosingElement(282), - JsxOpeningElement(283), - JsxClosingElement(284), - JsxFragment(285), - JsxOpeningFragment(286), - JsxClosingFragment(287), - JsxAttribute(288), - JsxAttributes(289), - JsxSpreadAttribute(290), - JsxExpression(291), - CaseClause(292), - DefaultClause(293), - HeritageClause(294), - CatchClause(295), - AssertClause(296), - AssertEntry(297), - ImportTypeAssertionContainer(298), - PropertyAssignment(299), - ShorthandPropertyAssignment(300), - SpreadAssignment(301), - EnumMember(302), - UnparsedPrologue(303), - UnparsedPrepend(304), - UnparsedText(305), - UnparsedInternalText(306), - UnparsedSyntheticReference(307), - SourceFile(308), - Bundle(309), - UnparsedSource(310), - InputFiles(311), + DebuggerStatement(259), + VariableDeclaration(260), + VariableDeclarationList(261), + FunctionDeclaration(262), + ClassDeclaration(263), + InterfaceDeclaration(264), + TypeAliasDeclaration(265), + EnumDeclaration(266), + ModuleDeclaration(267), + ModuleBlock(268), + CaseBlock(269), + NamespaceExportDeclaration(270), + ImportEqualsDeclaration(271), + ImportDeclaration(272), + ImportClause(273), + NamespaceImport(274), + NamedImports(275), + ImportSpecifier(276), + ExportAssignment(277), + ExportDeclaration(278), + NamedExports(279), + NamespaceExport(280), + ExportSpecifier(281), + MissingDeclaration(282), + ExternalModuleReference(283), + JsxElement(284), + JsxSelfClosingElement(285), + JsxOpeningElement(286), + JsxClosingElement(287), + JsxFragment(288), + JsxOpeningFragment(289), + JsxClosingFragment(290), + JsxAttribute(291), + JsxAttributes(292), + JsxSpreadAttribute(293), + JsxExpression(294), + JsxNamespacedName(295), + CaseClause(296), + DefaultClause(297), + HeritageClause(298), + CatchClause(299), + AssertClause(300), + AssertEntry(301), + ImportTypeAssertionContainer(302), + PropertyAssignment(303), + ShorthandPropertyAssignment(304), + SpreadAssignment(305), + EnumMember(306), + UnparsedPrologue(307), + UnparsedPrepend(308), + UnparsedText(309), + UnparsedInternalText(310), + UnparsedSyntheticReference(311), + SourceFile(312), + Bundle(313), + UnparsedSource(314), + InputFiles(315), /** Also includes FirstJSDocNode */ - JSDocTypeExpression(312), - JSDocNameReference(313), - JSDocMemberName(314), - JSDocAllType(315), - JSDocUnknownType(316), - JSDocNullableType(317), - JSDocNonNullableType(318), - JSDocOptionalType(319), - JSDocFunctionType(320), - JSDocVariadicType(321), - JSDocNamepathType(322), + JSDocTypeExpression(316), + JSDocNameReference(317), + JSDocMemberName(318), + JSDocAllType(319), + JSDocUnknownType(320), + JSDocNullableType(321), + JSDocNonNullableType(322), + JSDocOptionalType(323), + JSDocFunctionType(324), + JSDocVariadicType(325), + JSDocNamepathType(326), /** Also includes JSDocComment */ - JSDoc(323), - JSDocText(324), - JSDocTypeLiteral(325), - JSDocSignature(326), - JSDocLink(327), - JSDocLinkCode(328), - JSDocLinkPlain(329), + JSDoc(327), + JSDocText(328), + JSDocTypeLiteral(329), + JSDocSignature(330), + JSDocLink(331), + JSDocLinkCode(332), + JSDocLinkPlain(333), /** Also includes FirstJSDocTagNode */ - JSDocTag(330), - JSDocAugmentsTag(331), - JSDocImplementsTag(332), - JSDocAuthorTag(333), - JSDocDeprecatedTag(334), - JSDocClassTag(335), - JSDocPublicTag(336), - JSDocPrivateTag(337), - JSDocProtectedTag(338), - JSDocReadonlyTag(339), - JSDocOverrideTag(340), - JSDocCallbackTag(341), - JSDocOverloadTag(342), - JSDocEnumTag(343), - JSDocParameterTag(344), - JSDocReturnTag(345), - JSDocThisTag(346), - JSDocTypeTag(347), - JSDocTemplateTag(348), - JSDocTypedefTag(349), - JSDocSeeTag(350), - JSDocPropertyTag(351), - JSDocThrowsTag(352), + JSDocTag(334), + JSDocAugmentsTag(335), + JSDocImplementsTag(336), + JSDocAuthorTag(337), + JSDocDeprecatedTag(338), + JSDocClassTag(339), + JSDocPublicTag(340), + JSDocPrivateTag(341), + JSDocProtectedTag(342), + JSDocReadonlyTag(343), + JSDocOverrideTag(344), + JSDocCallbackTag(345), + JSDocOverloadTag(346), + JSDocEnumTag(347), + JSDocParameterTag(348), + JSDocReturnTag(349), + JSDocThisTag(350), + JSDocTypeTag(351), + JSDocTemplateTag(352), + JSDocTypedefTag(353), + JSDocSeeTag(354), + JSDocPropertyTag(355), + JSDocThrowsTag(356), /** Also includes LastJSDocNode, LastJSDocTagNode */ - JSDocSatisfiesTag(353), - SyntaxList(354), - NotEmittedStatement(355), - PartiallyEmittedExpression(356), - CommaListExpression(357), - MergeDeclarationMarker(358), - EndOfDeclarationMarker(359), - SyntheticReferenceExpression(360), - Count(361); + JSDocSatisfiesTag(357), + SyntaxList(358), + NotEmittedStatement(359), + PartiallyEmittedExpression(360), + CommaListExpression(361), + SyntheticReferenceExpression(362), + Count(363); public final int code; @@ -437,712 +439,716 @@ public static TSCSyntaxKind fromCode(int code) { case 7: return TSCSyntaxKind.ConflictMarkerTrivia; case 8: - return TSCSyntaxKind.NumericLiteral; + return TSCSyntaxKind.NonTextFileMarkerTrivia; case 9: - return TSCSyntaxKind.BigIntLiteral; + return TSCSyntaxKind.NumericLiteral; case 10: - return TSCSyntaxKind.StringLiteral; + return TSCSyntaxKind.BigIntLiteral; case 11: - return TSCSyntaxKind.JsxText; + return TSCSyntaxKind.StringLiteral; case 12: - return TSCSyntaxKind.JsxTextAllWhiteSpaces; + return TSCSyntaxKind.JsxText; case 13: - return TSCSyntaxKind.RegularExpressionLiteral; + return TSCSyntaxKind.JsxTextAllWhiteSpaces; case 14: - return TSCSyntaxKind.NoSubstitutionTemplateLiteral; + return TSCSyntaxKind.RegularExpressionLiteral; case 15: - return TSCSyntaxKind.TemplateHead; + return TSCSyntaxKind.NoSubstitutionTemplateLiteral; case 16: - return TSCSyntaxKind.TemplateMiddle; + return TSCSyntaxKind.TemplateHead; case 17: - return TSCSyntaxKind.TemplateTail; + return TSCSyntaxKind.TemplateMiddle; case 18: - return TSCSyntaxKind.OpenBraceToken; + return TSCSyntaxKind.TemplateTail; case 19: - return TSCSyntaxKind.CloseBraceToken; + return TSCSyntaxKind.OpenBraceToken; case 20: - return TSCSyntaxKind.OpenParenToken; + return TSCSyntaxKind.CloseBraceToken; case 21: - return TSCSyntaxKind.CloseParenToken; + return TSCSyntaxKind.OpenParenToken; case 22: - return TSCSyntaxKind.OpenBracketToken; + return TSCSyntaxKind.CloseParenToken; case 23: - return TSCSyntaxKind.CloseBracketToken; + return TSCSyntaxKind.OpenBracketToken; case 24: - return TSCSyntaxKind.DotToken; + return TSCSyntaxKind.CloseBracketToken; case 25: - return TSCSyntaxKind.DotDotDotToken; + return TSCSyntaxKind.DotToken; case 26: - return TSCSyntaxKind.SemicolonToken; + return TSCSyntaxKind.DotDotDotToken; case 27: - return TSCSyntaxKind.CommaToken; + return TSCSyntaxKind.SemicolonToken; case 28: - return TSCSyntaxKind.QuestionDotToken; + return TSCSyntaxKind.CommaToken; case 29: - return TSCSyntaxKind.LessThanToken; + return TSCSyntaxKind.QuestionDotToken; case 30: - return TSCSyntaxKind.LessThanSlashToken; + return TSCSyntaxKind.LessThanToken; case 31: - return TSCSyntaxKind.GreaterThanToken; + return TSCSyntaxKind.LessThanSlashToken; case 32: - return TSCSyntaxKind.LessThanEqualsToken; + return TSCSyntaxKind.GreaterThanToken; case 33: - return TSCSyntaxKind.GreaterThanEqualsToken; + return TSCSyntaxKind.LessThanEqualsToken; case 34: - return TSCSyntaxKind.EqualsEqualsToken; + return TSCSyntaxKind.GreaterThanEqualsToken; case 35: - return TSCSyntaxKind.ExclamationEqualsToken; + return TSCSyntaxKind.EqualsEqualsToken; case 36: - return TSCSyntaxKind.EqualsEqualsEqualsToken; + return TSCSyntaxKind.ExclamationEqualsToken; case 37: - return TSCSyntaxKind.ExclamationEqualsEqualsToken; + return TSCSyntaxKind.EqualsEqualsEqualsToken; case 38: - return TSCSyntaxKind.EqualsGreaterThanToken; + return TSCSyntaxKind.ExclamationEqualsEqualsToken; case 39: - return TSCSyntaxKind.PlusToken; + return TSCSyntaxKind.EqualsGreaterThanToken; case 40: - return TSCSyntaxKind.MinusToken; + return TSCSyntaxKind.PlusToken; case 41: - return TSCSyntaxKind.AsteriskToken; + return TSCSyntaxKind.MinusToken; case 42: - return TSCSyntaxKind.AsteriskAsteriskToken; + return TSCSyntaxKind.AsteriskToken; case 43: - return TSCSyntaxKind.SlashToken; + return TSCSyntaxKind.AsteriskAsteriskToken; case 44: - return TSCSyntaxKind.PercentToken; + return TSCSyntaxKind.SlashToken; case 45: - return TSCSyntaxKind.PlusPlusToken; + return TSCSyntaxKind.PercentToken; case 46: - return TSCSyntaxKind.MinusMinusToken; + return TSCSyntaxKind.PlusPlusToken; case 47: - return TSCSyntaxKind.LessThanLessThanToken; + return TSCSyntaxKind.MinusMinusToken; case 48: - return TSCSyntaxKind.GreaterThanGreaterThanToken; + return TSCSyntaxKind.LessThanLessThanToken; case 49: - return TSCSyntaxKind.GreaterThanGreaterThanGreaterThanToken; + return TSCSyntaxKind.GreaterThanGreaterThanToken; case 50: - return TSCSyntaxKind.AmpersandToken; + return TSCSyntaxKind.GreaterThanGreaterThanGreaterThanToken; case 51: - return TSCSyntaxKind.BarToken; + return TSCSyntaxKind.AmpersandToken; case 52: - return TSCSyntaxKind.CaretToken; + return TSCSyntaxKind.BarToken; case 53: - return TSCSyntaxKind.ExclamationToken; + return TSCSyntaxKind.CaretToken; case 54: - return TSCSyntaxKind.TildeToken; + return TSCSyntaxKind.ExclamationToken; case 55: - return TSCSyntaxKind.AmpersandAmpersandToken; + return TSCSyntaxKind.TildeToken; case 56: - return TSCSyntaxKind.BarBarToken; + return TSCSyntaxKind.AmpersandAmpersandToken; case 57: - return TSCSyntaxKind.QuestionToken; + return TSCSyntaxKind.BarBarToken; case 58: - return TSCSyntaxKind.ColonToken; + return TSCSyntaxKind.QuestionToken; case 59: - return TSCSyntaxKind.AtToken; + return TSCSyntaxKind.ColonToken; case 60: - return TSCSyntaxKind.QuestionQuestionToken; + return TSCSyntaxKind.AtToken; case 61: - return TSCSyntaxKind.BacktickToken; + return TSCSyntaxKind.QuestionQuestionToken; case 62: - return TSCSyntaxKind.HashToken; + return TSCSyntaxKind.BacktickToken; case 63: - return TSCSyntaxKind.EqualsToken; + return TSCSyntaxKind.HashToken; case 64: - return TSCSyntaxKind.PlusEqualsToken; + return TSCSyntaxKind.EqualsToken; case 65: - return TSCSyntaxKind.MinusEqualsToken; + return TSCSyntaxKind.PlusEqualsToken; case 66: - return TSCSyntaxKind.AsteriskEqualsToken; + return TSCSyntaxKind.MinusEqualsToken; case 67: - return TSCSyntaxKind.AsteriskAsteriskEqualsToken; + return TSCSyntaxKind.AsteriskEqualsToken; case 68: - return TSCSyntaxKind.SlashEqualsToken; + return TSCSyntaxKind.AsteriskAsteriskEqualsToken; case 69: - return TSCSyntaxKind.PercentEqualsToken; + return TSCSyntaxKind.SlashEqualsToken; case 70: - return TSCSyntaxKind.LessThanLessThanEqualsToken; + return TSCSyntaxKind.PercentEqualsToken; case 71: - return TSCSyntaxKind.GreaterThanGreaterThanEqualsToken; + return TSCSyntaxKind.LessThanLessThanEqualsToken; case 72: - return TSCSyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken; + return TSCSyntaxKind.GreaterThanGreaterThanEqualsToken; case 73: - return TSCSyntaxKind.AmpersandEqualsToken; + return TSCSyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken; case 74: - return TSCSyntaxKind.BarEqualsToken; + return TSCSyntaxKind.AmpersandEqualsToken; case 75: - return TSCSyntaxKind.BarBarEqualsToken; + return TSCSyntaxKind.BarEqualsToken; case 76: - return TSCSyntaxKind.AmpersandAmpersandEqualsToken; + return TSCSyntaxKind.BarBarEqualsToken; case 77: - return TSCSyntaxKind.QuestionQuestionEqualsToken; + return TSCSyntaxKind.AmpersandAmpersandEqualsToken; case 78: - return TSCSyntaxKind.CaretEqualsToken; + return TSCSyntaxKind.QuestionQuestionEqualsToken; case 79: - return TSCSyntaxKind.Identifier; + return TSCSyntaxKind.CaretEqualsToken; case 80: - return TSCSyntaxKind.PrivateIdentifier; + return TSCSyntaxKind.Identifier; case 81: - return TSCSyntaxKind.BreakKeyword; + return TSCSyntaxKind.PrivateIdentifier; case 82: - return TSCSyntaxKind.CaseKeyword; + return TSCSyntaxKind.JSDocCommentTextToken; case 83: - return TSCSyntaxKind.CatchKeyword; + return TSCSyntaxKind.BreakKeyword; case 84: - return TSCSyntaxKind.ClassKeyword; + return TSCSyntaxKind.CaseKeyword; case 85: - return TSCSyntaxKind.ConstKeyword; + return TSCSyntaxKind.CatchKeyword; case 86: - return TSCSyntaxKind.ContinueKeyword; + return TSCSyntaxKind.ClassKeyword; case 87: - return TSCSyntaxKind.DebuggerKeyword; + return TSCSyntaxKind.ConstKeyword; case 88: - return TSCSyntaxKind.DefaultKeyword; + return TSCSyntaxKind.ContinueKeyword; case 89: - return TSCSyntaxKind.DeleteKeyword; + return TSCSyntaxKind.DebuggerKeyword; case 90: - return TSCSyntaxKind.DoKeyword; + return TSCSyntaxKind.DefaultKeyword; case 91: - return TSCSyntaxKind.ElseKeyword; + return TSCSyntaxKind.DeleteKeyword; case 92: - return TSCSyntaxKind.EnumKeyword; + return TSCSyntaxKind.DoKeyword; case 93: - return TSCSyntaxKind.ExportKeyword; + return TSCSyntaxKind.ElseKeyword; case 94: - return TSCSyntaxKind.ExtendsKeyword; + return TSCSyntaxKind.EnumKeyword; case 95: - return TSCSyntaxKind.FalseKeyword; + return TSCSyntaxKind.ExportKeyword; case 96: - return TSCSyntaxKind.FinallyKeyword; + return TSCSyntaxKind.ExtendsKeyword; case 97: - return TSCSyntaxKind.ForKeyword; + return TSCSyntaxKind.FalseKeyword; case 98: - return TSCSyntaxKind.FunctionKeyword; + return TSCSyntaxKind.FinallyKeyword; case 99: - return TSCSyntaxKind.IfKeyword; + return TSCSyntaxKind.ForKeyword; case 100: - return TSCSyntaxKind.ImportKeyword; + return TSCSyntaxKind.FunctionKeyword; case 101: - return TSCSyntaxKind.InKeyword; + return TSCSyntaxKind.IfKeyword; case 102: - return TSCSyntaxKind.InstanceOfKeyword; + return TSCSyntaxKind.ImportKeyword; case 103: - return TSCSyntaxKind.NewKeyword; + return TSCSyntaxKind.InKeyword; case 104: - return TSCSyntaxKind.NullKeyword; + return TSCSyntaxKind.InstanceOfKeyword; case 105: - return TSCSyntaxKind.ReturnKeyword; + return TSCSyntaxKind.NewKeyword; case 106: - return TSCSyntaxKind.SuperKeyword; + return TSCSyntaxKind.NullKeyword; case 107: - return TSCSyntaxKind.SwitchKeyword; + return TSCSyntaxKind.ReturnKeyword; case 108: - return TSCSyntaxKind.ThisKeyword; + return TSCSyntaxKind.SuperKeyword; case 109: - return TSCSyntaxKind.ThrowKeyword; + return TSCSyntaxKind.SwitchKeyword; case 110: - return TSCSyntaxKind.TrueKeyword; + return TSCSyntaxKind.ThisKeyword; case 111: - return TSCSyntaxKind.TryKeyword; + return TSCSyntaxKind.ThrowKeyword; case 112: - return TSCSyntaxKind.TypeOfKeyword; + return TSCSyntaxKind.TrueKeyword; case 113: - return TSCSyntaxKind.VarKeyword; + return TSCSyntaxKind.TryKeyword; case 114: - return TSCSyntaxKind.VoidKeyword; + return TSCSyntaxKind.TypeOfKeyword; case 115: - return TSCSyntaxKind.WhileKeyword; + return TSCSyntaxKind.VarKeyword; case 116: - return TSCSyntaxKind.WithKeyword; + return TSCSyntaxKind.VoidKeyword; case 117: - return TSCSyntaxKind.ImplementsKeyword; + return TSCSyntaxKind.WhileKeyword; case 118: - return TSCSyntaxKind.InterfaceKeyword; + return TSCSyntaxKind.WithKeyword; case 119: - return TSCSyntaxKind.LetKeyword; + return TSCSyntaxKind.ImplementsKeyword; case 120: - return TSCSyntaxKind.PackageKeyword; + return TSCSyntaxKind.InterfaceKeyword; case 121: - return TSCSyntaxKind.PrivateKeyword; + return TSCSyntaxKind.LetKeyword; case 122: - return TSCSyntaxKind.ProtectedKeyword; + return TSCSyntaxKind.PackageKeyword; case 123: - return TSCSyntaxKind.PublicKeyword; + return TSCSyntaxKind.PrivateKeyword; case 124: - return TSCSyntaxKind.StaticKeyword; + return TSCSyntaxKind.ProtectedKeyword; case 125: - return TSCSyntaxKind.YieldKeyword; + return TSCSyntaxKind.PublicKeyword; case 126: - return TSCSyntaxKind.AbstractKeyword; + return TSCSyntaxKind.StaticKeyword; case 127: - return TSCSyntaxKind.AccessorKeyword; + return TSCSyntaxKind.YieldKeyword; case 128: - return TSCSyntaxKind.AsKeyword; + return TSCSyntaxKind.AbstractKeyword; case 129: - return TSCSyntaxKind.AssertsKeyword; + return TSCSyntaxKind.AccessorKeyword; case 130: - return TSCSyntaxKind.AssertKeyword; + return TSCSyntaxKind.AsKeyword; case 131: - return TSCSyntaxKind.AnyKeyword; + return TSCSyntaxKind.AssertsKeyword; case 132: - return TSCSyntaxKind.AsyncKeyword; + return TSCSyntaxKind.AssertKeyword; case 133: - return TSCSyntaxKind.AwaitKeyword; + return TSCSyntaxKind.AnyKeyword; case 134: - return TSCSyntaxKind.BooleanKeyword; + return TSCSyntaxKind.AsyncKeyword; case 135: - return TSCSyntaxKind.ConstructorKeyword; + return TSCSyntaxKind.AwaitKeyword; case 136: - return TSCSyntaxKind.DeclareKeyword; + return TSCSyntaxKind.BooleanKeyword; case 137: - return TSCSyntaxKind.GetKeyword; + return TSCSyntaxKind.ConstructorKeyword; case 138: - return TSCSyntaxKind.InferKeyword; + return TSCSyntaxKind.DeclareKeyword; case 139: - return TSCSyntaxKind.IntrinsicKeyword; + return TSCSyntaxKind.GetKeyword; case 140: - return TSCSyntaxKind.IsKeyword; + return TSCSyntaxKind.InferKeyword; case 141: - return TSCSyntaxKind.KeyOfKeyword; + return TSCSyntaxKind.IntrinsicKeyword; case 142: - return TSCSyntaxKind.ModuleKeyword; + return TSCSyntaxKind.IsKeyword; case 143: - return TSCSyntaxKind.NamespaceKeyword; + return TSCSyntaxKind.KeyOfKeyword; case 144: - return TSCSyntaxKind.NeverKeyword; + return TSCSyntaxKind.ModuleKeyword; case 145: - return TSCSyntaxKind.OutKeyword; + return TSCSyntaxKind.NamespaceKeyword; case 146: - return TSCSyntaxKind.ReadonlyKeyword; + return TSCSyntaxKind.NeverKeyword; case 147: - return TSCSyntaxKind.RequireKeyword; + return TSCSyntaxKind.OutKeyword; case 148: - return TSCSyntaxKind.NumberKeyword; + return TSCSyntaxKind.ReadonlyKeyword; case 149: - return TSCSyntaxKind.ObjectKeyword; + return TSCSyntaxKind.RequireKeyword; case 150: - return TSCSyntaxKind.SatisfiesKeyword; + return TSCSyntaxKind.NumberKeyword; case 151: - return TSCSyntaxKind.SetKeyword; + return TSCSyntaxKind.ObjectKeyword; case 152: - return TSCSyntaxKind.StringKeyword; + return TSCSyntaxKind.SatisfiesKeyword; case 153: - return TSCSyntaxKind.SymbolKeyword; + return TSCSyntaxKind.SetKeyword; case 154: - return TSCSyntaxKind.TypeKeyword; + return TSCSyntaxKind.StringKeyword; case 155: - return TSCSyntaxKind.UndefinedKeyword; + return TSCSyntaxKind.SymbolKeyword; case 156: - return TSCSyntaxKind.UniqueKeyword; + return TSCSyntaxKind.TypeKeyword; case 157: - return TSCSyntaxKind.UnknownKeyword; + return TSCSyntaxKind.UndefinedKeyword; case 158: - return TSCSyntaxKind.FromKeyword; + return TSCSyntaxKind.UniqueKeyword; case 159: - return TSCSyntaxKind.GlobalKeyword; + return TSCSyntaxKind.UnknownKeyword; case 160: - return TSCSyntaxKind.BigIntKeyword; + return TSCSyntaxKind.UsingKeyword; case 161: - return TSCSyntaxKind.OverrideKeyword; + return TSCSyntaxKind.FromKeyword; case 162: - return TSCSyntaxKind.OfKeyword; + return TSCSyntaxKind.GlobalKeyword; case 163: - return TSCSyntaxKind.QualifiedName; + return TSCSyntaxKind.BigIntKeyword; case 164: - return TSCSyntaxKind.ComputedPropertyName; + return TSCSyntaxKind.OverrideKeyword; case 165: - return TSCSyntaxKind.TypeParameter; + return TSCSyntaxKind.OfKeyword; case 166: - return TSCSyntaxKind.Parameter; + return TSCSyntaxKind.QualifiedName; case 167: - return TSCSyntaxKind.Decorator; + return TSCSyntaxKind.ComputedPropertyName; case 168: - return TSCSyntaxKind.PropertySignature; + return TSCSyntaxKind.TypeParameter; case 169: - return TSCSyntaxKind.PropertyDeclaration; + return TSCSyntaxKind.Parameter; case 170: - return TSCSyntaxKind.MethodSignature; + return TSCSyntaxKind.Decorator; case 171: - return TSCSyntaxKind.MethodDeclaration; + return TSCSyntaxKind.PropertySignature; case 172: - return TSCSyntaxKind.ClassStaticBlockDeclaration; + return TSCSyntaxKind.PropertyDeclaration; case 173: - return TSCSyntaxKind.Constructor; + return TSCSyntaxKind.MethodSignature; case 174: - return TSCSyntaxKind.GetAccessor; + return TSCSyntaxKind.MethodDeclaration; case 175: - return TSCSyntaxKind.SetAccessor; + return TSCSyntaxKind.ClassStaticBlockDeclaration; case 176: - return TSCSyntaxKind.CallSignature; + return TSCSyntaxKind.Constructor; case 177: - return TSCSyntaxKind.ConstructSignature; + return TSCSyntaxKind.GetAccessor; case 178: - return TSCSyntaxKind.IndexSignature; + return TSCSyntaxKind.SetAccessor; case 179: - return TSCSyntaxKind.TypePredicate; + return TSCSyntaxKind.CallSignature; case 180: - return TSCSyntaxKind.TypeReference; + return TSCSyntaxKind.ConstructSignature; case 181: - return TSCSyntaxKind.FunctionType; + return TSCSyntaxKind.IndexSignature; case 182: - return TSCSyntaxKind.ConstructorType; + return TSCSyntaxKind.TypePredicate; case 183: - return TSCSyntaxKind.TypeQuery; + return TSCSyntaxKind.TypeReference; case 184: - return TSCSyntaxKind.TypeLiteral; + return TSCSyntaxKind.FunctionType; case 185: - return TSCSyntaxKind.ArrayType; + return TSCSyntaxKind.ConstructorType; case 186: - return TSCSyntaxKind.TupleType; + return TSCSyntaxKind.TypeQuery; case 187: - return TSCSyntaxKind.OptionalType; + return TSCSyntaxKind.TypeLiteral; case 188: - return TSCSyntaxKind.RestType; + return TSCSyntaxKind.ArrayType; case 189: - return TSCSyntaxKind.UnionType; + return TSCSyntaxKind.TupleType; case 190: - return TSCSyntaxKind.IntersectionType; + return TSCSyntaxKind.OptionalType; case 191: - return TSCSyntaxKind.ConditionalType; + return TSCSyntaxKind.RestType; case 192: - return TSCSyntaxKind.InferType; + return TSCSyntaxKind.UnionType; case 193: - return TSCSyntaxKind.ParenthesizedType; + return TSCSyntaxKind.IntersectionType; case 194: - return TSCSyntaxKind.ThisType; + return TSCSyntaxKind.ConditionalType; case 195: - return TSCSyntaxKind.TypeOperator; + return TSCSyntaxKind.InferType; case 196: - return TSCSyntaxKind.IndexedAccessType; + return TSCSyntaxKind.ParenthesizedType; case 197: - return TSCSyntaxKind.MappedType; + return TSCSyntaxKind.ThisType; case 198: - return TSCSyntaxKind.LiteralType; + return TSCSyntaxKind.TypeOperator; case 199: - return TSCSyntaxKind.NamedTupleMember; + return TSCSyntaxKind.IndexedAccessType; case 200: - return TSCSyntaxKind.TemplateLiteralType; + return TSCSyntaxKind.MappedType; case 201: - return TSCSyntaxKind.TemplateLiteralTypeSpan; + return TSCSyntaxKind.LiteralType; case 202: - return TSCSyntaxKind.ImportType; + return TSCSyntaxKind.NamedTupleMember; case 203: - return TSCSyntaxKind.ObjectBindingPattern; + return TSCSyntaxKind.TemplateLiteralType; case 204: - return TSCSyntaxKind.ArrayBindingPattern; + return TSCSyntaxKind.TemplateLiteralTypeSpan; case 205: - return TSCSyntaxKind.BindingElement; + return TSCSyntaxKind.ImportType; case 206: - return TSCSyntaxKind.ArrayLiteralExpression; + return TSCSyntaxKind.ObjectBindingPattern; case 207: - return TSCSyntaxKind.ObjectLiteralExpression; + return TSCSyntaxKind.ArrayBindingPattern; case 208: - return TSCSyntaxKind.PropertyAccessExpression; + return TSCSyntaxKind.BindingElement; case 209: - return TSCSyntaxKind.ElementAccessExpression; + return TSCSyntaxKind.ArrayLiteralExpression; case 210: - return TSCSyntaxKind.CallExpression; + return TSCSyntaxKind.ObjectLiteralExpression; case 211: - return TSCSyntaxKind.NewExpression; + return TSCSyntaxKind.PropertyAccessExpression; case 212: - return TSCSyntaxKind.TaggedTemplateExpression; + return TSCSyntaxKind.ElementAccessExpression; case 213: - return TSCSyntaxKind.TypeAssertionExpression; + return TSCSyntaxKind.CallExpression; case 214: - return TSCSyntaxKind.ParenthesizedExpression; + return TSCSyntaxKind.NewExpression; case 215: - return TSCSyntaxKind.FunctionExpression; + return TSCSyntaxKind.TaggedTemplateExpression; case 216: - return TSCSyntaxKind.ArrowFunction; + return TSCSyntaxKind.TypeAssertionExpression; case 217: - return TSCSyntaxKind.DeleteExpression; + return TSCSyntaxKind.ParenthesizedExpression; case 218: - return TSCSyntaxKind.TypeOfExpression; + return TSCSyntaxKind.FunctionExpression; case 219: - return TSCSyntaxKind.VoidExpression; + return TSCSyntaxKind.ArrowFunction; case 220: - return TSCSyntaxKind.AwaitExpression; + return TSCSyntaxKind.DeleteExpression; case 221: - return TSCSyntaxKind.PrefixUnaryExpression; + return TSCSyntaxKind.TypeOfExpression; case 222: - return TSCSyntaxKind.PostfixUnaryExpression; + return TSCSyntaxKind.VoidExpression; case 223: - return TSCSyntaxKind.BinaryExpression; + return TSCSyntaxKind.AwaitExpression; case 224: - return TSCSyntaxKind.ConditionalExpression; + return TSCSyntaxKind.PrefixUnaryExpression; case 225: - return TSCSyntaxKind.TemplateExpression; + return TSCSyntaxKind.PostfixUnaryExpression; case 226: - return TSCSyntaxKind.YieldExpression; + return TSCSyntaxKind.BinaryExpression; case 227: - return TSCSyntaxKind.SpreadElement; + return TSCSyntaxKind.ConditionalExpression; case 228: - return TSCSyntaxKind.ClassExpression; + return TSCSyntaxKind.TemplateExpression; case 229: - return TSCSyntaxKind.OmittedExpression; + return TSCSyntaxKind.YieldExpression; case 230: - return TSCSyntaxKind.ExpressionWithTypeArguments; + return TSCSyntaxKind.SpreadElement; case 231: - return TSCSyntaxKind.AsExpression; + return TSCSyntaxKind.ClassExpression; case 232: - return TSCSyntaxKind.NonNullExpression; + return TSCSyntaxKind.OmittedExpression; case 233: - return TSCSyntaxKind.MetaProperty; + return TSCSyntaxKind.ExpressionWithTypeArguments; case 234: - return TSCSyntaxKind.SyntheticExpression; + return TSCSyntaxKind.AsExpression; case 235: - return TSCSyntaxKind.SatisfiesExpression; + return TSCSyntaxKind.NonNullExpression; case 236: - return TSCSyntaxKind.TemplateSpan; + return TSCSyntaxKind.MetaProperty; case 237: - return TSCSyntaxKind.SemicolonClassElement; + return TSCSyntaxKind.SyntheticExpression; case 238: - return TSCSyntaxKind.Block; + return TSCSyntaxKind.SatisfiesExpression; case 239: - return TSCSyntaxKind.EmptyStatement; + return TSCSyntaxKind.TemplateSpan; case 240: - return TSCSyntaxKind.VariableStatement; + return TSCSyntaxKind.SemicolonClassElement; case 241: - return TSCSyntaxKind.ExpressionStatement; + return TSCSyntaxKind.Block; case 242: - return TSCSyntaxKind.IfStatement; + return TSCSyntaxKind.EmptyStatement; case 243: - return TSCSyntaxKind.DoStatement; + return TSCSyntaxKind.VariableStatement; case 244: - return TSCSyntaxKind.WhileStatement; + return TSCSyntaxKind.ExpressionStatement; case 245: - return TSCSyntaxKind.ForStatement; + return TSCSyntaxKind.IfStatement; case 246: - return TSCSyntaxKind.ForInStatement; + return TSCSyntaxKind.DoStatement; case 247: - return TSCSyntaxKind.ForOfStatement; + return TSCSyntaxKind.WhileStatement; case 248: - return TSCSyntaxKind.ContinueStatement; + return TSCSyntaxKind.ForStatement; case 249: - return TSCSyntaxKind.BreakStatement; + return TSCSyntaxKind.ForInStatement; case 250: - return TSCSyntaxKind.ReturnStatement; + return TSCSyntaxKind.ForOfStatement; case 251: - return TSCSyntaxKind.WithStatement; + return TSCSyntaxKind.ContinueStatement; case 252: - return TSCSyntaxKind.SwitchStatement; + return TSCSyntaxKind.BreakStatement; case 253: - return TSCSyntaxKind.LabeledStatement; + return TSCSyntaxKind.ReturnStatement; case 254: - return TSCSyntaxKind.ThrowStatement; + return TSCSyntaxKind.WithStatement; case 255: - return TSCSyntaxKind.TryStatement; + return TSCSyntaxKind.SwitchStatement; case 256: - return TSCSyntaxKind.DebuggerStatement; + return TSCSyntaxKind.LabeledStatement; case 257: - return TSCSyntaxKind.VariableDeclaration; + return TSCSyntaxKind.ThrowStatement; case 258: - return TSCSyntaxKind.VariableDeclarationList; + return TSCSyntaxKind.TryStatement; case 259: - return TSCSyntaxKind.FunctionDeclaration; + return TSCSyntaxKind.DebuggerStatement; case 260: - return TSCSyntaxKind.ClassDeclaration; + return TSCSyntaxKind.VariableDeclaration; case 261: - return TSCSyntaxKind.InterfaceDeclaration; + return TSCSyntaxKind.VariableDeclarationList; case 262: - return TSCSyntaxKind.TypeAliasDeclaration; + return TSCSyntaxKind.FunctionDeclaration; case 263: - return TSCSyntaxKind.EnumDeclaration; + return TSCSyntaxKind.ClassDeclaration; case 264: - return TSCSyntaxKind.ModuleDeclaration; + return TSCSyntaxKind.InterfaceDeclaration; case 265: - return TSCSyntaxKind.ModuleBlock; + return TSCSyntaxKind.TypeAliasDeclaration; case 266: - return TSCSyntaxKind.CaseBlock; + return TSCSyntaxKind.EnumDeclaration; case 267: - return TSCSyntaxKind.NamespaceExportDeclaration; + return TSCSyntaxKind.ModuleDeclaration; case 268: - return TSCSyntaxKind.ImportEqualsDeclaration; + return TSCSyntaxKind.ModuleBlock; case 269: - return TSCSyntaxKind.ImportDeclaration; + return TSCSyntaxKind.CaseBlock; case 270: - return TSCSyntaxKind.ImportClause; + return TSCSyntaxKind.NamespaceExportDeclaration; case 271: - return TSCSyntaxKind.NamespaceImport; + return TSCSyntaxKind.ImportEqualsDeclaration; case 272: - return TSCSyntaxKind.NamedImports; + return TSCSyntaxKind.ImportDeclaration; case 273: - return TSCSyntaxKind.ImportSpecifier; + return TSCSyntaxKind.ImportClause; case 274: - return TSCSyntaxKind.ExportAssignment; + return TSCSyntaxKind.NamespaceImport; case 275: - return TSCSyntaxKind.ExportDeclaration; + return TSCSyntaxKind.NamedImports; case 276: - return TSCSyntaxKind.NamedExports; + return TSCSyntaxKind.ImportSpecifier; case 277: - return TSCSyntaxKind.NamespaceExport; + return TSCSyntaxKind.ExportAssignment; case 278: - return TSCSyntaxKind.ExportSpecifier; + return TSCSyntaxKind.ExportDeclaration; case 279: - return TSCSyntaxKind.MissingDeclaration; + return TSCSyntaxKind.NamedExports; case 280: - return TSCSyntaxKind.ExternalModuleReference; + return TSCSyntaxKind.NamespaceExport; case 281: - return TSCSyntaxKind.JsxElement; + return TSCSyntaxKind.ExportSpecifier; case 282: - return TSCSyntaxKind.JsxSelfClosingElement; + return TSCSyntaxKind.MissingDeclaration; case 283: - return TSCSyntaxKind.JsxOpeningElement; + return TSCSyntaxKind.ExternalModuleReference; case 284: - return TSCSyntaxKind.JsxClosingElement; + return TSCSyntaxKind.JsxElement; case 285: - return TSCSyntaxKind.JsxFragment; + return TSCSyntaxKind.JsxSelfClosingElement; case 286: - return TSCSyntaxKind.JsxOpeningFragment; + return TSCSyntaxKind.JsxOpeningElement; case 287: - return TSCSyntaxKind.JsxClosingFragment; + return TSCSyntaxKind.JsxClosingElement; case 288: - return TSCSyntaxKind.JsxAttribute; + return TSCSyntaxKind.JsxFragment; case 289: - return TSCSyntaxKind.JsxAttributes; + return TSCSyntaxKind.JsxOpeningFragment; case 290: - return TSCSyntaxKind.JsxSpreadAttribute; + return TSCSyntaxKind.JsxClosingFragment; case 291: - return TSCSyntaxKind.JsxExpression; + return TSCSyntaxKind.JsxAttribute; case 292: - return TSCSyntaxKind.CaseClause; + return TSCSyntaxKind.JsxAttributes; case 293: - return TSCSyntaxKind.DefaultClause; + return TSCSyntaxKind.JsxSpreadAttribute; case 294: - return TSCSyntaxKind.HeritageClause; + return TSCSyntaxKind.JsxExpression; case 295: - return TSCSyntaxKind.CatchClause; + return TSCSyntaxKind.JsxNamespacedName; case 296: - return TSCSyntaxKind.AssertClause; + return TSCSyntaxKind.CaseClause; case 297: - return TSCSyntaxKind.AssertEntry; + return TSCSyntaxKind.DefaultClause; case 298: - return TSCSyntaxKind.ImportTypeAssertionContainer; + return TSCSyntaxKind.HeritageClause; case 299: - return TSCSyntaxKind.PropertyAssignment; + return TSCSyntaxKind.CatchClause; case 300: - return TSCSyntaxKind.ShorthandPropertyAssignment; + return TSCSyntaxKind.AssertClause; case 301: - return TSCSyntaxKind.SpreadAssignment; + return TSCSyntaxKind.AssertEntry; case 302: - return TSCSyntaxKind.EnumMember; + return TSCSyntaxKind.ImportTypeAssertionContainer; case 303: - return TSCSyntaxKind.UnparsedPrologue; + return TSCSyntaxKind.PropertyAssignment; case 304: - return TSCSyntaxKind.UnparsedPrepend; + return TSCSyntaxKind.ShorthandPropertyAssignment; case 305: - return TSCSyntaxKind.UnparsedText; + return TSCSyntaxKind.SpreadAssignment; case 306: - return TSCSyntaxKind.UnparsedInternalText; + return TSCSyntaxKind.EnumMember; case 307: - return TSCSyntaxKind.UnparsedSyntheticReference; + return TSCSyntaxKind.UnparsedPrologue; case 308: - return TSCSyntaxKind.SourceFile; + return TSCSyntaxKind.UnparsedPrepend; case 309: - return TSCSyntaxKind.Bundle; + return TSCSyntaxKind.UnparsedText; case 310: - return TSCSyntaxKind.UnparsedSource; + return TSCSyntaxKind.UnparsedInternalText; case 311: - return TSCSyntaxKind.InputFiles; + return TSCSyntaxKind.UnparsedSyntheticReference; case 312: - return TSCSyntaxKind.JSDocTypeExpression; + return TSCSyntaxKind.SourceFile; case 313: - return TSCSyntaxKind.JSDocNameReference; + return TSCSyntaxKind.Bundle; case 314: - return TSCSyntaxKind.JSDocMemberName; + return TSCSyntaxKind.UnparsedSource; case 315: - return TSCSyntaxKind.JSDocAllType; + return TSCSyntaxKind.InputFiles; case 316: - return TSCSyntaxKind.JSDocUnknownType; + return TSCSyntaxKind.JSDocTypeExpression; case 317: - return TSCSyntaxKind.JSDocNullableType; + return TSCSyntaxKind.JSDocNameReference; case 318: - return TSCSyntaxKind.JSDocNonNullableType; + return TSCSyntaxKind.JSDocMemberName; case 319: - return TSCSyntaxKind.JSDocOptionalType; + return TSCSyntaxKind.JSDocAllType; case 320: - return TSCSyntaxKind.JSDocFunctionType; + return TSCSyntaxKind.JSDocUnknownType; case 321: - return TSCSyntaxKind.JSDocVariadicType; + return TSCSyntaxKind.JSDocNullableType; case 322: - return TSCSyntaxKind.JSDocNamepathType; + return TSCSyntaxKind.JSDocNonNullableType; case 323: - return TSCSyntaxKind.JSDoc; + return TSCSyntaxKind.JSDocOptionalType; case 324: - return TSCSyntaxKind.JSDocText; + return TSCSyntaxKind.JSDocFunctionType; case 325: - return TSCSyntaxKind.JSDocTypeLiteral; + return TSCSyntaxKind.JSDocVariadicType; case 326: - return TSCSyntaxKind.JSDocSignature; + return TSCSyntaxKind.JSDocNamepathType; case 327: - return TSCSyntaxKind.JSDocLink; + return TSCSyntaxKind.JSDoc; case 328: - return TSCSyntaxKind.JSDocLinkCode; + return TSCSyntaxKind.JSDocText; case 329: - return TSCSyntaxKind.JSDocLinkPlain; + return TSCSyntaxKind.JSDocTypeLiteral; case 330: - return TSCSyntaxKind.JSDocTag; + return TSCSyntaxKind.JSDocSignature; case 331: - return TSCSyntaxKind.JSDocAugmentsTag; + return TSCSyntaxKind.JSDocLink; case 332: - return TSCSyntaxKind.JSDocImplementsTag; + return TSCSyntaxKind.JSDocLinkCode; case 333: - return TSCSyntaxKind.JSDocAuthorTag; + return TSCSyntaxKind.JSDocLinkPlain; case 334: - return TSCSyntaxKind.JSDocDeprecatedTag; + return TSCSyntaxKind.JSDocTag; case 335: - return TSCSyntaxKind.JSDocClassTag; + return TSCSyntaxKind.JSDocAugmentsTag; case 336: - return TSCSyntaxKind.JSDocPublicTag; + return TSCSyntaxKind.JSDocImplementsTag; case 337: - return TSCSyntaxKind.JSDocPrivateTag; + return TSCSyntaxKind.JSDocAuthorTag; case 338: - return TSCSyntaxKind.JSDocProtectedTag; + return TSCSyntaxKind.JSDocDeprecatedTag; case 339: - return TSCSyntaxKind.JSDocReadonlyTag; + return TSCSyntaxKind.JSDocClassTag; case 340: - return TSCSyntaxKind.JSDocOverrideTag; + return TSCSyntaxKind.JSDocPublicTag; case 341: - return TSCSyntaxKind.JSDocCallbackTag; + return TSCSyntaxKind.JSDocPrivateTag; case 342: - return TSCSyntaxKind.JSDocOverloadTag; + return TSCSyntaxKind.JSDocProtectedTag; case 343: - return TSCSyntaxKind.JSDocEnumTag; + return TSCSyntaxKind.JSDocReadonlyTag; case 344: - return TSCSyntaxKind.JSDocParameterTag; + return TSCSyntaxKind.JSDocOverrideTag; case 345: - return TSCSyntaxKind.JSDocReturnTag; + return TSCSyntaxKind.JSDocCallbackTag; case 346: - return TSCSyntaxKind.JSDocThisTag; + return TSCSyntaxKind.JSDocOverloadTag; case 347: - return TSCSyntaxKind.JSDocTypeTag; + return TSCSyntaxKind.JSDocEnumTag; case 348: - return TSCSyntaxKind.JSDocTemplateTag; + return TSCSyntaxKind.JSDocParameterTag; case 349: - return TSCSyntaxKind.JSDocTypedefTag; + return TSCSyntaxKind.JSDocReturnTag; case 350: - return TSCSyntaxKind.JSDocSeeTag; + return TSCSyntaxKind.JSDocThisTag; case 351: - return TSCSyntaxKind.JSDocPropertyTag; + return TSCSyntaxKind.JSDocTypeTag; case 352: - return TSCSyntaxKind.JSDocThrowsTag; + return TSCSyntaxKind.JSDocTemplateTag; case 353: - return TSCSyntaxKind.JSDocSatisfiesTag; + return TSCSyntaxKind.JSDocTypedefTag; case 354: - return TSCSyntaxKind.SyntaxList; + return TSCSyntaxKind.JSDocSeeTag; case 355: - return TSCSyntaxKind.NotEmittedStatement; + return TSCSyntaxKind.JSDocPropertyTag; case 356: - return TSCSyntaxKind.PartiallyEmittedExpression; + return TSCSyntaxKind.JSDocThrowsTag; case 357: - return TSCSyntaxKind.CommaListExpression; + return TSCSyntaxKind.JSDocSatisfiesTag; case 358: - return TSCSyntaxKind.MergeDeclarationMarker; + return TSCSyntaxKind.SyntaxList; case 359: - return TSCSyntaxKind.EndOfDeclarationMarker; + return TSCSyntaxKind.NotEmittedStatement; case 360: - return TSCSyntaxKind.SyntheticReferenceExpression; + return TSCSyntaxKind.PartiallyEmittedExpression; case 361: + return TSCSyntaxKind.CommaListExpression; + case 362: + return TSCSyntaxKind.SyntheticReferenceExpression; + case 363: return TSCSyntaxKind.Count; default: throw new IllegalArgumentException("unknown TSCSyntaxKind code: " + code); diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCTokenFlag.java b/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCTokenFlag.java index 57b46fff..b2d59b96 100644 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCTokenFlag.java +++ b/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCTokenFlag.java @@ -34,10 +34,16 @@ public enum TSCTokenFlag { OctalSpecifier(256), ContainsSeparator(512), UnicodeEscape(1024), - /** Also includes TemplateLiteralLikeFlags */ ContainsInvalidEscape(2048), + HexEscape(4096), + ContainsLeadingZero(8192), + ContainsInvalidSeparator(16384), BinaryOrOctalSpecifier(384), - NumericLiteralFlags(1008); + WithSpecifier(448), + /** Also includes TemplateLiteralLikeFlags */ + StringLiteralFlags(7176), + NumericLiteralFlags(25584), + IsInvalid(26656); public final int code; @@ -74,10 +80,22 @@ public static TSCTokenFlag fromMaskExact(int code) { return TSCTokenFlag.UnicodeEscape; case 2048: return TSCTokenFlag.ContainsInvalidEscape; + case 4096: + return TSCTokenFlag.HexEscape; + case 8192: + return TSCTokenFlag.ContainsLeadingZero; + case 16384: + return TSCTokenFlag.ContainsInvalidSeparator; case 384: return TSCTokenFlag.BinaryOrOctalSpecifier; - case 1008: + case 448: + return TSCTokenFlag.WithSpecifier; + case 7176: + return TSCTokenFlag.StringLiteralFlags; + case 25584: return TSCTokenFlag.NumericLiteralFlags; + case 26656: + return TSCTokenFlag.IsInvalid; default: throw new IllegalArgumentException("unknown TSCTokenFlag code: " + code); } diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCTypeFlag.java b/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCTypeFlag.java index 56693fad..3764f753 100644 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCTypeFlag.java +++ b/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCTypeFlag.java @@ -66,7 +66,6 @@ public enum TSCTypeFlag { DefinitelyFalsy(117632), PossiblyFalsy(117724), Intrinsic(67359327), - Primitive(134348796), StringLike(402653316), NumberLike(296), BigIntLike(2112), @@ -74,6 +73,7 @@ public enum TSCTypeFlag { EnumLike(1056), ESSymbolLike(12288), VoidLike(49152), + Primitive(402784252), DefinitelyNonNullable(470302716), DisjointDomains(469892092), UnionOrIntersection(3145728), @@ -83,12 +83,12 @@ public enum TSCTypeFlag { InstantiablePrimitive(406847488), Instantiable(465829888), StructuredOrInstantiable(469499904), - ObjectFlagsType(3899393), + ObjectFlagsType(138117121), Simplifiable(25165824), Singleton(67358815), Narrowable(536624127), - IncludesMask(205258751), - NotPrimitiveUnion(36323363); + IncludesMask(473694207), + NotPrimitiveUnion(36323331); public final int code; @@ -177,8 +177,6 @@ public static TSCTypeFlag fromMaskExact(int code) { return TSCTypeFlag.PossiblyFalsy; case 67359327: return TSCTypeFlag.Intrinsic; - case 134348796: - return TSCTypeFlag.Primitive; case 402653316: return TSCTypeFlag.StringLike; case 296: @@ -193,6 +191,8 @@ public static TSCTypeFlag fromMaskExact(int code) { return TSCTypeFlag.ESSymbolLike; case 49152: return TSCTypeFlag.VoidLike; + case 402784252: + return TSCTypeFlag.Primitive; case 470302716: return TSCTypeFlag.DefinitelyNonNullable; case 469892092: @@ -211,7 +211,7 @@ public static TSCTypeFlag fromMaskExact(int code) { return TSCTypeFlag.Instantiable; case 469499904: return TSCTypeFlag.StructuredOrInstantiable; - case 3899393: + case 138117121: return TSCTypeFlag.ObjectFlagsType; case 25165824: return TSCTypeFlag.Simplifiable; @@ -219,9 +219,9 @@ public static TSCTypeFlag fromMaskExact(int code) { return TSCTypeFlag.Singleton; case 536624127: return TSCTypeFlag.Narrowable; - case 205258751: + case 473694207: return TSCTypeFlag.IncludesMask; - case 36323363: + case 36323331: return TSCTypeFlag.NotPrimitiveUnion; default: throw new IllegalArgumentException("unknown TSCTypeFlag code: " + code); diff --git a/src/main/resources/javet-jni-classnames.txt b/src/main/resources/javet-jni-classnames.txt index 1356a713..6112a172 100644 --- a/src/main/resources/javet-jni-classnames.txt +++ b/src/main/resources/javet-jni-classnames.txt @@ -16,6 +16,7 @@ com.caoccao.javet.interop.options.NodeRuntimeOptions com.caoccao.javet.interop.options.V8Flags com.caoccao.javet.interop.options.V8RuntimeOptions com.caoccao.javet.utils.JavetResourceUtils +com.caoccao.javet.values.V8Value com.caoccao.javet.values.primitive.V8ValueBigInteger com.caoccao.javet.values.primitive.V8ValueBoolean com.caoccao.javet.values.primitive.V8ValueDouble diff --git a/src/main/resources/tsc/index.js b/src/main/resources/tsc/index.js index c5c39556..d2668784 100644 --- a/src/main/resources/tsc/index.js +++ b/src/main/resources/tsc/index.js @@ -15,29 +15,26 @@ */ var $6N5CW$process = require("process"); + function $parcel$interopDefault(a) { return a && a.__esModule ? a.default : a; } + function $parcel$defineInteropFlag(a) { Object.defineProperty(a, '__esModule', {value: true, configurable: true}); } + function $parcel$export(e, n, v, s) { Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true}); } -var $parcel$global = -typeof globalThis !== 'undefined' - ? globalThis - : typeof self !== 'undefined' - ? self - : typeof window !== 'undefined' - ? window - : typeof global !== 'undefined' - ? global - : {}; + + var $parcel$global = globalThis; + var $parcel$modules = {}; var $parcel$inits = {}; var parcelRequire = $parcel$global["parcelRequire3a9e"]; + if (parcelRequire == null) { parcelRequire = function(id) { if (id in $parcel$modules) { @@ -62,7 +59,9 @@ if (parcelRequire == null) { $parcel$global["parcelRequire3a9e"] = parcelRequire; } -parcelRequire.register("cY7r0", function(module, exports) { + +var parcelRegister = parcelRequire.register; +parcelRegister("cY7r0", function(module, exports) { "use strict"; }); @@ -100,8 +99,8 @@ MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ -var $1b3769ee38aa2ff9$var$__dirname = "node_modules/typescript/lib"; var $1b3769ee38aa2ff9$var$__filename = "node_modules/typescript/lib/typescript.js"; +var $1b3769ee38aa2ff9$var$__dirname = "node_modules/typescript/lib"; "use strict"; @@ -134,8 +133,8 @@ var $1b3769ee38aa2ff9$var$ts = (()=>{ var init_corePublic = __esm({ "src/compiler/corePublic.ts" () { "use strict"; - versionMajorMinor = "5.0"; - version = "5.0.4"; + versionMajorMinor = "5.2"; + version = "5.2.2"; Comparison = /* @__PURE__ */ ((Comparison3)=>{ Comparison3[Comparison3["LessThan"] = -1] = "LessThan"; Comparison3[Comparison3["EqualTo"] = 0] = "EqualTo"; @@ -211,7 +210,7 @@ var $1b3769ee38aa2ff9$var$ts = (()=>{ } function find(array, predicate, startIndex) { if (array === void 0) return void 0; - for(let i = startIndex != null ? startIndex : 0; i < array.length; i++){ + for(let i = startIndex ?? 0; i < array.length; i++){ const value1 = array[i]; if (predicate(value1, i)) return value1; } @@ -219,7 +218,7 @@ var $1b3769ee38aa2ff9$var$ts = (()=>{ } function findLast(array, predicate, startIndex) { if (array === void 0) return void 0; - for(let i = startIndex != null ? startIndex : array.length - 1; i >= 0; i--){ + for(let i = startIndex ?? array.length - 1; i >= 0; i--){ const value1 = array[i]; if (predicate(value1, i)) return value1; } @@ -227,14 +226,14 @@ var $1b3769ee38aa2ff9$var$ts = (()=>{ } function findIndex(array, predicate, startIndex) { if (array === void 0) return -1; - for(let i = startIndex != null ? startIndex : 0; i < array.length; i++){ + for(let i = startIndex ?? 0; i < array.length; i++){ if (predicate(array[i], i)) return i; } return -1; } function findLastIndex(array, predicate, startIndex) { if (array === void 0) return -1; - for(let i = startIndex != null ? startIndex : array.length - 1; i >= 0; i--){ + for(let i = startIndex ?? array.length - 1; i >= 0; i--){ if (predicate(array[i], i)) return i; } return -1; @@ -840,11 +839,10 @@ var $1b3769ee38aa2ff9$var$ts = (()=>{ return arrayFrom(arrayToMultiMap(values, getGroupId).values(), resultSelector); } function groupBy(values, keySelector) { - var _a2; const result = {}; if (values) for (const value1 of values){ const key = `${keySelector(value1)}`; - const array = (_a2 = result[key]) != null ? _a2 : result[key] = []; + const array = result[key] ?? (result[key] = []); array.push(value1); } return result; @@ -887,9 +885,6 @@ var $1b3769ee38aa2ff9$var$ts = (()=>{ if (!values.length) this.delete(key); } } - function createUnderscoreEscapedMultiMap() { - return createMultiMap(); - } function createQueue(items) { const elements = (items == null ? void 0 : items.slice()) || []; let headIndex = 0; @@ -1283,10 +1278,10 @@ var $1b3769ee38aa2ff9$var$ts = (()=>{ } return false; } - function createGetCanonicalFileName(useCaseSensitiveFileNames) { - return useCaseSensitiveFileNames ? identity : toFileNameLowerCase; + function createGetCanonicalFileName(useCaseSensitiveFileNames2) { + return useCaseSensitiveFileNames2 ? identity : toFileNameLowerCase; } - function patternText({ prefix: prefix , suffix: suffix }) { + function patternText({ prefix: prefix, suffix: suffix }) { return `${prefix}*${suffix}`; } function matchedText(pattern, candidate) { @@ -1314,7 +1309,7 @@ var $1b3769ee38aa2ff9$var$ts = (()=>{ function tryRemovePrefix(str, prefix, getCanonicalFileName = identity) { return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : void 0; } - function isPatternMatch({ prefix: prefix , suffix: suffix }, candidate) { + function isPatternMatch({ prefix: prefix, suffix: suffix }, candidate) { return candidate.length >= prefix.length + suffix.length && startsWith(candidate, prefix) && endsWith(candidate, suffix); } function and(f, g) { @@ -1423,9 +1418,9 @@ var $1b3769ee38aa2ff9$var$ts = (()=>{ return s.slice(0, end + 1); } function isNodeLikeSystem() { - return typeof $6N5CW$process !== "undefined" && $6N5CW$process.nextTick && false; + return typeof $6N5CW$process !== "undefined" && !!$6N5CW$process.nextTick && false; } - var emptyArray, emptyMap, emptySet, SortKind, elementAt, hasOwnProperty, noopPush, fileNameLowerCaseRegExp, AssertionLevel, createUIStringComparer, uiComparerCaseSensitive, uiLocale, trimString, trimStringEnd, trimStringStart; + var emptyArray, emptyMap, emptySet, SortKind, elementAt, hasOwnProperty, fileNameLowerCaseRegExp, AssertionLevel, createUIStringComparer, uiComparerCaseSensitive, uiLocale, trimString, trimStringEnd, trimStringStart; var init_core = __esm({ "src/compiler/core.ts" () { "use strict"; @@ -1448,11 +1443,7 @@ var $1b3769ee38aa2ff9$var$ts = (()=>{ return void 0; }; hasOwnProperty = Object.prototype.hasOwnProperty; - noopPush = { - push: noop, - length: 0 - }; - fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g; + fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_. ]+/g; AssertionLevel = /* @__PURE__ */ ((AssertionLevel2)=>{ AssertionLevel2[AssertionLevel2["None"] = 0] = "None"; AssertionLevel2[AssertionLevel2["Normal"] = 1] = "Normal"; @@ -1542,10 +1533,10 @@ var $1b3769ee38aa2ff9$var$ts = (()=>{ } Debug2.log = log; ((_log)=>{ - function error(s) { + function error2(s) { logMessage(1 /* Error */ , s); } - _log.error = error; + _log.error = error2; function warn(s) { logMessage(2 /* Warning */ , s); } @@ -1684,7 +1675,7 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, stackCrawlMark || failBadS else if (hasProperty(func, "name")) return func.name; else { const text = Function.prototype.toString.call(func); - const match = /^function\s+([\w\$]+)\s*\(/.exec(text); + const match = /^function\s+([\w$]+)\s*\(/.exec(text); return match ? match[1] : ""; } } @@ -1737,6 +1728,10 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, stackCrawlMark || failBadS return formatEnum(kind, SnippetKind, /*isFlags*/ false); } Debug2.formatSnippetKind = formatSnippetKind; + function formatScriptKind(kind) { + return formatEnum(kind, ScriptKind, /*isFlags*/ false); + } + Debug2.formatScriptKind = formatScriptKind; function formatNodeFlags(flags) { return formatEnum(flags, NodeFlags, /*isFlags*/ true); } @@ -1905,8 +1900,8 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, stackCrawlMark || failBadS }, __debugSignatureToString: { value () { - var _a2; - return (_a2 = this.checker) == null ? void 0 : _a2.signatureToString(this); + var _a; + return (_a = this.checker) == null ? void 0 : _a.signatureToString(this); } } }); @@ -1981,11 +1976,11 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, stackCrawlMark || failBadS Debug2.formatVariance = formatVariance; class DebugTypeMapper { __debugToString() { - var _a2; + var _a; type(this); switch(this.kind){ case 3 /* Function */ : - return ((_a2 = this.debugInfo) == null ? void 0 : _a2.call(this)) || "(function mapper)"; + return ((_a = this.debugInfo) == null ? void 0 : _a.call(this)) || "(function mapper)"; case 0 /* Simple */ : return `${this.source.__debugTypeToString()} -> ${this.target.__debugTypeToString()}`; case 1 /* Array */ : @@ -2022,17 +2017,17 @@ m2: ${this.mapper2.__debugToString().split("\n").join("\n ")}`; } let BoxCharacter; ((BoxCharacter2)=>{ - BoxCharacter2["lr"] = "─"; - BoxCharacter2["ud"] = "│"; - BoxCharacter2["dr"] = "╭"; - BoxCharacter2["dl"] = "╮"; - BoxCharacter2["ul"] = "╯"; - BoxCharacter2["ur"] = "╰"; - BoxCharacter2["udr"] = "├"; - BoxCharacter2["udl"] = "┤"; - BoxCharacter2["dlr"] = "┬"; - BoxCharacter2["ulr"] = "┴"; - BoxCharacter2["udlr"] = "╫"; + BoxCharacter2["lr"] = "\u2500"; + BoxCharacter2["ud"] = "\u2502"; + BoxCharacter2["dr"] = "\u256D"; + BoxCharacter2["dl"] = "\u256E"; + BoxCharacter2["ul"] = "\u256F"; + BoxCharacter2["ur"] = "\u2570"; + BoxCharacter2["udr"] = "\u251C"; + BoxCharacter2["udl"] = "\u2524"; + BoxCharacter2["dlr"] = "\u252C"; + BoxCharacter2["ulr"] = "\u2534"; + BoxCharacter2["udlr"] = "\u256B"; })(BoxCharacter || (BoxCharacter = {})); let Connection; ((Connection2)=>{ @@ -2240,7 +2235,7 @@ m2: ${this.mapper2.__debugToString().split("\n").join("\n ")}`; } for(let column = 0; column < columnCount; column++)for(let lane = 0; lane < lanes.length; lane++){ const connector = connectors[column][lane]; - const fill2 = connector & 4 /* Left */ ? "─" /* lr */ : " "; + const fill2 = connector & 4 /* Left */ ? "\u2500" /* lr */ : " "; const node = grid[column][lane]; if (!node) { if (column < columnCount - 1) writeLane(lane, repeat(fill2, columnWidths[column] + 1)); @@ -2252,7 +2247,7 @@ m2: ${this.mapper2.__debugToString().split("\n").join("\n ")}`; } } writeLane(lane, getBoxCharacter(connector)); - writeLane(lane, connector & 8 /* Right */ && column < columnCount - 1 && !grid[column + 1][lane] ? "─" /* lr */ : " "); + writeLane(lane, connector & 8 /* Right */ && column < columnCount - 1 && !grid[column + 1][lane] ? "\u2500" /* lr */ : " "); } return ` ${lanes.join("\n")} @@ -2264,27 +2259,27 @@ ${lanes.join("\n")} function getBoxCharacter(connector) { switch(connector){ case 3 /* UpDown */ : - return "│" /* ud */ ; + return "\u2502" /* ud */ ; case 12 /* LeftRight */ : - return "─" /* lr */ ; + return "\u2500" /* lr */ ; case 5 /* UpLeft */ : - return "╯" /* ul */ ; + return "\u256F" /* ul */ ; case 9 /* UpRight */ : - return "╰" /* ur */ ; + return "\u2570" /* ur */ ; case 6 /* DownLeft */ : - return "╮" /* dl */ ; + return "\u256E" /* dl */ ; case 10 /* DownRight */ : - return "╭" /* dr */ ; + return "\u256D" /* dr */ ; case 7 /* UpDownLeft */ : - return "┤" /* udl */ ; + return "\u2524" /* udl */ ; case 11 /* UpDownRight */ : - return "├" /* udr */ ; + return "\u251C" /* udr */ ; case 13 /* UpLeftRight */ : - return "┴" /* ulr */ ; + return "\u2534" /* ulr */ ; case 14 /* DownLeftRight */ : - return "┬" /* dlr */ ; + return "\u252C" /* dlr */ ; case 15 /* UpDownLeftRight */ : - return "╫" /* udlr */ ; + return "\u256B" /* udlr */ ; } return " "; } @@ -2382,7 +2377,7 @@ ${lanes.join("\n")} function parseComparator(operator, text, comparators) { const result = parsePartial(text); if (!result) return false; - const { version: version2 , major: major , minor: minor , patch: patch } = result; + const { version: version2, major: major, minor: minor, patch: patch } = result; if (!isWildcard(major)) switch(operator){ case "~": comparators.push(createComparator(">=", version2)); @@ -2476,17 +2471,17 @@ ${lanes.join("\n")} "src/compiler/semver.ts" () { "use strict"; init_ts2(); - versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; prereleasePartRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)$/i; buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; buildPartRegExp = /^[a-z0-9-]+$/i; numericIdentifierRegExp = /^(0|[1-9]\d*)$/; - _Version = class { + _Version = class _Version { constructor(major, minor = 0, patch = 0, prerelease = "", build2 = ""){ if (typeof major === "string") { const result = Debug.checkDefined(tryParseComponents(major), "Invalid version"); - ({ major: major , minor: minor , patch: patch , prerelease: prerelease , build: build2 } = result); + ({ major: major, minor: minor, patch: patch, prerelease: prerelease, build: build2 } = result); } Debug.assert(major >= 0, "Invalid argument: major"); Debug.assert(minor >= 0, "Invalid argument: minor"); @@ -2504,7 +2499,7 @@ ${lanes.join("\n")} static tryParse(text) { const result = tryParseComponents(text); if (!result) return void 0; - const { major: major , minor: minor , patch: patch , prerelease: prerelease , build: build2 } = result; + const { major: major, minor: minor, patch: patch, prerelease: prerelease, build: build2 } = result; return new _Version(major, minor, patch, prerelease, build2); } compareTo(other) { @@ -2525,7 +2520,7 @@ ${lanes.join("\n")} } } with(fields) { - const { major: major = this.major , minor: minor = this.minor , patch: patch = this.patch , prerelease: prerelease = this.prerelease , build: build2 = this.build } = fields; + const { major: major = this.major, minor: minor = this.minor, patch: patch = this.patch, prerelease: prerelease = this.prerelease, build: build2 = this.build } = fields; return new _Version(major, minor, patch, prerelease, build2); } toString() { @@ -2535,18 +2530,18 @@ ${lanes.join("\n")} return result; } }; - Version = _Version; - Version.zero = new _Version(0, 0, 0, [ + _Version.zero = new _Version(0, 0, 0, [ "0" ]); - VersionRange = class { + Version = _Version; + VersionRange = class _VersionRange { constructor(spec){ this._alternatives = spec ? Debug.checkDefined(parseRange(spec), "Invalid range spec.") : emptyArray; } static tryParse(text) { const sets = parseRange(text); if (sets) { - const range = new VersionRange(""); + const range = new _VersionRange(""); range._alternatives = sets; return range; } @@ -2586,45 +2581,14 @@ ${lanes.join("\n")} } function tryGetNodePerformanceHooks() { if (isNodeLikeSystem()) try { - let performance2; - const { performance: nodePerformance , PerformanceObserver: PerformanceObserver2 } = $1b3769ee38aa2ff9$import$b8c3ce69b7564bfd; - if (hasRequiredAPI(nodePerformance, PerformanceObserver2)) { - performance2 = nodePerformance; - const version2 = new Version($6N5CW$process.versions.node); - const range = new VersionRange("<12.16.3 || 13 <13.13"); - if (range.test(version2)) performance2 = { - get timeOrigin () { - return nodePerformance.timeOrigin; - }, - now () { - return nodePerformance.now(); - }, - mark (name) { - return nodePerformance.mark(name); - }, - measure (name, start = "nodeStart", end) { - if (end === void 0) { - end = "__performance.measure-fix__"; - nodePerformance.mark(end); - } - nodePerformance.measure(name, start, end); - if (end === "__performance.measure-fix__") nodePerformance.clearMarks("__performance.measure-fix__"); - }, - clearMarks (name) { - return nodePerformance.clearMarks(name); - }, - clearMeasures (name) { - return nodePerformance.clearMeasures(name); - } - }; - return { - // By default, only write native events when generating a cpu profile or using the v8 profiler. - shouldWriteNativeEvents: false, - performance: performance2, - PerformanceObserver: PerformanceObserver2 - }; - } - } catch (e) {} + const { performance: performance2, PerformanceObserver: PerformanceObserver2 } = $1b3769ee38aa2ff9$import$306f4689b1de2e8c; + if (hasRequiredAPI(performance2, PerformanceObserver2)) return { + // By default, only write native events when generating a cpu profile or using the v8 profiler. + shouldWriteNativeEvents: false, + performance: performance2, + PerformanceObserver: PerformanceObserver2 + }; + } catch {} } function tryGetNativePerformanceHooks() { return nativePerformanceHooks; @@ -2640,40 +2604,17 @@ ${lanes.join("\n")} } }); // src/compiler/perfLogger.ts - var nullLogger, etwModule, _a, perfLogger; + var etwModule, perfLogger; var init_perfLogger = __esm({ "src/compiler/perfLogger.ts" () { "use strict"; - init_ts2(); - nullLogger = { - logEvent: noop, - logErrEvent: noop, - logPerfEvent: noop, - logInfoEvent: noop, - logStartCommand: noop, - logStopCommand: noop, - logStartUpdateProgram: noop, - logStopUpdateProgram: noop, - logStartUpdateGraph: noop, - logStopUpdateGraph: noop, - logStartResolveModule: noop, - logStopResolveModule: noop, - logStartParseSourceFile: noop, - logStopParseSourceFile: noop, - logStartReadFile: noop, - logStopReadFile: noop, - logStartBindFile: noop, - logStopBindFile: noop, - logStartScheduledOperation: noop, - logStopScheduledOperation: noop - }; try { - const etwModulePath = (_a = undefined, "./node_modules/@microsoft/typescript-etw"); + const etwModulePath = undefined ?? "./node_modules/@microsoft/typescript-etw"; etwModule = require(etwModulePath); } catch (e) { etwModule = void 0; } - perfLogger = (etwModule == null ? void 0 : etwModule.logEvent) ? etwModule : nullLogger; + perfLogger = (etwModule == null ? void 0 : etwModule.logEvent) ? etwModule : void 0; } }); // src/compiler/performance.ts @@ -2697,9 +2638,8 @@ ${lanes.join("\n")} } } function mark(markName) { - var _a2; if (enabled) { - const count = (_a2 = counts.get(markName)) != null ? _a2 : 0; + const count = counts.get(markName) ?? 0; counts.set(markName, count + 1); marks.set(markName, timestamp()); performanceImpl == null || performanceImpl.mark(markName); @@ -2707,10 +2647,9 @@ ${lanes.join("\n")} } } function measure(measureName, startMarkName, endMarkName) { - var _a2, _b; if (enabled) { - const end = (_a2 = endMarkName !== void 0 ? marks.get(endMarkName) : void 0) != null ? _a2 : timestamp(); - const start = (_b = startMarkName !== void 0 ? marks.get(startMarkName) : void 0) != null ? _b : timeorigin; + const end = (endMarkName !== void 0 ? marks.get(endMarkName) : void 0) ?? timestamp(); + const start = (startMarkName !== void 0 ? marks.get(startMarkName) : void 0) ?? timeorigin; const previousDuration = durations.get(measureName) || 0; durations.set(measureName, previousDuration + (end - start)); performanceImpl == null || performanceImpl.measure(measureName, startMarkName, endMarkName); @@ -2747,13 +2686,13 @@ ${lanes.join("\n")} return enabled; } function enable(system = sys) { - var _a2; + var _a; if (!enabled) { enabled = true; perfHooks || (perfHooks = tryGetNativePerformanceHooks()); if (perfHooks) { timeorigin = perfHooks.performance.timeOrigin; - if (perfHooks.shouldWriteNativeEvents || ((_a2 = system == null ? void 0 : system.cpuProfilingEnabled) == null ? void 0 : _a2.call(system)) || (system == null ? void 0 : system.debugMode)) performanceImpl = perfHooks.performance; + if (perfHooks.shouldWriteNativeEvents || ((_a = system == null ? void 0 : system.cpuProfilingEnabled) == null ? void 0 : _a.call(system)) || (system == null ? void 0 : system.debugMode)) performanceImpl = perfHooks.performance; } } return true; @@ -2932,7 +2871,7 @@ ${lanes.join("\n")} tracingEnabled2.popAll = popAll; const sampleInterval = 10000; function writeStackEvent(index, endTime, results) { - const { phase: phase , name: name , args: args , time: time , separateBeginAndEnd: separateBeginAndEnd } = eventStack[index]; + const { phase: phase, name: name, args: args, time: time, separateBeginAndEnd: separateBeginAndEnd } = eventStack[index]; if (separateBeginAndEnd) { Debug.assert(!results, "`results` are not supported for events with `separateBeginAndEnd`"); writeEvent("E", phase, name, args, /*extras*/ void 0, endTime); @@ -2967,7 +2906,7 @@ ${lanes.join("\n")} } } function dumpTypes(types) { - var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v; + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s; mark("beginDumpTypes"); const typesPath = legend[legend.length - 1].typesPath; const typesFd = fs.openSync(typesPath, "w"); @@ -2977,27 +2916,27 @@ ${lanes.join("\n")} for(let i = 0; i < numTypes; i++){ const type = types[i]; const objectFlags = type.objectFlags; - const symbol = (_a2 = type.aliasSymbol) != null ? _a2 : type.symbol; + const symbol = type.aliasSymbol ?? type.symbol; let display; if (objectFlags & 16 /* Anonymous */ | type.flags & 2944 /* Literal */ ) try { - display = (_b = type.checker) == null ? void 0 : _b.typeToString(type); - } catch (e) { + display = (_a = type.checker) == null ? void 0 : _a.typeToString(type); + } catch { display = void 0; } let indexedAccessProperties = {}; if (type.flags & 8388608 /* IndexedAccess */ ) { const indexedAccessType = type; indexedAccessProperties = { - indexedAccessObjectType: (_c = indexedAccessType.objectType) == null ? void 0 : _c.id, - indexedAccessIndexType: (_d = indexedAccessType.indexType) == null ? void 0 : _d.id + indexedAccessObjectType: (_b = indexedAccessType.objectType) == null ? void 0 : _b.id, + indexedAccessIndexType: (_c = indexedAccessType.indexType) == null ? void 0 : _c.id }; } let referenceProperties = {}; if (objectFlags & 4 /* Reference */ ) { const referenceType = type; referenceProperties = { - instantiatedType: (_e = referenceType.target) == null ? void 0 : _e.id, - typeArguments: (_f = referenceType.resolvedTypeArguments) == null ? void 0 : _f.map((t)=>t.id), + instantiatedType: (_d = referenceType.target) == null ? void 0 : _d.id, + typeArguments: (_e = referenceType.resolvedTypeArguments) == null ? void 0 : _e.map((t)=>t.id), referenceLocation: getLocation(referenceType.node) }; } @@ -3005,27 +2944,27 @@ ${lanes.join("\n")} if (type.flags & 16777216 /* Conditional */ ) { const conditionalType = type; conditionalProperties = { - conditionalCheckType: (_g = conditionalType.checkType) == null ? void 0 : _g.id, - conditionalExtendsType: (_h = conditionalType.extendsType) == null ? void 0 : _h.id, - conditionalTrueType: (_j = (_i = conditionalType.resolvedTrueType) == null ? void 0 : _i.id) != null ? _j : -1, - conditionalFalseType: (_l = (_k = conditionalType.resolvedFalseType) == null ? void 0 : _k.id) != null ? _l : -1 + conditionalCheckType: (_f = conditionalType.checkType) == null ? void 0 : _f.id, + conditionalExtendsType: (_g = conditionalType.extendsType) == null ? void 0 : _g.id, + conditionalTrueType: ((_h = conditionalType.resolvedTrueType) == null ? void 0 : _h.id) ?? -1, + conditionalFalseType: ((_i = conditionalType.resolvedFalseType) == null ? void 0 : _i.id) ?? -1 }; } let substitutionProperties = {}; if (type.flags & 33554432 /* Substitution */ ) { const substitutionType = type; substitutionProperties = { - substitutionBaseType: (_m = substitutionType.baseType) == null ? void 0 : _m.id, - constraintType: (_n = substitutionType.constraint) == null ? void 0 : _n.id + substitutionBaseType: (_j = substitutionType.baseType) == null ? void 0 : _j.id, + constraintType: (_k = substitutionType.constraint) == null ? void 0 : _k.id }; } let reverseMappedProperties = {}; if (objectFlags & 1024 /* ReverseMapped */ ) { const reverseMappedType = type; reverseMappedProperties = { - reverseMappedSourceType: (_o = reverseMappedType.source) == null ? void 0 : _o.id, - reverseMappedMappedType: (_p = reverseMappedType.mappedType) == null ? void 0 : _p.id, - reverseMappedConstraintType: (_q = reverseMappedType.constraintType) == null ? void 0 : _q.id + reverseMappedSourceType: (_l = reverseMappedType.source) == null ? void 0 : _l.id, + reverseMappedMappedType: (_m = reverseMappedType.mappedType) == null ? void 0 : _m.id, + reverseMappedConstraintType: (_n = reverseMappedType.constraintType) == null ? void 0 : _n.id }; } let evolvingArrayProperties = {}; @@ -3033,7 +2972,7 @@ ${lanes.join("\n")} const evolvingArrayType = type; evolvingArrayProperties = { evolvingArrayElementType: evolvingArrayType.elementType.id, - evolvingArrayFinalType: (_r = evolvingArrayType.finalArrayType) == null ? void 0 : _r.id + evolvingArrayFinalType: (_o = evolvingArrayType.finalArrayType) == null ? void 0 : _o.id }; } let recursionToken; @@ -3051,10 +2990,10 @@ ${lanes.join("\n")} symbolName: (symbol == null ? void 0 : symbol.escapedName) && unescapeLeadingUnderscores(symbol.escapedName), recursionId: recursionToken, isTuple: objectFlags & 8 /* Tuple */ ? true : void 0, - unionTypes: type.flags & 1048576 /* Union */ ? (_s = type.types) == null ? void 0 : _s.map((t)=>t.id) : void 0, + unionTypes: type.flags & 1048576 /* Union */ ? (_p = type.types) == null ? void 0 : _p.map((t)=>t.id) : void 0, intersectionTypes: type.flags & 2097152 /* Intersection */ ? type.types.map((t)=>t.id) : void 0, - aliasTypeArguments: (_t = type.aliasTypeArguments) == null ? void 0 : _t.map((t)=>t.id), - keyofType: type.flags & 4194304 /* Index */ ? (_u = type.type) == null ? void 0 : _u.id : void 0, + aliasTypeArguments: (_q = type.aliasTypeArguments) == null ? void 0 : _q.map((t)=>t.id), + keyofType: type.flags & 4194304 /* Index */ ? (_r = type.type) == null ? void 0 : _r.id : void 0, ...indexedAccessProperties, ...referenceProperties, ...conditionalProperties, @@ -3062,7 +3001,7 @@ ${lanes.join("\n")} ...reverseMappedProperties, ...evolvingArrayProperties, destructuringPattern: getLocation(type.pattern), - firstDeclaration: getLocation((_v = symbol == null ? void 0 : symbol.declarations) == null ? void 0 : _v[0]), + firstDeclaration: getLocation((_s = symbol == null ? void 0 : symbol.declarations) == null ? void 0 : _s[0]), flags: Debug.formatTypeFlags(type.flags).split("|"), display: display }; @@ -3089,7 +3028,7 @@ ${lanes.join("\n")} const name = DiagnosticCategory[d.category]; return lowerCase ? name.toLowerCase() : name; } - var SyntaxKind, NodeFlags, ModifierFlags, JsxFlags, RelationComparisonResult, GeneratedIdentifierFlags, TokenFlags, FlowFlags, CommentDirectiveType, OperationCanceledException, FileIncludeKind, FilePreprocessingDiagnosticsKind, EmitOnly, StructureIsReused, ExitStatus, MemberOverrideStatus, UnionReduction, ContextFlags, NodeBuilderFlags, TypeFormatFlags, SymbolFormatFlags, SymbolAccessibility, SyntheticSymbolKind, TypePredicateKind, TypeReferenceSerializationKind, SymbolFlags, EnumKind, CheckFlags, InternalSymbolName, NodeCheckFlags, TypeFlags, ObjectFlags, VarianceFlags, ElementFlags, AccessFlags, JsxReferenceKind, SignatureKind, SignatureFlags, IndexKind, TypeMapKind, InferencePriority, InferenceFlags, Ternary, AssignmentDeclarationKind, DiagnosticCategory, ModuleResolutionKind, ModuleDetectionKind, WatchFileKind, WatchDirectoryKind, PollingWatchKind, ModuleKind, JsxEmit, ImportsNotUsedAsValues, NewLineKind, ScriptKind, ScriptTarget, LanguageVariant, WatchDirectoryFlags, CharacterCodes, Extension, TransformFlags, SnippetKind, EmitFlags, InternalEmitFlags, ExternalEmitHelpers, EmitHint, OuterExpressionKinds, LexicalEnvironmentFlags, BundleFileSectionKind, ListFormat, PragmaKindFlags, commentPragmas; + var SyntaxKind, NodeFlags, ModifierFlags, JsxFlags, RelationComparisonResult, GeneratedIdentifierFlags, TokenFlags, FlowFlags, CommentDirectiveType, OperationCanceledException, FileIncludeKind, FilePreprocessingDiagnosticsKind, EmitOnly, StructureIsReused, ExitStatus, MemberOverrideStatus, UnionReduction, ContextFlags, NodeBuilderFlags, TypeFormatFlags, SymbolFormatFlags, SymbolAccessibility, SyntheticSymbolKind, TypePredicateKind, TypeReferenceSerializationKind, SymbolFlags, EnumKind, CheckFlags, InternalSymbolName, NodeCheckFlags, TypeFlags, ObjectFlags, VarianceFlags, ElementFlags, AccessFlags, IndexFlags, JsxReferenceKind, SignatureKind, SignatureFlags, IndexKind, TypeMapKind, InferencePriority, InferenceFlags, Ternary, AssignmentDeclarationKind, DiagnosticCategory, ModuleResolutionKind, ModuleDetectionKind, WatchFileKind, WatchDirectoryKind, PollingWatchKind, ModuleKind, JsxEmit, ImportsNotUsedAsValues, NewLineKind, ScriptKind, ScriptTarget, LanguageVariant, WatchDirectoryFlags, CharacterCodes, Extension, TransformFlags, SnippetKind, EmitFlags, InternalEmitFlags, ExternalEmitHelpers, EmitHint, OuterExpressionKinds, LexicalEnvironmentFlags, BundleFileSectionKind, ListFormat, PragmaKindFlags, commentPragmas; var init_types = __esm({ "src/compiler/types.ts" () { "use strict"; @@ -3102,435 +3041,440 @@ ${lanes.join("\n")} SyntaxKind5[SyntaxKind5["WhitespaceTrivia"] = 5] = "WhitespaceTrivia"; SyntaxKind5[SyntaxKind5["ShebangTrivia"] = 6] = "ShebangTrivia"; SyntaxKind5[SyntaxKind5["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia"; - SyntaxKind5[SyntaxKind5["NumericLiteral"] = 8] = "NumericLiteral"; - SyntaxKind5[SyntaxKind5["BigIntLiteral"] = 9] = "BigIntLiteral"; - SyntaxKind5[SyntaxKind5["StringLiteral"] = 10] = "StringLiteral"; - SyntaxKind5[SyntaxKind5["JsxText"] = 11] = "JsxText"; - SyntaxKind5[SyntaxKind5["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces"; - SyntaxKind5[SyntaxKind5["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral"; - SyntaxKind5[SyntaxKind5["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral"; - SyntaxKind5[SyntaxKind5["TemplateHead"] = 15] = "TemplateHead"; - SyntaxKind5[SyntaxKind5["TemplateMiddle"] = 16] = "TemplateMiddle"; - SyntaxKind5[SyntaxKind5["TemplateTail"] = 17] = "TemplateTail"; - SyntaxKind5[SyntaxKind5["OpenBraceToken"] = 18] = "OpenBraceToken"; - SyntaxKind5[SyntaxKind5["CloseBraceToken"] = 19] = "CloseBraceToken"; - SyntaxKind5[SyntaxKind5["OpenParenToken"] = 20] = "OpenParenToken"; - SyntaxKind5[SyntaxKind5["CloseParenToken"] = 21] = "CloseParenToken"; - SyntaxKind5[SyntaxKind5["OpenBracketToken"] = 22] = "OpenBracketToken"; - SyntaxKind5[SyntaxKind5["CloseBracketToken"] = 23] = "CloseBracketToken"; - SyntaxKind5[SyntaxKind5["DotToken"] = 24] = "DotToken"; - SyntaxKind5[SyntaxKind5["DotDotDotToken"] = 25] = "DotDotDotToken"; - SyntaxKind5[SyntaxKind5["SemicolonToken"] = 26] = "SemicolonToken"; - SyntaxKind5[SyntaxKind5["CommaToken"] = 27] = "CommaToken"; - SyntaxKind5[SyntaxKind5["QuestionDotToken"] = 28] = "QuestionDotToken"; - SyntaxKind5[SyntaxKind5["LessThanToken"] = 29] = "LessThanToken"; - SyntaxKind5[SyntaxKind5["LessThanSlashToken"] = 30] = "LessThanSlashToken"; - SyntaxKind5[SyntaxKind5["GreaterThanToken"] = 31] = "GreaterThanToken"; - SyntaxKind5[SyntaxKind5["LessThanEqualsToken"] = 32] = "LessThanEqualsToken"; - SyntaxKind5[SyntaxKind5["GreaterThanEqualsToken"] = 33] = "GreaterThanEqualsToken"; - SyntaxKind5[SyntaxKind5["EqualsEqualsToken"] = 34] = "EqualsEqualsToken"; - SyntaxKind5[SyntaxKind5["ExclamationEqualsToken"] = 35] = "ExclamationEqualsToken"; - SyntaxKind5[SyntaxKind5["EqualsEqualsEqualsToken"] = 36] = "EqualsEqualsEqualsToken"; - SyntaxKind5[SyntaxKind5["ExclamationEqualsEqualsToken"] = 37] = "ExclamationEqualsEqualsToken"; - SyntaxKind5[SyntaxKind5["EqualsGreaterThanToken"] = 38] = "EqualsGreaterThanToken"; - SyntaxKind5[SyntaxKind5["PlusToken"] = 39] = "PlusToken"; - SyntaxKind5[SyntaxKind5["MinusToken"] = 40] = "MinusToken"; - SyntaxKind5[SyntaxKind5["AsteriskToken"] = 41] = "AsteriskToken"; - SyntaxKind5[SyntaxKind5["AsteriskAsteriskToken"] = 42] = "AsteriskAsteriskToken"; - SyntaxKind5[SyntaxKind5["SlashToken"] = 43] = "SlashToken"; - SyntaxKind5[SyntaxKind5["PercentToken"] = 44] = "PercentToken"; - SyntaxKind5[SyntaxKind5["PlusPlusToken"] = 45] = "PlusPlusToken"; - SyntaxKind5[SyntaxKind5["MinusMinusToken"] = 46] = "MinusMinusToken"; - SyntaxKind5[SyntaxKind5["LessThanLessThanToken"] = 47] = "LessThanLessThanToken"; - SyntaxKind5[SyntaxKind5["GreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanToken"; - SyntaxKind5[SyntaxKind5["GreaterThanGreaterThanGreaterThanToken"] = 49] = "GreaterThanGreaterThanGreaterThanToken"; - SyntaxKind5[SyntaxKind5["AmpersandToken"] = 50] = "AmpersandToken"; - SyntaxKind5[SyntaxKind5["BarToken"] = 51] = "BarToken"; - SyntaxKind5[SyntaxKind5["CaretToken"] = 52] = "CaretToken"; - SyntaxKind5[SyntaxKind5["ExclamationToken"] = 53] = "ExclamationToken"; - SyntaxKind5[SyntaxKind5["TildeToken"] = 54] = "TildeToken"; - SyntaxKind5[SyntaxKind5["AmpersandAmpersandToken"] = 55] = "AmpersandAmpersandToken"; - SyntaxKind5[SyntaxKind5["BarBarToken"] = 56] = "BarBarToken"; - SyntaxKind5[SyntaxKind5["QuestionToken"] = 57] = "QuestionToken"; - SyntaxKind5[SyntaxKind5["ColonToken"] = 58] = "ColonToken"; - SyntaxKind5[SyntaxKind5["AtToken"] = 59] = "AtToken"; - SyntaxKind5[SyntaxKind5["QuestionQuestionToken"] = 60] = "QuestionQuestionToken"; - SyntaxKind5[SyntaxKind5["BacktickToken"] = 61] = "BacktickToken"; - SyntaxKind5[SyntaxKind5["HashToken"] = 62] = "HashToken"; - SyntaxKind5[SyntaxKind5["EqualsToken"] = 63] = "EqualsToken"; - SyntaxKind5[SyntaxKind5["PlusEqualsToken"] = 64] = "PlusEqualsToken"; - SyntaxKind5[SyntaxKind5["MinusEqualsToken"] = 65] = "MinusEqualsToken"; - SyntaxKind5[SyntaxKind5["AsteriskEqualsToken"] = 66] = "AsteriskEqualsToken"; - SyntaxKind5[SyntaxKind5["AsteriskAsteriskEqualsToken"] = 67] = "AsteriskAsteriskEqualsToken"; - SyntaxKind5[SyntaxKind5["SlashEqualsToken"] = 68] = "SlashEqualsToken"; - SyntaxKind5[SyntaxKind5["PercentEqualsToken"] = 69] = "PercentEqualsToken"; - SyntaxKind5[SyntaxKind5["LessThanLessThanEqualsToken"] = 70] = "LessThanLessThanEqualsToken"; - SyntaxKind5[SyntaxKind5["GreaterThanGreaterThanEqualsToken"] = 71] = "GreaterThanGreaterThanEqualsToken"; - SyntaxKind5[SyntaxKind5["GreaterThanGreaterThanGreaterThanEqualsToken"] = 72] = "GreaterThanGreaterThanGreaterThanEqualsToken"; - SyntaxKind5[SyntaxKind5["AmpersandEqualsToken"] = 73] = "AmpersandEqualsToken"; - SyntaxKind5[SyntaxKind5["BarEqualsToken"] = 74] = "BarEqualsToken"; - SyntaxKind5[SyntaxKind5["BarBarEqualsToken"] = 75] = "BarBarEqualsToken"; - SyntaxKind5[SyntaxKind5["AmpersandAmpersandEqualsToken"] = 76] = "AmpersandAmpersandEqualsToken"; - SyntaxKind5[SyntaxKind5["QuestionQuestionEqualsToken"] = 77] = "QuestionQuestionEqualsToken"; - SyntaxKind5[SyntaxKind5["CaretEqualsToken"] = 78] = "CaretEqualsToken"; - SyntaxKind5[SyntaxKind5["Identifier"] = 79] = "Identifier"; - SyntaxKind5[SyntaxKind5["PrivateIdentifier"] = 80] = "PrivateIdentifier"; - SyntaxKind5[SyntaxKind5["BreakKeyword"] = 81] = "BreakKeyword"; - SyntaxKind5[SyntaxKind5["CaseKeyword"] = 82] = "CaseKeyword"; - SyntaxKind5[SyntaxKind5["CatchKeyword"] = 83] = "CatchKeyword"; - SyntaxKind5[SyntaxKind5["ClassKeyword"] = 84] = "ClassKeyword"; - SyntaxKind5[SyntaxKind5["ConstKeyword"] = 85] = "ConstKeyword"; - SyntaxKind5[SyntaxKind5["ContinueKeyword"] = 86] = "ContinueKeyword"; - SyntaxKind5[SyntaxKind5["DebuggerKeyword"] = 87] = "DebuggerKeyword"; - SyntaxKind5[SyntaxKind5["DefaultKeyword"] = 88] = "DefaultKeyword"; - SyntaxKind5[SyntaxKind5["DeleteKeyword"] = 89] = "DeleteKeyword"; - SyntaxKind5[SyntaxKind5["DoKeyword"] = 90] = "DoKeyword"; - SyntaxKind5[SyntaxKind5["ElseKeyword"] = 91] = "ElseKeyword"; - SyntaxKind5[SyntaxKind5["EnumKeyword"] = 92] = "EnumKeyword"; - SyntaxKind5[SyntaxKind5["ExportKeyword"] = 93] = "ExportKeyword"; - SyntaxKind5[SyntaxKind5["ExtendsKeyword"] = 94] = "ExtendsKeyword"; - SyntaxKind5[SyntaxKind5["FalseKeyword"] = 95] = "FalseKeyword"; - SyntaxKind5[SyntaxKind5["FinallyKeyword"] = 96] = "FinallyKeyword"; - SyntaxKind5[SyntaxKind5["ForKeyword"] = 97] = "ForKeyword"; - SyntaxKind5[SyntaxKind5["FunctionKeyword"] = 98] = "FunctionKeyword"; - SyntaxKind5[SyntaxKind5["IfKeyword"] = 99] = "IfKeyword"; - SyntaxKind5[SyntaxKind5["ImportKeyword"] = 100] = "ImportKeyword"; - SyntaxKind5[SyntaxKind5["InKeyword"] = 101] = "InKeyword"; - SyntaxKind5[SyntaxKind5["InstanceOfKeyword"] = 102] = "InstanceOfKeyword"; - SyntaxKind5[SyntaxKind5["NewKeyword"] = 103] = "NewKeyword"; - SyntaxKind5[SyntaxKind5["NullKeyword"] = 104] = "NullKeyword"; - SyntaxKind5[SyntaxKind5["ReturnKeyword"] = 105] = "ReturnKeyword"; - SyntaxKind5[SyntaxKind5["SuperKeyword"] = 106] = "SuperKeyword"; - SyntaxKind5[SyntaxKind5["SwitchKeyword"] = 107] = "SwitchKeyword"; - SyntaxKind5[SyntaxKind5["ThisKeyword"] = 108] = "ThisKeyword"; - SyntaxKind5[SyntaxKind5["ThrowKeyword"] = 109] = "ThrowKeyword"; - SyntaxKind5[SyntaxKind5["TrueKeyword"] = 110] = "TrueKeyword"; - SyntaxKind5[SyntaxKind5["TryKeyword"] = 111] = "TryKeyword"; - SyntaxKind5[SyntaxKind5["TypeOfKeyword"] = 112] = "TypeOfKeyword"; - SyntaxKind5[SyntaxKind5["VarKeyword"] = 113] = "VarKeyword"; - SyntaxKind5[SyntaxKind5["VoidKeyword"] = 114] = "VoidKeyword"; - SyntaxKind5[SyntaxKind5["WhileKeyword"] = 115] = "WhileKeyword"; - SyntaxKind5[SyntaxKind5["WithKeyword"] = 116] = "WithKeyword"; - SyntaxKind5[SyntaxKind5["ImplementsKeyword"] = 117] = "ImplementsKeyword"; - SyntaxKind5[SyntaxKind5["InterfaceKeyword"] = 118] = "InterfaceKeyword"; - SyntaxKind5[SyntaxKind5["LetKeyword"] = 119] = "LetKeyword"; - SyntaxKind5[SyntaxKind5["PackageKeyword"] = 120] = "PackageKeyword"; - SyntaxKind5[SyntaxKind5["PrivateKeyword"] = 121] = "PrivateKeyword"; - SyntaxKind5[SyntaxKind5["ProtectedKeyword"] = 122] = "ProtectedKeyword"; - SyntaxKind5[SyntaxKind5["PublicKeyword"] = 123] = "PublicKeyword"; - SyntaxKind5[SyntaxKind5["StaticKeyword"] = 124] = "StaticKeyword"; - SyntaxKind5[SyntaxKind5["YieldKeyword"] = 125] = "YieldKeyword"; - SyntaxKind5[SyntaxKind5["AbstractKeyword"] = 126] = "AbstractKeyword"; - SyntaxKind5[SyntaxKind5["AccessorKeyword"] = 127] = "AccessorKeyword"; - SyntaxKind5[SyntaxKind5["AsKeyword"] = 128] = "AsKeyword"; - SyntaxKind5[SyntaxKind5["AssertsKeyword"] = 129] = "AssertsKeyword"; - SyntaxKind5[SyntaxKind5["AssertKeyword"] = 130] = "AssertKeyword"; - SyntaxKind5[SyntaxKind5["AnyKeyword"] = 131] = "AnyKeyword"; - SyntaxKind5[SyntaxKind5["AsyncKeyword"] = 132] = "AsyncKeyword"; - SyntaxKind5[SyntaxKind5["AwaitKeyword"] = 133] = "AwaitKeyword"; - SyntaxKind5[SyntaxKind5["BooleanKeyword"] = 134] = "BooleanKeyword"; - SyntaxKind5[SyntaxKind5["ConstructorKeyword"] = 135] = "ConstructorKeyword"; - SyntaxKind5[SyntaxKind5["DeclareKeyword"] = 136] = "DeclareKeyword"; - SyntaxKind5[SyntaxKind5["GetKeyword"] = 137] = "GetKeyword"; - SyntaxKind5[SyntaxKind5["InferKeyword"] = 138] = "InferKeyword"; - SyntaxKind5[SyntaxKind5["IntrinsicKeyword"] = 139] = "IntrinsicKeyword"; - SyntaxKind5[SyntaxKind5["IsKeyword"] = 140] = "IsKeyword"; - SyntaxKind5[SyntaxKind5["KeyOfKeyword"] = 141] = "KeyOfKeyword"; - SyntaxKind5[SyntaxKind5["ModuleKeyword"] = 142] = "ModuleKeyword"; - SyntaxKind5[SyntaxKind5["NamespaceKeyword"] = 143] = "NamespaceKeyword"; - SyntaxKind5[SyntaxKind5["NeverKeyword"] = 144] = "NeverKeyword"; - SyntaxKind5[SyntaxKind5["OutKeyword"] = 145] = "OutKeyword"; - SyntaxKind5[SyntaxKind5["ReadonlyKeyword"] = 146] = "ReadonlyKeyword"; - SyntaxKind5[SyntaxKind5["RequireKeyword"] = 147] = "RequireKeyword"; - SyntaxKind5[SyntaxKind5["NumberKeyword"] = 148] = "NumberKeyword"; - SyntaxKind5[SyntaxKind5["ObjectKeyword"] = 149] = "ObjectKeyword"; - SyntaxKind5[SyntaxKind5["SatisfiesKeyword"] = 150] = "SatisfiesKeyword"; - SyntaxKind5[SyntaxKind5["SetKeyword"] = 151] = "SetKeyword"; - SyntaxKind5[SyntaxKind5["StringKeyword"] = 152] = "StringKeyword"; - SyntaxKind5[SyntaxKind5["SymbolKeyword"] = 153] = "SymbolKeyword"; - SyntaxKind5[SyntaxKind5["TypeKeyword"] = 154] = "TypeKeyword"; - SyntaxKind5[SyntaxKind5["UndefinedKeyword"] = 155] = "UndefinedKeyword"; - SyntaxKind5[SyntaxKind5["UniqueKeyword"] = 156] = "UniqueKeyword"; - SyntaxKind5[SyntaxKind5["UnknownKeyword"] = 157] = "UnknownKeyword"; - SyntaxKind5[SyntaxKind5["FromKeyword"] = 158] = "FromKeyword"; - SyntaxKind5[SyntaxKind5["GlobalKeyword"] = 159] = "GlobalKeyword"; - SyntaxKind5[SyntaxKind5["BigIntKeyword"] = 160] = "BigIntKeyword"; - SyntaxKind5[SyntaxKind5["OverrideKeyword"] = 161] = "OverrideKeyword"; - SyntaxKind5[SyntaxKind5["OfKeyword"] = 162] = "OfKeyword"; - SyntaxKind5[SyntaxKind5["QualifiedName"] = 163] = "QualifiedName"; - SyntaxKind5[SyntaxKind5["ComputedPropertyName"] = 164] = "ComputedPropertyName"; - SyntaxKind5[SyntaxKind5["TypeParameter"] = 165] = "TypeParameter"; - SyntaxKind5[SyntaxKind5["Parameter"] = 166] = "Parameter"; - SyntaxKind5[SyntaxKind5["Decorator"] = 167] = "Decorator"; - SyntaxKind5[SyntaxKind5["PropertySignature"] = 168] = "PropertySignature"; - SyntaxKind5[SyntaxKind5["PropertyDeclaration"] = 169] = "PropertyDeclaration"; - SyntaxKind5[SyntaxKind5["MethodSignature"] = 170] = "MethodSignature"; - SyntaxKind5[SyntaxKind5["MethodDeclaration"] = 171] = "MethodDeclaration"; - SyntaxKind5[SyntaxKind5["ClassStaticBlockDeclaration"] = 172] = "ClassStaticBlockDeclaration"; - SyntaxKind5[SyntaxKind5["Constructor"] = 173] = "Constructor"; - SyntaxKind5[SyntaxKind5["GetAccessor"] = 174] = "GetAccessor"; - SyntaxKind5[SyntaxKind5["SetAccessor"] = 175] = "SetAccessor"; - SyntaxKind5[SyntaxKind5["CallSignature"] = 176] = "CallSignature"; - SyntaxKind5[SyntaxKind5["ConstructSignature"] = 177] = "ConstructSignature"; - SyntaxKind5[SyntaxKind5["IndexSignature"] = 178] = "IndexSignature"; - SyntaxKind5[SyntaxKind5["TypePredicate"] = 179] = "TypePredicate"; - SyntaxKind5[SyntaxKind5["TypeReference"] = 180] = "TypeReference"; - SyntaxKind5[SyntaxKind5["FunctionType"] = 181] = "FunctionType"; - SyntaxKind5[SyntaxKind5["ConstructorType"] = 182] = "ConstructorType"; - SyntaxKind5[SyntaxKind5["TypeQuery"] = 183] = "TypeQuery"; - SyntaxKind5[SyntaxKind5["TypeLiteral"] = 184] = "TypeLiteral"; - SyntaxKind5[SyntaxKind5["ArrayType"] = 185] = "ArrayType"; - SyntaxKind5[SyntaxKind5["TupleType"] = 186] = "TupleType"; - SyntaxKind5[SyntaxKind5["OptionalType"] = 187] = "OptionalType"; - SyntaxKind5[SyntaxKind5["RestType"] = 188] = "RestType"; - SyntaxKind5[SyntaxKind5["UnionType"] = 189] = "UnionType"; - SyntaxKind5[SyntaxKind5["IntersectionType"] = 190] = "IntersectionType"; - SyntaxKind5[SyntaxKind5["ConditionalType"] = 191] = "ConditionalType"; - SyntaxKind5[SyntaxKind5["InferType"] = 192] = "InferType"; - SyntaxKind5[SyntaxKind5["ParenthesizedType"] = 193] = "ParenthesizedType"; - SyntaxKind5[SyntaxKind5["ThisType"] = 194] = "ThisType"; - SyntaxKind5[SyntaxKind5["TypeOperator"] = 195] = "TypeOperator"; - SyntaxKind5[SyntaxKind5["IndexedAccessType"] = 196] = "IndexedAccessType"; - SyntaxKind5[SyntaxKind5["MappedType"] = 197] = "MappedType"; - SyntaxKind5[SyntaxKind5["LiteralType"] = 198] = "LiteralType"; - SyntaxKind5[SyntaxKind5["NamedTupleMember"] = 199] = "NamedTupleMember"; - SyntaxKind5[SyntaxKind5["TemplateLiteralType"] = 200] = "TemplateLiteralType"; - SyntaxKind5[SyntaxKind5["TemplateLiteralTypeSpan"] = 201] = "TemplateLiteralTypeSpan"; - SyntaxKind5[SyntaxKind5["ImportType"] = 202] = "ImportType"; - SyntaxKind5[SyntaxKind5["ObjectBindingPattern"] = 203] = "ObjectBindingPattern"; - SyntaxKind5[SyntaxKind5["ArrayBindingPattern"] = 204] = "ArrayBindingPattern"; - SyntaxKind5[SyntaxKind5["BindingElement"] = 205] = "BindingElement"; - SyntaxKind5[SyntaxKind5["ArrayLiteralExpression"] = 206] = "ArrayLiteralExpression"; - SyntaxKind5[SyntaxKind5["ObjectLiteralExpression"] = 207] = "ObjectLiteralExpression"; - SyntaxKind5[SyntaxKind5["PropertyAccessExpression"] = 208] = "PropertyAccessExpression"; - SyntaxKind5[SyntaxKind5["ElementAccessExpression"] = 209] = "ElementAccessExpression"; - SyntaxKind5[SyntaxKind5["CallExpression"] = 210] = "CallExpression"; - SyntaxKind5[SyntaxKind5["NewExpression"] = 211] = "NewExpression"; - SyntaxKind5[SyntaxKind5["TaggedTemplateExpression"] = 212] = "TaggedTemplateExpression"; - SyntaxKind5[SyntaxKind5["TypeAssertionExpression"] = 213] = "TypeAssertionExpression"; - SyntaxKind5[SyntaxKind5["ParenthesizedExpression"] = 214] = "ParenthesizedExpression"; - SyntaxKind5[SyntaxKind5["FunctionExpression"] = 215] = "FunctionExpression"; - SyntaxKind5[SyntaxKind5["ArrowFunction"] = 216] = "ArrowFunction"; - SyntaxKind5[SyntaxKind5["DeleteExpression"] = 217] = "DeleteExpression"; - SyntaxKind5[SyntaxKind5["TypeOfExpression"] = 218] = "TypeOfExpression"; - SyntaxKind5[SyntaxKind5["VoidExpression"] = 219] = "VoidExpression"; - SyntaxKind5[SyntaxKind5["AwaitExpression"] = 220] = "AwaitExpression"; - SyntaxKind5[SyntaxKind5["PrefixUnaryExpression"] = 221] = "PrefixUnaryExpression"; - SyntaxKind5[SyntaxKind5["PostfixUnaryExpression"] = 222] = "PostfixUnaryExpression"; - SyntaxKind5[SyntaxKind5["BinaryExpression"] = 223] = "BinaryExpression"; - SyntaxKind5[SyntaxKind5["ConditionalExpression"] = 224] = "ConditionalExpression"; - SyntaxKind5[SyntaxKind5["TemplateExpression"] = 225] = "TemplateExpression"; - SyntaxKind5[SyntaxKind5["YieldExpression"] = 226] = "YieldExpression"; - SyntaxKind5[SyntaxKind5["SpreadElement"] = 227] = "SpreadElement"; - SyntaxKind5[SyntaxKind5["ClassExpression"] = 228] = "ClassExpression"; - SyntaxKind5[SyntaxKind5["OmittedExpression"] = 229] = "OmittedExpression"; - SyntaxKind5[SyntaxKind5["ExpressionWithTypeArguments"] = 230] = "ExpressionWithTypeArguments"; - SyntaxKind5[SyntaxKind5["AsExpression"] = 231] = "AsExpression"; - SyntaxKind5[SyntaxKind5["NonNullExpression"] = 232] = "NonNullExpression"; - SyntaxKind5[SyntaxKind5["MetaProperty"] = 233] = "MetaProperty"; - SyntaxKind5[SyntaxKind5["SyntheticExpression"] = 234] = "SyntheticExpression"; - SyntaxKind5[SyntaxKind5["SatisfiesExpression"] = 235] = "SatisfiesExpression"; - SyntaxKind5[SyntaxKind5["TemplateSpan"] = 236] = "TemplateSpan"; - SyntaxKind5[SyntaxKind5["SemicolonClassElement"] = 237] = "SemicolonClassElement"; - SyntaxKind5[SyntaxKind5["Block"] = 238] = "Block"; - SyntaxKind5[SyntaxKind5["EmptyStatement"] = 239] = "EmptyStatement"; - SyntaxKind5[SyntaxKind5["VariableStatement"] = 240] = "VariableStatement"; - SyntaxKind5[SyntaxKind5["ExpressionStatement"] = 241] = "ExpressionStatement"; - SyntaxKind5[SyntaxKind5["IfStatement"] = 242] = "IfStatement"; - SyntaxKind5[SyntaxKind5["DoStatement"] = 243] = "DoStatement"; - SyntaxKind5[SyntaxKind5["WhileStatement"] = 244] = "WhileStatement"; - SyntaxKind5[SyntaxKind5["ForStatement"] = 245] = "ForStatement"; - SyntaxKind5[SyntaxKind5["ForInStatement"] = 246] = "ForInStatement"; - SyntaxKind5[SyntaxKind5["ForOfStatement"] = 247] = "ForOfStatement"; - SyntaxKind5[SyntaxKind5["ContinueStatement"] = 248] = "ContinueStatement"; - SyntaxKind5[SyntaxKind5["BreakStatement"] = 249] = "BreakStatement"; - SyntaxKind5[SyntaxKind5["ReturnStatement"] = 250] = "ReturnStatement"; - SyntaxKind5[SyntaxKind5["WithStatement"] = 251] = "WithStatement"; - SyntaxKind5[SyntaxKind5["SwitchStatement"] = 252] = "SwitchStatement"; - SyntaxKind5[SyntaxKind5["LabeledStatement"] = 253] = "LabeledStatement"; - SyntaxKind5[SyntaxKind5["ThrowStatement"] = 254] = "ThrowStatement"; - SyntaxKind5[SyntaxKind5["TryStatement"] = 255] = "TryStatement"; - SyntaxKind5[SyntaxKind5["DebuggerStatement"] = 256] = "DebuggerStatement"; - SyntaxKind5[SyntaxKind5["VariableDeclaration"] = 257] = "VariableDeclaration"; - SyntaxKind5[SyntaxKind5["VariableDeclarationList"] = 258] = "VariableDeclarationList"; - SyntaxKind5[SyntaxKind5["FunctionDeclaration"] = 259] = "FunctionDeclaration"; - SyntaxKind5[SyntaxKind5["ClassDeclaration"] = 260] = "ClassDeclaration"; - SyntaxKind5[SyntaxKind5["InterfaceDeclaration"] = 261] = "InterfaceDeclaration"; - SyntaxKind5[SyntaxKind5["TypeAliasDeclaration"] = 262] = "TypeAliasDeclaration"; - SyntaxKind5[SyntaxKind5["EnumDeclaration"] = 263] = "EnumDeclaration"; - SyntaxKind5[SyntaxKind5["ModuleDeclaration"] = 264] = "ModuleDeclaration"; - SyntaxKind5[SyntaxKind5["ModuleBlock"] = 265] = "ModuleBlock"; - SyntaxKind5[SyntaxKind5["CaseBlock"] = 266] = "CaseBlock"; - SyntaxKind5[SyntaxKind5["NamespaceExportDeclaration"] = 267] = "NamespaceExportDeclaration"; - SyntaxKind5[SyntaxKind5["ImportEqualsDeclaration"] = 268] = "ImportEqualsDeclaration"; - SyntaxKind5[SyntaxKind5["ImportDeclaration"] = 269] = "ImportDeclaration"; - SyntaxKind5[SyntaxKind5["ImportClause"] = 270] = "ImportClause"; - SyntaxKind5[SyntaxKind5["NamespaceImport"] = 271] = "NamespaceImport"; - SyntaxKind5[SyntaxKind5["NamedImports"] = 272] = "NamedImports"; - SyntaxKind5[SyntaxKind5["ImportSpecifier"] = 273] = "ImportSpecifier"; - SyntaxKind5[SyntaxKind5["ExportAssignment"] = 274] = "ExportAssignment"; - SyntaxKind5[SyntaxKind5["ExportDeclaration"] = 275] = "ExportDeclaration"; - SyntaxKind5[SyntaxKind5["NamedExports"] = 276] = "NamedExports"; - SyntaxKind5[SyntaxKind5["NamespaceExport"] = 277] = "NamespaceExport"; - SyntaxKind5[SyntaxKind5["ExportSpecifier"] = 278] = "ExportSpecifier"; - SyntaxKind5[SyntaxKind5["MissingDeclaration"] = 279] = "MissingDeclaration"; - SyntaxKind5[SyntaxKind5["ExternalModuleReference"] = 280] = "ExternalModuleReference"; - SyntaxKind5[SyntaxKind5["JsxElement"] = 281] = "JsxElement"; - SyntaxKind5[SyntaxKind5["JsxSelfClosingElement"] = 282] = "JsxSelfClosingElement"; - SyntaxKind5[SyntaxKind5["JsxOpeningElement"] = 283] = "JsxOpeningElement"; - SyntaxKind5[SyntaxKind5["JsxClosingElement"] = 284] = "JsxClosingElement"; - SyntaxKind5[SyntaxKind5["JsxFragment"] = 285] = "JsxFragment"; - SyntaxKind5[SyntaxKind5["JsxOpeningFragment"] = 286] = "JsxOpeningFragment"; - SyntaxKind5[SyntaxKind5["JsxClosingFragment"] = 287] = "JsxClosingFragment"; - SyntaxKind5[SyntaxKind5["JsxAttribute"] = 288] = "JsxAttribute"; - SyntaxKind5[SyntaxKind5["JsxAttributes"] = 289] = "JsxAttributes"; - SyntaxKind5[SyntaxKind5["JsxSpreadAttribute"] = 290] = "JsxSpreadAttribute"; - SyntaxKind5[SyntaxKind5["JsxExpression"] = 291] = "JsxExpression"; - SyntaxKind5[SyntaxKind5["CaseClause"] = 292] = "CaseClause"; - SyntaxKind5[SyntaxKind5["DefaultClause"] = 293] = "DefaultClause"; - SyntaxKind5[SyntaxKind5["HeritageClause"] = 294] = "HeritageClause"; - SyntaxKind5[SyntaxKind5["CatchClause"] = 295] = "CatchClause"; - SyntaxKind5[SyntaxKind5["AssertClause"] = 296] = "AssertClause"; - SyntaxKind5[SyntaxKind5["AssertEntry"] = 297] = "AssertEntry"; - SyntaxKind5[SyntaxKind5["ImportTypeAssertionContainer"] = 298] = "ImportTypeAssertionContainer"; - SyntaxKind5[SyntaxKind5["PropertyAssignment"] = 299] = "PropertyAssignment"; - SyntaxKind5[SyntaxKind5["ShorthandPropertyAssignment"] = 300] = "ShorthandPropertyAssignment"; - SyntaxKind5[SyntaxKind5["SpreadAssignment"] = 301] = "SpreadAssignment"; - SyntaxKind5[SyntaxKind5["EnumMember"] = 302] = "EnumMember"; - SyntaxKind5[SyntaxKind5["UnparsedPrologue"] = 303] = "UnparsedPrologue"; - SyntaxKind5[SyntaxKind5["UnparsedPrepend"] = 304] = "UnparsedPrepend"; - SyntaxKind5[SyntaxKind5["UnparsedText"] = 305] = "UnparsedText"; - SyntaxKind5[SyntaxKind5["UnparsedInternalText"] = 306] = "UnparsedInternalText"; - SyntaxKind5[SyntaxKind5["UnparsedSyntheticReference"] = 307] = "UnparsedSyntheticReference"; - SyntaxKind5[SyntaxKind5["SourceFile"] = 308] = "SourceFile"; - SyntaxKind5[SyntaxKind5["Bundle"] = 309] = "Bundle"; - SyntaxKind5[SyntaxKind5["UnparsedSource"] = 310] = "UnparsedSource"; - SyntaxKind5[SyntaxKind5["InputFiles"] = 311] = "InputFiles"; - SyntaxKind5[SyntaxKind5["JSDocTypeExpression"] = 312] = "JSDocTypeExpression"; - SyntaxKind5[SyntaxKind5["JSDocNameReference"] = 313] = "JSDocNameReference"; - SyntaxKind5[SyntaxKind5["JSDocMemberName"] = 314] = "JSDocMemberName"; - SyntaxKind5[SyntaxKind5["JSDocAllType"] = 315] = "JSDocAllType"; - SyntaxKind5[SyntaxKind5["JSDocUnknownType"] = 316] = "JSDocUnknownType"; - SyntaxKind5[SyntaxKind5["JSDocNullableType"] = 317] = "JSDocNullableType"; - SyntaxKind5[SyntaxKind5["JSDocNonNullableType"] = 318] = "JSDocNonNullableType"; - SyntaxKind5[SyntaxKind5["JSDocOptionalType"] = 319] = "JSDocOptionalType"; - SyntaxKind5[SyntaxKind5["JSDocFunctionType"] = 320] = "JSDocFunctionType"; - SyntaxKind5[SyntaxKind5["JSDocVariadicType"] = 321] = "JSDocVariadicType"; - SyntaxKind5[SyntaxKind5["JSDocNamepathType"] = 322] = "JSDocNamepathType"; - SyntaxKind5[SyntaxKind5["JSDoc"] = 323] = "JSDoc"; - SyntaxKind5[SyntaxKind5["JSDocComment"] = 323 /* JSDoc */ ] = "JSDocComment"; - SyntaxKind5[SyntaxKind5["JSDocText"] = 324] = "JSDocText"; - SyntaxKind5[SyntaxKind5["JSDocTypeLiteral"] = 325] = "JSDocTypeLiteral"; - SyntaxKind5[SyntaxKind5["JSDocSignature"] = 326] = "JSDocSignature"; - SyntaxKind5[SyntaxKind5["JSDocLink"] = 327] = "JSDocLink"; - SyntaxKind5[SyntaxKind5["JSDocLinkCode"] = 328] = "JSDocLinkCode"; - SyntaxKind5[SyntaxKind5["JSDocLinkPlain"] = 329] = "JSDocLinkPlain"; - SyntaxKind5[SyntaxKind5["JSDocTag"] = 330] = "JSDocTag"; - SyntaxKind5[SyntaxKind5["JSDocAugmentsTag"] = 331] = "JSDocAugmentsTag"; - SyntaxKind5[SyntaxKind5["JSDocImplementsTag"] = 332] = "JSDocImplementsTag"; - SyntaxKind5[SyntaxKind5["JSDocAuthorTag"] = 333] = "JSDocAuthorTag"; - SyntaxKind5[SyntaxKind5["JSDocDeprecatedTag"] = 334] = "JSDocDeprecatedTag"; - SyntaxKind5[SyntaxKind5["JSDocClassTag"] = 335] = "JSDocClassTag"; - SyntaxKind5[SyntaxKind5["JSDocPublicTag"] = 336] = "JSDocPublicTag"; - SyntaxKind5[SyntaxKind5["JSDocPrivateTag"] = 337] = "JSDocPrivateTag"; - SyntaxKind5[SyntaxKind5["JSDocProtectedTag"] = 338] = "JSDocProtectedTag"; - SyntaxKind5[SyntaxKind5["JSDocReadonlyTag"] = 339] = "JSDocReadonlyTag"; - SyntaxKind5[SyntaxKind5["JSDocOverrideTag"] = 340] = "JSDocOverrideTag"; - SyntaxKind5[SyntaxKind5["JSDocCallbackTag"] = 341] = "JSDocCallbackTag"; - SyntaxKind5[SyntaxKind5["JSDocOverloadTag"] = 342] = "JSDocOverloadTag"; - SyntaxKind5[SyntaxKind5["JSDocEnumTag"] = 343] = "JSDocEnumTag"; - SyntaxKind5[SyntaxKind5["JSDocParameterTag"] = 344] = "JSDocParameterTag"; - SyntaxKind5[SyntaxKind5["JSDocReturnTag"] = 345] = "JSDocReturnTag"; - SyntaxKind5[SyntaxKind5["JSDocThisTag"] = 346] = "JSDocThisTag"; - SyntaxKind5[SyntaxKind5["JSDocTypeTag"] = 347] = "JSDocTypeTag"; - SyntaxKind5[SyntaxKind5["JSDocTemplateTag"] = 348] = "JSDocTemplateTag"; - SyntaxKind5[SyntaxKind5["JSDocTypedefTag"] = 349] = "JSDocTypedefTag"; - SyntaxKind5[SyntaxKind5["JSDocSeeTag"] = 350] = "JSDocSeeTag"; - SyntaxKind5[SyntaxKind5["JSDocPropertyTag"] = 351] = "JSDocPropertyTag"; - SyntaxKind5[SyntaxKind5["JSDocThrowsTag"] = 352] = "JSDocThrowsTag"; - SyntaxKind5[SyntaxKind5["JSDocSatisfiesTag"] = 353] = "JSDocSatisfiesTag"; - SyntaxKind5[SyntaxKind5["SyntaxList"] = 354] = "SyntaxList"; - SyntaxKind5[SyntaxKind5["NotEmittedStatement"] = 355] = "NotEmittedStatement"; - SyntaxKind5[SyntaxKind5["PartiallyEmittedExpression"] = 356] = "PartiallyEmittedExpression"; - SyntaxKind5[SyntaxKind5["CommaListExpression"] = 357] = "CommaListExpression"; - SyntaxKind5[SyntaxKind5["MergeDeclarationMarker"] = 358] = "MergeDeclarationMarker"; - SyntaxKind5[SyntaxKind5["EndOfDeclarationMarker"] = 359] = "EndOfDeclarationMarker"; - SyntaxKind5[SyntaxKind5["SyntheticReferenceExpression"] = 360] = "SyntheticReferenceExpression"; - SyntaxKind5[SyntaxKind5["Count"] = 361] = "Count"; - SyntaxKind5[SyntaxKind5["FirstAssignment"] = 63 /* EqualsToken */ ] = "FirstAssignment"; - SyntaxKind5[SyntaxKind5["LastAssignment"] = 78 /* CaretEqualsToken */ ] = "LastAssignment"; - SyntaxKind5[SyntaxKind5["FirstCompoundAssignment"] = 64 /* PlusEqualsToken */ ] = "FirstCompoundAssignment"; - SyntaxKind5[SyntaxKind5["LastCompoundAssignment"] = 78 /* CaretEqualsToken */ ] = "LastCompoundAssignment"; - SyntaxKind5[SyntaxKind5["FirstReservedWord"] = 81 /* BreakKeyword */ ] = "FirstReservedWord"; - SyntaxKind5[SyntaxKind5["LastReservedWord"] = 116 /* WithKeyword */ ] = "LastReservedWord"; - SyntaxKind5[SyntaxKind5["FirstKeyword"] = 81 /* BreakKeyword */ ] = "FirstKeyword"; - SyntaxKind5[SyntaxKind5["LastKeyword"] = 162 /* OfKeyword */ ] = "LastKeyword"; - SyntaxKind5[SyntaxKind5["FirstFutureReservedWord"] = 117 /* ImplementsKeyword */ ] = "FirstFutureReservedWord"; - SyntaxKind5[SyntaxKind5["LastFutureReservedWord"] = 125 /* YieldKeyword */ ] = "LastFutureReservedWord"; - SyntaxKind5[SyntaxKind5["FirstTypeNode"] = 179 /* TypePredicate */ ] = "FirstTypeNode"; - SyntaxKind5[SyntaxKind5["LastTypeNode"] = 202 /* ImportType */ ] = "LastTypeNode"; - SyntaxKind5[SyntaxKind5["FirstPunctuation"] = 18 /* OpenBraceToken */ ] = "FirstPunctuation"; - SyntaxKind5[SyntaxKind5["LastPunctuation"] = 78 /* CaretEqualsToken */ ] = "LastPunctuation"; + SyntaxKind5[SyntaxKind5["NonTextFileMarkerTrivia"] = 8] = "NonTextFileMarkerTrivia"; + SyntaxKind5[SyntaxKind5["NumericLiteral"] = 9] = "NumericLiteral"; + SyntaxKind5[SyntaxKind5["BigIntLiteral"] = 10] = "BigIntLiteral"; + SyntaxKind5[SyntaxKind5["StringLiteral"] = 11] = "StringLiteral"; + SyntaxKind5[SyntaxKind5["JsxText"] = 12] = "JsxText"; + SyntaxKind5[SyntaxKind5["JsxTextAllWhiteSpaces"] = 13] = "JsxTextAllWhiteSpaces"; + SyntaxKind5[SyntaxKind5["RegularExpressionLiteral"] = 14] = "RegularExpressionLiteral"; + SyntaxKind5[SyntaxKind5["NoSubstitutionTemplateLiteral"] = 15] = "NoSubstitutionTemplateLiteral"; + SyntaxKind5[SyntaxKind5["TemplateHead"] = 16] = "TemplateHead"; + SyntaxKind5[SyntaxKind5["TemplateMiddle"] = 17] = "TemplateMiddle"; + SyntaxKind5[SyntaxKind5["TemplateTail"] = 18] = "TemplateTail"; + SyntaxKind5[SyntaxKind5["OpenBraceToken"] = 19] = "OpenBraceToken"; + SyntaxKind5[SyntaxKind5["CloseBraceToken"] = 20] = "CloseBraceToken"; + SyntaxKind5[SyntaxKind5["OpenParenToken"] = 21] = "OpenParenToken"; + SyntaxKind5[SyntaxKind5["CloseParenToken"] = 22] = "CloseParenToken"; + SyntaxKind5[SyntaxKind5["OpenBracketToken"] = 23] = "OpenBracketToken"; + SyntaxKind5[SyntaxKind5["CloseBracketToken"] = 24] = "CloseBracketToken"; + SyntaxKind5[SyntaxKind5["DotToken"] = 25] = "DotToken"; + SyntaxKind5[SyntaxKind5["DotDotDotToken"] = 26] = "DotDotDotToken"; + SyntaxKind5[SyntaxKind5["SemicolonToken"] = 27] = "SemicolonToken"; + SyntaxKind5[SyntaxKind5["CommaToken"] = 28] = "CommaToken"; + SyntaxKind5[SyntaxKind5["QuestionDotToken"] = 29] = "QuestionDotToken"; + SyntaxKind5[SyntaxKind5["LessThanToken"] = 30] = "LessThanToken"; + SyntaxKind5[SyntaxKind5["LessThanSlashToken"] = 31] = "LessThanSlashToken"; + SyntaxKind5[SyntaxKind5["GreaterThanToken"] = 32] = "GreaterThanToken"; + SyntaxKind5[SyntaxKind5["LessThanEqualsToken"] = 33] = "LessThanEqualsToken"; + SyntaxKind5[SyntaxKind5["GreaterThanEqualsToken"] = 34] = "GreaterThanEqualsToken"; + SyntaxKind5[SyntaxKind5["EqualsEqualsToken"] = 35] = "EqualsEqualsToken"; + SyntaxKind5[SyntaxKind5["ExclamationEqualsToken"] = 36] = "ExclamationEqualsToken"; + SyntaxKind5[SyntaxKind5["EqualsEqualsEqualsToken"] = 37] = "EqualsEqualsEqualsToken"; + SyntaxKind5[SyntaxKind5["ExclamationEqualsEqualsToken"] = 38] = "ExclamationEqualsEqualsToken"; + SyntaxKind5[SyntaxKind5["EqualsGreaterThanToken"] = 39] = "EqualsGreaterThanToken"; + SyntaxKind5[SyntaxKind5["PlusToken"] = 40] = "PlusToken"; + SyntaxKind5[SyntaxKind5["MinusToken"] = 41] = "MinusToken"; + SyntaxKind5[SyntaxKind5["AsteriskToken"] = 42] = "AsteriskToken"; + SyntaxKind5[SyntaxKind5["AsteriskAsteriskToken"] = 43] = "AsteriskAsteriskToken"; + SyntaxKind5[SyntaxKind5["SlashToken"] = 44] = "SlashToken"; + SyntaxKind5[SyntaxKind5["PercentToken"] = 45] = "PercentToken"; + SyntaxKind5[SyntaxKind5["PlusPlusToken"] = 46] = "PlusPlusToken"; + SyntaxKind5[SyntaxKind5["MinusMinusToken"] = 47] = "MinusMinusToken"; + SyntaxKind5[SyntaxKind5["LessThanLessThanToken"] = 48] = "LessThanLessThanToken"; + SyntaxKind5[SyntaxKind5["GreaterThanGreaterThanToken"] = 49] = "GreaterThanGreaterThanToken"; + SyntaxKind5[SyntaxKind5["GreaterThanGreaterThanGreaterThanToken"] = 50] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind5[SyntaxKind5["AmpersandToken"] = 51] = "AmpersandToken"; + SyntaxKind5[SyntaxKind5["BarToken"] = 52] = "BarToken"; + SyntaxKind5[SyntaxKind5["CaretToken"] = 53] = "CaretToken"; + SyntaxKind5[SyntaxKind5["ExclamationToken"] = 54] = "ExclamationToken"; + SyntaxKind5[SyntaxKind5["TildeToken"] = 55] = "TildeToken"; + SyntaxKind5[SyntaxKind5["AmpersandAmpersandToken"] = 56] = "AmpersandAmpersandToken"; + SyntaxKind5[SyntaxKind5["BarBarToken"] = 57] = "BarBarToken"; + SyntaxKind5[SyntaxKind5["QuestionToken"] = 58] = "QuestionToken"; + SyntaxKind5[SyntaxKind5["ColonToken"] = 59] = "ColonToken"; + SyntaxKind5[SyntaxKind5["AtToken"] = 60] = "AtToken"; + SyntaxKind5[SyntaxKind5["QuestionQuestionToken"] = 61] = "QuestionQuestionToken"; + SyntaxKind5[SyntaxKind5["BacktickToken"] = 62] = "BacktickToken"; + SyntaxKind5[SyntaxKind5["HashToken"] = 63] = "HashToken"; + SyntaxKind5[SyntaxKind5["EqualsToken"] = 64] = "EqualsToken"; + SyntaxKind5[SyntaxKind5["PlusEqualsToken"] = 65] = "PlusEqualsToken"; + SyntaxKind5[SyntaxKind5["MinusEqualsToken"] = 66] = "MinusEqualsToken"; + SyntaxKind5[SyntaxKind5["AsteriskEqualsToken"] = 67] = "AsteriskEqualsToken"; + SyntaxKind5[SyntaxKind5["AsteriskAsteriskEqualsToken"] = 68] = "AsteriskAsteriskEqualsToken"; + SyntaxKind5[SyntaxKind5["SlashEqualsToken"] = 69] = "SlashEqualsToken"; + SyntaxKind5[SyntaxKind5["PercentEqualsToken"] = 70] = "PercentEqualsToken"; + SyntaxKind5[SyntaxKind5["LessThanLessThanEqualsToken"] = 71] = "LessThanLessThanEqualsToken"; + SyntaxKind5[SyntaxKind5["GreaterThanGreaterThanEqualsToken"] = 72] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind5[SyntaxKind5["GreaterThanGreaterThanGreaterThanEqualsToken"] = 73] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind5[SyntaxKind5["AmpersandEqualsToken"] = 74] = "AmpersandEqualsToken"; + SyntaxKind5[SyntaxKind5["BarEqualsToken"] = 75] = "BarEqualsToken"; + SyntaxKind5[SyntaxKind5["BarBarEqualsToken"] = 76] = "BarBarEqualsToken"; + SyntaxKind5[SyntaxKind5["AmpersandAmpersandEqualsToken"] = 77] = "AmpersandAmpersandEqualsToken"; + SyntaxKind5[SyntaxKind5["QuestionQuestionEqualsToken"] = 78] = "QuestionQuestionEqualsToken"; + SyntaxKind5[SyntaxKind5["CaretEqualsToken"] = 79] = "CaretEqualsToken"; + SyntaxKind5[SyntaxKind5["Identifier"] = 80] = "Identifier"; + SyntaxKind5[SyntaxKind5["PrivateIdentifier"] = 81] = "PrivateIdentifier"; + SyntaxKind5[SyntaxKind5["JSDocCommentTextToken"] = 82] = "JSDocCommentTextToken"; + SyntaxKind5[SyntaxKind5["BreakKeyword"] = 83] = "BreakKeyword"; + SyntaxKind5[SyntaxKind5["CaseKeyword"] = 84] = "CaseKeyword"; + SyntaxKind5[SyntaxKind5["CatchKeyword"] = 85] = "CatchKeyword"; + SyntaxKind5[SyntaxKind5["ClassKeyword"] = 86] = "ClassKeyword"; + SyntaxKind5[SyntaxKind5["ConstKeyword"] = 87] = "ConstKeyword"; + SyntaxKind5[SyntaxKind5["ContinueKeyword"] = 88] = "ContinueKeyword"; + SyntaxKind5[SyntaxKind5["DebuggerKeyword"] = 89] = "DebuggerKeyword"; + SyntaxKind5[SyntaxKind5["DefaultKeyword"] = 90] = "DefaultKeyword"; + SyntaxKind5[SyntaxKind5["DeleteKeyword"] = 91] = "DeleteKeyword"; + SyntaxKind5[SyntaxKind5["DoKeyword"] = 92] = "DoKeyword"; + SyntaxKind5[SyntaxKind5["ElseKeyword"] = 93] = "ElseKeyword"; + SyntaxKind5[SyntaxKind5["EnumKeyword"] = 94] = "EnumKeyword"; + SyntaxKind5[SyntaxKind5["ExportKeyword"] = 95] = "ExportKeyword"; + SyntaxKind5[SyntaxKind5["ExtendsKeyword"] = 96] = "ExtendsKeyword"; + SyntaxKind5[SyntaxKind5["FalseKeyword"] = 97] = "FalseKeyword"; + SyntaxKind5[SyntaxKind5["FinallyKeyword"] = 98] = "FinallyKeyword"; + SyntaxKind5[SyntaxKind5["ForKeyword"] = 99] = "ForKeyword"; + SyntaxKind5[SyntaxKind5["FunctionKeyword"] = 100] = "FunctionKeyword"; + SyntaxKind5[SyntaxKind5["IfKeyword"] = 101] = "IfKeyword"; + SyntaxKind5[SyntaxKind5["ImportKeyword"] = 102] = "ImportKeyword"; + SyntaxKind5[SyntaxKind5["InKeyword"] = 103] = "InKeyword"; + SyntaxKind5[SyntaxKind5["InstanceOfKeyword"] = 104] = "InstanceOfKeyword"; + SyntaxKind5[SyntaxKind5["NewKeyword"] = 105] = "NewKeyword"; + SyntaxKind5[SyntaxKind5["NullKeyword"] = 106] = "NullKeyword"; + SyntaxKind5[SyntaxKind5["ReturnKeyword"] = 107] = "ReturnKeyword"; + SyntaxKind5[SyntaxKind5["SuperKeyword"] = 108] = "SuperKeyword"; + SyntaxKind5[SyntaxKind5["SwitchKeyword"] = 109] = "SwitchKeyword"; + SyntaxKind5[SyntaxKind5["ThisKeyword"] = 110] = "ThisKeyword"; + SyntaxKind5[SyntaxKind5["ThrowKeyword"] = 111] = "ThrowKeyword"; + SyntaxKind5[SyntaxKind5["TrueKeyword"] = 112] = "TrueKeyword"; + SyntaxKind5[SyntaxKind5["TryKeyword"] = 113] = "TryKeyword"; + SyntaxKind5[SyntaxKind5["TypeOfKeyword"] = 114] = "TypeOfKeyword"; + SyntaxKind5[SyntaxKind5["VarKeyword"] = 115] = "VarKeyword"; + SyntaxKind5[SyntaxKind5["VoidKeyword"] = 116] = "VoidKeyword"; + SyntaxKind5[SyntaxKind5["WhileKeyword"] = 117] = "WhileKeyword"; + SyntaxKind5[SyntaxKind5["WithKeyword"] = 118] = "WithKeyword"; + SyntaxKind5[SyntaxKind5["ImplementsKeyword"] = 119] = "ImplementsKeyword"; + SyntaxKind5[SyntaxKind5["InterfaceKeyword"] = 120] = "InterfaceKeyword"; + SyntaxKind5[SyntaxKind5["LetKeyword"] = 121] = "LetKeyword"; + SyntaxKind5[SyntaxKind5["PackageKeyword"] = 122] = "PackageKeyword"; + SyntaxKind5[SyntaxKind5["PrivateKeyword"] = 123] = "PrivateKeyword"; + SyntaxKind5[SyntaxKind5["ProtectedKeyword"] = 124] = "ProtectedKeyword"; + SyntaxKind5[SyntaxKind5["PublicKeyword"] = 125] = "PublicKeyword"; + SyntaxKind5[SyntaxKind5["StaticKeyword"] = 126] = "StaticKeyword"; + SyntaxKind5[SyntaxKind5["YieldKeyword"] = 127] = "YieldKeyword"; + SyntaxKind5[SyntaxKind5["AbstractKeyword"] = 128] = "AbstractKeyword"; + SyntaxKind5[SyntaxKind5["AccessorKeyword"] = 129] = "AccessorKeyword"; + SyntaxKind5[SyntaxKind5["AsKeyword"] = 130] = "AsKeyword"; + SyntaxKind5[SyntaxKind5["AssertsKeyword"] = 131] = "AssertsKeyword"; + SyntaxKind5[SyntaxKind5["AssertKeyword"] = 132] = "AssertKeyword"; + SyntaxKind5[SyntaxKind5["AnyKeyword"] = 133] = "AnyKeyword"; + SyntaxKind5[SyntaxKind5["AsyncKeyword"] = 134] = "AsyncKeyword"; + SyntaxKind5[SyntaxKind5["AwaitKeyword"] = 135] = "AwaitKeyword"; + SyntaxKind5[SyntaxKind5["BooleanKeyword"] = 136] = "BooleanKeyword"; + SyntaxKind5[SyntaxKind5["ConstructorKeyword"] = 137] = "ConstructorKeyword"; + SyntaxKind5[SyntaxKind5["DeclareKeyword"] = 138] = "DeclareKeyword"; + SyntaxKind5[SyntaxKind5["GetKeyword"] = 139] = "GetKeyword"; + SyntaxKind5[SyntaxKind5["InferKeyword"] = 140] = "InferKeyword"; + SyntaxKind5[SyntaxKind5["IntrinsicKeyword"] = 141] = "IntrinsicKeyword"; + SyntaxKind5[SyntaxKind5["IsKeyword"] = 142] = "IsKeyword"; + SyntaxKind5[SyntaxKind5["KeyOfKeyword"] = 143] = "KeyOfKeyword"; + SyntaxKind5[SyntaxKind5["ModuleKeyword"] = 144] = "ModuleKeyword"; + SyntaxKind5[SyntaxKind5["NamespaceKeyword"] = 145] = "NamespaceKeyword"; + SyntaxKind5[SyntaxKind5["NeverKeyword"] = 146] = "NeverKeyword"; + SyntaxKind5[SyntaxKind5["OutKeyword"] = 147] = "OutKeyword"; + SyntaxKind5[SyntaxKind5["ReadonlyKeyword"] = 148] = "ReadonlyKeyword"; + SyntaxKind5[SyntaxKind5["RequireKeyword"] = 149] = "RequireKeyword"; + SyntaxKind5[SyntaxKind5["NumberKeyword"] = 150] = "NumberKeyword"; + SyntaxKind5[SyntaxKind5["ObjectKeyword"] = 151] = "ObjectKeyword"; + SyntaxKind5[SyntaxKind5["SatisfiesKeyword"] = 152] = "SatisfiesKeyword"; + SyntaxKind5[SyntaxKind5["SetKeyword"] = 153] = "SetKeyword"; + SyntaxKind5[SyntaxKind5["StringKeyword"] = 154] = "StringKeyword"; + SyntaxKind5[SyntaxKind5["SymbolKeyword"] = 155] = "SymbolKeyword"; + SyntaxKind5[SyntaxKind5["TypeKeyword"] = 156] = "TypeKeyword"; + SyntaxKind5[SyntaxKind5["UndefinedKeyword"] = 157] = "UndefinedKeyword"; + SyntaxKind5[SyntaxKind5["UniqueKeyword"] = 158] = "UniqueKeyword"; + SyntaxKind5[SyntaxKind5["UnknownKeyword"] = 159] = "UnknownKeyword"; + SyntaxKind5[SyntaxKind5["UsingKeyword"] = 160] = "UsingKeyword"; + SyntaxKind5[SyntaxKind5["FromKeyword"] = 161] = "FromKeyword"; + SyntaxKind5[SyntaxKind5["GlobalKeyword"] = 162] = "GlobalKeyword"; + SyntaxKind5[SyntaxKind5["BigIntKeyword"] = 163] = "BigIntKeyword"; + SyntaxKind5[SyntaxKind5["OverrideKeyword"] = 164] = "OverrideKeyword"; + SyntaxKind5[SyntaxKind5["OfKeyword"] = 165] = "OfKeyword"; + SyntaxKind5[SyntaxKind5["QualifiedName"] = 166] = "QualifiedName"; + SyntaxKind5[SyntaxKind5["ComputedPropertyName"] = 167] = "ComputedPropertyName"; + SyntaxKind5[SyntaxKind5["TypeParameter"] = 168] = "TypeParameter"; + SyntaxKind5[SyntaxKind5["Parameter"] = 169] = "Parameter"; + SyntaxKind5[SyntaxKind5["Decorator"] = 170] = "Decorator"; + SyntaxKind5[SyntaxKind5["PropertySignature"] = 171] = "PropertySignature"; + SyntaxKind5[SyntaxKind5["PropertyDeclaration"] = 172] = "PropertyDeclaration"; + SyntaxKind5[SyntaxKind5["MethodSignature"] = 173] = "MethodSignature"; + SyntaxKind5[SyntaxKind5["MethodDeclaration"] = 174] = "MethodDeclaration"; + SyntaxKind5[SyntaxKind5["ClassStaticBlockDeclaration"] = 175] = "ClassStaticBlockDeclaration"; + SyntaxKind5[SyntaxKind5["Constructor"] = 176] = "Constructor"; + SyntaxKind5[SyntaxKind5["GetAccessor"] = 177] = "GetAccessor"; + SyntaxKind5[SyntaxKind5["SetAccessor"] = 178] = "SetAccessor"; + SyntaxKind5[SyntaxKind5["CallSignature"] = 179] = "CallSignature"; + SyntaxKind5[SyntaxKind5["ConstructSignature"] = 180] = "ConstructSignature"; + SyntaxKind5[SyntaxKind5["IndexSignature"] = 181] = "IndexSignature"; + SyntaxKind5[SyntaxKind5["TypePredicate"] = 182] = "TypePredicate"; + SyntaxKind5[SyntaxKind5["TypeReference"] = 183] = "TypeReference"; + SyntaxKind5[SyntaxKind5["FunctionType"] = 184] = "FunctionType"; + SyntaxKind5[SyntaxKind5["ConstructorType"] = 185] = "ConstructorType"; + SyntaxKind5[SyntaxKind5["TypeQuery"] = 186] = "TypeQuery"; + SyntaxKind5[SyntaxKind5["TypeLiteral"] = 187] = "TypeLiteral"; + SyntaxKind5[SyntaxKind5["ArrayType"] = 188] = "ArrayType"; + SyntaxKind5[SyntaxKind5["TupleType"] = 189] = "TupleType"; + SyntaxKind5[SyntaxKind5["OptionalType"] = 190] = "OptionalType"; + SyntaxKind5[SyntaxKind5["RestType"] = 191] = "RestType"; + SyntaxKind5[SyntaxKind5["UnionType"] = 192] = "UnionType"; + SyntaxKind5[SyntaxKind5["IntersectionType"] = 193] = "IntersectionType"; + SyntaxKind5[SyntaxKind5["ConditionalType"] = 194] = "ConditionalType"; + SyntaxKind5[SyntaxKind5["InferType"] = 195] = "InferType"; + SyntaxKind5[SyntaxKind5["ParenthesizedType"] = 196] = "ParenthesizedType"; + SyntaxKind5[SyntaxKind5["ThisType"] = 197] = "ThisType"; + SyntaxKind5[SyntaxKind5["TypeOperator"] = 198] = "TypeOperator"; + SyntaxKind5[SyntaxKind5["IndexedAccessType"] = 199] = "IndexedAccessType"; + SyntaxKind5[SyntaxKind5["MappedType"] = 200] = "MappedType"; + SyntaxKind5[SyntaxKind5["LiteralType"] = 201] = "LiteralType"; + SyntaxKind5[SyntaxKind5["NamedTupleMember"] = 202] = "NamedTupleMember"; + SyntaxKind5[SyntaxKind5["TemplateLiteralType"] = 203] = "TemplateLiteralType"; + SyntaxKind5[SyntaxKind5["TemplateLiteralTypeSpan"] = 204] = "TemplateLiteralTypeSpan"; + SyntaxKind5[SyntaxKind5["ImportType"] = 205] = "ImportType"; + SyntaxKind5[SyntaxKind5["ObjectBindingPattern"] = 206] = "ObjectBindingPattern"; + SyntaxKind5[SyntaxKind5["ArrayBindingPattern"] = 207] = "ArrayBindingPattern"; + SyntaxKind5[SyntaxKind5["BindingElement"] = 208] = "BindingElement"; + SyntaxKind5[SyntaxKind5["ArrayLiteralExpression"] = 209] = "ArrayLiteralExpression"; + SyntaxKind5[SyntaxKind5["ObjectLiteralExpression"] = 210] = "ObjectLiteralExpression"; + SyntaxKind5[SyntaxKind5["PropertyAccessExpression"] = 211] = "PropertyAccessExpression"; + SyntaxKind5[SyntaxKind5["ElementAccessExpression"] = 212] = "ElementAccessExpression"; + SyntaxKind5[SyntaxKind5["CallExpression"] = 213] = "CallExpression"; + SyntaxKind5[SyntaxKind5["NewExpression"] = 214] = "NewExpression"; + SyntaxKind5[SyntaxKind5["TaggedTemplateExpression"] = 215] = "TaggedTemplateExpression"; + SyntaxKind5[SyntaxKind5["TypeAssertionExpression"] = 216] = "TypeAssertionExpression"; + SyntaxKind5[SyntaxKind5["ParenthesizedExpression"] = 217] = "ParenthesizedExpression"; + SyntaxKind5[SyntaxKind5["FunctionExpression"] = 218] = "FunctionExpression"; + SyntaxKind5[SyntaxKind5["ArrowFunction"] = 219] = "ArrowFunction"; + SyntaxKind5[SyntaxKind5["DeleteExpression"] = 220] = "DeleteExpression"; + SyntaxKind5[SyntaxKind5["TypeOfExpression"] = 221] = "TypeOfExpression"; + SyntaxKind5[SyntaxKind5["VoidExpression"] = 222] = "VoidExpression"; + SyntaxKind5[SyntaxKind5["AwaitExpression"] = 223] = "AwaitExpression"; + SyntaxKind5[SyntaxKind5["PrefixUnaryExpression"] = 224] = "PrefixUnaryExpression"; + SyntaxKind5[SyntaxKind5["PostfixUnaryExpression"] = 225] = "PostfixUnaryExpression"; + SyntaxKind5[SyntaxKind5["BinaryExpression"] = 226] = "BinaryExpression"; + SyntaxKind5[SyntaxKind5["ConditionalExpression"] = 227] = "ConditionalExpression"; + SyntaxKind5[SyntaxKind5["TemplateExpression"] = 228] = "TemplateExpression"; + SyntaxKind5[SyntaxKind5["YieldExpression"] = 229] = "YieldExpression"; + SyntaxKind5[SyntaxKind5["SpreadElement"] = 230] = "SpreadElement"; + SyntaxKind5[SyntaxKind5["ClassExpression"] = 231] = "ClassExpression"; + SyntaxKind5[SyntaxKind5["OmittedExpression"] = 232] = "OmittedExpression"; + SyntaxKind5[SyntaxKind5["ExpressionWithTypeArguments"] = 233] = "ExpressionWithTypeArguments"; + SyntaxKind5[SyntaxKind5["AsExpression"] = 234] = "AsExpression"; + SyntaxKind5[SyntaxKind5["NonNullExpression"] = 235] = "NonNullExpression"; + SyntaxKind5[SyntaxKind5["MetaProperty"] = 236] = "MetaProperty"; + SyntaxKind5[SyntaxKind5["SyntheticExpression"] = 237] = "SyntheticExpression"; + SyntaxKind5[SyntaxKind5["SatisfiesExpression"] = 238] = "SatisfiesExpression"; + SyntaxKind5[SyntaxKind5["TemplateSpan"] = 239] = "TemplateSpan"; + SyntaxKind5[SyntaxKind5["SemicolonClassElement"] = 240] = "SemicolonClassElement"; + SyntaxKind5[SyntaxKind5["Block"] = 241] = "Block"; + SyntaxKind5[SyntaxKind5["EmptyStatement"] = 242] = "EmptyStatement"; + SyntaxKind5[SyntaxKind5["VariableStatement"] = 243] = "VariableStatement"; + SyntaxKind5[SyntaxKind5["ExpressionStatement"] = 244] = "ExpressionStatement"; + SyntaxKind5[SyntaxKind5["IfStatement"] = 245] = "IfStatement"; + SyntaxKind5[SyntaxKind5["DoStatement"] = 246] = "DoStatement"; + SyntaxKind5[SyntaxKind5["WhileStatement"] = 247] = "WhileStatement"; + SyntaxKind5[SyntaxKind5["ForStatement"] = 248] = "ForStatement"; + SyntaxKind5[SyntaxKind5["ForInStatement"] = 249] = "ForInStatement"; + SyntaxKind5[SyntaxKind5["ForOfStatement"] = 250] = "ForOfStatement"; + SyntaxKind5[SyntaxKind5["ContinueStatement"] = 251] = "ContinueStatement"; + SyntaxKind5[SyntaxKind5["BreakStatement"] = 252] = "BreakStatement"; + SyntaxKind5[SyntaxKind5["ReturnStatement"] = 253] = "ReturnStatement"; + SyntaxKind5[SyntaxKind5["WithStatement"] = 254] = "WithStatement"; + SyntaxKind5[SyntaxKind5["SwitchStatement"] = 255] = "SwitchStatement"; + SyntaxKind5[SyntaxKind5["LabeledStatement"] = 256] = "LabeledStatement"; + SyntaxKind5[SyntaxKind5["ThrowStatement"] = 257] = "ThrowStatement"; + SyntaxKind5[SyntaxKind5["TryStatement"] = 258] = "TryStatement"; + SyntaxKind5[SyntaxKind5["DebuggerStatement"] = 259] = "DebuggerStatement"; + SyntaxKind5[SyntaxKind5["VariableDeclaration"] = 260] = "VariableDeclaration"; + SyntaxKind5[SyntaxKind5["VariableDeclarationList"] = 261] = "VariableDeclarationList"; + SyntaxKind5[SyntaxKind5["FunctionDeclaration"] = 262] = "FunctionDeclaration"; + SyntaxKind5[SyntaxKind5["ClassDeclaration"] = 263] = "ClassDeclaration"; + SyntaxKind5[SyntaxKind5["InterfaceDeclaration"] = 264] = "InterfaceDeclaration"; + SyntaxKind5[SyntaxKind5["TypeAliasDeclaration"] = 265] = "TypeAliasDeclaration"; + SyntaxKind5[SyntaxKind5["EnumDeclaration"] = 266] = "EnumDeclaration"; + SyntaxKind5[SyntaxKind5["ModuleDeclaration"] = 267] = "ModuleDeclaration"; + SyntaxKind5[SyntaxKind5["ModuleBlock"] = 268] = "ModuleBlock"; + SyntaxKind5[SyntaxKind5["CaseBlock"] = 269] = "CaseBlock"; + SyntaxKind5[SyntaxKind5["NamespaceExportDeclaration"] = 270] = "NamespaceExportDeclaration"; + SyntaxKind5[SyntaxKind5["ImportEqualsDeclaration"] = 271] = "ImportEqualsDeclaration"; + SyntaxKind5[SyntaxKind5["ImportDeclaration"] = 272] = "ImportDeclaration"; + SyntaxKind5[SyntaxKind5["ImportClause"] = 273] = "ImportClause"; + SyntaxKind5[SyntaxKind5["NamespaceImport"] = 274] = "NamespaceImport"; + SyntaxKind5[SyntaxKind5["NamedImports"] = 275] = "NamedImports"; + SyntaxKind5[SyntaxKind5["ImportSpecifier"] = 276] = "ImportSpecifier"; + SyntaxKind5[SyntaxKind5["ExportAssignment"] = 277] = "ExportAssignment"; + SyntaxKind5[SyntaxKind5["ExportDeclaration"] = 278] = "ExportDeclaration"; + SyntaxKind5[SyntaxKind5["NamedExports"] = 279] = "NamedExports"; + SyntaxKind5[SyntaxKind5["NamespaceExport"] = 280] = "NamespaceExport"; + SyntaxKind5[SyntaxKind5["ExportSpecifier"] = 281] = "ExportSpecifier"; + SyntaxKind5[SyntaxKind5["MissingDeclaration"] = 282] = "MissingDeclaration"; + SyntaxKind5[SyntaxKind5["ExternalModuleReference"] = 283] = "ExternalModuleReference"; + SyntaxKind5[SyntaxKind5["JsxElement"] = 284] = "JsxElement"; + SyntaxKind5[SyntaxKind5["JsxSelfClosingElement"] = 285] = "JsxSelfClosingElement"; + SyntaxKind5[SyntaxKind5["JsxOpeningElement"] = 286] = "JsxOpeningElement"; + SyntaxKind5[SyntaxKind5["JsxClosingElement"] = 287] = "JsxClosingElement"; + SyntaxKind5[SyntaxKind5["JsxFragment"] = 288] = "JsxFragment"; + SyntaxKind5[SyntaxKind5["JsxOpeningFragment"] = 289] = "JsxOpeningFragment"; + SyntaxKind5[SyntaxKind5["JsxClosingFragment"] = 290] = "JsxClosingFragment"; + SyntaxKind5[SyntaxKind5["JsxAttribute"] = 291] = "JsxAttribute"; + SyntaxKind5[SyntaxKind5["JsxAttributes"] = 292] = "JsxAttributes"; + SyntaxKind5[SyntaxKind5["JsxSpreadAttribute"] = 293] = "JsxSpreadAttribute"; + SyntaxKind5[SyntaxKind5["JsxExpression"] = 294] = "JsxExpression"; + SyntaxKind5[SyntaxKind5["JsxNamespacedName"] = 295] = "JsxNamespacedName"; + SyntaxKind5[SyntaxKind5["CaseClause"] = 296] = "CaseClause"; + SyntaxKind5[SyntaxKind5["DefaultClause"] = 297] = "DefaultClause"; + SyntaxKind5[SyntaxKind5["HeritageClause"] = 298] = "HeritageClause"; + SyntaxKind5[SyntaxKind5["CatchClause"] = 299] = "CatchClause"; + SyntaxKind5[SyntaxKind5["AssertClause"] = 300] = "AssertClause"; + SyntaxKind5[SyntaxKind5["AssertEntry"] = 301] = "AssertEntry"; + SyntaxKind5[SyntaxKind5["ImportTypeAssertionContainer"] = 302] = "ImportTypeAssertionContainer"; + SyntaxKind5[SyntaxKind5["PropertyAssignment"] = 303] = "PropertyAssignment"; + SyntaxKind5[SyntaxKind5["ShorthandPropertyAssignment"] = 304] = "ShorthandPropertyAssignment"; + SyntaxKind5[SyntaxKind5["SpreadAssignment"] = 305] = "SpreadAssignment"; + SyntaxKind5[SyntaxKind5["EnumMember"] = 306] = "EnumMember"; + SyntaxKind5[SyntaxKind5["UnparsedPrologue"] = 307] = "UnparsedPrologue"; + SyntaxKind5[SyntaxKind5["UnparsedPrepend"] = 308] = "UnparsedPrepend"; + SyntaxKind5[SyntaxKind5["UnparsedText"] = 309] = "UnparsedText"; + SyntaxKind5[SyntaxKind5["UnparsedInternalText"] = 310] = "UnparsedInternalText"; + SyntaxKind5[SyntaxKind5["UnparsedSyntheticReference"] = 311] = "UnparsedSyntheticReference"; + SyntaxKind5[SyntaxKind5["SourceFile"] = 312] = "SourceFile"; + SyntaxKind5[SyntaxKind5["Bundle"] = 313] = "Bundle"; + SyntaxKind5[SyntaxKind5["UnparsedSource"] = 314] = "UnparsedSource"; + SyntaxKind5[SyntaxKind5["InputFiles"] = 315] = "InputFiles"; + SyntaxKind5[SyntaxKind5["JSDocTypeExpression"] = 316] = "JSDocTypeExpression"; + SyntaxKind5[SyntaxKind5["JSDocNameReference"] = 317] = "JSDocNameReference"; + SyntaxKind5[SyntaxKind5["JSDocMemberName"] = 318] = "JSDocMemberName"; + SyntaxKind5[SyntaxKind5["JSDocAllType"] = 319] = "JSDocAllType"; + SyntaxKind5[SyntaxKind5["JSDocUnknownType"] = 320] = "JSDocUnknownType"; + SyntaxKind5[SyntaxKind5["JSDocNullableType"] = 321] = "JSDocNullableType"; + SyntaxKind5[SyntaxKind5["JSDocNonNullableType"] = 322] = "JSDocNonNullableType"; + SyntaxKind5[SyntaxKind5["JSDocOptionalType"] = 323] = "JSDocOptionalType"; + SyntaxKind5[SyntaxKind5["JSDocFunctionType"] = 324] = "JSDocFunctionType"; + SyntaxKind5[SyntaxKind5["JSDocVariadicType"] = 325] = "JSDocVariadicType"; + SyntaxKind5[SyntaxKind5["JSDocNamepathType"] = 326] = "JSDocNamepathType"; + SyntaxKind5[SyntaxKind5["JSDoc"] = 327] = "JSDoc"; + SyntaxKind5[SyntaxKind5["JSDocComment"] = 327 /* JSDoc */ ] = "JSDocComment"; + SyntaxKind5[SyntaxKind5["JSDocText"] = 328] = "JSDocText"; + SyntaxKind5[SyntaxKind5["JSDocTypeLiteral"] = 329] = "JSDocTypeLiteral"; + SyntaxKind5[SyntaxKind5["JSDocSignature"] = 330] = "JSDocSignature"; + SyntaxKind5[SyntaxKind5["JSDocLink"] = 331] = "JSDocLink"; + SyntaxKind5[SyntaxKind5["JSDocLinkCode"] = 332] = "JSDocLinkCode"; + SyntaxKind5[SyntaxKind5["JSDocLinkPlain"] = 333] = "JSDocLinkPlain"; + SyntaxKind5[SyntaxKind5["JSDocTag"] = 334] = "JSDocTag"; + SyntaxKind5[SyntaxKind5["JSDocAugmentsTag"] = 335] = "JSDocAugmentsTag"; + SyntaxKind5[SyntaxKind5["JSDocImplementsTag"] = 336] = "JSDocImplementsTag"; + SyntaxKind5[SyntaxKind5["JSDocAuthorTag"] = 337] = "JSDocAuthorTag"; + SyntaxKind5[SyntaxKind5["JSDocDeprecatedTag"] = 338] = "JSDocDeprecatedTag"; + SyntaxKind5[SyntaxKind5["JSDocClassTag"] = 339] = "JSDocClassTag"; + SyntaxKind5[SyntaxKind5["JSDocPublicTag"] = 340] = "JSDocPublicTag"; + SyntaxKind5[SyntaxKind5["JSDocPrivateTag"] = 341] = "JSDocPrivateTag"; + SyntaxKind5[SyntaxKind5["JSDocProtectedTag"] = 342] = "JSDocProtectedTag"; + SyntaxKind5[SyntaxKind5["JSDocReadonlyTag"] = 343] = "JSDocReadonlyTag"; + SyntaxKind5[SyntaxKind5["JSDocOverrideTag"] = 344] = "JSDocOverrideTag"; + SyntaxKind5[SyntaxKind5["JSDocCallbackTag"] = 345] = "JSDocCallbackTag"; + SyntaxKind5[SyntaxKind5["JSDocOverloadTag"] = 346] = "JSDocOverloadTag"; + SyntaxKind5[SyntaxKind5["JSDocEnumTag"] = 347] = "JSDocEnumTag"; + SyntaxKind5[SyntaxKind5["JSDocParameterTag"] = 348] = "JSDocParameterTag"; + SyntaxKind5[SyntaxKind5["JSDocReturnTag"] = 349] = "JSDocReturnTag"; + SyntaxKind5[SyntaxKind5["JSDocThisTag"] = 350] = "JSDocThisTag"; + SyntaxKind5[SyntaxKind5["JSDocTypeTag"] = 351] = "JSDocTypeTag"; + SyntaxKind5[SyntaxKind5["JSDocTemplateTag"] = 352] = "JSDocTemplateTag"; + SyntaxKind5[SyntaxKind5["JSDocTypedefTag"] = 353] = "JSDocTypedefTag"; + SyntaxKind5[SyntaxKind5["JSDocSeeTag"] = 354] = "JSDocSeeTag"; + SyntaxKind5[SyntaxKind5["JSDocPropertyTag"] = 355] = "JSDocPropertyTag"; + SyntaxKind5[SyntaxKind5["JSDocThrowsTag"] = 356] = "JSDocThrowsTag"; + SyntaxKind5[SyntaxKind5["JSDocSatisfiesTag"] = 357] = "JSDocSatisfiesTag"; + SyntaxKind5[SyntaxKind5["SyntaxList"] = 358] = "SyntaxList"; + SyntaxKind5[SyntaxKind5["NotEmittedStatement"] = 359] = "NotEmittedStatement"; + SyntaxKind5[SyntaxKind5["PartiallyEmittedExpression"] = 360] = "PartiallyEmittedExpression"; + SyntaxKind5[SyntaxKind5["CommaListExpression"] = 361] = "CommaListExpression"; + SyntaxKind5[SyntaxKind5["SyntheticReferenceExpression"] = 362] = "SyntheticReferenceExpression"; + SyntaxKind5[SyntaxKind5["Count"] = 363] = "Count"; + SyntaxKind5[SyntaxKind5["FirstAssignment"] = 64 /* EqualsToken */ ] = "FirstAssignment"; + SyntaxKind5[SyntaxKind5["LastAssignment"] = 79 /* CaretEqualsToken */ ] = "LastAssignment"; + SyntaxKind5[SyntaxKind5["FirstCompoundAssignment"] = 65 /* PlusEqualsToken */ ] = "FirstCompoundAssignment"; + SyntaxKind5[SyntaxKind5["LastCompoundAssignment"] = 79 /* CaretEqualsToken */ ] = "LastCompoundAssignment"; + SyntaxKind5[SyntaxKind5["FirstReservedWord"] = 83 /* BreakKeyword */ ] = "FirstReservedWord"; + SyntaxKind5[SyntaxKind5["LastReservedWord"] = 118 /* WithKeyword */ ] = "LastReservedWord"; + SyntaxKind5[SyntaxKind5["FirstKeyword"] = 83 /* BreakKeyword */ ] = "FirstKeyword"; + SyntaxKind5[SyntaxKind5["LastKeyword"] = 165 /* OfKeyword */ ] = "LastKeyword"; + SyntaxKind5[SyntaxKind5["FirstFutureReservedWord"] = 119 /* ImplementsKeyword */ ] = "FirstFutureReservedWord"; + SyntaxKind5[SyntaxKind5["LastFutureReservedWord"] = 127 /* YieldKeyword */ ] = "LastFutureReservedWord"; + SyntaxKind5[SyntaxKind5["FirstTypeNode"] = 182 /* TypePredicate */ ] = "FirstTypeNode"; + SyntaxKind5[SyntaxKind5["LastTypeNode"] = 205 /* ImportType */ ] = "LastTypeNode"; + SyntaxKind5[SyntaxKind5["FirstPunctuation"] = 19 /* OpenBraceToken */ ] = "FirstPunctuation"; + SyntaxKind5[SyntaxKind5["LastPunctuation"] = 79 /* CaretEqualsToken */ ] = "LastPunctuation"; SyntaxKind5[SyntaxKind5["FirstToken"] = 0 /* Unknown */ ] = "FirstToken"; - SyntaxKind5[SyntaxKind5["LastToken"] = 162 /* LastKeyword */ ] = "LastToken"; + SyntaxKind5[SyntaxKind5["LastToken"] = 165 /* LastKeyword */ ] = "LastToken"; SyntaxKind5[SyntaxKind5["FirstTriviaToken"] = 2 /* SingleLineCommentTrivia */ ] = "FirstTriviaToken"; SyntaxKind5[SyntaxKind5["LastTriviaToken"] = 7 /* ConflictMarkerTrivia */ ] = "LastTriviaToken"; - SyntaxKind5[SyntaxKind5["FirstLiteralToken"] = 8 /* NumericLiteral */ ] = "FirstLiteralToken"; - SyntaxKind5[SyntaxKind5["LastLiteralToken"] = 14 /* NoSubstitutionTemplateLiteral */ ] = "LastLiteralToken"; - SyntaxKind5[SyntaxKind5["FirstTemplateToken"] = 14 /* NoSubstitutionTemplateLiteral */ ] = "FirstTemplateToken"; - SyntaxKind5[SyntaxKind5["LastTemplateToken"] = 17 /* TemplateTail */ ] = "LastTemplateToken"; - SyntaxKind5[SyntaxKind5["FirstBinaryOperator"] = 29 /* LessThanToken */ ] = "FirstBinaryOperator"; - SyntaxKind5[SyntaxKind5["LastBinaryOperator"] = 78 /* CaretEqualsToken */ ] = "LastBinaryOperator"; - SyntaxKind5[SyntaxKind5["FirstStatement"] = 240 /* VariableStatement */ ] = "FirstStatement"; - SyntaxKind5[SyntaxKind5["LastStatement"] = 256 /* DebuggerStatement */ ] = "LastStatement"; - SyntaxKind5[SyntaxKind5["FirstNode"] = 163 /* QualifiedName */ ] = "FirstNode"; - SyntaxKind5[SyntaxKind5["FirstJSDocNode"] = 312 /* JSDocTypeExpression */ ] = "FirstJSDocNode"; - SyntaxKind5[SyntaxKind5["LastJSDocNode"] = 353 /* JSDocSatisfiesTag */ ] = "LastJSDocNode"; - SyntaxKind5[SyntaxKind5["FirstJSDocTagNode"] = 330 /* JSDocTag */ ] = "FirstJSDocTagNode"; - SyntaxKind5[SyntaxKind5["LastJSDocTagNode"] = 353 /* JSDocSatisfiesTag */ ] = "LastJSDocTagNode"; - SyntaxKind5[SyntaxKind5["FirstContextualKeyword"] = 126 /* AbstractKeyword */ ] = "FirstContextualKeyword"; - SyntaxKind5[SyntaxKind5["LastContextualKeyword"] = 162 /* OfKeyword */ ] = "LastContextualKeyword"; + SyntaxKind5[SyntaxKind5["FirstLiteralToken"] = 9 /* NumericLiteral */ ] = "FirstLiteralToken"; + SyntaxKind5[SyntaxKind5["LastLiteralToken"] = 15 /* NoSubstitutionTemplateLiteral */ ] = "LastLiteralToken"; + SyntaxKind5[SyntaxKind5["FirstTemplateToken"] = 15 /* NoSubstitutionTemplateLiteral */ ] = "FirstTemplateToken"; + SyntaxKind5[SyntaxKind5["LastTemplateToken"] = 18 /* TemplateTail */ ] = "LastTemplateToken"; + SyntaxKind5[SyntaxKind5["FirstBinaryOperator"] = 30 /* LessThanToken */ ] = "FirstBinaryOperator"; + SyntaxKind5[SyntaxKind5["LastBinaryOperator"] = 79 /* CaretEqualsToken */ ] = "LastBinaryOperator"; + SyntaxKind5[SyntaxKind5["FirstStatement"] = 243 /* VariableStatement */ ] = "FirstStatement"; + SyntaxKind5[SyntaxKind5["LastStatement"] = 259 /* DebuggerStatement */ ] = "LastStatement"; + SyntaxKind5[SyntaxKind5["FirstNode"] = 166 /* QualifiedName */ ] = "FirstNode"; + SyntaxKind5[SyntaxKind5["FirstJSDocNode"] = 316 /* JSDocTypeExpression */ ] = "FirstJSDocNode"; + SyntaxKind5[SyntaxKind5["LastJSDocNode"] = 357 /* JSDocSatisfiesTag */ ] = "LastJSDocNode"; + SyntaxKind5[SyntaxKind5["FirstJSDocTagNode"] = 334 /* JSDocTag */ ] = "FirstJSDocTagNode"; + SyntaxKind5[SyntaxKind5["LastJSDocTagNode"] = 357 /* JSDocSatisfiesTag */ ] = "LastJSDocTagNode"; + SyntaxKind5[SyntaxKind5["FirstContextualKeyword"] = 128 /* AbstractKeyword */ ] = "FirstContextualKeyword"; + SyntaxKind5[SyntaxKind5["LastContextualKeyword"] = 165 /* OfKeyword */ ] = "LastContextualKeyword"; return SyntaxKind5; })(SyntaxKind || {}); NodeFlags = /* @__PURE__ */ ((NodeFlags3)=>{ NodeFlags3[NodeFlags3["None"] = 0] = "None"; NodeFlags3[NodeFlags3["Let"] = 1] = "Let"; NodeFlags3[NodeFlags3["Const"] = 2] = "Const"; - NodeFlags3[NodeFlags3["NestedNamespace"] = 4] = "NestedNamespace"; - NodeFlags3[NodeFlags3["Synthesized"] = 8] = "Synthesized"; - NodeFlags3[NodeFlags3["Namespace"] = 16] = "Namespace"; - NodeFlags3[NodeFlags3["OptionalChain"] = 32] = "OptionalChain"; - NodeFlags3[NodeFlags3["ExportContext"] = 64] = "ExportContext"; - NodeFlags3[NodeFlags3["ContainsThis"] = 128] = "ContainsThis"; - NodeFlags3[NodeFlags3["HasImplicitReturn"] = 256] = "HasImplicitReturn"; - NodeFlags3[NodeFlags3["HasExplicitReturn"] = 512] = "HasExplicitReturn"; - NodeFlags3[NodeFlags3["GlobalAugmentation"] = 1024] = "GlobalAugmentation"; - NodeFlags3[NodeFlags3["HasAsyncFunctions"] = 2048] = "HasAsyncFunctions"; - NodeFlags3[NodeFlags3["DisallowInContext"] = 4096] = "DisallowInContext"; - NodeFlags3[NodeFlags3["YieldContext"] = 8192] = "YieldContext"; - NodeFlags3[NodeFlags3["DecoratorContext"] = 16384] = "DecoratorContext"; - NodeFlags3[NodeFlags3["AwaitContext"] = 32768] = "AwaitContext"; - NodeFlags3[NodeFlags3["DisallowConditionalTypesContext"] = 65536] = "DisallowConditionalTypesContext"; - NodeFlags3[NodeFlags3["ThisNodeHasError"] = 131072] = "ThisNodeHasError"; - NodeFlags3[NodeFlags3["JavaScriptFile"] = 262144] = "JavaScriptFile"; - NodeFlags3[NodeFlags3["ThisNodeOrAnySubNodesHasError"] = 524288] = "ThisNodeOrAnySubNodesHasError"; - NodeFlags3[NodeFlags3["HasAggregatedChildData"] = 1048576] = "HasAggregatedChildData"; - NodeFlags3[NodeFlags3["PossiblyContainsDynamicImport"] = 2097152] = "PossiblyContainsDynamicImport"; - NodeFlags3[NodeFlags3["PossiblyContainsImportMeta"] = 4194304] = "PossiblyContainsImportMeta"; - NodeFlags3[NodeFlags3["JSDoc"] = 8388608] = "JSDoc"; - NodeFlags3[NodeFlags3["Ambient"] = 16777216] = "Ambient"; - NodeFlags3[NodeFlags3["InWithStatement"] = 33554432] = "InWithStatement"; - NodeFlags3[NodeFlags3["JsonFile"] = 67108864] = "JsonFile"; - NodeFlags3[NodeFlags3["TypeCached"] = 134217728] = "TypeCached"; - NodeFlags3[NodeFlags3["Deprecated"] = 268435456] = "Deprecated"; - NodeFlags3[NodeFlags3["BlockScoped"] = 3] = "BlockScoped"; - NodeFlags3[NodeFlags3["ReachabilityCheckFlags"] = 768] = "ReachabilityCheckFlags"; - NodeFlags3[NodeFlags3["ReachabilityAndEmitFlags"] = 2816] = "ReachabilityAndEmitFlags"; - NodeFlags3[NodeFlags3["ContextFlags"] = 50720768] = "ContextFlags"; - NodeFlags3[NodeFlags3["TypeExcludesFlags"] = 40960] = "TypeExcludesFlags"; - NodeFlags3[NodeFlags3["PermanentlySetIncrementalFlags"] = 6291456] = "PermanentlySetIncrementalFlags"; - NodeFlags3[NodeFlags3["IdentifierHasExtendedUnicodeEscape"] = 128 /* ContainsThis */ ] = "IdentifierHasExtendedUnicodeEscape"; - NodeFlags3[NodeFlags3["IdentifierIsInJSDocNamespace"] = 2048 /* HasAsyncFunctions */ ] = "IdentifierIsInJSDocNamespace"; + NodeFlags3[NodeFlags3["Using"] = 4] = "Using"; + NodeFlags3[NodeFlags3["AwaitUsing"] = 6] = "AwaitUsing"; + NodeFlags3[NodeFlags3["NestedNamespace"] = 8] = "NestedNamespace"; + NodeFlags3[NodeFlags3["Synthesized"] = 16] = "Synthesized"; + NodeFlags3[NodeFlags3["Namespace"] = 32] = "Namespace"; + NodeFlags3[NodeFlags3["OptionalChain"] = 64] = "OptionalChain"; + NodeFlags3[NodeFlags3["ExportContext"] = 128] = "ExportContext"; + NodeFlags3[NodeFlags3["ContainsThis"] = 256] = "ContainsThis"; + NodeFlags3[NodeFlags3["HasImplicitReturn"] = 512] = "HasImplicitReturn"; + NodeFlags3[NodeFlags3["HasExplicitReturn"] = 1024] = "HasExplicitReturn"; + NodeFlags3[NodeFlags3["GlobalAugmentation"] = 2048] = "GlobalAugmentation"; + NodeFlags3[NodeFlags3["HasAsyncFunctions"] = 4096] = "HasAsyncFunctions"; + NodeFlags3[NodeFlags3["DisallowInContext"] = 8192] = "DisallowInContext"; + NodeFlags3[NodeFlags3["YieldContext"] = 16384] = "YieldContext"; + NodeFlags3[NodeFlags3["DecoratorContext"] = 32768] = "DecoratorContext"; + NodeFlags3[NodeFlags3["AwaitContext"] = 65536] = "AwaitContext"; + NodeFlags3[NodeFlags3["DisallowConditionalTypesContext"] = 131072] = "DisallowConditionalTypesContext"; + NodeFlags3[NodeFlags3["ThisNodeHasError"] = 262144] = "ThisNodeHasError"; + NodeFlags3[NodeFlags3["JavaScriptFile"] = 524288] = "JavaScriptFile"; + NodeFlags3[NodeFlags3["ThisNodeOrAnySubNodesHasError"] = 1048576] = "ThisNodeOrAnySubNodesHasError"; + NodeFlags3[NodeFlags3["HasAggregatedChildData"] = 2097152] = "HasAggregatedChildData"; + NodeFlags3[NodeFlags3["PossiblyContainsDynamicImport"] = 4194304] = "PossiblyContainsDynamicImport"; + NodeFlags3[NodeFlags3["PossiblyContainsImportMeta"] = 8388608] = "PossiblyContainsImportMeta"; + NodeFlags3[NodeFlags3["JSDoc"] = 16777216] = "JSDoc"; + NodeFlags3[NodeFlags3["Ambient"] = 33554432] = "Ambient"; + NodeFlags3[NodeFlags3["InWithStatement"] = 67108864] = "InWithStatement"; + NodeFlags3[NodeFlags3["JsonFile"] = 134217728] = "JsonFile"; + NodeFlags3[NodeFlags3["TypeCached"] = 268435456] = "TypeCached"; + NodeFlags3[NodeFlags3["Deprecated"] = 536870912] = "Deprecated"; + NodeFlags3[NodeFlags3["BlockScoped"] = 7] = "BlockScoped"; + NodeFlags3[NodeFlags3["Constant"] = 6] = "Constant"; + NodeFlags3[NodeFlags3["ReachabilityCheckFlags"] = 1536] = "ReachabilityCheckFlags"; + NodeFlags3[NodeFlags3["ReachabilityAndEmitFlags"] = 5632] = "ReachabilityAndEmitFlags"; + NodeFlags3[NodeFlags3["ContextFlags"] = 101441536] = "ContextFlags"; + NodeFlags3[NodeFlags3["TypeExcludesFlags"] = 81920] = "TypeExcludesFlags"; + NodeFlags3[NodeFlags3["PermanentlySetIncrementalFlags"] = 12582912] = "PermanentlySetIncrementalFlags"; + NodeFlags3[NodeFlags3["IdentifierHasExtendedUnicodeEscape"] = 256 /* ContainsThis */ ] = "IdentifierHasExtendedUnicodeEscape"; + NodeFlags3[NodeFlags3["IdentifierIsInJSDocNamespace"] = 4096 /* HasAsyncFunctions */ ] = "IdentifierIsInJSDocNamespace"; return NodeFlags3; })(NodeFlags || {}); ModifierFlags = /* @__PURE__ */ ((ModifierFlags3)=>{ @@ -3606,9 +3550,15 @@ ${lanes.join("\n")} TokenFlags2[TokenFlags2["ContainsSeparator"] = 512] = "ContainsSeparator"; TokenFlags2[TokenFlags2["UnicodeEscape"] = 1024] = "UnicodeEscape"; TokenFlags2[TokenFlags2["ContainsInvalidEscape"] = 2048] = "ContainsInvalidEscape"; + TokenFlags2[TokenFlags2["HexEscape"] = 4096] = "HexEscape"; + TokenFlags2[TokenFlags2["ContainsLeadingZero"] = 8192] = "ContainsLeadingZero"; + TokenFlags2[TokenFlags2["ContainsInvalidSeparator"] = 16384] = "ContainsInvalidSeparator"; TokenFlags2[TokenFlags2["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier"; - TokenFlags2[TokenFlags2["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; - TokenFlags2[TokenFlags2["TemplateLiteralLikeFlags"] = 2048 /* ContainsInvalidEscape */ ] = "TemplateLiteralLikeFlags"; + TokenFlags2[TokenFlags2["WithSpecifier"] = 448] = "WithSpecifier"; + TokenFlags2[TokenFlags2["StringLiteralFlags"] = 7176] = "StringLiteralFlags"; + TokenFlags2[TokenFlags2["NumericLiteralFlags"] = 25584] = "NumericLiteralFlags"; + TokenFlags2[TokenFlags2["TemplateLiteralLikeFlags"] = 7176] = "TemplateLiteralLikeFlags"; + TokenFlags2[TokenFlags2["IsInvalid"] = 26656] = "IsInvalid"; return TokenFlags2; })(TokenFlags || {}); FlowFlags = /* @__PURE__ */ ((FlowFlags2)=>{ @@ -3937,15 +3887,13 @@ ${lanes.join("\n")} NodeCheckFlags2[NodeCheckFlags2["ContainsCapturedBlockScopeBinding"] = 8192] = "ContainsCapturedBlockScopeBinding"; NodeCheckFlags2[NodeCheckFlags2["CapturedBlockScopedBinding"] = 16384] = "CapturedBlockScopedBinding"; NodeCheckFlags2[NodeCheckFlags2["BlockScopedBindingInLoop"] = 32768] = "BlockScopedBindingInLoop"; - NodeCheckFlags2[NodeCheckFlags2["ClassWithBodyScopedClassBinding"] = 65536] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags2[NodeCheckFlags2["BodyScopedClassBinding"] = 131072] = "BodyScopedClassBinding"; - NodeCheckFlags2[NodeCheckFlags2["NeedsLoopOutParameter"] = 262144] = "NeedsLoopOutParameter"; - NodeCheckFlags2[NodeCheckFlags2["AssignmentsMarked"] = 524288] = "AssignmentsMarked"; - NodeCheckFlags2[NodeCheckFlags2["ClassWithConstructorReference"] = 1048576] = "ClassWithConstructorReference"; - NodeCheckFlags2[NodeCheckFlags2["ConstructorReferenceInClass"] = 2097152] = "ConstructorReferenceInClass"; - NodeCheckFlags2[NodeCheckFlags2["ContainsClassWithPrivateIdentifiers"] = 4194304] = "ContainsClassWithPrivateIdentifiers"; - NodeCheckFlags2[NodeCheckFlags2["ContainsSuperPropertyInStaticInitializer"] = 8388608] = "ContainsSuperPropertyInStaticInitializer"; - NodeCheckFlags2[NodeCheckFlags2["InCheckIdentifier"] = 16777216] = "InCheckIdentifier"; + NodeCheckFlags2[NodeCheckFlags2["NeedsLoopOutParameter"] = 65536] = "NeedsLoopOutParameter"; + NodeCheckFlags2[NodeCheckFlags2["AssignmentsMarked"] = 131072] = "AssignmentsMarked"; + NodeCheckFlags2[NodeCheckFlags2["ContainsConstructorReference"] = 262144] = "ContainsConstructorReference"; + NodeCheckFlags2[NodeCheckFlags2["ConstructorReference"] = 536870912] = "ConstructorReference"; + NodeCheckFlags2[NodeCheckFlags2["ContainsClassWithPrivateIdentifiers"] = 1048576] = "ContainsClassWithPrivateIdentifiers"; + NodeCheckFlags2[NodeCheckFlags2["ContainsSuperPropertyInStaticInitializer"] = 2097152] = "ContainsSuperPropertyInStaticInitializer"; + NodeCheckFlags2[NodeCheckFlags2["InCheckIdentifier"] = 4194304] = "InCheckIdentifier"; return NodeCheckFlags2; })(NodeCheckFlags || {}); TypeFlags = /* @__PURE__ */ ((TypeFlags2)=>{ @@ -3988,7 +3936,6 @@ ${lanes.join("\n")} TypeFlags2[TypeFlags2["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy"; TypeFlags2[TypeFlags2["PossiblyFalsy"] = 117724] = "PossiblyFalsy"; TypeFlags2[TypeFlags2["Intrinsic"] = 67359327] = "Intrinsic"; - TypeFlags2[TypeFlags2["Primitive"] = 134348796] = "Primitive"; TypeFlags2[TypeFlags2["StringLike"] = 402653316] = "StringLike"; TypeFlags2[TypeFlags2["NumberLike"] = 296] = "NumberLike"; TypeFlags2[TypeFlags2["BigIntLike"] = 2112] = "BigIntLike"; @@ -3996,6 +3943,7 @@ ${lanes.join("\n")} TypeFlags2[TypeFlags2["EnumLike"] = 1056] = "EnumLike"; TypeFlags2[TypeFlags2["ESSymbolLike"] = 12288] = "ESSymbolLike"; TypeFlags2[TypeFlags2["VoidLike"] = 49152] = "VoidLike"; + TypeFlags2[TypeFlags2["Primitive"] = 402784252] = "Primitive"; TypeFlags2[TypeFlags2["DefinitelyNonNullable"] = 470302716] = "DefinitelyNonNullable"; TypeFlags2[TypeFlags2["DisjointDomains"] = 469892092] = "DisjointDomains"; TypeFlags2[TypeFlags2["UnionOrIntersection"] = 3145728] = "UnionOrIntersection"; @@ -4005,17 +3953,17 @@ ${lanes.join("\n")} TypeFlags2[TypeFlags2["InstantiablePrimitive"] = 406847488] = "InstantiablePrimitive"; TypeFlags2[TypeFlags2["Instantiable"] = 465829888] = "Instantiable"; TypeFlags2[TypeFlags2["StructuredOrInstantiable"] = 469499904] = "StructuredOrInstantiable"; - TypeFlags2[TypeFlags2["ObjectFlagsType"] = 3899393] = "ObjectFlagsType"; + TypeFlags2[TypeFlags2["ObjectFlagsType"] = 138117121] = "ObjectFlagsType"; TypeFlags2[TypeFlags2["Simplifiable"] = 25165824] = "Simplifiable"; TypeFlags2[TypeFlags2["Singleton"] = 67358815] = "Singleton"; TypeFlags2[TypeFlags2["Narrowable"] = 536624127] = "Narrowable"; - TypeFlags2[TypeFlags2["IncludesMask"] = 205258751] = "IncludesMask"; + TypeFlags2[TypeFlags2["IncludesMask"] = 473694207] = "IncludesMask"; TypeFlags2[TypeFlags2["IncludesMissingType"] = 262144 /* TypeParameter */ ] = "IncludesMissingType"; TypeFlags2[TypeFlags2["IncludesNonWideningType"] = 4194304 /* Index */ ] = "IncludesNonWideningType"; TypeFlags2[TypeFlags2["IncludesWildcard"] = 8388608 /* IndexedAccess */ ] = "IncludesWildcard"; TypeFlags2[TypeFlags2["IncludesEmptyObject"] = 16777216 /* Conditional */ ] = "IncludesEmptyObject"; TypeFlags2[TypeFlags2["IncludesInstantiable"] = 33554432 /* Substitution */ ] = "IncludesInstantiable"; - TypeFlags2[TypeFlags2["NotPrimitiveUnion"] = 36323363] = "NotPrimitiveUnion"; + TypeFlags2[TypeFlags2["NotPrimitiveUnion"] = 36323331] = "NotPrimitiveUnion"; return TypeFlags2; })(TypeFlags || {}); ObjectFlags = /* @__PURE__ */ ((ObjectFlags3)=>{ @@ -4099,6 +4047,13 @@ ${lanes.join("\n")} AccessFlags2[AccessFlags2["Persistent"] = 1 /* IncludeUndefined */ ] = "Persistent"; return AccessFlags2; })(AccessFlags || {}); + IndexFlags = /* @__PURE__ */ ((IndexFlags2)=>{ + IndexFlags2[IndexFlags2["None"] = 0] = "None"; + IndexFlags2[IndexFlags2["StringsOnly"] = 1] = "StringsOnly"; + IndexFlags2[IndexFlags2["NoIndexSignatures"] = 2] = "NoIndexSignatures"; + IndexFlags2[IndexFlags2["NoReducibleCheck"] = 4] = "NoReducibleCheck"; + return IndexFlags2; + })(IndexFlags || {}); JsxReferenceKind = /* @__PURE__ */ ((JsxReferenceKind2)=>{ JsxReferenceKind2[JsxReferenceKind2["Component"] = 0] = "Component"; JsxReferenceKind2[JsxReferenceKind2["Function"] = 1] = "Function"; @@ -4118,7 +4073,9 @@ ${lanes.join("\n")} SignatureFlags5[SignatureFlags5["IsInnerCallChain"] = 8] = "IsInnerCallChain"; SignatureFlags5[SignatureFlags5["IsOuterCallChain"] = 16] = "IsOuterCallChain"; SignatureFlags5[SignatureFlags5["IsUntypedSignatureInJSFile"] = 32] = "IsUntypedSignatureInJSFile"; - SignatureFlags5[SignatureFlags5["PropagatingFlags"] = 39] = "PropagatingFlags"; + SignatureFlags5[SignatureFlags5["IsNonInferrable"] = 64] = "IsNonInferrable"; + SignatureFlags5[SignatureFlags5["IsSignatureCandidateForOverloadFailure"] = 128] = "IsSignatureCandidateForOverloadFailure"; + SignatureFlags5[SignatureFlags5["PropagatingFlags"] = 167] = "PropagatingFlags"; SignatureFlags5[SignatureFlags5["CallChainFlags"] = 24] = "CallChainFlags"; return SignatureFlags5; })(SignatureFlags || {}); @@ -4260,16 +4217,16 @@ ${lanes.join("\n")} NewLineKind2[NewLineKind2["LineFeed"] = 1] = "LineFeed"; return NewLineKind2; })(NewLineKind || {}); - ScriptKind = /* @__PURE__ */ ((ScriptKind5)=>{ - ScriptKind5[ScriptKind5["Unknown"] = 0] = "Unknown"; - ScriptKind5[ScriptKind5["JS"] = 1] = "JS"; - ScriptKind5[ScriptKind5["JSX"] = 2] = "JSX"; - ScriptKind5[ScriptKind5["TS"] = 3] = "TS"; - ScriptKind5[ScriptKind5["TSX"] = 4] = "TSX"; - ScriptKind5[ScriptKind5["External"] = 5] = "External"; - ScriptKind5[ScriptKind5["JSON"] = 6] = "JSON"; - ScriptKind5[ScriptKind5["Deferred"] = 7] = "Deferred"; - return ScriptKind5; + ScriptKind = /* @__PURE__ */ ((ScriptKind6)=>{ + ScriptKind6[ScriptKind6["Unknown"] = 0] = "Unknown"; + ScriptKind6[ScriptKind6["JS"] = 1] = "JS"; + ScriptKind6[ScriptKind6["JSX"] = 2] = "JSX"; + ScriptKind6[ScriptKind6["TS"] = 3] = "TS"; + ScriptKind6[ScriptKind6["TSX"] = 4] = "TSX"; + ScriptKind6[ScriptKind6["External"] = 5] = "External"; + ScriptKind6[ScriptKind6["JSON"] = 6] = "JSON"; + ScriptKind6[ScriptKind6["Deferred"] = 7] = "Deferred"; + return ScriptKind6; })(ScriptKind || {}); ScriptTarget = /* @__PURE__ */ ((ScriptTarget10)=>{ ScriptTarget10[ScriptTarget10["ES3"] = 0] = "ES3"; @@ -4323,6 +4280,7 @@ ${lanes.join("\n")} CharacterCodes2[CharacterCodes2["ideographicSpace"] = 12288] = "ideographicSpace"; CharacterCodes2[CharacterCodes2["mathematicalSpace"] = 8287] = "mathematicalSpace"; CharacterCodes2[CharacterCodes2["ogham"] = 5760] = "ogham"; + CharacterCodes2[CharacterCodes2["replacementCharacter"] = 65533] = "replacementCharacter"; CharacterCodes2[CharacterCodes2["_"] = 95] = "_"; CharacterCodes2[CharacterCodes2["$"] = 36] = "$"; CharacterCodes2[CharacterCodes2["_0"] = 48] = "_0"; @@ -4542,9 +4500,8 @@ ${lanes.join("\n")} EmitFlags3[EmitFlags3["ReuseTempVariableScope"] = 1048576] = "ReuseTempVariableScope"; EmitFlags3[EmitFlags3["CustomPrologue"] = 2097152] = "CustomPrologue"; EmitFlags3[EmitFlags3["NoHoisting"] = 4194304] = "NoHoisting"; - EmitFlags3[EmitFlags3["HasEndOfDeclarationMarker"] = 8388608] = "HasEndOfDeclarationMarker"; - EmitFlags3[EmitFlags3["Iterator"] = 16777216] = "Iterator"; - EmitFlags3[EmitFlags3["NoAsciiEscaping"] = 33554432] = "NoAsciiEscaping"; + EmitFlags3[EmitFlags3["Iterator"] = 8388608] = "Iterator"; + EmitFlags3[EmitFlags3["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; return EmitFlags3; })(EmitFlags || {}); InternalEmitFlags = /* @__PURE__ */ ((InternalEmitFlags3)=>{ @@ -4584,8 +4541,9 @@ ${lanes.join("\n")} ExternalEmitHelpers2[ExternalEmitHelpers2["CreateBinding"] = 4194304] = "CreateBinding"; ExternalEmitHelpers2[ExternalEmitHelpers2["SetFunctionName"] = 8388608] = "SetFunctionName"; ExternalEmitHelpers2[ExternalEmitHelpers2["PropKey"] = 16777216] = "PropKey"; + ExternalEmitHelpers2[ExternalEmitHelpers2["AddDisposableResourceAndDisposeResources"] = 33554432] = "AddDisposableResourceAndDisposeResources"; ExternalEmitHelpers2[ExternalEmitHelpers2["FirstEmitHelper"] = 1 /* Extends */ ] = "FirstEmitHelper"; - ExternalEmitHelpers2[ExternalEmitHelpers2["LastEmitHelper"] = 16777216 /* PropKey */ ] = "LastEmitHelper"; + ExternalEmitHelpers2[ExternalEmitHelpers2["LastEmitHelper"] = 33554432 /* AddDisposableResourceAndDisposeResources */ ] = "LastEmitHelper"; ExternalEmitHelpers2[ExternalEmitHelpers2["ForOfIncludes"] = 256 /* Values */ ] = "ForOfIncludes"; ExternalEmitHelpers2[ExternalEmitHelpers2["ForAwaitOfIncludes"] = 16384 /* AsyncValues */ ] = "ForAwaitOfIncludes"; ExternalEmitHelpers2[ExternalEmitHelpers2["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; @@ -4926,7 +4884,7 @@ ${lanes.join("\n")} queue.pollScheduled = false; return queue; } - function pollPollingIntervalQueue(queue) { + function pollPollingIntervalQueue(_timeoutType, queue) { queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]); if (queue.length) scheduleNextPoll(queue.pollingInterval); else { @@ -4934,9 +4892,9 @@ ${lanes.join("\n")} queue.pollScheduled = false; } } - function pollLowPollingIntervalQueue(queue) { + function pollLowPollingIntervalQueue(_timeoutType, queue) { pollQueue(changedFilesInLastPoll, 250 /* Low */ , /*pollIndex*/ 0, changedFilesInLastPoll.length); - pollPollingIntervalQueue(queue); + pollPollingIntervalQueue(_timeoutType, queue); if (!queue.pollScheduled && changedFilesInLastPoll.length) scheduleNextPoll(250 /* Low */ ); } function pollQueue(queue, pollingInterval, pollIndex, chunkSize) { @@ -4982,13 +4940,13 @@ ${lanes.join("\n")} if (!pollingIntervalQueue(pollingInterval).pollScheduled) scheduleNextPoll(pollingInterval); } function scheduleNextPoll(pollingInterval) { - pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === 250 /* Low */ ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); + pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === 250 /* Low */ ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingInterval === 250 /* Low */ ? "pollLowPollingIntervalQueue" : "pollPollingIntervalQueue", pollingIntervalQueue(pollingInterval)); } } - function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) { + function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames2) { const fileWatcherCallbacks = createMultiMap(); const dirWatchers = /* @__PURE__ */ new Map(); - const toCanonicalName = createGetCanonicalFileName(useCaseSensitiveFileNames); + const toCanonicalName = createGetCanonicalFileName(useCaseSensitiveFileNames2); return nonPollingWatchFile; function nonPollingWatchFile(fileName, callback, _pollingInterval, fallbackOptions) { const filePath = toCanonicalName(fileName); @@ -5045,19 +5003,19 @@ ${lanes.join("\n")} } function scheduleNextPoll() { if (!watchedFiles.length || pollScheduled) return; - pollScheduled = host.setTimeout(pollQueue, 2e3 /* High */ ); + pollScheduled = host.setTimeout(pollQueue, 2e3 /* High */ , "pollQueue"); } } - function createSingleWatcherPerName(cache, useCaseSensitiveFileNames, name, callback, createWatcher) { - const toCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); + function createSingleWatcherPerName(cache, useCaseSensitiveFileNames2, name, callback, createWatcher) { + const toCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); const path = toCanonicalFileName(name); const existing = cache.get(path); if (existing) existing.callbacks.push(callback); else cache.set(path, { watcher: createWatcher(// Cant infer types correctly so lets satisfy checker (param1, param2, param3)=>{ - var _a2; - return (_a2 = cache.get(path)) == null ? void 0 : _a2.callbacks.slice().forEach((cb)=>cb(param1, param2, param3)); + var _a; + return (_a = cache.get(path)) == null ? void 0 : _a.callbacks.slice().forEach((cb)=>cb(param1, param2, param3)); }), callbacks: [ callback @@ -5092,13 +5050,13 @@ ${lanes.join("\n")} function setSysLog(logger) { curSysLog = logger; } - function createDirectoryWatcherSupportingRecursive({ watchDirectory: watchDirectory , useCaseSensitiveFileNames: useCaseSensitiveFileNames , getCurrentDirectory: getCurrentDirectory , getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories , fileSystemEntryExists: fileSystemEntryExists , realpath: realpath , setTimeout: setTimeout2 , clearTimeout: clearTimeout2 }) { + function createDirectoryWatcherSupportingRecursive({ watchDirectory: watchDirectory, useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory: getCurrentDirectory, getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories, fileSystemEntryExists: fileSystemEntryExists, realpath: realpath, setTimeout: setTimeout2, clearTimeout: clearTimeout2 }) { const cache = /* @__PURE__ */ new Map(); const callbackCache = createMultiMap(); const cacheToUpdateChildWatches = /* @__PURE__ */ new Map(); let timerToUpdateChildWatches; - const filePathComparer = getStringComparer(!useCaseSensitiveFileNames); - const toCanonicalFilePath = createGetCanonicalFileName(useCaseSensitiveFileNames); + const filePathComparer = getStringComparer(!useCaseSensitiveFileNames2); + const toCanonicalFilePath = createGetCanonicalFileName(useCaseSensitiveFileNames2); return (dirName, callback, recursive, options)=>recursive ? createDirectoryWatcher(dirName, options, callback) : watchDirectory(dirName, callback, recursive, options); function createDirectoryWatcher(dirName, options, callback) { const dirPath = toCanonicalFilePath(dirName); @@ -5151,7 +5109,7 @@ ${lanes.join("\n")} if (existing) existing.push(...fileNames); else invokeMap.set(rootDirName, fileNames.slice()); } else invokeMap.set(rootDirName, true); - } else callbacks.forEach(({ callback: callback })=>callback(fileName)); + } else callbacks.forEach(({ callback: callback })=>callback(fileName)); } }); } @@ -5178,7 +5136,7 @@ ${lanes.join("\n")} clearTimeout2(timerToUpdateChildWatches); timerToUpdateChildWatches = void 0; } - timerToUpdateChildWatches = setTimeout2(onTimerToUpdateChildWatches, 1e3); + timerToUpdateChildWatches = setTimeout2(onTimerToUpdateChildWatches, 1e3, "timerToUpdateChildWatches"); } function onTimerToUpdateChildWatches() { timerToUpdateChildWatches = void 0; @@ -5188,7 +5146,7 @@ ${lanes.join("\n")} while(!timerToUpdateChildWatches && cacheToUpdateChildWatches.size){ const result = cacheToUpdateChildWatches.entries().next(); Debug.assert(!result.done); - const { value: [dirPath, { dirName: dirName , options: options , fileNames: fileNames }] } = result; + const { value: [dirPath, { dirName: dirName, options: options, fileNames: fileNames }] } = result; cacheToUpdateChildWatches.delete(dirPath); const hasChanges = updateChildWatches(dirName, dirPath, options); invokeCallbacks(dirPath, invokeMap, hasChanges ? void 0 : fileNames); @@ -5196,7 +5154,7 @@ ${lanes.join("\n")} sysLog(`sysLog:: invokingWatchers:: Elapsed:: ${timestamp() - start}ms:: ${cacheToUpdateChildWatches.size}`); callbackCache.forEach((callbacks, rootDirName)=>{ const existing = invokeMap.get(rootDirName); - if (existing) callbacks.forEach(({ callback: callback , dirName: dirName })=>{ + if (existing) callbacks.forEach(({ callback: callback, dirName: dirName })=>{ if (isArray(existing)) existing.forEach(callback); else callback(dirName); }); @@ -5232,11 +5190,11 @@ ${lanes.join("\n")} } } function isIgnoredPath(path, options) { - return some(ignoredPaths, (searchPath)=>isInPath(path, searchPath)) || isIgnoredByWatchOptions(path, options, useCaseSensitiveFileNames, getCurrentDirectory); + return some(ignoredPaths, (searchPath)=>isInPath(path, searchPath)) || isIgnoredByWatchOptions(path, options, useCaseSensitiveFileNames2, getCurrentDirectory); } function isInPath(path, searchPath) { if (stringContains(path, searchPath)) return true; - if (useCaseSensitiveFileNames) return false; + if (useCaseSensitiveFileNames2) return false; return stringContains(toCanonicalFilePath(path), searchPath); } } @@ -5251,18 +5209,18 @@ ${lanes.join("\n")} } else callback(fileName, 1 /* Changed */ , modifiedTime); }; } - function isIgnoredByWatchOptions(pathToCheck, options, useCaseSensitiveFileNames, getCurrentDirectory) { - return ((options == null ? void 0 : options.excludeDirectories) || (options == null ? void 0 : options.excludeFiles)) && (matchesExclude(pathToCheck, options == null ? void 0 : options.excludeFiles, useCaseSensitiveFileNames, getCurrentDirectory()) || matchesExclude(pathToCheck, options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames, getCurrentDirectory())); + function isIgnoredByWatchOptions(pathToCheck, options, useCaseSensitiveFileNames2, getCurrentDirectory) { + return ((options == null ? void 0 : options.excludeDirectories) || (options == null ? void 0 : options.excludeFiles)) && (matchesExclude(pathToCheck, options == null ? void 0 : options.excludeFiles, useCaseSensitiveFileNames2, getCurrentDirectory()) || matchesExclude(pathToCheck, options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames2, getCurrentDirectory())); } - function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory) { + function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory) { return (eventName, relativeFileName)=>{ if (eventName === "rename") { const fileName = !relativeFileName ? directoryName : normalizePath(combinePaths(directoryName, relativeFileName)); - if (!relativeFileName || !isIgnoredByWatchOptions(fileName, options, useCaseSensitiveFileNames, getCurrentDirectory)) callback(fileName); + if (!relativeFileName || !isIgnoredByWatchOptions(fileName, options, useCaseSensitiveFileNames2, getCurrentDirectory)) callback(fileName); } }; } - function createSystemWatchFunctions({ pollingWatchFileWorker: pollingWatchFileWorker , getModifiedTime: getModifiedTime3 , setTimeout: setTimeout2 , clearTimeout: clearTimeout2 , fsWatchWorker: fsWatchWorker , fileSystemEntryExists: fileSystemEntryExists , useCaseSensitiveFileNames: useCaseSensitiveFileNames , getCurrentDirectory: getCurrentDirectory , fsSupportsRecursiveFsWatch: fsSupportsRecursiveFsWatch , getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories , realpath: realpath , tscWatchFile: tscWatchFile , useNonPollingWatchers: useNonPollingWatchers , tscWatchDirectory: tscWatchDirectory , inodeWatching: inodeWatching , sysLog: sysLog2 }) { + function createSystemWatchFunctions({ pollingWatchFileWorker: pollingWatchFileWorker, getModifiedTime: getModifiedTime3, setTimeout: setTimeout2, clearTimeout: clearTimeout2, fsWatchWorker: fsWatchWorker, fileSystemEntryExists: fileSystemEntryExists, useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory: getCurrentDirectory, fsSupportsRecursiveFsWatch: fsSupportsRecursiveFsWatch, getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories, realpath: realpath, tscWatchFile: tscWatchFile, useNonPollingWatchers: useNonPollingWatchers, tscWatchDirectory: tscWatchDirectory, inodeWatching: inodeWatching, sysLog: sysLog2 }) { const pollingWatches = /* @__PURE__ */ new Map(); const fsWatches = /* @__PURE__ */ new Map(); const fsWatchesRecursive = /* @__PURE__ */ new Map(); @@ -5290,7 +5248,7 @@ ${lanes.join("\n")} case 4 /* UseFsEvents */ : return fsWatch(fileName, 0 /* File */ , createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModifiedTime3), /*recursive*/ false, pollingInterval, getFallbackOptions(options)); case 5 /* UseFsEventsOnParentDirectory */ : - if (!nonPollingWatchFile) nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames); + if (!nonPollingWatchFile) nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames2); return nonPollingWatchFile(fileName, callback, pollingInterval, getFallbackOptions(options)); default: Debug.assertNever(watchFileKind); @@ -5341,9 +5299,9 @@ ${lanes.join("\n")} }; } function watchDirectory(directoryName, callback, recursive, options) { - if (fsSupportsRecursiveFsWatch) return fsWatch(directoryName, 1 /* Directory */ , createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), recursive, 500 /* Medium */ , getFallbackOptions(options)); + if (fsSupportsRecursiveFsWatch) return fsWatch(directoryName, 1 /* Directory */ , createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory), recursive, 500 /* Medium */ , getFallbackOptions(options)); if (!hostRecursiveDirectoryWatcher) hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({ - useCaseSensitiveFileNames: useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory: getCurrentDirectory, fileSystemEntryExists: fileSystemEntryExists, getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories, @@ -5366,7 +5324,7 @@ ${lanes.join("\n")} case 3 /* FixedChunkSizePolling */ : return ensureFixedChunkSizePollingWatchFile()(directoryName, ()=>callback(directoryName), /* pollingInterval */ void 0, /*options*/ void 0); case 0 /* UseFsEvents */ : - return fsWatch(directoryName, 1 /* Directory */ , createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), recursive, 500 /* Medium */ , getFallbackOptions(watchDirectoryOptions)); + return fsWatch(directoryName, 1 /* Directory */ , createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory), recursive, 500 /* Medium */ , getFallbackOptions(watchDirectoryOptions)); default: Debug.assertNever(watchDirectoryKind); } @@ -5391,10 +5349,10 @@ ${lanes.join("\n")} } } function pollingWatchFile(fileName, callback, pollingInterval, options) { - return createSingleWatcherPerName(pollingWatches, useCaseSensitiveFileNames, fileName, callback, (cb)=>pollingWatchFileWorker(fileName, cb, pollingInterval, options)); + return createSingleWatcherPerName(pollingWatches, useCaseSensitiveFileNames2, fileName, callback, (cb)=>pollingWatchFileWorker(fileName, cb, pollingInterval, options)); } function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { - return createSingleWatcherPerName(recursive ? fsWatchesRecursive : fsWatches, useCaseSensitiveFileNames, fileOrDirectory, callback, (cb)=>fsWatchHandlingExistenceOnHost(fileOrDirectory, entryKind, cb, recursive, fallbackPollingInterval, fallbackOptions)); + return createSingleWatcherPerName(recursive ? fsWatchesRecursive : fsWatches, useCaseSensitiveFileNames2, fileOrDirectory, callback, (cb)=>fsWatchHandlingExistenceOnHost(fileOrDirectory, entryKind, cb, recursive, fallbackPollingInterval, fallbackOptions)); } function fsWatchHandlingExistenceOnHost(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { let lastDirectoryPartWithDirectorySeparator; @@ -5523,7 +5481,7 @@ ${lanes.join("\n")} let _crypto; try { _crypto = (parcelRequire("cY7r0")); - } catch (e) { + } catch { _crypto = void 0; } let activeSession; @@ -5531,18 +5489,18 @@ ${lanes.join("\n")} const Buffer2 = (parcelRequire("cY7r0")).Buffer; const isLinuxOrMacOs = $6N5CW$process.platform === "linux" || $6N5CW$process.platform === "darwin"; const platform = _os.platform(); - const useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + const useCaseSensitiveFileNames2 = isFileSystemCaseSensitive(); const fsRealpath = !!_fs.realpathSync.native ? $6N5CW$process.platform === "win32" ? fsRealPathHandlingLongPath : _fs.realpathSync.native : _fs.realpathSync; const executingFilePath = $1b3769ee38aa2ff9$var$__filename.endsWith("sys.js") ? _path.join(_path.dirname($1b3769ee38aa2ff9$var$__dirname), "__fake__.js") : $1b3769ee38aa2ff9$var$__filename; const fsSupportsRecursiveFsWatch = $6N5CW$process.platform === "win32" || $6N5CW$process.platform === "darwin"; const getCurrentDirectory = memoize(()=>$6N5CW$process.cwd()); - const { watchFile: watchFile2 , watchDirectory: watchDirectory } = createSystemWatchFunctions({ + const { watchFile: watchFile2, watchDirectory: watchDirectory } = createSystemWatchFunctions({ pollingWatchFileWorker: fsWatchFileWorker, getModifiedTime: getModifiedTime3, setTimeout: setTimeout, clearTimeout: clearTimeout, fsWatchWorker: fsWatchWorker, - useCaseSensitiveFileNames: useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory: getCurrentDirectory, fileSystemEntryExists: fileSystemEntryExists, fsSupportsRecursiveFsWatch: // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows @@ -5551,7 +5509,7 @@ ${lanes.join("\n")} getAccessibleSortedChildDirectories: (path)=>getAccessibleFileSystemEntries(path).directories, realpath: realpath, tscWatchFile: undefined, - useNonPollingWatchers: undefined, + useNonPollingWatchers: false, tscWatchDirectory: undefined, inodeWatching: isLinuxOrMacOs, sysLog: sysLog @@ -5559,7 +5517,7 @@ ${lanes.join("\n")} const nodeSystem = { args: $6N5CW$process.argv.slice(2), newLine: _os.EOL, - useCaseSensitiveFileNames: useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, write (s) { $6N5CW$process.stdout.write(s); }, @@ -5605,7 +5563,7 @@ ${lanes.join("\n")} try { const stat = statSync(path); if (stat == null ? void 0 : stat.isFile()) return stat.size; - } catch (e) {} + } catch {} return 0; }, exit (exitCode) { @@ -5615,11 +5573,11 @@ ${lanes.join("\n")} disableCPUProfiler: disableCPUProfiler, cpuProfilingEnabled: ()=>!!activeSession || contains($6N5CW$process.execArgv, "--cpu-prof") || contains($6N5CW$process.execArgv, "--prof"), realpath: realpath, - debugMode: some($6N5CW$process.execArgv, (arg)=>/^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg)), + debugMode: some($6N5CW$process.execArgv, (arg)=>/^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg)) || !!$6N5CW$process.recordreplay, tryEnableSourceMapsForHost () { try { (parcelRequire("cY7r0")).install(); - } catch (e) {} + } catch {} }, setTimeout: setTimeout, clearTimeout: clearTimeout, @@ -5627,7 +5585,9 @@ ${lanes.join("\n")} $6N5CW$process.stdout.write("\x1bc"); }, setBlocking: ()=>{ - if ($6N5CW$process.stdout && $6N5CW$process.stdout._handle && $6N5CW$process.stdout._handle.setBlocking) $6N5CW$process.stdout._handle.setBlocking(true); + var _a; + const handle = (_a = $6N5CW$process.stdout) == null ? void 0 : _a._handle; + if (handle && handle.setBlocking) handle.setBlocking(true); }, bufferFrom: bufferFrom, base64decode: (input)=>bufferFrom(input, "base64").toString("utf8"), @@ -5640,11 +5600,11 @@ ${lanes.join("\n")} modulePath: modulePath, error: void 0 }; - } catch (error) { + } catch (error2) { return { module: void 0, modulePath: void 0, - error: error + error: error2 }; } } @@ -5683,7 +5643,7 @@ ${lanes.join("\n")} const fileUrlRoot = `file://${getRootLength(normalizedDir) === 1 ? "" : "/"}${normalizedDir}`; for (const node of profile.nodes)if (node.callFrame.url) { const url = normalizeSlashes(node.callFrame.url); - if (containsPath(fileUrlRoot, url, useCaseSensitiveFileNames)) node.callFrame.url = getRelativePathToDirectoryOrUrl(fileUrlRoot, url, fileUrlRoot, createGetCanonicalFileName(useCaseSensitiveFileNames), /*isAbsolutePathAnUrl*/ true); + if (containsPath(fileUrlRoot, url, useCaseSensitiveFileNames2)) node.callFrame.url = getRelativePathToDirectoryOrUrl(fileUrlRoot, url, fileUrlRoot, createGetCanonicalFileName(useCaseSensitiveFileNames2), /*isAbsolutePathAnUrl*/ true); else if (!nativePattern.test(url)) { node.callFrame.url = (remappedPaths.has(url) ? remappedPaths : remappedPaths.set(url, `external${externalFileCounter}.js`)).get(url); externalFileCounter++; @@ -5694,17 +5654,17 @@ ${lanes.join("\n")} function disableCPUProfiler(cb) { if (activeSession && activeSession !== "stopping") { const s = activeSession; - activeSession.post("Profiler.stop", (err, { profile: profile })=>{ - var _a2; + activeSession.post("Profiler.stop", (err, { profile: profile })=>{ + var _a; if (!err) { try { - if ((_a2 = statSync(profilePath)) == null ? void 0 : _a2.isDirectory()) profilePath = _path.join(profilePath, `${/* @__PURE__ */ new Date().toISOString().replace(/:/g, "-")}+P${$6N5CW$process.pid}.cpuprofile`); - } catch (e) {} + if ((_a = statSync(profilePath)) == null ? void 0 : _a.isDirectory()) profilePath = _path.join(profilePath, `${/* @__PURE__ */ new Date().toISOString().replace(/:/g, "-")}+P${$6N5CW$process.pid}.cpuprofile`); + } catch {} try { _fs.mkdirSync(_path.dirname(profilePath), { recursive: true }); - } catch (e) {} + } catch {} _fs.writeFileSync(profilePath, JSON.stringify(cleanupPaths(profile))); } activeSession = void 0; @@ -5781,13 +5741,15 @@ ${lanes.join("\n")} return buffer.toString("utf8"); } function readFile(fileName, _encoding) { - perfLogger.logStartReadFile(fileName); + var _a, _b; + (_a = perfLogger) == null || _a.logStartReadFile(fileName); const file = readFileWorker(fileName, _encoding); - perfLogger.logStopReadFile(); + (_b = perfLogger) == null || _b.logStopReadFile(); return file; } function writeFile2(fileName, data, writeByteOrderMark) { - perfLogger.logEvent("WriteFile: " + fileName); + var _a; + (_a = perfLogger) == null || _a.logEvent("WriteFile: " + fileName); if (writeByteOrderMark) data = byteOrderMarkIndicator + data; let fd; try { @@ -5798,7 +5760,8 @@ ${lanes.join("\n")} } } function getAccessibleFileSystemEntries(path) { - perfLogger.logEvent("ReadDir: " + (path || ".")); + var _a; + (_a = perfLogger) == null || _a.logEvent("ReadDir: " + (path || ".")); try { const entries = _fs.readdirSync(path || ".", { withFileTypes: true @@ -5832,7 +5795,7 @@ ${lanes.join("\n")} } } function readDirectory(path, extensions, excludes, includes, depth) { - return matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, $6N5CW$process.cwd(), depth, getAccessibleFileSystemEntries, realpath); + return matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames2, $6N5CW$process.cwd(), depth, getAccessibleFileSystemEntries, realpath); } function fileSystemEntryExists(path, entryKind) { const originalStackTraceLimit = Error.stackTraceLimit; @@ -5869,16 +5832,16 @@ ${lanes.join("\n")} function realpath(path) { try { return fsRealpath(path); - } catch (e) { + } catch { return path; } } function getModifiedTime3(path) { - var _a2; + var _a; const originalStackTraceLimit = Error.stackTraceLimit; Error.stackTraceLimit = 0; try { - return (_a2 = statSync(path)) == null ? void 0 : _a2.mtime; + return (_a = statSync(path)) == null ? void 0 : _a.mtime; } catch (e) { return void 0; } finally{ @@ -6056,10 +6019,10 @@ ${lanes.join("\n")} path = combinePaths(currentDirectory, path); return pathComponents(path, getRootLength(path)); } - function getPathFromPathComponents(pathComponents2) { + function getPathFromPathComponents(pathComponents2, length2) { if (pathComponents2.length === 0) return ""; const root = pathComponents2[0] && ensureTrailingDirectorySeparator(pathComponents2[0]); - return root + pathComponents2.slice(1).join(directorySeparator); + return root + pathComponents2.slice(1, length2).join(directorySeparator); } function normalizeSlashes(path) { return path.indexOf("\\") !== -1 ? path.replace(backslashRegExp, directorySeparator) : path; @@ -6330,6 +6293,7 @@ ${lanes.join("\n")} Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, 1 /* Error */ , "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, 1 /* Error */ , "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0: diag(1064, 1 /* Error */ , "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064", "The return type of an async function or method must be the global Promise type. Did you mean to write 'Promise<{0}>'?"), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1065, 1 /* Error */ , "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1065", "The return type of an async function or method must be the global Promise type."), In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, 1 /* Error */ , "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, 1 /* Error */ , "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, 1 /* Error */ , "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."), @@ -6337,7 +6301,6 @@ ${lanes.join("\n")} _0_modifier_cannot_appear_on_an_index_signature: diag(1071, 1 /* Error */ , "_0_modifier_cannot_appear_on_an_index_signature_1071", "'{0}' modifier cannot appear on an index signature."), A_0_modifier_cannot_be_used_with_an_import_declaration: diag(1079, 1 /* Error */ , "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", "A '{0}' modifier cannot be used with an import declaration."), Invalid_reference_directive_syntax: diag(1084, 1 /* Error */ , "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."), - Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: diag(1085, 1 /* Error */ , "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'."), _0_modifier_cannot_appear_on_a_constructor_declaration: diag(1089, 1 /* Error */ , "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", "'{0}' modifier cannot appear on a constructor declaration."), _0_modifier_cannot_appear_on_a_parameter: diag(1090, 1 /* Error */ , "_0_modifier_cannot_appear_on_a_parameter_1090", "'{0}' modifier cannot appear on a parameter."), Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: diag(1091, 1 /* Error */ , "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", "Only a single variable declaration is allowed in a 'for...in' statement."), @@ -6360,6 +6323,7 @@ ${lanes.join("\n")} A_return_statement_can_only_be_used_within_a_function_body: diag(1108, 1 /* Error */ , "A_return_statement_can_only_be_used_within_a_function_body_1108", "A 'return' statement can only be used within a function body."), Expression_expected: diag(1109, 1 /* Error */ , "Expression_expected_1109", "Expression expected."), Type_expected: diag(1110, 1 /* Error */ , "Type_expected_1110", "Type expected."), + Private_field_0_must_be_declared_in_an_enclosing_class: diag(1111, 1 /* Error */ , "Private_field_0_must_be_declared_in_an_enclosing_class_1111", "Private field '{0}' must be declared in an enclosing class."), A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: diag(1113, 1 /* Error */ , "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", "A 'default' clause cannot appear more than once in a 'switch' statement."), Duplicate_label_0: diag(1114, 1 /* Error */ , "Duplicate_label_0_1114", "Duplicate label '{0}'."), A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: diag(1115, 1 /* Error */ , "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", "A 'continue' statement can only jump to a label of an enclosing iteration statement."), @@ -6368,7 +6332,7 @@ ${lanes.join("\n")} An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: diag(1118, 1 /* Error */ , "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", "An object literal cannot have multiple get/set accessors with the same name."), An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, 1 /* Error */ , "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."), An_export_assignment_cannot_have_modifiers: diag(1120, 1 /* Error */ , "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."), - Octal_literals_are_not_allowed_in_strict_mode: diag(1121, 1 /* Error */ , "Octal_literals_are_not_allowed_in_strict_mode_1121", "Octal literals are not allowed in strict mode."), + Octal_literals_are_not_allowed_Use_the_syntax_0: diag(1121, 1 /* Error */ , "Octal_literals_are_not_allowed_Use_the_syntax_0_1121", "Octal literals are not allowed. Use the syntax '{0}'."), Variable_declaration_list_cannot_be_empty: diag(1123, 1 /* Error */ , "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."), Digit_expected: diag(1124, 1 /* Error */ , "Digit_expected_1124", "Digit expected."), Hexadecimal_digit_expected: diag(1125, 1 /* Error */ , "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."), @@ -6394,9 +6358,8 @@ ${lanes.join("\n")} Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, 1 /* Error */ , "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."), Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, 1 /* Error */ , "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."), File_name_0_differs_from_already_included_file_name_1_only_in_casing: diag(1149, 1 /* Error */ , "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", "File name '{0}' differs from already included file name '{1}' only in casing."), - const_declarations_must_be_initialized: diag(1155, 1 /* Error */ , "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."), - const_declarations_can_only_be_declared_inside_a_block: diag(1156, 1 /* Error */ , "const_declarations_can_only_be_declared_inside_a_block_1156", "'const' declarations can only be declared inside a block."), - let_declarations_can_only_be_declared_inside_a_block: diag(1157, 1 /* Error */ , "let_declarations_can_only_be_declared_inside_a_block_1157", "'let' declarations can only be declared inside a block."), + _0_declarations_must_be_initialized: diag(1155, 1 /* Error */ , "_0_declarations_must_be_initialized_1155", "'{0}' declarations must be initialized."), + _0_declarations_can_only_be_declared_inside_a_block: diag(1156, 1 /* Error */ , "_0_declarations_can_only_be_declared_inside_a_block_1156", "'{0}' declarations can only be declared inside a block."), Unterminated_template_literal: diag(1160, 1 /* Error */ , "Unterminated_template_literal_1160", "Unterminated template literal."), Unterminated_regular_expression_literal: diag(1161, 1 /* Error */ , "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."), An_object_member_cannot_be_declared_optional: diag(1162, 1 /* Error */ , "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."), @@ -6483,6 +6446,7 @@ ${lanes.join("\n")} Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: diag(1250, 1 /* Error */ , "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, 1 /* Error */ , "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, 1 /* Error */ , "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), + Abstract_properties_can_only_appear_within_an_abstract_class: diag(1253, 1 /* Error */ , "Abstract_properties_can_only_appear_within_an_abstract_class_1253", "Abstract properties can only appear within an abstract class."), A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, 1 /* Error */ , "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, 1 /* Error */ , "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_required_element_cannot_follow_an_optional_element: diag(1257, 1 /* Error */ , "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -6577,8 +6541,6 @@ ${lanes.join("\n")} Class_constructor_may_not_be_a_generator: diag(1368, 1 /* Error */ , "Class_constructor_may_not_be_a_generator_1368", "Class constructor may not be a generator."), Did_you_mean_0: diag(1369, 3 /* Message */ , "Did_you_mean_0_1369", "Did you mean '{0}'?"), This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set_to_error: diag(1371, 1 /* Error */ , "This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set__1371", "This import is never used as a value and must use 'import type' because 'importsNotUsedAsValues' is set to 'error'."), - Convert_to_type_only_import: diag(1373, 3 /* Message */ , "Convert_to_type_only_import_1373", "Convert to type-only import"), - Convert_all_imports_not_used_as_a_value_to_type_only_imports: diag(1374, 3 /* Message */ , "Convert_all_imports_not_used_as_a_value_to_type_only_imports_1374", "Convert all imports not used as a value to type-only imports"), await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1375, 1 /* Error */ , "await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_fi_1375", "'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), _0_was_imported_here: diag(1376, 3 /* Message */ , "_0_was_imported_here_1376", "'{0}' was imported here."), _0_was_exported_here: diag(1377, 3 /* Message */ , "_0_was_exported_here_1377", "'{0}' was exported here."), @@ -6678,6 +6640,15 @@ ${lanes.join("\n")} _0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled: diag(1484, 1 /* Error */ , "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled_1484", "'{0}' is a type and must be imported using a type-only import when 'verbatimModuleSyntax' is enabled."), _0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled: diag(1485, 1 /* Error */ , "_0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimMo_1485", "'{0}' resolves to a type-only declaration and must be imported using a type-only import when 'verbatimModuleSyntax' is enabled."), Decorator_used_before_export_here: diag(1486, 1 /* Error */ , "Decorator_used_before_export_here_1486", "Decorator used before 'export' here."), + Octal_escape_sequences_are_not_allowed_Use_the_syntax_0: diag(1487, 1 /* Error */ , "Octal_escape_sequences_are_not_allowed_Use_the_syntax_0_1487", "Octal escape sequences are not allowed. Use the syntax '{0}'."), + Escape_sequence_0_is_not_allowed: diag(1488, 1 /* Error */ , "Escape_sequence_0_is_not_allowed_1488", "Escape sequence '{0}' is not allowed."), + Decimals_with_leading_zeros_are_not_allowed: diag(1489, 1 /* Error */ , "Decimals_with_leading_zeros_are_not_allowed_1489", "Decimals with leading zeros are not allowed."), + File_appears_to_be_binary: diag(1490, 1 /* Error */ , "File_appears_to_be_binary_1490", "File appears to be binary."), + _0_modifier_cannot_appear_on_a_using_declaration: diag(1491, 1 /* Error */ , "_0_modifier_cannot_appear_on_a_using_declaration_1491", "'{0}' modifier cannot appear on a 'using' declaration."), + _0_declarations_may_not_have_binding_patterns: diag(1492, 1 /* Error */ , "_0_declarations_may_not_have_binding_patterns_1492", "'{0}' declarations may not have binding patterns."), + The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration: diag(1493, 1 /* Error */ , "The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration_1493", "The left-hand side of a 'for...in' statement cannot be a 'using' declaration."), + The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration: diag(1494, 1 /* Error */ , "The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration_1494", "The left-hand side of a 'for...in' statement cannot be an 'await using' declaration."), + _0_modifier_cannot_appear_on_an_await_using_declaration: diag(1495, 1 /* Error */ , "_0_modifier_cannot_appear_on_an_await_using_declaration_1495", "'{0}' modifier cannot appear on an 'await using' declaration."), The_types_of_0_are_incompatible_between_these_types: diag(2200, 1 /* Error */ , "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, 1 /* Error */ , "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, 1 /* Error */ , "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ void 0, /*elidedInCompatabilityPyramid*/ true), @@ -6736,7 +6707,6 @@ ${lanes.join("\n")} This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0: diag(2343, 1 /* Error */ , "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343", "This syntax requires an imported helper named '{1}' which does not exist in '{0}'. Consider upgrading your version of '{0}'."), Type_0_does_not_satisfy_the_constraint_1: diag(2344, 1 /* Error */ , "Type_0_does_not_satisfy_the_constraint_1_2344", "Type '{0}' does not satisfy the constraint '{1}'."), Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: diag(2345, 1 /* Error */ , "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", "Argument of type '{0}' is not assignable to parameter of type '{1}'."), - Call_target_does_not_contain_any_signatures: diag(2346, 1 /* Error */ , "Call_target_does_not_contain_any_signatures_2346", "Call target does not contain any signatures."), Untyped_function_calls_may_not_accept_type_arguments: diag(2347, 1 /* Error */ , "Untyped_function_calls_may_not_accept_type_arguments_2347", "Untyped function calls may not accept type arguments."), Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: diag(2348, 1 /* Error */ , "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", "Value of type '{0}' is not callable. Did you mean to include 'new'?"), This_expression_is_not_callable: diag(2349, 1 /* Error */ , "This_expression_is_not_callable_2349", "This expression is not callable."), @@ -6745,7 +6715,7 @@ ${lanes.join("\n")} Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first: diag(2352, 1 /* Error */ , "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352", "Conversion of type '{0}' to type '{1}' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first."), Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, 1 /* Error */ , "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, 1 /* Error */ , "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), - A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, 1 /* Error */ , "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), + A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value: diag(2355, 1 /* Error */ , "A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value."), An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2356, 1 /* Error */ , "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type."), The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, 1 /* Error */ , "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."), The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, 1 /* Error */ , "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), @@ -6768,7 +6738,6 @@ ${lanes.join("\n")} Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, 1 /* Error */ , "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."), A_get_accessor_must_return_a_value: diag(2378, 1 /* Error */ , "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."), Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties: diag(2379, 1 /* Error */ , "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_tr_2379", "Argument of type '{0}' is not assignable to parameter of type '{1}' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties."), - The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type: diag(2380, 1 /* Error */ , "The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type_2380", "The return type of a 'get' accessor must be assignable to its 'set' accessor type"), Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, 1 /* Error */ , "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."), Overload_signatures_must_all_be_ambient_or_non_ambient: diag(2384, 1 /* Error */ , "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", "Overload signatures must all be ambient or non-ambient."), Overload_signatures_must_all_be_public_private_or_protected: diag(2385, 1 /* Error */ , "Overload_signatures_must_all_be_public_private_or_protected_2385", "Overload signatures must all be public, private or protected."), @@ -6998,6 +6967,7 @@ ${lanes.join("\n")} Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation: diag(2636, 1 /* Error */ , "Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation_2636", "Type '{0}' is not assignable to type '{1}' as implied by variance annotation."), Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_types: diag(2637, 1 /* Error */ , "Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_t_2637", "Variance annotations are only supported in type aliases for object, function, constructor, and mapped types."), Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operator: diag(2638, 1 /* Error */ , "Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operato_2638", "Type '{0}' may represent a primitive value, which is not permitted as the right operand of the 'in' operator."), + React_components_cannot_include_JSX_namespace_names: diag(2639, 1 /* Error */ , "React_components_cannot_include_JSX_namespace_names_2639", "React components cannot include JSX namespace names"), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, 1 /* Error */ , "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, 1 /* Error */ , "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, 1 /* Error */ , "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -7179,6 +7149,13 @@ ${lanes.join("\n")} Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2844, 1 /* Error */ , "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844", "Type of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), This_condition_will_always_return_0: diag(2845, 1 /* Error */ , "This_condition_will_always_return_0_2845", "This condition will always return '{0}'."), A_declaration_file_cannot_be_imported_without_import_type_Did_you_mean_to_import_an_implementation_file_0_instead: diag(2846, 1 /* Error */ , "A_declaration_file_cannot_be_imported_without_import_type_Did_you_mean_to_import_an_implementation_f_2846", "A declaration file cannot be imported without 'import type'. Did you mean to import an implementation file '{0}' instead?"), + The_right_hand_side_of_an_instanceof_expression_must_not_be_an_instantiation_expression: diag(2848, 1 /* Error */ , "The_right_hand_side_of_an_instanceof_expression_must_not_be_an_instantiation_expression_2848", "The right-hand side of an 'instanceof' expression must not be an instantiation expression."), + Target_signature_provides_too_few_arguments_Expected_0_or_more_but_got_1: diag(2849, 1 /* Error */ , "Target_signature_provides_too_few_arguments_Expected_0_or_more_but_got_1_2849", "Target signature provides too few arguments. Expected {0} or more, but got {1}."), + The_initializer_of_a_using_declaration_must_be_either_an_object_with_a_Symbol_dispose_method_or_be_null_or_undefined: diag(2850, 1 /* Error */ , "The_initializer_of_a_using_declaration_must_be_either_an_object_with_a_Symbol_dispose_method_or_be_n_2850", "The initializer of a 'using' declaration must be either an object with a '[Symbol.dispose]()' method, or be 'null' or 'undefined'."), + The_initializer_of_an_await_using_declaration_must_be_either_an_object_with_a_Symbol_asyncDispose_or_Symbol_dispose_method_or_be_null_or_undefined: diag(2851, 1 /* Error */ , "The_initializer_of_an_await_using_declaration_must_be_either_an_object_with_a_Symbol_asyncDispose_or_2851", "The initializer of an 'await using' declaration must be either an object with a '[Symbol.asyncDispose]()' or '[Symbol.dispose]()' method, or be 'null' or 'undefined'."), + await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(2852, 1 /* Error */ , "await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_2852", "'await using' statements are only allowed within async functions and at the top levels of modules."), + await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(2853, 1 /* Error */ , "await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_th_2853", "'await using' statements are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), + Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher: diag(2854, 1 /* Error */ , "Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_sys_2854", "Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher."), Import_declaration_0_is_using_private_name_1: diag(4e3, 1 /* Error */ , "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, 1 /* Error */ , "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, 1 /* Error */ , "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -7332,7 +7309,6 @@ ${lanes.join("\n")} Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0: diag(5081, 1 /* Error */ , "Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0_5081", "Cannot find a tsconfig.json file at the current directory: {0}."), _0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1: diag(5082, 1 /* Error */ , "_0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1_5082", "'{0}' could be instantiated with an arbitrary type which could be unrelated to '{1}'."), Cannot_read_file_0: diag(5083, 1 /* Error */ , "Cannot_read_file_0_5083", "Cannot read file '{0}'."), - Tuple_members_must_all_have_names_or_all_not_have_names: diag(5084, 1 /* Error */ , "Tuple_members_must_all_have_names_or_all_not_have_names_5084", "Tuple members must all have names or all not have names."), A_tuple_member_cannot_be_both_optional_and_rest: diag(5085, 1 /* Error */ , "A_tuple_member_cannot_be_both_optional_and_rest_5085", "A tuple member cannot be both optional and rest."), A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type: diag(5086, 1 /* Error */ , "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086", "A labeled tuple element is declared as optional with a question mark after the name and before the colon, rather than after the type."), A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, 1 /* Error */ , "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a '...' before the name, rather than before the type."), @@ -7355,6 +7331,8 @@ ${lanes.join("\n")} Use_0_instead: diag(5106, 3 /* Message */ , "Use_0_instead_5106", "Use '{0}' instead."), Option_0_1_is_deprecated_and_will_stop_functioning_in_TypeScript_2_Specify_compilerOption_ignoreDeprecations_Colon_3_to_silence_this_error: diag(5107, 1 /* Error */ , "Option_0_1_is_deprecated_and_will_stop_functioning_in_TypeScript_2_Specify_compilerOption_ignoreDepr_5107", `Option '{0}={1}' is deprecated and will stop functioning in TypeScript {2}. Specify compilerOption '"ignoreDeprecations": "{3}"' to silence this error.`), Option_0_1_has_been_removed_Please_remove_it_from_your_configuration: diag(5108, 1 /* Error */ , "Option_0_1_has_been_removed_Please_remove_it_from_your_configuration_5108", "Option '{0}={1}' has been removed. Please remove it from your configuration."), + Option_moduleResolution_must_be_set_to_0_or_left_unspecified_when_option_module_is_set_to_1: diag(5109, 1 /* Error */ , "Option_moduleResolution_must_be_set_to_0_or_left_unspecified_when_option_module_is_set_to_1_5109", "Option 'moduleResolution' must be set to '{0}' (or left unspecified) when option 'module' is set to '{1}'."), + Option_module_must_be_set_to_0_when_option_moduleResolution_is_set_to_1: diag(5110, 1 /* Error */ , "Option_module_must_be_set_to_0_when_option_moduleResolution_is_set_to_1_5110", "Option 'module' must be set to '{0}' when option 'moduleResolution' is set to '{1}'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6e3, 3 /* Message */ , "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, 3 /* Message */ , "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, 3 /* Message */ , "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -7499,6 +7477,7 @@ ${lanes.join("\n")} List_of_folders_to_include_type_definitions_from: diag(6161, 3 /* Message */ , "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."), Disable_size_limitations_on_JavaScript_projects: diag(6162, 3 /* Message */ , "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."), The_character_set_of_the_input_files: diag(6163, 3 /* Message */ , "The_character_set_of_the_input_files_6163", "The character set of the input files."), + Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1: diag(6164, 3 /* Message */ , "Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1_6164", "Skipping module '{0}' that looks like an absolute URI, target file types: {1}."), Do_not_truncate_error_messages: diag(6165, 3 /* Message */ , "Do_not_truncate_error_messages_6165", "Do not truncate error messages."), Output_directory_for_generated_declaration_files: diag(6166, 3 /* Message */ , "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."), A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, 3 /* Message */ , "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."), @@ -7582,12 +7561,14 @@ ${lanes.join("\n")} Output_Formatting: diag(6256, 3 /* Message */ , "Output_Formatting_6256", "Output Formatting"), Completeness: diag(6257, 3 /* Message */ , "Completeness_6257", "Completeness"), _0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file: diag(6258, 1 /* Error */ , "_0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file_6258", "'{0}' should be set inside the 'compilerOptions' object of the config json file"), - Found_1_error_in_1: diag(6259, 3 /* Message */ , "Found_1_error_in_1_6259", "Found 1 error in {1}"), + Found_1_error_in_0: diag(6259, 3 /* Message */ , "Found_1_error_in_0_6259", "Found 1 error in {0}"), Found_0_errors_in_the_same_file_starting_at_Colon_1: diag(6260, 3 /* Message */ , "Found_0_errors_in_the_same_file_starting_at_Colon_1_6260", "Found {0} errors in the same file, starting at: {1}"), Found_0_errors_in_1_files: diag(6261, 3 /* Message */ , "Found_0_errors_in_1_files_6261", "Found {0} errors in {1} files."), File_name_0_has_a_1_extension_looking_up_2_instead: diag(6262, 3 /* Message */ , "File_name_0_has_a_1_extension_looking_up_2_instead_6262", "File name '{0}' has a '{1}' extension - looking up '{2}' instead."), Module_0_was_resolved_to_1_but_allowArbitraryExtensions_is_not_set: diag(6263, 1 /* Error */ , "Module_0_was_resolved_to_1_but_allowArbitraryExtensions_is_not_set_6263", "Module '{0}' was resolved to '{1}', but '--allowArbitraryExtensions' is not set."), Enable_importing_files_with_any_extension_provided_a_declaration_file_is_present: diag(6264, 3 /* Message */ , "Enable_importing_files_with_any_extension_provided_a_declaration_file_is_present_6264", "Enable importing files with any extension, provided a declaration file is present."), + Resolving_type_reference_directive_for_program_that_specifies_custom_typeRoots_skipping_lookup_in_node_modules_folder: diag(6265, 3 /* Message */ , "Resolving_type_reference_directive_for_program_that_specifies_custom_typeRoots_skipping_lookup_in_no_6265", "Resolving type reference directive for program that specifies custom typeRoots, skipping lookup in 'node_modules' folder."), + Option_0_can_only_be_specified_on_command_line: diag(6266, 1 /* Error */ , "Option_0_can_only_be_specified_on_command_line_6266", "Option '{0}' can only be specified on command line."), Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve: diag(6270, 3 /* Message */ , "Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve_6270", "Directory '{0}' has no containing package.json scope. Imports will not resolve."), Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1: diag(6271, 3 /* Message */ , "Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6271", "Import specifier '{0}' does not exist in package.json scope at path '{1}'."), Invalid_import_specifier_0_has_no_possible_resolutions: diag(6272, 3 /* Message */ , "Invalid_import_specifier_0_has_no_possible_resolutions_6272", "Invalid import specifier '{0}' has no possible resolutions."), @@ -7668,6 +7649,8 @@ ${lanes.join("\n")} Resolved_under_condition_0: diag(6414, 3 /* Message */ , "Resolved_under_condition_0_6414", "Resolved under condition '{0}'."), Failed_to_resolve_under_condition_0: diag(6415, 3 /* Message */ , "Failed_to_resolve_under_condition_0_6415", "Failed to resolve under condition '{0}'."), Exiting_conditional_exports: diag(6416, 3 /* Message */ , "Exiting_conditional_exports_6416", "Exiting conditional exports."), + Searching_all_ancestor_node_modules_directories_for_preferred_extensions_Colon_0: diag(6417, 3 /* Message */ , "Searching_all_ancestor_node_modules_directories_for_preferred_extensions_Colon_0_6417", "Searching all ancestor node_modules directories for preferred extensions: {0}."), + Searching_all_ancestor_node_modules_directories_for_fallback_extensions_Colon_0: diag(6418, 3 /* Message */ , "Searching_all_ancestor_node_modules_directories_for_fallback_extensions_Colon_0_6418", "Searching all ancestor node_modules directories for fallback extensions: {0}."), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, 3 /* Message */ , "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, 3 /* Message */ , "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, 3 /* Message */ , "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -7892,8 +7875,7 @@ ${lanes.join("\n")} Parameter_modifiers_can_only_be_used_in_TypeScript_files: diag(8012, 1 /* Error */ , "Parameter_modifiers_can_only_be_used_in_TypeScript_files_8012", "Parameter modifiers can only be used in TypeScript files."), Non_null_assertions_can_only_be_used_in_TypeScript_files: diag(8013, 1 /* Error */ , "Non_null_assertions_can_only_be_used_in_TypeScript_files_8013", "Non-null assertions can only be used in TypeScript files."), Type_assertion_expressions_can_only_be_used_in_TypeScript_files: diag(8016, 1 /* Error */ , "Type_assertion_expressions_can_only_be_used_in_TypeScript_files_8016", "Type assertion expressions can only be used in TypeScript files."), - Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: diag(8017, 1 /* Error */ , "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", "Octal literal types must use ES2015 syntax. Use the syntax '{0}'."), - Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, 1 /* Error */ , "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."), + Signature_declarations_can_only_be_used_in_TypeScript_files: diag(8017, 1 /* Error */ , "Signature_declarations_can_only_be_used_in_TypeScript_files_8017", "Signature declarations can only be used in TypeScript files."), Report_errors_in_js_files: diag(8019, 3 /* Message */ , "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, 1 /* Error */ , "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, 1 /* Error */ , "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), @@ -7914,6 +7896,7 @@ ${lanes.join("\n")} You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder: diag(8036, 1 /* Error */ , "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036", "You cannot rename elements that are defined in another 'node_modules' folder."), Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files: diag(8037, 1 /* Error */ , "Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files_8037", "Type satisfaction expressions can only be used in TypeScript files."), Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export: diag(8038, 1 /* Error */ , "Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export_8038", "Decorators may not appear after 'export' or 'export default' if they also appear before 'export'."), + A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag: diag(8039, 1 /* Error */ , "A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag_8039", "A JSDoc '@template' tag may not follow a '@typedef', '@callback', or '@overload' tag"), Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9005, 1 /* Error */ , "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005", "Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit."), Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9006, 1 /* Error */ , "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006", "Declaration emit for this file requires using private name '{0}' from module '{1}'. An explicit type annotation may unblock declaration emit."), JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17e3, 1 /* Error */ , "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), @@ -7947,6 +7930,8 @@ ${lanes.join("\n")} This_may_be_converted_to_an_async_function: diag(80006, 2 /* Suggestion */ , "This_may_be_converted_to_an_async_function_80006", "This may be converted to an async function."), await_has_no_effect_on_the_type_of_this_expression: diag(80007, 2 /* Suggestion */ , "await_has_no_effect_on_the_type_of_this_expression_80007", "'await' has no effect on the type of this expression."), Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers: diag(80008, 2 /* Suggestion */ , "Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accur_80008", "Numeric literals with absolute values equal to 2^53 or greater are too large to be represented accurately as integers."), + JSDoc_typedef_may_be_converted_to_TypeScript_type: diag(80009, 2 /* Suggestion */ , "JSDoc_typedef_may_be_converted_to_TypeScript_type_80009", "JSDoc typedef may be converted to TypeScript type."), + JSDoc_typedefs_may_be_converted_to_TypeScript_types: diag(80010, 2 /* Suggestion */ , "JSDoc_typedefs_may_be_converted_to_TypeScript_types_80010", "JSDoc typedefs may be converted to TypeScript types."), Add_missing_super_call: diag(90001, 3 /* Message */ , "Add_missing_super_call_90001", "Add missing 'super()' call"), Make_super_call_the_first_statement_in_the_constructor: diag(90002, 3 /* Message */ , "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), Change_extends_to_implements: diag(90003, 3 /* Message */ , "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), @@ -8161,6 +8146,18 @@ ${lanes.join("\n")} Rename_param_tag_name_0_to_1: diag(95173, 3 /* Message */ , "Rename_param_tag_name_0_to_1_95173", "Rename '@param' tag name '{0}' to '{1}'"), Use_0: diag(95174, 3 /* Message */ , "Use_0_95174", "Use `{0}`."), Use_Number_isNaN_in_all_conditions: diag(95175, 3 /* Message */ , "Use_Number_isNaN_in_all_conditions_95175", "Use `Number.isNaN` in all conditions."), + Convert_typedef_to_TypeScript_type: diag(95176, 3 /* Message */ , "Convert_typedef_to_TypeScript_type_95176", "Convert typedef to TypeScript type."), + Convert_all_typedef_to_TypeScript_types: diag(95177, 3 /* Message */ , "Convert_all_typedef_to_TypeScript_types_95177", "Convert all typedef to TypeScript types."), + Move_to_file: diag(95178, 3 /* Message */ , "Move_to_file_95178", "Move to file"), + Cannot_move_to_file_selected_file_is_invalid: diag(95179, 3 /* Message */ , "Cannot_move_to_file_selected_file_is_invalid_95179", "Cannot move to file, selected file is invalid"), + Use_import_type: diag(95180, 3 /* Message */ , "Use_import_type_95180", "Use 'import type'"), + Use_type_0: diag(95181, 3 /* Message */ , "Use_type_0_95181", "Use 'type {0}'"), + Fix_all_with_type_only_imports: diag(95182, 3 /* Message */ , "Fix_all_with_type_only_imports_95182", "Fix all with type-only imports"), + Cannot_move_statements_to_the_selected_file: diag(95183, 3 /* Message */ , "Cannot_move_statements_to_the_selected_file_95183", "Cannot move statements to the selected file"), + Inline_variable: diag(95184, 3 /* Message */ , "Inline_variable_95184", "Inline variable"), + Could_not_find_variable_to_inline: diag(95185, 3 /* Message */ , "Could_not_find_variable_to_inline_95185", "Could not find variable to inline."), + Variables_with_multiple_declarations_cannot_be_inlined: diag(95186, 3 /* Message */ , "Variables_with_multiple_declarations_cannot_be_inlined_95186", "Variables with multiple declarations cannot be inlined."), + Add_missing_comma_for_object_member_completion_0: diag(95187, 3 /* Message */ , "Add_missing_comma_for_object_member_completion_0_95187", "Add missing comma for object member completion '{0}'."), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, 1 /* Error */ , "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, 1 /* Error */ , "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, 1 /* Error */ , "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), @@ -8187,8 +8184,8 @@ ${lanes.join("\n")} Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compiler_option_is_specified_e_g_Fragment: diag(18034, 3 /* Message */ , "Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compi_18034", "Specify the JSX fragment factory function to use when targeting 'react' JSX emit with 'jsxFactory' compiler option is specified, e.g. 'Fragment'."), Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(18035, 1 /* Error */ , "Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name_18035", "Invalid value for 'jsxFragmentFactory'. '{0}' is not a valid identifier or qualified-name."), Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator: diag(18036, 1 /* Error */ , "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036", "Class decorators can't be used with static private identifier. Consider removing the experimental decorator."), - Await_expression_cannot_be_used_inside_a_class_static_block: diag(18037, 1 /* Error */ , "Await_expression_cannot_be_used_inside_a_class_static_block_18037", "Await expression cannot be used inside a class static block."), - For_await_loops_cannot_be_used_inside_a_class_static_block: diag(18038, 1 /* Error */ , "For_await_loops_cannot_be_used_inside_a_class_static_block_18038", "'For await' loops cannot be used inside a class static block."), + await_expression_cannot_be_used_inside_a_class_static_block: diag(18037, 1 /* Error */ , "await_expression_cannot_be_used_inside_a_class_static_block_18037", "'await' expression cannot be used inside a class static block."), + for_await_loops_cannot_be_used_inside_a_class_static_block: diag(18038, 1 /* Error */ , "for_await_loops_cannot_be_used_inside_a_class_static_block_18038", "'for await' loops cannot be used inside a class static block."), Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block: diag(18039, 1 /* Error */ , "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039", "Invalid use of '{0}'. It cannot be used inside a class static block."), A_return_statement_cannot_be_used_inside_a_class_static_block: diag(18041, 1 /* Error */ , "A_return_statement_cannot_be_used_inside_a_class_static_block_18041", "A 'return' statement cannot be used inside a class static block."), _0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation: diag(18042, 1 /* Error */ , "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042", "'{0}' is a type and cannot be imported in JavaScript files. Use '{1}' in a JSDoc type annotation."), @@ -8200,16 +8197,19 @@ ${lanes.join("\n")} _0_is_possibly_undefined: diag(18048, 1 /* Error */ , "_0_is_possibly_undefined_18048", "'{0}' is possibly 'undefined'."), _0_is_possibly_null_or_undefined: diag(18049, 1 /* Error */ , "_0_is_possibly_null_or_undefined_18049", "'{0}' is possibly 'null' or 'undefined'."), The_value_0_cannot_be_used_here: diag(18050, 1 /* Error */ , "The_value_0_cannot_be_used_here_18050", "The value '{0}' cannot be used here."), - Compiler_option_0_cannot_be_given_an_empty_string: diag(18051, 1 /* Error */ , "Compiler_option_0_cannot_be_given_an_empty_string_18051", "Compiler option '{0}' cannot be given an empty string.") + Compiler_option_0_cannot_be_given_an_empty_string: diag(18051, 1 /* Error */ , "Compiler_option_0_cannot_be_given_an_empty_string_18051", "Compiler option '{0}' cannot be given an empty string."), + Non_abstract_class_0_does_not_implement_all_abstract_members_of_1: diag(18052, 1 /* Error */ , "Non_abstract_class_0_does_not_implement_all_abstract_members_of_1_18052", "Non-abstract class '{0}' does not implement all abstract members of '{1}'"), + Its_type_0_is_not_a_valid_JSX_element_type: diag(18053, 1 /* Error */ , "Its_type_0_is_not_a_valid_JSX_element_type_18053", "Its type '{0}' is not a valid JSX element type."), + await_using_statements_cannot_be_used_inside_a_class_static_block: diag(18054, 1 /* Error */ , "await_using_statements_cannot_be_used_inside_a_class_static_block_18054", "'await using' statements cannot be used inside a class static block.") }; } }); // src/compiler/scanner.ts function tokenIsIdentifierOrKeyword(token) { - return token >= 79 /* Identifier */ ; + return token >= 80 /* Identifier */ ; } function tokenIsIdentifierOrKeywordOrGreaterThan(token) { - return token === 31 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); + return token === 32 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); } function lookupInUnicodeMap(code, map2) { if (code < map2[0]) return false; @@ -8446,8 +8446,8 @@ ${lanes.join("\n")} } return false; } - function scanConflictMarkerTrivia(text, pos, error) { - if (error) error(Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength); + function scanConflictMarkerTrivia(text, pos, error2) { + if (error2) error2(Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength); const ch = text.charCodeAt(pos); const len = text.length; if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */ ) while(pos < len && !isLineBreak(text.charCodeAt(pos)))pos++; @@ -8597,8 +8597,8 @@ ${lanes.join("\n")} var text = textInitial; var pos; var end; - var startPos; - var tokenPos; + var fullStartPos; + var tokenStart; var token; var tokenValue; var tokenFlags; @@ -8606,21 +8606,24 @@ ${lanes.join("\n")} var inJSDocType = 0; setText(text, start, length2); var scanner2 = { - getStartPos: ()=>startPos, + getTokenFullStart: ()=>fullStartPos, + getStartPos: ()=>fullStartPos, + getTokenEnd: ()=>pos, getTextPos: ()=>pos, getToken: ()=>token, - getTokenPos: ()=>tokenPos, - getTokenText: ()=>text.substring(tokenPos, pos), + getTokenStart: ()=>tokenStart, + getTokenPos: ()=>tokenStart, + getTokenText: ()=>text.substring(tokenStart, pos), getTokenValue: ()=>tokenValue, hasUnicodeEscape: ()=>(tokenFlags & 1024 /* UnicodeEscape */ ) !== 0, hasExtendedUnicodeEscape: ()=>(tokenFlags & 8 /* ExtendedUnicodeEscape */ ) !== 0, hasPrecedingLineBreak: ()=>(tokenFlags & 1 /* PrecedingLineBreak */ ) !== 0, hasPrecedingJSDocComment: ()=>(tokenFlags & 2 /* PrecedingJSDocComment */ ) !== 0, - isIdentifier: ()=>token === 79 /* Identifier */ || token > 116 /* LastReservedWord */ , - isReservedWord: ()=>token >= 81 /* FirstReservedWord */ && token <= 116 /* LastReservedWord */ , + isIdentifier: ()=>token === 80 /* Identifier */ || token > 118 /* LastReservedWord */ , + isReservedWord: ()=>token >= 83 /* FirstReservedWord */ && token <= 118 /* LastReservedWord */ , isUnterminated: ()=>(tokenFlags & 4 /* Unterminated */ ) !== 0, getCommentDirectives: ()=>commentDirectives, - getNumericLiteralFlags: ()=>tokenFlags & 1008 /* NumericLiteralFlags */ , + getNumericLiteralFlags: ()=>tokenFlags & 25584 /* NumericLiteralFlags */ , getTokenFlags: ()=>tokenFlags, reScanGreaterToken: reScanGreaterToken, reScanAsteriskEqualsToken: reScanAsteriskEqualsToken, @@ -8637,6 +8640,7 @@ ${lanes.join("\n")} reScanInvalidIdentifier: reScanInvalidIdentifier, scanJsxToken: scanJsxToken, scanJsDocToken: scanJsDocToken, + scanJSDocCommentTextToken: scanJSDocCommentTextToken, scan: scan, getText: getText, clearCommentDirectives: clearCommentDirectives, @@ -8644,7 +8648,8 @@ ${lanes.join("\n")} setScriptTarget: setScriptTarget, setLanguageVariant: setLanguageVariant, setOnError: setOnError, - setTextPos: setTextPos, + resetTokenState: resetTokenState, + setTextPos: resetTokenState, setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, @@ -8653,15 +8658,15 @@ ${lanes.join("\n")} if (Debug.isDebugging) Object.defineProperty(scanner2, "__debugShowCurrentPositionInText", { get: ()=>{ const text2 = scanner2.getText(); - return text2.slice(0, scanner2.getStartPos()) + "║" + text2.slice(scanner2.getStartPos()); + return text2.slice(0, scanner2.getTokenFullStart()) + "\u2551" + text2.slice(scanner2.getTokenFullStart()); } }); return scanner2; - function error(message, errPos = pos, length3) { + function error2(message, errPos = pos, length3, arg0) { if (onError) { const oldPos = pos; pos = errPos; - onError(message, length3 || 0); + onError(message, length3 || 0, arg0); pos = oldPos; } } @@ -8678,8 +8683,11 @@ ${lanes.join("\n")} allowSeparator = false; isPreviousTokenSeparator = true; result += text.substring(start2, pos); - } else if (isPreviousTokenSeparator) error(Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); - else error(Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } else { + tokenFlags |= 16384 /* ContainsInvalidSeparator */ ; + if (isPreviousTokenSeparator) error2(Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + else error2(Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } pos++; start2 = pos; continue; @@ -8692,12 +8700,36 @@ ${lanes.join("\n")} } break; } - if (text.charCodeAt(pos - 1) === 95 /* _ */ ) error(Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + if (text.charCodeAt(pos - 1) === 95 /* _ */ ) { + tokenFlags |= 16384 /* ContainsInvalidSeparator */ ; + error2(Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } return result + text.substring(start2, pos); } function scanNumber() { - const start2 = pos; - const mainFragment = scanNumberFragment(); + let start2 = pos; + let mainFragment; + if (text.charCodeAt(pos) === 48 /* _0 */ ) { + pos++; + if (text.charCodeAt(pos) === 95 /* _ */ ) { + tokenFlags |= 16896 /* ContainsInvalidSeparator */ ; + error2(Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + pos--; + mainFragment = scanNumberFragment(); + } else if (!scanDigits()) { + tokenFlags |= 8192 /* ContainsLeadingZero */ ; + mainFragment = "" + +tokenValue; + } else if (!tokenValue) mainFragment = "0"; + else { + tokenValue = "" + parseInt(tokenValue, 8); + tokenFlags |= 32 /* Octal */ ; + const withMinus = token === 41 /* MinusToken */ ; + const literal = (withMinus ? "-" : "") + "0o" + (+tokenValue).toString(8); + if (withMinus) start2--; + error2(Diagnostics.Octal_literals_are_not_allowed_Use_the_syntax_0, start2, pos - start2, literal); + return 9 /* NumericLiteral */ ; + } + } else mainFragment = scanNumberFragment(); let decimalFragment; let scientificFragment; if (text.charCodeAt(pos) === 46 /* dot */ ) { @@ -8711,7 +8743,7 @@ ${lanes.join("\n")} if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */ ) pos++; const preNumericPart = pos; const finalFragment = scanNumberFragment(); - if (!finalFragment) error(Diagnostics.Digit_expected); + if (!finalFragment) error2(Diagnostics.Digit_expected); else { scientificFragment = text.substring(end2, preNumericPart) + finalFragment; end2 = pos; @@ -8723,38 +8755,43 @@ ${lanes.join("\n")} if (decimalFragment) result += "." + decimalFragment; if (scientificFragment) result += scientificFragment; } else result = text.substring(start2, end2); + if (tokenFlags & 8192 /* ContainsLeadingZero */ ) { + error2(Diagnostics.Decimals_with_leading_zeros_are_not_allowed, start2, end2 - start2); + tokenValue = "" + +result; + return 9 /* NumericLiteral */ ; + } if (decimalFragment !== void 0 || tokenFlags & 16 /* Scientific */ ) { checkForIdentifierStartAfterNumericLiteral(start2, decimalFragment === void 0 && !!(tokenFlags & 16 /* Scientific */ )); - return { - type: 8 /* NumericLiteral */ , - value: "" + +result - }; + tokenValue = "" + +result; + return 9 /* NumericLiteral */ ; } else { tokenValue = result; const type = checkBigIntSuffix(); checkForIdentifierStartAfterNumericLiteral(start2); - return { - type: type, - value: tokenValue - }; + return type; } } function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) { if (!isIdentifierStart(codePointAt(text, pos), languageVersion)) return; const identifierStart = pos; - const { length: length3 } = scanIdentifierParts(); + const { length: length3 } = scanIdentifierParts(); if (length3 === 1 && text[identifierStart] === "n") { - if (isScientific) error(Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1); - else error(Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1); + if (isScientific) error2(Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1); + else error2(Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1); } else { - error(Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length3); + error2(Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length3); pos = identifierStart; } } - function scanOctalDigits() { + function scanDigits() { const start2 = pos; - while(isOctalDigit(text.charCodeAt(pos)))pos++; - return +text.substring(start2, pos); + let isOctal = true; + while(isDigit(text.charCodeAt(pos))){ + if (!isOctalDigit(text.charCodeAt(pos))) isOctal = false; + pos++; + } + tokenValue = text.substring(start2, pos); + return isOctal; } function scanExactNumberOfHexDigits(count, canHaveSeparators) { const valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); @@ -8774,8 +8811,8 @@ ${lanes.join("\n")} if (allowSeparator) { allowSeparator = false; isPreviousTokenSeparator = true; - } else if (isPreviousTokenSeparator) error(Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); - else error(Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } else if (isPreviousTokenSeparator) error2(Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + else error2(Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); pos++; continue; } @@ -8787,7 +8824,7 @@ ${lanes.join("\n")} isPreviousTokenSeparator = false; } if (valueChars.length < minCount) valueChars = []; - if (text.charCodeAt(pos - 1) === 95 /* _ */ ) error(Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + if (text.charCodeAt(pos - 1) === 95 /* _ */ ) error2(Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); return String.fromCharCode(...valueChars); } function scanString(jsxAttributeString = false) { @@ -8799,7 +8836,7 @@ ${lanes.join("\n")} if (pos >= end) { result += text.substring(start2, pos); tokenFlags |= 4 /* Unterminated */ ; - error(Diagnostics.Unterminated_string_literal); + error2(Diagnostics.Unterminated_string_literal); break; } const ch = text.charCodeAt(pos); @@ -8810,21 +8847,21 @@ ${lanes.join("\n")} } if (ch === 92 /* backslash */ && !jsxAttributeString) { result += text.substring(start2, pos); - result += scanEscapeSequence(); + result += scanEscapeSequence(/*shouldEmitInvalidEscapeError*/ true); start2 = pos; continue; } if (isLineBreak(ch) && !jsxAttributeString) { result += text.substring(start2, pos); tokenFlags |= 4 /* Unterminated */ ; - error(Diagnostics.Unterminated_string_literal); + error2(Diagnostics.Unterminated_string_literal); break; } pos++; } return result; } - function scanTemplateAndSetTokenValue(isTaggedTemplate) { + function scanTemplateAndSetTokenValue(shouldEmitInvalidEscapeError) { const startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */ ; pos++; let start2 = pos; @@ -8834,26 +8871,26 @@ ${lanes.join("\n")} if (pos >= end) { contents += text.substring(start2, pos); tokenFlags |= 4 /* Unterminated */ ; - error(Diagnostics.Unterminated_template_literal); - resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */ ; + error2(Diagnostics.Unterminated_template_literal); + resultingToken = startedWithBacktick ? 15 /* NoSubstitutionTemplateLiteral */ : 18 /* TemplateTail */ ; break; } const currChar = text.charCodeAt(pos); if (currChar === 96 /* backtick */ ) { contents += text.substring(start2, pos); pos++; - resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */ ; + resultingToken = startedWithBacktick ? 15 /* NoSubstitutionTemplateLiteral */ : 18 /* TemplateTail */ ; break; } if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */ ) { contents += text.substring(start2, pos); pos += 2; - resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */ ; + resultingToken = startedWithBacktick ? 16 /* TemplateHead */ : 17 /* TemplateMiddle */ ; break; } if (currChar === 92 /* backslash */ ) { contents += text.substring(start2, pos); - contents += scanEscapeSequence(isTaggedTemplate); + contents += scanEscapeSequence(shouldEmitInvalidEscapeError); start2 = pos; continue; } @@ -8871,23 +8908,42 @@ ${lanes.join("\n")} tokenValue = contents; return resultingToken; } - function scanEscapeSequence(isTaggedTemplate) { + function scanEscapeSequence(shouldEmitInvalidEscapeError) { const start2 = pos; pos++; if (pos >= end) { - error(Diagnostics.Unexpected_end_of_text); + error2(Diagnostics.Unexpected_end_of_text); return ""; } const ch = text.charCodeAt(pos); pos++; switch(ch){ case 48 /* _0 */ : - if (isTaggedTemplate && pos < end && isDigit(text.charCodeAt(pos))) { - pos++; - tokenFlags |= 2048 /* ContainsInvalidEscape */ ; - return text.substring(start2, pos); - } - return "\0"; + if (pos >= end || !isDigit(text.charCodeAt(pos))) return "\x00"; + case 49 /* _1 */ : + case 50 /* _2 */ : + case 51 /* _3 */ : + if (pos < end && isOctalDigit(text.charCodeAt(pos))) pos++; + case 52 /* _4 */ : + case 53 /* _5 */ : + case 54 /* _6 */ : + case 55 /* _7 */ : + if (pos < end && isOctalDigit(text.charCodeAt(pos))) pos++; + tokenFlags |= 2048 /* ContainsInvalidEscape */ ; + if (shouldEmitInvalidEscapeError) { + const code = parseInt(text.substring(start2 + 1, pos), 8); + error2(Diagnostics.Octal_escape_sequences_are_not_allowed_Use_the_syntax_0, start2, pos - start2, "\\x" + padLeft(code.toString(16), 2, "0")); + return String.fromCharCode(code); + } + return text.substring(start2, pos); + case 56 /* _8 */ : + case 57 /* _9 */ : + tokenFlags |= 2048 /* ContainsInvalidEscape */ ; + if (shouldEmitInvalidEscapeError) { + error2(Diagnostics.Escape_sequence_0_is_not_allowed, start2, pos - start2, text.substring(start2, pos)); + return String.fromCharCode(ch); + } + return text.substring(start2, pos); case 98 /* b */ : return "\b"; case 116 /* t */ : @@ -8905,45 +8961,49 @@ ${lanes.join("\n")} case 34 /* doubleQuote */ : return '"'; case 117 /* u */ : - if (isTaggedTemplate) { - for(let escapePos = pos; escapePos < pos + 4; escapePos++)if (escapePos < end && !isHexDigit(text.charCodeAt(escapePos)) && text.charCodeAt(escapePos) !== 123 /* openBrace */ ) { - pos = escapePos; - tokenFlags |= 2048 /* ContainsInvalidEscape */ ; - return text.substring(start2, pos); - } - } if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */ ) { pos++; - if (isTaggedTemplate && !isHexDigit(text.charCodeAt(pos))) { + const escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); + const escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; + if (escapedValue < 0) { tokenFlags |= 2048 /* ContainsInvalidEscape */ ; + if (shouldEmitInvalidEscapeError) error2(Diagnostics.Hexadecimal_digit_expected); return text.substring(start2, pos); } - if (isTaggedTemplate) { - const savePos = pos; - const escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); - const escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; - if (!isCodePoint(escapedValue) || text.charCodeAt(pos) !== 125 /* closeBrace */ ) { - tokenFlags |= 2048 /* ContainsInvalidEscape */ ; - return text.substring(start2, pos); - } else pos = savePos; + if (!isCodePoint(escapedValue)) { + tokenFlags |= 2048 /* ContainsInvalidEscape */ ; + if (shouldEmitInvalidEscapeError) error2(Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive); + return text.substring(start2, pos); } - tokenFlags |= 8 /* ExtendedUnicodeEscape */ ; - return scanExtendedUnicodeEscape(); - } - tokenFlags |= 1024 /* UnicodeEscape */ ; - return scanHexadecimalEscape(/*numDigits*/ 4); - case 120 /* x */ : - if (isTaggedTemplate) { - if (!isHexDigit(text.charCodeAt(pos))) { + if (pos >= end) { tokenFlags |= 2048 /* ContainsInvalidEscape */ ; + if (shouldEmitInvalidEscapeError) error2(Diagnostics.Unexpected_end_of_text); return text.substring(start2, pos); - } else if (!isHexDigit(text.charCodeAt(pos + 1))) { - pos++; + } + if (text.charCodeAt(pos) !== 125 /* closeBrace */ ) { tokenFlags |= 2048 /* ContainsInvalidEscape */ ; + if (shouldEmitInvalidEscapeError) error2(Diagnostics.Unterminated_Unicode_escape_sequence); return text.substring(start2, pos); } + pos++; + tokenFlags |= 8 /* ExtendedUnicodeEscape */ ; + return utf16EncodeAsString(escapedValue); } - return scanHexadecimalEscape(/*numDigits*/ 2); + for(; pos < start2 + 6; pos++)if (!(pos < end && isHexDigit(text.charCodeAt(pos)))) { + tokenFlags |= 2048 /* ContainsInvalidEscape */ ; + if (shouldEmitInvalidEscapeError) error2(Diagnostics.Hexadecimal_digit_expected); + return text.substring(start2, pos); + } + tokenFlags |= 1024 /* UnicodeEscape */ ; + return String.fromCharCode(parseInt(text.substring(start2 + 2, pos), 16)); + case 120 /* x */ : + for(; pos < start2 + 4; pos++)if (!(pos < end && isHexDigit(text.charCodeAt(pos)))) { + tokenFlags |= 2048 /* ContainsInvalidEscape */ ; + if (shouldEmitInvalidEscapeError) error2(Diagnostics.Hexadecimal_digit_expected); + return text.substring(start2, pos); + } + tokenFlags |= 4096 /* HexEscape */ ; + return String.fromCharCode(parseInt(text.substring(start2 + 2, pos), 16)); case 13 /* carriageReturn */ : if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */ ) pos++; case 10 /* lineFeed */ : @@ -8954,31 +9014,23 @@ ${lanes.join("\n")} return String.fromCharCode(ch); } } - function scanHexadecimalEscape(numDigits) { - const escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false); - if (escapedValue >= 0) return String.fromCharCode(escapedValue); - else { - error(Diagnostics.Hexadecimal_digit_expected); - return ""; - } - } function scanExtendedUnicodeEscape() { const escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); const escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; let isInvalidExtendedEscape = false; if (escapedValue < 0) { - error(Diagnostics.Hexadecimal_digit_expected); + error2(Diagnostics.Hexadecimal_digit_expected); isInvalidExtendedEscape = true; } else if (escapedValue > 1114111) { - error(Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive); + error2(Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive); isInvalidExtendedEscape = true; } if (pos >= end) { - error(Diagnostics.Unexpected_end_of_text); + error2(Diagnostics.Unexpected_end_of_text); isInvalidExtendedEscape = true; } else if (text.charCodeAt(pos) === 125 /* closeBrace */ ) pos++; else { - error(Diagnostics.Unterminated_Unicode_escape_sequence); + error2(Diagnostics.Unterminated_Unicode_escape_sequence); isInvalidExtendedEscape = true; } if (isInvalidExtendedEscape) return ""; @@ -9041,7 +9093,7 @@ ${lanes.join("\n")} if (keyword !== void 0) return token = keyword; } } - return token = 79 /* Identifier */ ; + return token = 80 /* Identifier */ ; } function scanBinaryOrOctalDigits(base) { let value1 = ""; @@ -9054,8 +9106,8 @@ ${lanes.join("\n")} if (separatorAllowed) { separatorAllowed = false; isPreviousTokenSeparator = true; - } else if (isPreviousTokenSeparator) error(Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); - else error(Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } else if (isPreviousTokenSeparator) error2(Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + else error2(Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); pos++; continue; } @@ -9065,7 +9117,7 @@ ${lanes.join("\n")} pos++; isPreviousTokenSeparator = false; } - if (text.charCodeAt(pos - 1) === 95 /* _ */ ) error(Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + if (text.charCodeAt(pos - 1) === 95 /* _ */ ) error2(Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); return value1; } function checkBigIntSuffix() { @@ -9073,25 +9125,32 @@ ${lanes.join("\n")} tokenValue += "n"; if (tokenFlags & 384 /* BinaryOrOctalSpecifier */ ) tokenValue = parsePseudoBigInt(tokenValue) + "n"; pos++; - return 9 /* BigIntLiteral */ ; + return 10 /* BigIntLiteral */ ; } else { const numericValue = tokenFlags & 128 /* BinarySpecifier */ ? parseInt(tokenValue.slice(2), 2) : tokenFlags & 256 /* OctalSpecifier */ ? parseInt(tokenValue.slice(2), 8) : +tokenValue; tokenValue = "" + numericValue; - return 8 /* NumericLiteral */ ; + return 9 /* NumericLiteral */ ; } } function scan() { - startPos = pos; + fullStartPos = pos; tokenFlags = 0 /* None */ ; let asteriskSeen = false; while(true){ - tokenPos = pos; + tokenStart = pos; if (pos >= end) return token = 1 /* EndOfFileToken */ ; const ch = codePointAt(text, pos); - if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) { - pos = scanShebangTrivia(text, pos); - if (skipTrivia2) continue; - else return token = 6 /* ShebangTrivia */ ; + if (pos === 0) { + if (ch === 65533 /* replacementCharacter */ ) { + error2(Diagnostics.File_appears_to_be_binary); + pos = end; + return token = 8 /* NonTextFileMarkerTrivia */ ; + } + if (ch === 35 /* hash */ && isShebangTrivia(text, pos)) { + pos = scanShebangTrivia(text, pos); + if (skipTrivia2) continue; + else return token = 6 /* ShebangTrivia */ ; + } } switch(ch){ case 10 /* lineFeed */ : @@ -9136,68 +9195,68 @@ ${lanes.join("\n")} } case 33 /* exclamation */ : if (text.charCodeAt(pos + 1) === 61 /* equals */ ) { - if (text.charCodeAt(pos + 2) === 61 /* equals */ ) return pos += 3, token = 37 /* ExclamationEqualsEqualsToken */ ; - return pos += 2, token = 35 /* ExclamationEqualsToken */ ; + if (text.charCodeAt(pos + 2) === 61 /* equals */ ) return pos += 3, token = 38 /* ExclamationEqualsEqualsToken */ ; + return pos += 2, token = 36 /* ExclamationEqualsToken */ ; } pos++; - return token = 53 /* ExclamationToken */ ; + return token = 54 /* ExclamationToken */ ; case 34 /* doubleQuote */ : case 39 /* singleQuote */ : tokenValue = scanString(); - return token = 10 /* StringLiteral */ ; + return token = 11 /* StringLiteral */ ; case 96 /* backtick */ : - return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ false); + return token = scanTemplateAndSetTokenValue(/*shouldEmitInvalidEscapeError*/ false); case 37 /* percent */ : - if (text.charCodeAt(pos + 1) === 61 /* equals */ ) return pos += 2, token = 69 /* PercentEqualsToken */ ; + if (text.charCodeAt(pos + 1) === 61 /* equals */ ) return pos += 2, token = 70 /* PercentEqualsToken */ ; pos++; - return token = 44 /* PercentToken */ ; + return token = 45 /* PercentToken */ ; case 38 /* ampersand */ : if (text.charCodeAt(pos + 1) === 38 /* ampersand */ ) { - if (text.charCodeAt(pos + 2) === 61 /* equals */ ) return pos += 3, token = 76 /* AmpersandAmpersandEqualsToken */ ; - return pos += 2, token = 55 /* AmpersandAmpersandToken */ ; + if (text.charCodeAt(pos + 2) === 61 /* equals */ ) return pos += 3, token = 77 /* AmpersandAmpersandEqualsToken */ ; + return pos += 2, token = 56 /* AmpersandAmpersandToken */ ; } - if (text.charCodeAt(pos + 1) === 61 /* equals */ ) return pos += 2, token = 73 /* AmpersandEqualsToken */ ; + if (text.charCodeAt(pos + 1) === 61 /* equals */ ) return pos += 2, token = 74 /* AmpersandEqualsToken */ ; pos++; - return token = 50 /* AmpersandToken */ ; + return token = 51 /* AmpersandToken */ ; case 40 /* openParen */ : pos++; - return token = 20 /* OpenParenToken */ ; + return token = 21 /* OpenParenToken */ ; case 41 /* closeParen */ : pos++; - return token = 21 /* CloseParenToken */ ; + return token = 22 /* CloseParenToken */ ; case 42 /* asterisk */ : - if (text.charCodeAt(pos + 1) === 61 /* equals */ ) return pos += 2, token = 66 /* AsteriskEqualsToken */ ; + if (text.charCodeAt(pos + 1) === 61 /* equals */ ) return pos += 2, token = 67 /* AsteriskEqualsToken */ ; if (text.charCodeAt(pos + 1) === 42 /* asterisk */ ) { - if (text.charCodeAt(pos + 2) === 61 /* equals */ ) return pos += 3, token = 67 /* AsteriskAsteriskEqualsToken */ ; - return pos += 2, token = 42 /* AsteriskAsteriskToken */ ; + if (text.charCodeAt(pos + 2) === 61 /* equals */ ) return pos += 3, token = 68 /* AsteriskAsteriskEqualsToken */ ; + return pos += 2, token = 43 /* AsteriskAsteriskToken */ ; } pos++; if (inJSDocType && !asteriskSeen && tokenFlags & 1 /* PrecedingLineBreak */ ) { asteriskSeen = true; continue; } - return token = 41 /* AsteriskToken */ ; + return token = 42 /* AsteriskToken */ ; case 43 /* plus */ : - if (text.charCodeAt(pos + 1) === 43 /* plus */ ) return pos += 2, token = 45 /* PlusPlusToken */ ; - if (text.charCodeAt(pos + 1) === 61 /* equals */ ) return pos += 2, token = 64 /* PlusEqualsToken */ ; + if (text.charCodeAt(pos + 1) === 43 /* plus */ ) return pos += 2, token = 46 /* PlusPlusToken */ ; + if (text.charCodeAt(pos + 1) === 61 /* equals */ ) return pos += 2, token = 65 /* PlusEqualsToken */ ; pos++; - return token = 39 /* PlusToken */ ; + return token = 40 /* PlusToken */ ; case 44 /* comma */ : pos++; - return token = 27 /* CommaToken */ ; + return token = 28 /* CommaToken */ ; case 45 /* minus */ : - if (text.charCodeAt(pos + 1) === 45 /* minus */ ) return pos += 2, token = 46 /* MinusMinusToken */ ; - if (text.charCodeAt(pos + 1) === 61 /* equals */ ) return pos += 2, token = 65 /* MinusEqualsToken */ ; + if (text.charCodeAt(pos + 1) === 45 /* minus */ ) return pos += 2, token = 47 /* MinusMinusToken */ ; + if (text.charCodeAt(pos + 1) === 61 /* equals */ ) return pos += 2, token = 66 /* MinusEqualsToken */ ; pos++; - return token = 40 /* MinusToken */ ; + return token = 41 /* MinusToken */ ; case 46 /* dot */ : if (isDigit(text.charCodeAt(pos + 1))) { - tokenValue = scanNumber().value; - return token = 8 /* NumericLiteral */ ; + scanNumber(); + return token = 9 /* NumericLiteral */ ; } - if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */ ) return pos += 3, token = 25 /* DotDotDotToken */ ; + if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */ ) return pos += 3, token = 26 /* DotDotDotToken */ ; pos++; - return token = 24 /* DotToken */ ; + return token = 25 /* DotToken */ ; case 47 /* slash */ : if (text.charCodeAt(pos + 1) === 47 /* slash */ ) { pos += 2; @@ -9205,7 +9264,7 @@ ${lanes.join("\n")} if (isLineBreak(text.charCodeAt(pos))) break; pos++; } - commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenPos, pos), commentDirectiveRegExSingleLine, tokenPos); + commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenStart, pos), commentDirectiveRegExSingleLine, tokenStart); if (skipTrivia2) continue; else return token = 2 /* SingleLineCommentTrivia */ ; } @@ -9213,7 +9272,7 @@ ${lanes.join("\n")} pos += 2; if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */ ) tokenFlags |= 2 /* PrecedingJSDocComment */ ; let commentClosed = false; - let lastLineStart = tokenPos; + let lastLineStart = tokenStart; while(pos < end){ const ch2 = text.charCodeAt(pos); if (ch2 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */ ) { @@ -9228,22 +9287,22 @@ ${lanes.join("\n")} } } commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart); - if (!commentClosed) error(Diagnostics.Asterisk_Slash_expected); + if (!commentClosed) error2(Diagnostics.Asterisk_Slash_expected); if (skipTrivia2) continue; else { if (!commentClosed) tokenFlags |= 4 /* Unterminated */ ; return token = 3 /* MultiLineCommentTrivia */ ; } } - if (text.charCodeAt(pos + 1) === 61 /* equals */ ) return pos += 2, token = 68 /* SlashEqualsToken */ ; + if (text.charCodeAt(pos + 1) === 61 /* equals */ ) return pos += 2, token = 69 /* SlashEqualsToken */ ; pos++; - return token = 43 /* SlashToken */ ; + return token = 44 /* SlashToken */ ; case 48 /* _0 */ : if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */ )) { pos += 2; tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); if (!tokenValue) { - error(Diagnostics.Hexadecimal_digit_expected); + error2(Diagnostics.Hexadecimal_digit_expected); tokenValue = "0"; } tokenValue = "0x" + tokenValue; @@ -9253,7 +9312,7 @@ ${lanes.join("\n")} pos += 2; tokenValue = scanBinaryOrOctalDigits(/* base */ 2); if (!tokenValue) { - error(Diagnostics.Binary_digit_expected); + error2(Diagnostics.Binary_digit_expected); tokenValue = "0"; } tokenValue = "0b" + tokenValue; @@ -9263,18 +9322,13 @@ ${lanes.join("\n")} pos += 2; tokenValue = scanBinaryOrOctalDigits(/* base */ 8); if (!tokenValue) { - error(Diagnostics.Octal_digit_expected); + error2(Diagnostics.Octal_digit_expected); tokenValue = "0"; } tokenValue = "0o" + tokenValue; tokenFlags |= 256 /* OctalSpecifier */ ; return token = checkBigIntSuffix(); } - if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) { - tokenValue = "" + scanOctalDigits(); - tokenFlags |= 32 /* Octal */ ; - return token = 8 /* NumericLiteral */ ; - } case 49 /* _1 */ : case 50 /* _2 */ : case 51 /* _3 */ : @@ -9284,92 +9338,91 @@ ${lanes.join("\n")} case 55 /* _7 */ : case 56 /* _8 */ : case 57 /* _9 */ : - ({ type: token , value: tokenValue } = scanNumber()); - return token; + return token = scanNumber(); case 58 /* colon */ : pos++; - return token = 58 /* ColonToken */ ; + return token = 59 /* ColonToken */ ; case 59 /* semicolon */ : pos++; - return token = 26 /* SemicolonToken */ ; + return token = 27 /* SemicolonToken */ ; case 60 /* lessThan */ : if (isConflictMarkerTrivia(text, pos)) { - pos = scanConflictMarkerTrivia(text, pos, error); + pos = scanConflictMarkerTrivia(text, pos, error2); if (skipTrivia2) continue; else return token = 7 /* ConflictMarkerTrivia */ ; } if (text.charCodeAt(pos + 1) === 60 /* lessThan */ ) { - if (text.charCodeAt(pos + 2) === 61 /* equals */ ) return pos += 3, token = 70 /* LessThanLessThanEqualsToken */ ; - return pos += 2, token = 47 /* LessThanLessThanToken */ ; + if (text.charCodeAt(pos + 2) === 61 /* equals */ ) return pos += 3, token = 71 /* LessThanLessThanEqualsToken */ ; + return pos += 2, token = 48 /* LessThanLessThanToken */ ; } - if (text.charCodeAt(pos + 1) === 61 /* equals */ ) return pos += 2, token = 32 /* LessThanEqualsToken */ ; - if (languageVariant === 1 /* JSX */ && text.charCodeAt(pos + 1) === 47 /* slash */ && text.charCodeAt(pos + 2) !== 42 /* asterisk */ ) return pos += 2, token = 30 /* LessThanSlashToken */ ; + if (text.charCodeAt(pos + 1) === 61 /* equals */ ) return pos += 2, token = 33 /* LessThanEqualsToken */ ; + if (languageVariant === 1 /* JSX */ && text.charCodeAt(pos + 1) === 47 /* slash */ && text.charCodeAt(pos + 2) !== 42 /* asterisk */ ) return pos += 2, token = 31 /* LessThanSlashToken */ ; pos++; - return token = 29 /* LessThanToken */ ; + return token = 30 /* LessThanToken */ ; case 61 /* equals */ : if (isConflictMarkerTrivia(text, pos)) { - pos = scanConflictMarkerTrivia(text, pos, error); + pos = scanConflictMarkerTrivia(text, pos, error2); if (skipTrivia2) continue; else return token = 7 /* ConflictMarkerTrivia */ ; } if (text.charCodeAt(pos + 1) === 61 /* equals */ ) { - if (text.charCodeAt(pos + 2) === 61 /* equals */ ) return pos += 3, token = 36 /* EqualsEqualsEqualsToken */ ; - return pos += 2, token = 34 /* EqualsEqualsToken */ ; + if (text.charCodeAt(pos + 2) === 61 /* equals */ ) return pos += 3, token = 37 /* EqualsEqualsEqualsToken */ ; + return pos += 2, token = 35 /* EqualsEqualsToken */ ; } - if (text.charCodeAt(pos + 1) === 62 /* greaterThan */ ) return pos += 2, token = 38 /* EqualsGreaterThanToken */ ; + if (text.charCodeAt(pos + 1) === 62 /* greaterThan */ ) return pos += 2, token = 39 /* EqualsGreaterThanToken */ ; pos++; - return token = 63 /* EqualsToken */ ; + return token = 64 /* EqualsToken */ ; case 62 /* greaterThan */ : if (isConflictMarkerTrivia(text, pos)) { - pos = scanConflictMarkerTrivia(text, pos, error); + pos = scanConflictMarkerTrivia(text, pos, error2); if (skipTrivia2) continue; else return token = 7 /* ConflictMarkerTrivia */ ; } pos++; - return token = 31 /* GreaterThanToken */ ; + return token = 32 /* GreaterThanToken */ ; case 63 /* question */ : - if (text.charCodeAt(pos + 1) === 46 /* dot */ && !isDigit(text.charCodeAt(pos + 2))) return pos += 2, token = 28 /* QuestionDotToken */ ; + if (text.charCodeAt(pos + 1) === 46 /* dot */ && !isDigit(text.charCodeAt(pos + 2))) return pos += 2, token = 29 /* QuestionDotToken */ ; if (text.charCodeAt(pos + 1) === 63 /* question */ ) { - if (text.charCodeAt(pos + 2) === 61 /* equals */ ) return pos += 3, token = 77 /* QuestionQuestionEqualsToken */ ; - return pos += 2, token = 60 /* QuestionQuestionToken */ ; + if (text.charCodeAt(pos + 2) === 61 /* equals */ ) return pos += 3, token = 78 /* QuestionQuestionEqualsToken */ ; + return pos += 2, token = 61 /* QuestionQuestionToken */ ; } pos++; - return token = 57 /* QuestionToken */ ; + return token = 58 /* QuestionToken */ ; case 91 /* openBracket */ : pos++; - return token = 22 /* OpenBracketToken */ ; + return token = 23 /* OpenBracketToken */ ; case 93 /* closeBracket */ : pos++; - return token = 23 /* CloseBracketToken */ ; + return token = 24 /* CloseBracketToken */ ; case 94 /* caret */ : - if (text.charCodeAt(pos + 1) === 61 /* equals */ ) return pos += 2, token = 78 /* CaretEqualsToken */ ; + if (text.charCodeAt(pos + 1) === 61 /* equals */ ) return pos += 2, token = 79 /* CaretEqualsToken */ ; pos++; - return token = 52 /* CaretToken */ ; + return token = 53 /* CaretToken */ ; case 123 /* openBrace */ : pos++; - return token = 18 /* OpenBraceToken */ ; + return token = 19 /* OpenBraceToken */ ; case 124 /* bar */ : if (isConflictMarkerTrivia(text, pos)) { - pos = scanConflictMarkerTrivia(text, pos, error); + pos = scanConflictMarkerTrivia(text, pos, error2); if (skipTrivia2) continue; else return token = 7 /* ConflictMarkerTrivia */ ; } if (text.charCodeAt(pos + 1) === 124 /* bar */ ) { - if (text.charCodeAt(pos + 2) === 61 /* equals */ ) return pos += 3, token = 75 /* BarBarEqualsToken */ ; - return pos += 2, token = 56 /* BarBarToken */ ; + if (text.charCodeAt(pos + 2) === 61 /* equals */ ) return pos += 3, token = 76 /* BarBarEqualsToken */ ; + return pos += 2, token = 57 /* BarBarToken */ ; } - if (text.charCodeAt(pos + 1) === 61 /* equals */ ) return pos += 2, token = 74 /* BarEqualsToken */ ; + if (text.charCodeAt(pos + 1) === 61 /* equals */ ) return pos += 2, token = 75 /* BarEqualsToken */ ; pos++; - return token = 51 /* BarToken */ ; + return token = 52 /* BarToken */ ; case 125 /* closeBrace */ : pos++; - return token = 19 /* CloseBraceToken */ ; + return token = 20 /* CloseBraceToken */ ; case 126 /* tilde */ : pos++; - return token = 54 /* TildeToken */ ; + return token = 55 /* TildeToken */ ; case 64 /* at */ : pos++; - return token = 59 /* AtToken */ ; + return token = 60 /* AtToken */ ; case 92 /* backslash */ : const extendedCookedChar = peekExtendedUnicodeEscape(); if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) { @@ -9385,12 +9438,12 @@ ${lanes.join("\n")} tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts(); return token = getIdentifierToken(); } - error(Diagnostics.Invalid_character); + error2(Diagnostics.Invalid_character); pos++; return token = 0 /* Unknown */ ; case 35 /* hash */ : if (pos !== 0 && text[pos + 1] === "!") { - error(Diagnostics.can_only_be_used_at_the_start_of_a_file); + error2(Diagnostics.can_only_be_used_at_the_start_of_a_file); pos++; return token = 0 /* Unknown */ ; } @@ -9402,14 +9455,14 @@ ${lanes.join("\n")} pos += 3; tokenFlags |= 8 /* ExtendedUnicodeEscape */ ; tokenValue = "#" + scanExtendedUnicodeEscape() + scanIdentifierParts(); - return token = 80 /* PrivateIdentifier */ ; + return token = 81 /* PrivateIdentifier */ ; } const cookedChar2 = peekUnicodeEscape(); if (cookedChar2 >= 0 && isIdentifierStart(cookedChar2, languageVersion)) { pos += 6; tokenFlags |= 1024 /* UnicodeEscape */ ; tokenValue = "#" + String.fromCharCode(cookedChar2) + scanIdentifierParts(); - return token = 80 /* PrivateIdentifier */ ; + return token = 81 /* PrivateIdentifier */ ; } pos--; } @@ -9418,9 +9471,9 @@ ${lanes.join("\n")} scanIdentifier(charAfterHash, languageVersion); } else { tokenValue = "#"; - error(Diagnostics.Invalid_character, pos++, charSize(ch)); + error2(Diagnostics.Invalid_character, pos++, charSize(ch)); } - return token = 80 /* PrivateIdentifier */ ; + return token = 81 /* PrivateIdentifier */ ; default: const identifierKind = scanIdentifier(ch, languageVersion); if (identifierKind) return token = identifierKind; @@ -9433,7 +9486,7 @@ ${lanes.join("\n")} continue; } const size = charSize(ch); - error(Diagnostics.Invalid_character, pos, size); + error2(Diagnostics.Invalid_character, pos, size); pos += size; return token = 0 /* Unknown */ ; } @@ -9441,7 +9494,7 @@ ${lanes.join("\n")} } function reScanInvalidIdentifier() { Debug.assert(token === 0 /* Unknown */ , "'reScanInvalidIdentifier' should only be called when the current token is 'SyntaxKind.Unknown'."); - pos = tokenPos = startPos; + pos = tokenStart = fullStartPos; tokenFlags = 0; const ch = codePointAt(text, pos); const identifierKind = scanIdentifier(ch, 99 /* ESNext */ ); @@ -9454,49 +9507,49 @@ ${lanes.join("\n")} if (isIdentifierStart(ch, languageVersion2)) { pos += charSize(ch); while(pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion2))pos += charSize(ch); - tokenValue = text.substring(tokenPos, pos); + tokenValue = text.substring(tokenStart, pos); if (ch === 92 /* backslash */ ) tokenValue += scanIdentifierParts(); return getIdentifierToken(); } } function reScanGreaterToken() { - if (token === 31 /* GreaterThanToken */ ) { + if (token === 32 /* GreaterThanToken */ ) { if (text.charCodeAt(pos) === 62 /* greaterThan */ ) { if (text.charCodeAt(pos + 1) === 62 /* greaterThan */ ) { - if (text.charCodeAt(pos + 2) === 61 /* equals */ ) return pos += 3, token = 72 /* GreaterThanGreaterThanGreaterThanEqualsToken */ ; - return pos += 2, token = 49 /* GreaterThanGreaterThanGreaterThanToken */ ; + if (text.charCodeAt(pos + 2) === 61 /* equals */ ) return pos += 3, token = 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */ ; + return pos += 2, token = 50 /* GreaterThanGreaterThanGreaterThanToken */ ; } - if (text.charCodeAt(pos + 1) === 61 /* equals */ ) return pos += 2, token = 71 /* GreaterThanGreaterThanEqualsToken */ ; + if (text.charCodeAt(pos + 1) === 61 /* equals */ ) return pos += 2, token = 72 /* GreaterThanGreaterThanEqualsToken */ ; pos++; - return token = 48 /* GreaterThanGreaterThanToken */ ; + return token = 49 /* GreaterThanGreaterThanToken */ ; } if (text.charCodeAt(pos) === 61 /* equals */ ) { pos++; - return token = 33 /* GreaterThanEqualsToken */ ; + return token = 34 /* GreaterThanEqualsToken */ ; } } return token; } function reScanAsteriskEqualsToken() { - Debug.assert(token === 66 /* AsteriskEqualsToken */ , "'reScanAsteriskEqualsToken' should only be called on a '*='"); - pos = tokenPos + 1; - return token = 63 /* EqualsToken */ ; + Debug.assert(token === 67 /* AsteriskEqualsToken */ , "'reScanAsteriskEqualsToken' should only be called on a '*='"); + pos = tokenStart + 1; + return token = 64 /* EqualsToken */ ; } function reScanSlashToken() { - if (token === 43 /* SlashToken */ || token === 68 /* SlashEqualsToken */ ) { - let p = tokenPos + 1; + if (token === 44 /* SlashToken */ || token === 69 /* SlashEqualsToken */ ) { + let p = tokenStart + 1; let inEscape = false; let inCharacterClass = false; while(true){ if (p >= end) { tokenFlags |= 4 /* Unterminated */ ; - error(Diagnostics.Unterminated_regular_expression_literal); + error2(Diagnostics.Unterminated_regular_expression_literal); break; } const ch = text.charCodeAt(p); if (isLineBreak(ch)) { tokenFlags |= 4 /* Unterminated */ ; - error(Diagnostics.Unterminated_regular_expression_literal); + error2(Diagnostics.Unterminated_regular_expression_literal); break; } if (inEscape) inEscape = false; @@ -9510,8 +9563,8 @@ ${lanes.join("\n")} } while(p < end && isIdentifierPart(text.charCodeAt(p), languageVersion))p++; pos = p; - tokenValue = text.substring(tokenPos, pos); - token = 13 /* RegularExpressionLiteral */ ; + tokenValue = text.substring(tokenStart, pos); + token = 14 /* RegularExpressionLiteral */ ; } return token; } @@ -9538,52 +9591,51 @@ ${lanes.join("\n")} return void 0; } function reScanTemplateToken(isTaggedTemplate) { - Debug.assert(token === 19 /* CloseBraceToken */ , "'reScanTemplateToken' should only be called on a '}'"); - pos = tokenPos; - return token = scanTemplateAndSetTokenValue(isTaggedTemplate); + pos = tokenStart; + return token = scanTemplateAndSetTokenValue(!isTaggedTemplate); } function reScanTemplateHeadOrNoSubstitutionTemplate() { - pos = tokenPos; - return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ true); + pos = tokenStart; + return token = scanTemplateAndSetTokenValue(/*shouldEmitInvalidEscapeError*/ true); } function reScanJsxToken(allowMultilineJsxText = true) { - pos = tokenPos = startPos; + pos = tokenStart = fullStartPos; return token = scanJsxToken(allowMultilineJsxText); } function reScanLessThanToken() { - if (token === 47 /* LessThanLessThanToken */ ) { - pos = tokenPos + 1; - return token = 29 /* LessThanToken */ ; + if (token === 48 /* LessThanLessThanToken */ ) { + pos = tokenStart + 1; + return token = 30 /* LessThanToken */ ; } return token; } function reScanHashToken() { - if (token === 80 /* PrivateIdentifier */ ) { - pos = tokenPos + 1; - return token = 62 /* HashToken */ ; + if (token === 81 /* PrivateIdentifier */ ) { + pos = tokenStart + 1; + return token = 63 /* HashToken */ ; } return token; } function reScanQuestionToken() { - Debug.assert(token === 60 /* QuestionQuestionToken */ , "'reScanQuestionToken' should only be called on a '??'"); - pos = tokenPos + 1; - return token = 57 /* QuestionToken */ ; + Debug.assert(token === 61 /* QuestionQuestionToken */ , "'reScanQuestionToken' should only be called on a '??'"); + pos = tokenStart + 1; + return token = 58 /* QuestionToken */ ; } function scanJsxToken(allowMultilineJsxText = true) { - startPos = tokenPos = pos; + fullStartPos = tokenStart = pos; if (pos >= end) return token = 1 /* EndOfFileToken */ ; let char = text.charCodeAt(pos); if (char === 60 /* lessThan */ ) { if (text.charCodeAt(pos + 1) === 47 /* slash */ ) { pos += 2; - return token = 30 /* LessThanSlashToken */ ; + return token = 31 /* LessThanSlashToken */ ; } pos++; - return token = 29 /* LessThanToken */ ; + return token = 30 /* LessThanToken */ ; } if (char === 123 /* openBrace */ ) { pos++; - return token = 18 /* OpenBraceToken */ ; + return token = 19 /* OpenBraceToken */ ; } let firstNonWhitespace = 0; while(pos < end){ @@ -9591,66 +9643,67 @@ ${lanes.join("\n")} if (char === 123 /* openBrace */ ) break; if (char === 60 /* lessThan */ ) { if (isConflictMarkerTrivia(text, pos)) { - pos = scanConflictMarkerTrivia(text, pos, error); + pos = scanConflictMarkerTrivia(text, pos, error2); return token = 7 /* ConflictMarkerTrivia */ ; } break; } - if (char === 62 /* greaterThan */ ) error(Diagnostics.Unexpected_token_Did_you_mean_or_gt, pos, 1); - if (char === 125 /* closeBrace */ ) error(Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1); + if (char === 62 /* greaterThan */ ) error2(Diagnostics.Unexpected_token_Did_you_mean_or_gt, pos, 1); + if (char === 125 /* closeBrace */ ) error2(Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1); if (isLineBreak(char) && firstNonWhitespace === 0) firstNonWhitespace = -1; else if (!allowMultilineJsxText && isLineBreak(char) && firstNonWhitespace > 0) break; else if (!isWhiteSpaceLike(char)) firstNonWhitespace = pos; pos++; } - tokenValue = text.substring(startPos, pos); - return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */ ; + tokenValue = text.substring(fullStartPos, pos); + return firstNonWhitespace === -1 ? 13 /* JsxTextAllWhiteSpaces */ : 12 /* JsxText */ ; } function scanJsxIdentifier() { if (tokenIsIdentifierOrKeyword(token)) { - let namespaceSeparator = false; while(pos < end){ const ch = text.charCodeAt(pos); if (ch === 45 /* minus */ ) { tokenValue += "-"; pos++; continue; - } else if (ch === 58 /* colon */ && !namespaceSeparator) { - tokenValue += ":"; - pos++; - namespaceSeparator = true; - token = 79 /* Identifier */ ; - continue; } const oldPos = pos; tokenValue += scanIdentifierParts(); if (pos === oldPos) break; } - if (tokenValue.slice(-1) === ":") { - tokenValue = tokenValue.slice(0, -1); - pos--; - } return getIdentifierToken(); } return token; } function scanJsxAttributeValue() { - startPos = pos; + fullStartPos = pos; switch(text.charCodeAt(pos)){ case 34 /* doubleQuote */ : case 39 /* singleQuote */ : tokenValue = scanString(/*jsxAttributeString*/ true); - return token = 10 /* StringLiteral */ ; + return token = 11 /* StringLiteral */ ; default: return scan(); } } function reScanJsxAttributeValue() { - pos = tokenPos = startPos; + pos = tokenStart = fullStartPos; return scanJsxAttributeValue(); } + function scanJSDocCommentTextToken(inBackticks) { + fullStartPos = tokenStart = pos; + tokenFlags = 0 /* None */ ; + if (pos >= end) return token = 1 /* EndOfFileToken */ ; + for(let ch = text.charCodeAt(pos); pos < end && !isLineBreak(ch) && ch !== 96 /* backtick */ ; ch = codePointAt(text, ++pos))if (!inBackticks) { + if (ch === 123 /* openBrace */ ) break; + else if (ch === 64 /* at */ && pos - 1 >= 0 && isWhiteSpaceSingleLine(text.charCodeAt(pos - 1)) && !(pos + 1 < end && isWhiteSpaceLike(text.charCodeAt(pos + 1)))) break; + } + if (pos === tokenStart) return scanJsDocToken(); + tokenValue = text.substring(tokenStart, pos); + return token = 82 /* JSDocCommentTextToken */ ; + } function scanJsDocToken() { - startPos = tokenPos = pos; + fullStartPos = tokenStart = pos; tokenFlags = 0 /* None */ ; if (pos >= end) return token = 1 /* EndOfFileToken */ ; const ch = codePointAt(text, pos); @@ -9663,36 +9716,36 @@ ${lanes.join("\n")} while(pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos)))pos++; return token = 5 /* WhitespaceTrivia */ ; case 64 /* at */ : - return token = 59 /* AtToken */ ; + return token = 60 /* AtToken */ ; case 13 /* carriageReturn */ : if (text.charCodeAt(pos) === 10 /* lineFeed */ ) pos++; case 10 /* lineFeed */ : tokenFlags |= 1 /* PrecedingLineBreak */ ; return token = 4 /* NewLineTrivia */ ; case 42 /* asterisk */ : - return token = 41 /* AsteriskToken */ ; + return token = 42 /* AsteriskToken */ ; case 123 /* openBrace */ : - return token = 18 /* OpenBraceToken */ ; + return token = 19 /* OpenBraceToken */ ; case 125 /* closeBrace */ : - return token = 19 /* CloseBraceToken */ ; + return token = 20 /* CloseBraceToken */ ; case 91 /* openBracket */ : - return token = 22 /* OpenBracketToken */ ; + return token = 23 /* OpenBracketToken */ ; case 93 /* closeBracket */ : - return token = 23 /* CloseBracketToken */ ; + return token = 24 /* CloseBracketToken */ ; case 60 /* lessThan */ : - return token = 29 /* LessThanToken */ ; + return token = 30 /* LessThanToken */ ; case 62 /* greaterThan */ : - return token = 31 /* GreaterThanToken */ ; + return token = 32 /* GreaterThanToken */ ; case 61 /* equals */ : - return token = 63 /* EqualsToken */ ; + return token = 64 /* EqualsToken */ ; case 44 /* comma */ : - return token = 27 /* CommaToken */ ; + return token = 28 /* CommaToken */ ; case 46 /* dot */ : - return token = 24 /* DotToken */ ; + return token = 25 /* DotToken */ ; case 96 /* backtick */ : - return token = 61 /* BacktickToken */ ; + return token = 62 /* BacktickToken */ ; case 35 /* hash */ : - return token = 62 /* HashToken */ ; + return token = 63 /* HashToken */ ; case 92 /* backslash */ : pos--; const extendedCookedChar = peekExtendedUnicodeEscape(); @@ -9715,23 +9768,23 @@ ${lanes.join("\n")} if (isIdentifierStart(ch, languageVersion)) { let char = ch; while(pos < end && isIdentifierPart(char = codePointAt(text, pos), languageVersion) || text.charCodeAt(pos) === 45 /* minus */ )pos += charSize(char); - tokenValue = text.substring(tokenPos, pos); + tokenValue = text.substring(tokenStart, pos); if (char === 92 /* backslash */ ) tokenValue += scanIdentifierParts(); return token = getIdentifierToken(); } else return token = 0 /* Unknown */ ; } function speculationHelper(callback, isLookahead) { const savePos = pos; - const saveStartPos = startPos; - const saveTokenPos = tokenPos; + const saveStartPos = fullStartPos; + const saveTokenPos = tokenStart; const saveToken = token; const saveTokenValue = tokenValue; const saveTokenFlags = tokenFlags; const result = callback(); if (!result || isLookahead) { pos = savePos; - startPos = saveStartPos; - tokenPos = saveTokenPos; + fullStartPos = saveStartPos; + tokenStart = saveTokenPos; token = saveToken; tokenValue = saveTokenValue; tokenFlags = saveTokenFlags; @@ -9741,8 +9794,8 @@ ${lanes.join("\n")} function scanRange(start2, length3, callback) { const saveEnd = end; const savePos = pos; - const saveStartPos = startPos; - const saveTokenPos = tokenPos; + const saveStartPos = fullStartPos; + const saveTokenPos = tokenStart; const saveToken = token; const saveTokenValue = tokenValue; const saveTokenFlags = tokenFlags; @@ -9751,8 +9804,8 @@ ${lanes.join("\n")} const result = callback(); end = saveEnd; pos = savePos; - startPos = saveStartPos; - tokenPos = saveTokenPos; + fullStartPos = saveStartPos; + tokenStart = saveTokenPos; token = saveToken; tokenValue = saveTokenValue; tokenFlags = saveTokenFlags; @@ -9774,7 +9827,7 @@ ${lanes.join("\n")} function setText(newText, start2, length3) { text = newText || ""; end = length3 === void 0 ? text.length : start2 + length3; - setTextPos(start2 || 0); + resetTokenState(start2 || 0); } function setOnError(errorCallback) { onError = errorCallback; @@ -9785,11 +9838,11 @@ ${lanes.join("\n")} function setLanguageVariant(variant) { languageVariant = variant; } - function setTextPos(textPos) { - Debug.assert(textPos >= 0); - pos = textPos; - startPos = textPos; - tokenPos = textPos; + function resetTokenState(position) { + Debug.assert(position >= 0); + pos = position; + fullStartPos = position; + tokenStart = position; token = 0 /* Unknown */ ; tokenValue = void 0; tokenFlags = 0 /* None */ ; @@ -9818,153 +9871,154 @@ ${lanes.join("\n")} "use strict"; init_ts2(); textToKeywordObj = { - abstract: 126 /* AbstractKeyword */ , - accessor: 127 /* AccessorKeyword */ , - any: 131 /* AnyKeyword */ , - as: 128 /* AsKeyword */ , - asserts: 129 /* AssertsKeyword */ , - assert: 130 /* AssertKeyword */ , - bigint: 160 /* BigIntKeyword */ , - boolean: 134 /* BooleanKeyword */ , - break: 81 /* BreakKeyword */ , - case: 82 /* CaseKeyword */ , - catch: 83 /* CatchKeyword */ , - class: 84 /* ClassKeyword */ , - continue: 86 /* ContinueKeyword */ , - const: 85 /* ConstKeyword */ , - ["constructor"]: 135 /* ConstructorKeyword */ , - debugger: 87 /* DebuggerKeyword */ , - declare: 136 /* DeclareKeyword */ , - default: 88 /* DefaultKeyword */ , - delete: 89 /* DeleteKeyword */ , - do: 90 /* DoKeyword */ , - else: 91 /* ElseKeyword */ , - enum: 92 /* EnumKeyword */ , - export: 93 /* ExportKeyword */ , - extends: 94 /* ExtendsKeyword */ , - false: 95 /* FalseKeyword */ , - finally: 96 /* FinallyKeyword */ , - for: 97 /* ForKeyword */ , - from: 158 /* FromKeyword */ , - function: 98 /* FunctionKeyword */ , - get: 137 /* GetKeyword */ , - if: 99 /* IfKeyword */ , - implements: 117 /* ImplementsKeyword */ , - import: 100 /* ImportKeyword */ , - in: 101 /* InKeyword */ , - infer: 138 /* InferKeyword */ , - instanceof: 102 /* InstanceOfKeyword */ , - interface: 118 /* InterfaceKeyword */ , - intrinsic: 139 /* IntrinsicKeyword */ , - is: 140 /* IsKeyword */ , - keyof: 141 /* KeyOfKeyword */ , - let: 119 /* LetKeyword */ , - module: 142 /* ModuleKeyword */ , - namespace: 143 /* NamespaceKeyword */ , - never: 144 /* NeverKeyword */ , - new: 103 /* NewKeyword */ , - null: 104 /* NullKeyword */ , - number: 148 /* NumberKeyword */ , - object: 149 /* ObjectKeyword */ , - package: 120 /* PackageKeyword */ , - private: 121 /* PrivateKeyword */ , - protected: 122 /* ProtectedKeyword */ , - public: 123 /* PublicKeyword */ , - override: 161 /* OverrideKeyword */ , - out: 145 /* OutKeyword */ , - readonly: 146 /* ReadonlyKeyword */ , - require: 147 /* RequireKeyword */ , - global: 159 /* GlobalKeyword */ , - return: 105 /* ReturnKeyword */ , - satisfies: 150 /* SatisfiesKeyword */ , - set: 151 /* SetKeyword */ , - static: 124 /* StaticKeyword */ , - string: 152 /* StringKeyword */ , - super: 106 /* SuperKeyword */ , - switch: 107 /* SwitchKeyword */ , - symbol: 153 /* SymbolKeyword */ , - this: 108 /* ThisKeyword */ , - throw: 109 /* ThrowKeyword */ , - true: 110 /* TrueKeyword */ , - try: 111 /* TryKeyword */ , - type: 154 /* TypeKeyword */ , - typeof: 112 /* TypeOfKeyword */ , - undefined: 155 /* UndefinedKeyword */ , - unique: 156 /* UniqueKeyword */ , - unknown: 157 /* UnknownKeyword */ , - var: 113 /* VarKeyword */ , - void: 114 /* VoidKeyword */ , - while: 115 /* WhileKeyword */ , - with: 116 /* WithKeyword */ , - yield: 125 /* YieldKeyword */ , - async: 132 /* AsyncKeyword */ , - await: 133 /* AwaitKeyword */ , - of: 162 /* OfKeyword */ + abstract: 128 /* AbstractKeyword */ , + accessor: 129 /* AccessorKeyword */ , + any: 133 /* AnyKeyword */ , + as: 130 /* AsKeyword */ , + asserts: 131 /* AssertsKeyword */ , + assert: 132 /* AssertKeyword */ , + bigint: 163 /* BigIntKeyword */ , + boolean: 136 /* BooleanKeyword */ , + break: 83 /* BreakKeyword */ , + case: 84 /* CaseKeyword */ , + catch: 85 /* CatchKeyword */ , + class: 86 /* ClassKeyword */ , + continue: 88 /* ContinueKeyword */ , + const: 87 /* ConstKeyword */ , + ["constructor"]: 137 /* ConstructorKeyword */ , + debugger: 89 /* DebuggerKeyword */ , + declare: 138 /* DeclareKeyword */ , + default: 90 /* DefaultKeyword */ , + delete: 91 /* DeleteKeyword */ , + do: 92 /* DoKeyword */ , + else: 93 /* ElseKeyword */ , + enum: 94 /* EnumKeyword */ , + export: 95 /* ExportKeyword */ , + extends: 96 /* ExtendsKeyword */ , + false: 97 /* FalseKeyword */ , + finally: 98 /* FinallyKeyword */ , + for: 99 /* ForKeyword */ , + from: 161 /* FromKeyword */ , + function: 100 /* FunctionKeyword */ , + get: 139 /* GetKeyword */ , + if: 101 /* IfKeyword */ , + implements: 119 /* ImplementsKeyword */ , + import: 102 /* ImportKeyword */ , + in: 103 /* InKeyword */ , + infer: 140 /* InferKeyword */ , + instanceof: 104 /* InstanceOfKeyword */ , + interface: 120 /* InterfaceKeyword */ , + intrinsic: 141 /* IntrinsicKeyword */ , + is: 142 /* IsKeyword */ , + keyof: 143 /* KeyOfKeyword */ , + let: 121 /* LetKeyword */ , + module: 144 /* ModuleKeyword */ , + namespace: 145 /* NamespaceKeyword */ , + never: 146 /* NeverKeyword */ , + new: 105 /* NewKeyword */ , + null: 106 /* NullKeyword */ , + number: 150 /* NumberKeyword */ , + object: 151 /* ObjectKeyword */ , + package: 122 /* PackageKeyword */ , + private: 123 /* PrivateKeyword */ , + protected: 124 /* ProtectedKeyword */ , + public: 125 /* PublicKeyword */ , + override: 164 /* OverrideKeyword */ , + out: 147 /* OutKeyword */ , + readonly: 148 /* ReadonlyKeyword */ , + require: 149 /* RequireKeyword */ , + global: 162 /* GlobalKeyword */ , + return: 107 /* ReturnKeyword */ , + satisfies: 152 /* SatisfiesKeyword */ , + set: 153 /* SetKeyword */ , + static: 126 /* StaticKeyword */ , + string: 154 /* StringKeyword */ , + super: 108 /* SuperKeyword */ , + switch: 109 /* SwitchKeyword */ , + symbol: 155 /* SymbolKeyword */ , + this: 110 /* ThisKeyword */ , + throw: 111 /* ThrowKeyword */ , + true: 112 /* TrueKeyword */ , + try: 113 /* TryKeyword */ , + type: 156 /* TypeKeyword */ , + typeof: 114 /* TypeOfKeyword */ , + undefined: 157 /* UndefinedKeyword */ , + unique: 158 /* UniqueKeyword */ , + unknown: 159 /* UnknownKeyword */ , + using: 160 /* UsingKeyword */ , + var: 115 /* VarKeyword */ , + void: 116 /* VoidKeyword */ , + while: 117 /* WhileKeyword */ , + with: 118 /* WithKeyword */ , + yield: 127 /* YieldKeyword */ , + async: 134 /* AsyncKeyword */ , + await: 135 /* AwaitKeyword */ , + of: 165 /* OfKeyword */ }; textToKeyword = new Map(Object.entries(textToKeywordObj)); textToToken = new Map(Object.entries({ ...textToKeywordObj, - "{": 18 /* OpenBraceToken */ , - "}": 19 /* CloseBraceToken */ , - "(": 20 /* OpenParenToken */ , - ")": 21 /* CloseParenToken */ , - "[": 22 /* OpenBracketToken */ , - "]": 23 /* CloseBracketToken */ , - ".": 24 /* DotToken */ , - "...": 25 /* DotDotDotToken */ , - ";": 26 /* SemicolonToken */ , - ",": 27 /* CommaToken */ , - "<": 29 /* LessThanToken */ , - ">": 31 /* GreaterThanToken */ , - "<=": 32 /* LessThanEqualsToken */ , - ">=": 33 /* GreaterThanEqualsToken */ , - "==": 34 /* EqualsEqualsToken */ , - "!=": 35 /* ExclamationEqualsToken */ , - "===": 36 /* EqualsEqualsEqualsToken */ , - "!==": 37 /* ExclamationEqualsEqualsToken */ , - "=>": 38 /* EqualsGreaterThanToken */ , - "+": 39 /* PlusToken */ , - "-": 40 /* MinusToken */ , - "**": 42 /* AsteriskAsteriskToken */ , - "*": 41 /* AsteriskToken */ , - "/": 43 /* SlashToken */ , - "%": 44 /* PercentToken */ , - "++": 45 /* PlusPlusToken */ , - "--": 46 /* MinusMinusToken */ , - "<<": 47 /* LessThanLessThanToken */ , - ">": 48 /* GreaterThanGreaterThanToken */ , - ">>>": 49 /* GreaterThanGreaterThanGreaterThanToken */ , - "&": 50 /* AmpersandToken */ , - "|": 51 /* BarToken */ , - "^": 52 /* CaretToken */ , - "!": 53 /* ExclamationToken */ , - "~": 54 /* TildeToken */ , - "&&": 55 /* AmpersandAmpersandToken */ , - "||": 56 /* BarBarToken */ , - "?": 57 /* QuestionToken */ , - "??": 60 /* QuestionQuestionToken */ , - "?.": 28 /* QuestionDotToken */ , - ":": 58 /* ColonToken */ , - "=": 63 /* EqualsToken */ , - "+=": 64 /* PlusEqualsToken */ , - "-=": 65 /* MinusEqualsToken */ , - "*=": 66 /* AsteriskEqualsToken */ , - "**=": 67 /* AsteriskAsteriskEqualsToken */ , - "/=": 68 /* SlashEqualsToken */ , - "%=": 69 /* PercentEqualsToken */ , - "<<=": 70 /* LessThanLessThanEqualsToken */ , - ">>=": 71 /* GreaterThanGreaterThanEqualsToken */ , - ">>>=": 72 /* GreaterThanGreaterThanGreaterThanEqualsToken */ , - "&=": 73 /* AmpersandEqualsToken */ , - "|=": 74 /* BarEqualsToken */ , - "^=": 78 /* CaretEqualsToken */ , - "||=": 75 /* BarBarEqualsToken */ , - "&&=": 76 /* AmpersandAmpersandEqualsToken */ , - "??=": 77 /* QuestionQuestionEqualsToken */ , - "@": 59 /* AtToken */ , - "#": 62 /* HashToken */ , - "`": 61 /* BacktickToken */ + "{": 19 /* OpenBraceToken */ , + "}": 20 /* CloseBraceToken */ , + "(": 21 /* OpenParenToken */ , + ")": 22 /* CloseParenToken */ , + "[": 23 /* OpenBracketToken */ , + "]": 24 /* CloseBracketToken */ , + ".": 25 /* DotToken */ , + "...": 26 /* DotDotDotToken */ , + ";": 27 /* SemicolonToken */ , + ",": 28 /* CommaToken */ , + "<": 30 /* LessThanToken */ , + ">": 32 /* GreaterThanToken */ , + "<=": 33 /* LessThanEqualsToken */ , + ">=": 34 /* GreaterThanEqualsToken */ , + "==": 35 /* EqualsEqualsToken */ , + "!=": 36 /* ExclamationEqualsToken */ , + "===": 37 /* EqualsEqualsEqualsToken */ , + "!==": 38 /* ExclamationEqualsEqualsToken */ , + "=>": 39 /* EqualsGreaterThanToken */ , + "+": 40 /* PlusToken */ , + "-": 41 /* MinusToken */ , + "**": 43 /* AsteriskAsteriskToken */ , + "*": 42 /* AsteriskToken */ , + "/": 44 /* SlashToken */ , + "%": 45 /* PercentToken */ , + "++": 46 /* PlusPlusToken */ , + "--": 47 /* MinusMinusToken */ , + "<<": 48 /* LessThanLessThanToken */ , + ">": 49 /* GreaterThanGreaterThanToken */ , + ">>>": 50 /* GreaterThanGreaterThanGreaterThanToken */ , + "&": 51 /* AmpersandToken */ , + "|": 52 /* BarToken */ , + "^": 53 /* CaretToken */ , + "!": 54 /* ExclamationToken */ , + "~": 55 /* TildeToken */ , + "&&": 56 /* AmpersandAmpersandToken */ , + "||": 57 /* BarBarToken */ , + "?": 58 /* QuestionToken */ , + "??": 61 /* QuestionQuestionToken */ , + "?.": 29 /* QuestionDotToken */ , + ":": 59 /* ColonToken */ , + "=": 64 /* EqualsToken */ , + "+=": 65 /* PlusEqualsToken */ , + "-=": 66 /* MinusEqualsToken */ , + "*=": 67 /* AsteriskEqualsToken */ , + "**=": 68 /* AsteriskAsteriskEqualsToken */ , + "/=": 69 /* SlashEqualsToken */ , + "%=": 70 /* PercentEqualsToken */ , + "<<=": 71 /* LessThanLessThanEqualsToken */ , + ">>=": 72 /* GreaterThanGreaterThanEqualsToken */ , + ">>>=": 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */ , + "&=": 74 /* AmpersandEqualsToken */ , + "|=": 75 /* BarEqualsToken */ , + "^=": 79 /* CaretEqualsToken */ , + "||=": 76 /* BarBarEqualsToken */ , + "&&=": 77 /* AmpersandAmpersandEqualsToken */ , + "??=": 78 /* QuestionQuestionEqualsToken */ , + "@": 60 /* AtToken */ , + "#": 63 /* HashToken */ , + "`": 62 /* BacktickToken */ })); unicodeES3IdentifierStart = [ 170, @@ -15550,12 +15604,12 @@ ${lanes.join("\n")} return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN); } function getTypeParameterOwner(d) { - if (d && d.kind === 165 /* TypeParameter */ ) for(let current = d; current; current = current.parent){ - if (isFunctionLike(current) || isClassLike(current) || current.kind === 261 /* InterfaceDeclaration */ ) return current; + if (d && d.kind === 168 /* TypeParameter */ ) for(let current = d; current; current = current.parent){ + if (isFunctionLike(current) || isClassLike(current) || current.kind === 264 /* InterfaceDeclaration */ ) return current; } } function isParameterPropertyDeclaration(node, parent2) { - return isParameter(node) && hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */ ) && parent2.kind === 173 /* Constructor */ ; + return isParameter(node) && hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */ ) && parent2.kind === 176 /* Constructor */ ; } function isEmptyBindingPattern(node) { if (isBindingPattern(node)) return every(node.elements, isEmptyBindingElement); @@ -15573,12 +15627,12 @@ ${lanes.join("\n")} function getCombinedFlags(node, getFlags) { if (isBindingElement(node)) node = walkUpBindingElementsAndPatterns(node); let flags = getFlags(node); - if (node.kind === 257 /* VariableDeclaration */ ) node = node.parent; - if (node && node.kind === 258 /* VariableDeclarationList */ ) { + if (node.kind === 260 /* VariableDeclaration */ ) node = node.parent; + if (node && node.kind === 261 /* VariableDeclarationList */ ) { flags |= getFlags(node); node = node.parent; } - if (node && node.kind === 240 /* VariableStatement */ ) flags |= getFlags(node); + if (node && node.kind === 243 /* VariableStatement */ ) flags |= getFlags(node); return flags; } function getCombinedModifierFlags(node) { @@ -15588,11 +15642,14 @@ ${lanes.join("\n")} return getCombinedFlags(node, getEffectiveModifierFlagsAlwaysIncludeJSDoc); } function getCombinedNodeFlags(node) { - return getCombinedFlags(node, (n)=>n.flags); + return getCombinedFlags(node, getNodeFlags); + } + function getNodeFlags(node) { + return node.flags; } function validateLocaleAndSetLanguage(locale, sys2, errors) { const lowerCaseLocale = locale.toLowerCase(); - const matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(lowerCaseLocale); + const matchResult = /^([a-z]+)([_-]([a-z]+))?$/.exec(lowerCaseLocale); if (!matchResult) { if (errors) errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); return; @@ -15617,7 +15674,7 @@ ${lanes.join("\n")} } try { setLocalizedDiagnosticMessages(JSON.parse(fileContents)); - } catch (e) { + } catch { if (errors2) errors2.push(createCompilerDiagnostic(Diagnostics.Corrupted_locale_file_0, filePath)); return false; } @@ -15639,7 +15696,7 @@ ${lanes.join("\n")} return void 0; } function isParseTreeNode(node) { - return (node.flags & 8 /* Synthesized */ ) === 0; + return (node.flags & 16 /* Synthesized */ ) === 0; } function getParseTreeNode(node, nodeTest) { if (node === void 0 || isParseTreeNode(node)) return node; @@ -15672,23 +15729,23 @@ ${lanes.join("\n")} if (!hostNode) return void 0; if (isDeclaration(hostNode)) return getDeclarationIdentifier(hostNode); switch(hostNode.kind){ - case 240 /* VariableStatement */ : + case 243 /* VariableStatement */ : if (hostNode.declarationList && hostNode.declarationList.declarations[0]) return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); break; - case 241 /* ExpressionStatement */ : + case 244 /* ExpressionStatement */ : let expr = hostNode.expression; - if (expr.kind === 223 /* BinaryExpression */ && expr.operatorToken.kind === 63 /* EqualsToken */ ) expr = expr.left; + if (expr.kind === 226 /* BinaryExpression */ && expr.operatorToken.kind === 64 /* EqualsToken */ ) expr = expr.left; switch(expr.kind){ - case 208 /* PropertyAccessExpression */ : + case 211 /* PropertyAccessExpression */ : return expr.name; - case 209 /* ElementAccessExpression */ : + case 212 /* ElementAccessExpression */ : const arg = expr.argumentExpression; if (isIdentifier(arg)) return arg; } break; - case 214 /* ParenthesizedExpression */ : + case 217 /* ParenthesizedExpression */ : return getDeclarationIdentifier(hostNode.expression); - case 253 /* LabeledStatement */ : + case 256 /* LabeledStatement */ : if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) return getDeclarationIdentifier(hostNode.statement); break; } @@ -15710,17 +15767,17 @@ ${lanes.join("\n")} } function getNonAssignedNameOfDeclaration(declaration) { switch(declaration.kind){ - case 79 /* Identifier */ : + case 80 /* Identifier */ : return declaration; - case 351 /* JSDocPropertyTag */ : - case 344 /* JSDocParameterTag */ : + case 355 /* JSDocPropertyTag */ : + case 348 /* JSDocParameterTag */ : { - const { name: name } = declaration; - if (name.kind === 163 /* QualifiedName */ ) return name.right; + const { name: name } = declaration; + if (name.kind === 166 /* QualifiedName */ ) return name.right; break; } - case 210 /* CallExpression */ : - case 223 /* BinaryExpression */ : + case 213 /* CallExpression */ : + case 226 /* BinaryExpression */ : { const expr2 = declaration; switch(getAssignmentDeclarationKind(expr2)){ @@ -15737,16 +15794,16 @@ ${lanes.join("\n")} return void 0; } } - case 349 /* JSDocTypedefTag */ : + case 353 /* JSDocTypedefTag */ : return getNameOfJSDocTypedef(declaration); - case 343 /* JSDocEnumTag */ : + case 347 /* JSDocEnumTag */ : return nameForNamelessJSDocTypedef(declaration); - case 274 /* ExportAssignment */ : + case 277 /* ExportAssignment */ : { - const { expression: expression } = declaration; + const { expression: expression } = declaration; return isIdentifier(expression) ? expression : void 0; } - case 209 /* ElementAccessExpression */ : + case 212 /* ElementAccessExpression */ : const expr = declaration; if (isBindableStaticElementAccessExpression(expr)) return expr.argumentExpression; } @@ -15886,15 +15943,15 @@ ${lanes.join("\n")} } } function getJSDocTagsWorker(node, noCache) { - var _a2, _b; + var _a; if (!canHaveJSDoc(node)) return emptyArray; - let tags = (_a2 = node.jsDoc) == null ? void 0 : _a2.jsDocCache; + let tags = (_a = node.jsDoc) == null ? void 0 : _a.jsDocCache; if (tags === void 0 || noCache) { const comments = getJSDocCommentsAndTags(node, noCache); Debug.assert(comments.length < 2 || comments[0] !== comments[1]); tags = flatMap(comments, (j)=>isJSDoc(j) ? j.tags : j); if (!noCache) { - (_b = node.jsDoc) != null ? _b : node.jsDoc = []; + node.jsDoc ?? (node.jsDoc = []); node.jsDoc.jsDocCache = tags; } } @@ -15916,10 +15973,10 @@ ${lanes.join("\n")} return getJSDocTags(node).filter((doc)=>doc.kind === kind); } function getTextOfJSDocComment(comment) { - return typeof comment === "string" ? comment : comment == null ? void 0 : comment.map((c)=>c.kind === 324 /* JSDocText */ ? c.text : formatJSDocLink(c)).join(""); + return typeof comment === "string" ? comment : comment == null ? void 0 : comment.map((c)=>c.kind === 328 /* JSDocText */ ? c.text : formatJSDocLink(c)).join(""); } function formatJSDocLink(link) { - const kind = link.kind === 327 /* JSDocLink */ ? "link" : link.kind === 328 /* JSDocLinkCode */ ? "linkcode" : "linkplain"; + const kind = link.kind === 331 /* JSDocLink */ ? "link" : link.kind === 332 /* JSDocLinkCode */ ? "linkcode" : "linkplain"; const name = link.name ? entityNameToString(link.name) : ""; const space = link.name && link.text.startsWith("://") ? "" : " "; return `{@${kind} ${name}${space}${link.text}}`; @@ -15933,7 +15990,7 @@ ${lanes.join("\n")} return emptyArray; } if (isJSDocTypeAlias(node)) { - Debug.assert(node.parent.kind === 323 /* JSDoc */ ); + Debug.assert(node.parent.kind === 327 /* JSDoc */ ); return flatMap(node.parent.tags, (tag)=>isJSDocTemplateTag(tag) ? tag.typeParameters : void 0); } if (node.typeParameters) return node.typeParameters; @@ -15950,23 +16007,23 @@ ${lanes.join("\n")} return node.constraint ? node.constraint : isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] ? node.parent.constraint : void 0; } function isMemberName(node) { - return node.kind === 79 /* Identifier */ || node.kind === 80 /* PrivateIdentifier */ ; + return node.kind === 80 /* Identifier */ || node.kind === 81 /* PrivateIdentifier */ ; } function isGetOrSetAccessorDeclaration(node) { - return node.kind === 175 /* SetAccessor */ || node.kind === 174 /* GetAccessor */ ; + return node.kind === 178 /* SetAccessor */ || node.kind === 177 /* GetAccessor */ ; } function isPropertyAccessChain(node) { - return isPropertyAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */ ); + return isPropertyAccessExpression(node) && !!(node.flags & 64 /* OptionalChain */ ); } function isElementAccessChain(node) { - return isElementAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */ ); + return isElementAccessExpression(node) && !!(node.flags & 64 /* OptionalChain */ ); } function isCallChain(node) { - return isCallExpression(node) && !!(node.flags & 32 /* OptionalChain */ ); + return isCallExpression(node) && !!(node.flags & 64 /* OptionalChain */ ); } function isOptionalChain(node) { const kind = node.kind; - return !!(node.flags & 32 /* OptionalChain */ ) && (kind === 208 /* PropertyAccessExpression */ || kind === 209 /* ElementAccessExpression */ || kind === 210 /* CallExpression */ || kind === 232 /* NonNullExpression */ ); + return !!(node.flags & 64 /* OptionalChain */ ) && (kind === 211 /* PropertyAccessExpression */ || kind === 212 /* ElementAccessExpression */ || kind === 213 /* CallExpression */ || kind === 235 /* NonNullExpression */ ); } function isOptionalChainRoot(node) { return isOptionalChain(node) && !isNonNullExpression(node) && !!node.questionDotToken; @@ -15978,7 +16035,7 @@ ${lanes.join("\n")} return !isOptionalChain(node.parent) || isOptionalChainRoot(node.parent) || node !== node.parent.expression; } function isNullishCoalesce(node) { - return node.kind === 223 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */ ; + return node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 61 /* QuestionQuestionToken */ ; } function isConstTypeReference(node) { return isTypeReferenceNode(node) && isIdentifier(node.typeName) && node.typeName.escapedText === "const" && !node.typeArguments; @@ -15987,37 +16044,37 @@ ${lanes.join("\n")} return skipOuterExpressions(node, 8 /* PartiallyEmittedExpressions */ ); } function isNonNullChain(node) { - return isNonNullExpression(node) && !!(node.flags & 32 /* OptionalChain */ ); + return isNonNullExpression(node) && !!(node.flags & 64 /* OptionalChain */ ); } function isBreakOrContinueStatement(node) { - return node.kind === 249 /* BreakStatement */ || node.kind === 248 /* ContinueStatement */ ; + return node.kind === 252 /* BreakStatement */ || node.kind === 251 /* ContinueStatement */ ; } function isNamedExportBindings(node) { - return node.kind === 277 /* NamespaceExport */ || node.kind === 276 /* NamedExports */ ; + return node.kind === 280 /* NamespaceExport */ || node.kind === 279 /* NamedExports */ ; } function isUnparsedTextLike(node) { switch(node.kind){ - case 305 /* UnparsedText */ : - case 306 /* UnparsedInternalText */ : + case 309 /* UnparsedText */ : + case 310 /* UnparsedInternalText */ : return true; default: return false; } } function isUnparsedNode(node) { - return isUnparsedTextLike(node) || node.kind === 303 /* UnparsedPrologue */ || node.kind === 307 /* UnparsedSyntheticReference */ ; + return isUnparsedTextLike(node) || node.kind === 307 /* UnparsedPrologue */ || node.kind === 311 /* UnparsedSyntheticReference */ ; } function isJSDocPropertyLikeTag(node) { - return node.kind === 351 /* JSDocPropertyTag */ || node.kind === 344 /* JSDocParameterTag */ ; + return node.kind === 355 /* JSDocPropertyTag */ || node.kind === 348 /* JSDocParameterTag */ ; } function isNode(node) { return isNodeKind(node.kind); } function isNodeKind(kind) { - return kind >= 163 /* FirstNode */ ; + return kind >= 166 /* FirstNode */ ; } function isTokenKind(kind) { - return kind >= 0 /* FirstToken */ && kind <= 162 /* LastToken */ ; + return kind >= 0 /* FirstToken */ && kind <= 165 /* LastToken */ ; } function isToken(n) { return isTokenKind(n.kind); @@ -16026,54 +16083,54 @@ ${lanes.join("\n")} return hasProperty(array, "pos") && hasProperty(array, "end"); } function isLiteralKind(kind) { - return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */ ; + return 9 /* FirstLiteralToken */ <= kind && kind <= 15 /* LastLiteralToken */ ; } function isLiteralExpression(node) { return isLiteralKind(node.kind); } function isLiteralExpressionOfObject(node) { switch(node.kind){ - case 207 /* ObjectLiteralExpression */ : - case 206 /* ArrayLiteralExpression */ : - case 13 /* RegularExpressionLiteral */ : - case 215 /* FunctionExpression */ : - case 228 /* ClassExpression */ : + case 210 /* ObjectLiteralExpression */ : + case 209 /* ArrayLiteralExpression */ : + case 14 /* RegularExpressionLiteral */ : + case 218 /* FunctionExpression */ : + case 231 /* ClassExpression */ : return true; } return false; } function isTemplateLiteralKind(kind) { - return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */ ; + return 15 /* FirstTemplateToken */ <= kind && kind <= 18 /* LastTemplateToken */ ; } function isTemplateLiteralToken(node) { return isTemplateLiteralKind(node.kind); } function isTemplateMiddleOrTemplateTail(node) { const kind = node.kind; - return kind === 16 /* TemplateMiddle */ || kind === 17 /* TemplateTail */ ; + return kind === 17 /* TemplateMiddle */ || kind === 18 /* TemplateTail */ ; } function isImportOrExportSpecifier(node) { return isImportSpecifier(node) || isExportSpecifier(node); } function isTypeOnlyImportDeclaration(node) { switch(node.kind){ - case 273 /* ImportSpecifier */ : + case 276 /* ImportSpecifier */ : return node.isTypeOnly || node.parent.parent.isTypeOnly; - case 271 /* NamespaceImport */ : + case 274 /* NamespaceImport */ : return node.parent.isTypeOnly; - case 270 /* ImportClause */ : - case 268 /* ImportEqualsDeclaration */ : + case 273 /* ImportClause */ : + case 271 /* ImportEqualsDeclaration */ : return node.isTypeOnly; } return false; } function isTypeOnlyExportDeclaration(node) { switch(node.kind){ - case 278 /* ExportSpecifier */ : + case 281 /* ExportSpecifier */ : return node.isTypeOnly || node.parent.parent.isTypeOnly; - case 275 /* ExportDeclaration */ : + case 278 /* ExportDeclaration */ : return node.isTypeOnly && !!node.moduleSpecifier && !node.exportClause; - case 277 /* NamespaceExport */ : + case 280 /* NamespaceExport */ : return node.parent.isTypeOnly; } return false; @@ -16085,15 +16142,19 @@ ${lanes.join("\n")} return isStringLiteral(node) || isIdentifier(node); } function isStringTextContainingNode(node) { - return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind); + return node.kind === 11 /* StringLiteral */ || isTemplateLiteralKind(node.kind); } function isGeneratedIdentifier(node) { - var _a2; - return isIdentifier(node) && ((_a2 = node.emitNode) == null ? void 0 : _a2.autoGenerate) !== void 0; + var _a; + return isIdentifier(node) && ((_a = node.emitNode) == null ? void 0 : _a.autoGenerate) !== void 0; } function isGeneratedPrivateIdentifier(node) { - var _a2; - return isPrivateIdentifier(node) && ((_a2 = node.emitNode) == null ? void 0 : _a2.autoGenerate) !== void 0; + var _a; + return isPrivateIdentifier(node) && ((_a = node.emitNode) == null ? void 0 : _a.autoGenerate) !== void 0; + } + function isFileLevelReservedGeneratedIdentifier(node) { + const flags = node.emitNode.autoGenerate.flags; + return !!(flags & 32 /* FileLevel */ ) && !!(flags & 16 /* Optimistic */ ) && !!(flags & 8 /* ReservedInNestedScopes */ ); } function isPrivateIdentifierClassElementDeclaration(node) { return (isPropertyDeclaration(node) || isMethodOrAccessor(node)) && isPrivateIdentifier(node.name); @@ -16103,21 +16164,21 @@ ${lanes.join("\n")} } function isModifierKind(token) { switch(token){ - case 126 /* AbstractKeyword */ : - case 127 /* AccessorKeyword */ : - case 132 /* AsyncKeyword */ : - case 85 /* ConstKeyword */ : - case 136 /* DeclareKeyword */ : - case 88 /* DefaultKeyword */ : - case 93 /* ExportKeyword */ : - case 101 /* InKeyword */ : - case 123 /* PublicKeyword */ : - case 121 /* PrivateKeyword */ : - case 122 /* ProtectedKeyword */ : - case 146 /* ReadonlyKeyword */ : - case 124 /* StaticKeyword */ : - case 145 /* OutKeyword */ : - case 161 /* OverrideKeyword */ : + case 128 /* AbstractKeyword */ : + case 129 /* AccessorKeyword */ : + case 134 /* AsyncKeyword */ : + case 87 /* ConstKeyword */ : + case 138 /* DeclareKeyword */ : + case 90 /* DefaultKeyword */ : + case 95 /* ExportKeyword */ : + case 103 /* InKeyword */ : + case 125 /* PublicKeyword */ : + case 123 /* PrivateKeyword */ : + case 124 /* ProtectedKeyword */ : + case 148 /* ReadonlyKeyword */ : + case 126 /* StaticKeyword */ : + case 147 /* OutKeyword */ : + case 164 /* OverrideKeyword */ : return true; } return false; @@ -16126,22 +16187,22 @@ ${lanes.join("\n")} return !!(modifierToFlag(kind) & 16476 /* ParameterPropertyModifier */ ); } function isClassMemberModifier(idToken) { - return isParameterPropertyModifier(idToken) || idToken === 124 /* StaticKeyword */ || idToken === 161 /* OverrideKeyword */ || idToken === 127 /* AccessorKeyword */ ; + return isParameterPropertyModifier(idToken) || idToken === 126 /* StaticKeyword */ || idToken === 164 /* OverrideKeyword */ || idToken === 129 /* AccessorKeyword */ ; } function isModifier(node) { return isModifierKind(node.kind); } function isEntityName(node) { const kind = node.kind; - return kind === 163 /* QualifiedName */ || kind === 79 /* Identifier */ ; + return kind === 166 /* QualifiedName */ || kind === 80 /* Identifier */ ; } function isPropertyName(node) { const kind = node.kind; - return kind === 79 /* Identifier */ || kind === 80 /* PrivateIdentifier */ || kind === 10 /* StringLiteral */ || kind === 8 /* NumericLiteral */ || kind === 164 /* ComputedPropertyName */ ; + return kind === 80 /* Identifier */ || kind === 81 /* PrivateIdentifier */ || kind === 11 /* StringLiteral */ || kind === 9 /* NumericLiteral */ || kind === 167 /* ComputedPropertyName */ ; } function isBindingName(node) { const kind = node.kind; - return kind === 79 /* Identifier */ || kind === 203 /* ObjectBindingPattern */ || kind === 204 /* ArrayBindingPattern */ ; + return kind === 80 /* Identifier */ || kind === 206 /* ObjectBindingPattern */ || kind === 207 /* ArrayBindingPattern */ ; } function isFunctionLike(node) { return !!node && isFunctionLikeKind(node.kind); @@ -16153,17 +16214,17 @@ ${lanes.join("\n")} return node && isFunctionLikeDeclarationKind(node.kind); } function isBooleanLiteral(node) { - return node.kind === 110 /* TrueKeyword */ || node.kind === 95 /* FalseKeyword */ ; + return node.kind === 112 /* TrueKeyword */ || node.kind === 97 /* FalseKeyword */ ; } function isFunctionLikeDeclarationKind(kind) { switch(kind){ - case 259 /* FunctionDeclaration */ : - case 171 /* MethodDeclaration */ : - case 173 /* Constructor */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : + case 262 /* FunctionDeclaration */ : + case 174 /* MethodDeclaration */ : + case 176 /* Constructor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : return true; default: return false; @@ -16171,14 +16232,14 @@ ${lanes.join("\n")} } function isFunctionLikeKind(kind) { switch(kind){ - case 170 /* MethodSignature */ : - case 176 /* CallSignature */ : - case 326 /* JSDocSignature */ : - case 177 /* ConstructSignature */ : - case 178 /* IndexSignature */ : - case 181 /* FunctionType */ : - case 320 /* JSDocFunctionType */ : - case 182 /* ConstructorType */ : + case 173 /* MethodSignature */ : + case 179 /* CallSignature */ : + case 330 /* JSDocSignature */ : + case 180 /* ConstructSignature */ : + case 181 /* IndexSignature */ : + case 184 /* FunctionType */ : + case 324 /* JSDocFunctionType */ : + case 185 /* ConstructorType */ : return true; default: return isFunctionLikeDeclarationKind(kind); @@ -16189,22 +16250,22 @@ ${lanes.join("\n")} } function isClassElement(node) { const kind = node.kind; - return kind === 173 /* Constructor */ || kind === 169 /* PropertyDeclaration */ || kind === 171 /* MethodDeclaration */ || kind === 174 /* GetAccessor */ || kind === 175 /* SetAccessor */ || kind === 178 /* IndexSignature */ || kind === 172 /* ClassStaticBlockDeclaration */ || kind === 237 /* SemicolonClassElement */ ; + return kind === 176 /* Constructor */ || kind === 172 /* PropertyDeclaration */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ || kind === 181 /* IndexSignature */ || kind === 175 /* ClassStaticBlockDeclaration */ || kind === 240 /* SemicolonClassElement */ ; } function isClassLike(node) { - return node && (node.kind === 260 /* ClassDeclaration */ || node.kind === 228 /* ClassExpression */ ); + return node && (node.kind === 263 /* ClassDeclaration */ || node.kind === 231 /* ClassExpression */ ); } function isAccessor(node) { - return node && (node.kind === 174 /* GetAccessor */ || node.kind === 175 /* SetAccessor */ ); + return node && (node.kind === 177 /* GetAccessor */ || node.kind === 178 /* SetAccessor */ ); } function isAutoAccessorPropertyDeclaration(node) { return isPropertyDeclaration(node) && hasAccessorModifier(node); } function isMethodOrAccessor(node) { switch(node.kind){ - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : return true; default: return false; @@ -16212,10 +16273,10 @@ ${lanes.join("\n")} } function isNamedClassElement(node) { switch(node.kind){ - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 169 /* PropertyDeclaration */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 172 /* PropertyDeclaration */ : return true; default: return false; @@ -16226,22 +16287,22 @@ ${lanes.join("\n")} } function isTypeElement(node) { const kind = node.kind; - return kind === 177 /* ConstructSignature */ || kind === 176 /* CallSignature */ || kind === 168 /* PropertySignature */ || kind === 170 /* MethodSignature */ || kind === 178 /* IndexSignature */ || kind === 174 /* GetAccessor */ || kind === 175 /* SetAccessor */ ; + return kind === 180 /* ConstructSignature */ || kind === 179 /* CallSignature */ || kind === 171 /* PropertySignature */ || kind === 173 /* MethodSignature */ || kind === 181 /* IndexSignature */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ ; } function isClassOrTypeElement(node) { return isTypeElement(node) || isClassElement(node); } function isObjectLiteralElementLike(node) { const kind = node.kind; - return kind === 299 /* PropertyAssignment */ || kind === 300 /* ShorthandPropertyAssignment */ || kind === 301 /* SpreadAssignment */ || kind === 171 /* MethodDeclaration */ || kind === 174 /* GetAccessor */ || kind === 175 /* SetAccessor */ ; + return kind === 303 /* PropertyAssignment */ || kind === 304 /* ShorthandPropertyAssignment */ || kind === 305 /* SpreadAssignment */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ ; } function isTypeNode(node) { return isTypeNodeKind(node.kind); } function isFunctionOrConstructorTypeNode(node) { switch(node.kind){ - case 181 /* FunctionType */ : - case 182 /* ConstructorType */ : + case 184 /* FunctionType */ : + case 185 /* ConstructorType */ : return true; } return false; @@ -16249,23 +16310,23 @@ ${lanes.join("\n")} function isBindingPattern(node) { if (node) { const kind = node.kind; - return kind === 204 /* ArrayBindingPattern */ || kind === 203 /* ObjectBindingPattern */ ; + return kind === 207 /* ArrayBindingPattern */ || kind === 206 /* ObjectBindingPattern */ ; } return false; } function isAssignmentPattern(node) { const kind = node.kind; - return kind === 206 /* ArrayLiteralExpression */ || kind === 207 /* ObjectLiteralExpression */ ; + return kind === 209 /* ArrayLiteralExpression */ || kind === 210 /* ObjectLiteralExpression */ ; } function isArrayBindingElement(node) { const kind = node.kind; - return kind === 205 /* BindingElement */ || kind === 229 /* OmittedExpression */ ; + return kind === 208 /* BindingElement */ || kind === 232 /* OmittedExpression */ ; } function isDeclarationBindingElement(bindingElement) { switch(bindingElement.kind){ - case 257 /* VariableDeclaration */ : - case 166 /* Parameter */ : - case 205 /* BindingElement */ : + case 260 /* VariableDeclaration */ : + case 169 /* Parameter */ : + case 208 /* BindingElement */ : return true; } return false; @@ -16278,108 +16339,108 @@ ${lanes.join("\n")} } function isObjectBindingOrAssignmentPattern(node) { switch(node.kind){ - case 203 /* ObjectBindingPattern */ : - case 207 /* ObjectLiteralExpression */ : + case 206 /* ObjectBindingPattern */ : + case 210 /* ObjectLiteralExpression */ : return true; } return false; } function isObjectBindingOrAssignmentElement(node) { switch(node.kind){ - case 205 /* BindingElement */ : - case 299 /* PropertyAssignment */ : - case 300 /* ShorthandPropertyAssignment */ : - case 301 /* SpreadAssignment */ : + case 208 /* BindingElement */ : + case 303 /* PropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : + case 305 /* SpreadAssignment */ : return true; } return false; } function isArrayBindingOrAssignmentPattern(node) { switch(node.kind){ - case 204 /* ArrayBindingPattern */ : - case 206 /* ArrayLiteralExpression */ : + case 207 /* ArrayBindingPattern */ : + case 209 /* ArrayLiteralExpression */ : return true; } return false; } function isArrayBindingOrAssignmentElement(node) { switch(node.kind){ - case 205 /* BindingElement */ : - case 229 /* OmittedExpression */ : - case 227 /* SpreadElement */ : - case 206 /* ArrayLiteralExpression */ : - case 207 /* ObjectLiteralExpression */ : - case 79 /* Identifier */ : - case 208 /* PropertyAccessExpression */ : - case 209 /* ElementAccessExpression */ : + case 208 /* BindingElement */ : + case 232 /* OmittedExpression */ : + case 230 /* SpreadElement */ : + case 209 /* ArrayLiteralExpression */ : + case 210 /* ObjectLiteralExpression */ : + case 80 /* Identifier */ : + case 211 /* PropertyAccessExpression */ : + case 212 /* ElementAccessExpression */ : return true; } return isAssignmentExpression(node, /*excludeCompoundAssignment*/ true); } function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { const kind = node.kind; - return kind === 208 /* PropertyAccessExpression */ || kind === 163 /* QualifiedName */ || kind === 202 /* ImportType */ ; + return kind === 211 /* PropertyAccessExpression */ || kind === 166 /* QualifiedName */ || kind === 205 /* ImportType */ ; } function isPropertyAccessOrQualifiedName(node) { const kind = node.kind; - return kind === 208 /* PropertyAccessExpression */ || kind === 163 /* QualifiedName */ ; + return kind === 211 /* PropertyAccessExpression */ || kind === 166 /* QualifiedName */ ; } function isCallLikeExpression(node) { switch(node.kind){ - case 283 /* JsxOpeningElement */ : - case 282 /* JsxSelfClosingElement */ : - case 210 /* CallExpression */ : - case 211 /* NewExpression */ : - case 212 /* TaggedTemplateExpression */ : - case 167 /* Decorator */ : + case 286 /* JsxOpeningElement */ : + case 285 /* JsxSelfClosingElement */ : + case 213 /* CallExpression */ : + case 214 /* NewExpression */ : + case 215 /* TaggedTemplateExpression */ : + case 170 /* Decorator */ : return true; default: return false; } } function isCallOrNewExpression(node) { - return node.kind === 210 /* CallExpression */ || node.kind === 211 /* NewExpression */ ; + return node.kind === 213 /* CallExpression */ || node.kind === 214 /* NewExpression */ ; } function isTemplateLiteral(node) { const kind = node.kind; - return kind === 225 /* TemplateExpression */ || kind === 14 /* NoSubstitutionTemplateLiteral */ ; + return kind === 228 /* TemplateExpression */ || kind === 15 /* NoSubstitutionTemplateLiteral */ ; } function isLeftHandSideExpression(node) { return isLeftHandSideExpressionKind(skipPartiallyEmittedExpressions(node).kind); } function isLeftHandSideExpressionKind(kind) { switch(kind){ - case 208 /* PropertyAccessExpression */ : - case 209 /* ElementAccessExpression */ : - case 211 /* NewExpression */ : - case 210 /* CallExpression */ : - case 281 /* JsxElement */ : - case 282 /* JsxSelfClosingElement */ : - case 285 /* JsxFragment */ : - case 212 /* TaggedTemplateExpression */ : - case 206 /* ArrayLiteralExpression */ : - case 214 /* ParenthesizedExpression */ : - case 207 /* ObjectLiteralExpression */ : - case 228 /* ClassExpression */ : - case 215 /* FunctionExpression */ : - case 79 /* Identifier */ : - case 80 /* PrivateIdentifier */ : - case 13 /* RegularExpressionLiteral */ : - case 8 /* NumericLiteral */ : - case 9 /* BigIntLiteral */ : - case 10 /* StringLiteral */ : - case 14 /* NoSubstitutionTemplateLiteral */ : - case 225 /* TemplateExpression */ : - case 95 /* FalseKeyword */ : - case 104 /* NullKeyword */ : - case 108 /* ThisKeyword */ : - case 110 /* TrueKeyword */ : - case 106 /* SuperKeyword */ : - case 232 /* NonNullExpression */ : - case 230 /* ExpressionWithTypeArguments */ : - case 233 /* MetaProperty */ : - case 100 /* ImportKeyword */ : - case 279 /* MissingDeclaration */ : + case 211 /* PropertyAccessExpression */ : + case 212 /* ElementAccessExpression */ : + case 214 /* NewExpression */ : + case 213 /* CallExpression */ : + case 284 /* JsxElement */ : + case 285 /* JsxSelfClosingElement */ : + case 288 /* JsxFragment */ : + case 215 /* TaggedTemplateExpression */ : + case 209 /* ArrayLiteralExpression */ : + case 217 /* ParenthesizedExpression */ : + case 210 /* ObjectLiteralExpression */ : + case 231 /* ClassExpression */ : + case 218 /* FunctionExpression */ : + case 80 /* Identifier */ : + case 81 /* PrivateIdentifier */ : + case 14 /* RegularExpressionLiteral */ : + case 9 /* NumericLiteral */ : + case 10 /* BigIntLiteral */ : + case 11 /* StringLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + case 228 /* TemplateExpression */ : + case 97 /* FalseKeyword */ : + case 106 /* NullKeyword */ : + case 110 /* ThisKeyword */ : + case 112 /* TrueKeyword */ : + case 108 /* SuperKeyword */ : + case 235 /* NonNullExpression */ : + case 233 /* ExpressionWithTypeArguments */ : + case 236 /* MetaProperty */ : + case 102 /* ImportKeyword */ : + case 282 /* MissingDeclaration */ : return true; default: return false; @@ -16390,13 +16451,13 @@ ${lanes.join("\n")} } function isUnaryExpressionKind(kind) { switch(kind){ - case 221 /* PrefixUnaryExpression */ : - case 222 /* PostfixUnaryExpression */ : - case 217 /* DeleteExpression */ : - case 218 /* TypeOfExpression */ : - case 219 /* VoidExpression */ : - case 220 /* AwaitExpression */ : - case 213 /* TypeAssertionExpression */ : + case 224 /* PrefixUnaryExpression */ : + case 225 /* PostfixUnaryExpression */ : + case 220 /* DeleteExpression */ : + case 221 /* TypeOfExpression */ : + case 222 /* VoidExpression */ : + case 223 /* AwaitExpression */ : + case 216 /* TypeAssertionExpression */ : return true; default: return isLeftHandSideExpressionKind(kind); @@ -16404,20 +16465,20 @@ ${lanes.join("\n")} } function isUnaryExpressionWithWrite(expr) { switch(expr.kind){ - case 222 /* PostfixUnaryExpression */ : + case 225 /* PostfixUnaryExpression */ : return true; - case 221 /* PrefixUnaryExpression */ : - return expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */ ; + case 224 /* PrefixUnaryExpression */ : + return expr.operator === 46 /* PlusPlusToken */ || expr.operator === 47 /* MinusMinusToken */ ; default: return false; } } function isLiteralTypeLiteral(node) { switch(node.kind){ - case 104 /* NullKeyword */ : - case 110 /* TrueKeyword */ : - case 95 /* FalseKeyword */ : - case 221 /* PrefixUnaryExpression */ : + case 106 /* NullKeyword */ : + case 112 /* TrueKeyword */ : + case 97 /* FalseKeyword */ : + case 224 /* PrefixUnaryExpression */ : return true; default: return isLiteralExpression(node); @@ -16428,16 +16489,16 @@ ${lanes.join("\n")} } function isExpressionKind(kind) { switch(kind){ - case 224 /* ConditionalExpression */ : - case 226 /* YieldExpression */ : - case 216 /* ArrowFunction */ : - case 223 /* BinaryExpression */ : - case 227 /* SpreadElement */ : - case 231 /* AsExpression */ : - case 229 /* OmittedExpression */ : - case 357 /* CommaListExpression */ : - case 356 /* PartiallyEmittedExpression */ : - case 235 /* SatisfiesExpression */ : + case 227 /* ConditionalExpression */ : + case 229 /* YieldExpression */ : + case 219 /* ArrowFunction */ : + case 226 /* BinaryExpression */ : + case 230 /* SpreadElement */ : + case 234 /* AsExpression */ : + case 232 /* OmittedExpression */ : + case 361 /* CommaListExpression */ : + case 360 /* PartiallyEmittedExpression */ : + case 238 /* SatisfiesExpression */ : return true; default: return isUnaryExpressionKind(kind); @@ -16445,20 +16506,20 @@ ${lanes.join("\n")} } function isAssertionExpression(node) { const kind = node.kind; - return kind === 213 /* TypeAssertionExpression */ || kind === 231 /* AsExpression */ ; + return kind === 216 /* TypeAssertionExpression */ || kind === 234 /* AsExpression */ ; } function isNotEmittedOrPartiallyEmittedNode(node) { return isNotEmittedStatement(node) || isPartiallyEmittedExpression(node); } function isIterationStatement(node, lookInLabeledStatements) { switch(node.kind){ - case 245 /* ForStatement */ : - case 246 /* ForInStatement */ : - case 247 /* ForOfStatement */ : - case 243 /* DoStatement */ : - case 244 /* WhileStatement */ : + case 248 /* ForStatement */ : + case 249 /* ForInStatement */ : + case 250 /* ForOfStatement */ : + case 246 /* DoStatement */ : + case 247 /* WhileStatement */ : return true; - case 253 /* LabeledStatement */ : + case 256 /* LabeledStatement */ : return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -16476,7 +16537,7 @@ ${lanes.join("\n")} return isAnyImportOrReExport(result) || isExportAssignment(result) || hasSyntacticModifier(result, 1 /* Export */ ); } function isForInOrOfStatement(node) { - return node.kind === 246 /* ForInStatement */ || node.kind === 247 /* ForOfStatement */ ; + return node.kind === 249 /* ForInStatement */ || node.kind === 250 /* ForOfStatement */ ; } function isConciseBody(node) { return isBlock(node) || isExpression(node); @@ -16489,89 +16550,89 @@ ${lanes.join("\n")} } function isModuleBody(node) { const kind = node.kind; - return kind === 265 /* ModuleBlock */ || kind === 264 /* ModuleDeclaration */ || kind === 79 /* Identifier */ ; + return kind === 268 /* ModuleBlock */ || kind === 267 /* ModuleDeclaration */ || kind === 80 /* Identifier */ ; } function isNamespaceBody(node) { const kind = node.kind; - return kind === 265 /* ModuleBlock */ || kind === 264 /* ModuleDeclaration */ ; + return kind === 268 /* ModuleBlock */ || kind === 267 /* ModuleDeclaration */ ; } function isJSDocNamespaceBody(node) { const kind = node.kind; - return kind === 79 /* Identifier */ || kind === 264 /* ModuleDeclaration */ ; + return kind === 80 /* Identifier */ || kind === 267 /* ModuleDeclaration */ ; } function isNamedImportBindings(node) { const kind = node.kind; - return kind === 272 /* NamedImports */ || kind === 271 /* NamespaceImport */ ; + return kind === 275 /* NamedImports */ || kind === 274 /* NamespaceImport */ ; } function isModuleOrEnumDeclaration(node) { - return node.kind === 264 /* ModuleDeclaration */ || node.kind === 263 /* EnumDeclaration */ ; + return node.kind === 267 /* ModuleDeclaration */ || node.kind === 266 /* EnumDeclaration */ ; } function canHaveSymbol(node) { switch(node.kind){ - case 216 /* ArrowFunction */ : - case 223 /* BinaryExpression */ : - case 205 /* BindingElement */ : - case 210 /* CallExpression */ : - case 176 /* CallSignature */ : - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : - case 172 /* ClassStaticBlockDeclaration */ : - case 173 /* Constructor */ : - case 182 /* ConstructorType */ : - case 177 /* ConstructSignature */ : - case 209 /* ElementAccessExpression */ : - case 263 /* EnumDeclaration */ : - case 302 /* EnumMember */ : - case 274 /* ExportAssignment */ : - case 275 /* ExportDeclaration */ : - case 278 /* ExportSpecifier */ : - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 181 /* FunctionType */ : - case 174 /* GetAccessor */ : - case 79 /* Identifier */ : - case 270 /* ImportClause */ : - case 268 /* ImportEqualsDeclaration */ : - case 273 /* ImportSpecifier */ : - case 178 /* IndexSignature */ : - case 261 /* InterfaceDeclaration */ : - case 341 /* JSDocCallbackTag */ : - case 343 /* JSDocEnumTag */ : - case 320 /* JSDocFunctionType */ : - case 344 /* JSDocParameterTag */ : - case 351 /* JSDocPropertyTag */ : - case 326 /* JSDocSignature */ : - case 349 /* JSDocTypedefTag */ : - case 325 /* JSDocTypeLiteral */ : - case 288 /* JsxAttribute */ : - case 289 /* JsxAttributes */ : - case 290 /* JsxSpreadAttribute */ : - case 197 /* MappedType */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 264 /* ModuleDeclaration */ : - case 199 /* NamedTupleMember */ : - case 277 /* NamespaceExport */ : - case 267 /* NamespaceExportDeclaration */ : - case 271 /* NamespaceImport */ : - case 211 /* NewExpression */ : - case 14 /* NoSubstitutionTemplateLiteral */ : - case 8 /* NumericLiteral */ : - case 207 /* ObjectLiteralExpression */ : - case 166 /* Parameter */ : - case 208 /* PropertyAccessExpression */ : - case 299 /* PropertyAssignment */ : - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : - case 175 /* SetAccessor */ : - case 300 /* ShorthandPropertyAssignment */ : - case 308 /* SourceFile */ : - case 301 /* SpreadAssignment */ : - case 10 /* StringLiteral */ : - case 262 /* TypeAliasDeclaration */ : - case 184 /* TypeLiteral */ : - case 165 /* TypeParameter */ : - case 257 /* VariableDeclaration */ : + case 219 /* ArrowFunction */ : + case 226 /* BinaryExpression */ : + case 208 /* BindingElement */ : + case 213 /* CallExpression */ : + case 179 /* CallSignature */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 175 /* ClassStaticBlockDeclaration */ : + case 176 /* Constructor */ : + case 185 /* ConstructorType */ : + case 180 /* ConstructSignature */ : + case 212 /* ElementAccessExpression */ : + case 266 /* EnumDeclaration */ : + case 306 /* EnumMember */ : + case 277 /* ExportAssignment */ : + case 278 /* ExportDeclaration */ : + case 281 /* ExportSpecifier */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 184 /* FunctionType */ : + case 177 /* GetAccessor */ : + case 80 /* Identifier */ : + case 273 /* ImportClause */ : + case 271 /* ImportEqualsDeclaration */ : + case 276 /* ImportSpecifier */ : + case 181 /* IndexSignature */ : + case 264 /* InterfaceDeclaration */ : + case 345 /* JSDocCallbackTag */ : + case 347 /* JSDocEnumTag */ : + case 324 /* JSDocFunctionType */ : + case 348 /* JSDocParameterTag */ : + case 355 /* JSDocPropertyTag */ : + case 330 /* JSDocSignature */ : + case 353 /* JSDocTypedefTag */ : + case 329 /* JSDocTypeLiteral */ : + case 291 /* JsxAttribute */ : + case 292 /* JsxAttributes */ : + case 293 /* JsxSpreadAttribute */ : + case 200 /* MappedType */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 267 /* ModuleDeclaration */ : + case 202 /* NamedTupleMember */ : + case 280 /* NamespaceExport */ : + case 270 /* NamespaceExportDeclaration */ : + case 274 /* NamespaceImport */ : + case 214 /* NewExpression */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + case 9 /* NumericLiteral */ : + case 210 /* ObjectLiteralExpression */ : + case 169 /* Parameter */ : + case 211 /* PropertyAccessExpression */ : + case 303 /* PropertyAssignment */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : + case 178 /* SetAccessor */ : + case 304 /* ShorthandPropertyAssignment */ : + case 312 /* SourceFile */ : + case 305 /* SpreadAssignment */ : + case 11 /* StringLiteral */ : + case 265 /* TypeAliasDeclaration */ : + case 187 /* TypeLiteral */ : + case 168 /* TypeParameter */ : + case 260 /* VariableDeclaration */ : return true; default: return false; @@ -16579,52 +16640,52 @@ ${lanes.join("\n")} } function canHaveLocals(node) { switch(node.kind){ - case 216 /* ArrowFunction */ : - case 238 /* Block */ : - case 176 /* CallSignature */ : - case 266 /* CaseBlock */ : - case 295 /* CatchClause */ : - case 172 /* ClassStaticBlockDeclaration */ : - case 191 /* ConditionalType */ : - case 173 /* Constructor */ : - case 182 /* ConstructorType */ : - case 177 /* ConstructSignature */ : - case 245 /* ForStatement */ : - case 246 /* ForInStatement */ : - case 247 /* ForOfStatement */ : - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 181 /* FunctionType */ : - case 174 /* GetAccessor */ : - case 178 /* IndexSignature */ : - case 341 /* JSDocCallbackTag */ : - case 343 /* JSDocEnumTag */ : - case 320 /* JSDocFunctionType */ : - case 326 /* JSDocSignature */ : - case 349 /* JSDocTypedefTag */ : - case 197 /* MappedType */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 264 /* ModuleDeclaration */ : - case 175 /* SetAccessor */ : - case 308 /* SourceFile */ : - case 262 /* TypeAliasDeclaration */ : + case 219 /* ArrowFunction */ : + case 241 /* Block */ : + case 179 /* CallSignature */ : + case 269 /* CaseBlock */ : + case 299 /* CatchClause */ : + case 175 /* ClassStaticBlockDeclaration */ : + case 194 /* ConditionalType */ : + case 176 /* Constructor */ : + case 185 /* ConstructorType */ : + case 180 /* ConstructSignature */ : + case 248 /* ForStatement */ : + case 249 /* ForInStatement */ : + case 250 /* ForOfStatement */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 184 /* FunctionType */ : + case 177 /* GetAccessor */ : + case 181 /* IndexSignature */ : + case 345 /* JSDocCallbackTag */ : + case 347 /* JSDocEnumTag */ : + case 324 /* JSDocFunctionType */ : + case 330 /* JSDocSignature */ : + case 353 /* JSDocTypedefTag */ : + case 200 /* MappedType */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 267 /* ModuleDeclaration */ : + case 178 /* SetAccessor */ : + case 312 /* SourceFile */ : + case 265 /* TypeAliasDeclaration */ : return true; default: return false; } } function isDeclarationKind(kind) { - return kind === 216 /* ArrowFunction */ || kind === 205 /* BindingElement */ || kind === 260 /* ClassDeclaration */ || kind === 228 /* ClassExpression */ || kind === 172 /* ClassStaticBlockDeclaration */ || kind === 173 /* Constructor */ || kind === 263 /* EnumDeclaration */ || kind === 302 /* EnumMember */ || kind === 278 /* ExportSpecifier */ || kind === 259 /* FunctionDeclaration */ || kind === 215 /* FunctionExpression */ || kind === 174 /* GetAccessor */ || kind === 270 /* ImportClause */ || kind === 268 /* ImportEqualsDeclaration */ || kind === 273 /* ImportSpecifier */ || kind === 261 /* InterfaceDeclaration */ || kind === 288 /* JsxAttribute */ || kind === 171 /* MethodDeclaration */ || kind === 170 /* MethodSignature */ || kind === 264 /* ModuleDeclaration */ || kind === 267 /* NamespaceExportDeclaration */ || kind === 271 /* NamespaceImport */ || kind === 277 /* NamespaceExport */ || kind === 166 /* Parameter */ || kind === 299 /* PropertyAssignment */ || kind === 169 /* PropertyDeclaration */ || kind === 168 /* PropertySignature */ || kind === 175 /* SetAccessor */ || kind === 300 /* ShorthandPropertyAssignment */ || kind === 262 /* TypeAliasDeclaration */ || kind === 165 /* TypeParameter */ || kind === 257 /* VariableDeclaration */ || kind === 349 /* JSDocTypedefTag */ || kind === 341 /* JSDocCallbackTag */ || kind === 351 /* JSDocPropertyTag */ ; + return kind === 219 /* ArrowFunction */ || kind === 208 /* BindingElement */ || kind === 263 /* ClassDeclaration */ || kind === 231 /* ClassExpression */ || kind === 175 /* ClassStaticBlockDeclaration */ || kind === 176 /* Constructor */ || kind === 266 /* EnumDeclaration */ || kind === 306 /* EnumMember */ || kind === 281 /* ExportSpecifier */ || kind === 262 /* FunctionDeclaration */ || kind === 218 /* FunctionExpression */ || kind === 177 /* GetAccessor */ || kind === 273 /* ImportClause */ || kind === 271 /* ImportEqualsDeclaration */ || kind === 276 /* ImportSpecifier */ || kind === 264 /* InterfaceDeclaration */ || kind === 291 /* JsxAttribute */ || kind === 174 /* MethodDeclaration */ || kind === 173 /* MethodSignature */ || kind === 267 /* ModuleDeclaration */ || kind === 270 /* NamespaceExportDeclaration */ || kind === 274 /* NamespaceImport */ || kind === 280 /* NamespaceExport */ || kind === 169 /* Parameter */ || kind === 303 /* PropertyAssignment */ || kind === 172 /* PropertyDeclaration */ || kind === 171 /* PropertySignature */ || kind === 178 /* SetAccessor */ || kind === 304 /* ShorthandPropertyAssignment */ || kind === 265 /* TypeAliasDeclaration */ || kind === 168 /* TypeParameter */ || kind === 260 /* VariableDeclaration */ || kind === 353 /* JSDocTypedefTag */ || kind === 345 /* JSDocCallbackTag */ || kind === 355 /* JSDocPropertyTag */ ; } function isDeclarationStatementKind(kind) { - return kind === 259 /* FunctionDeclaration */ || kind === 279 /* MissingDeclaration */ || kind === 260 /* ClassDeclaration */ || kind === 261 /* InterfaceDeclaration */ || kind === 262 /* TypeAliasDeclaration */ || kind === 263 /* EnumDeclaration */ || kind === 264 /* ModuleDeclaration */ || kind === 269 /* ImportDeclaration */ || kind === 268 /* ImportEqualsDeclaration */ || kind === 275 /* ExportDeclaration */ || kind === 274 /* ExportAssignment */ || kind === 267 /* NamespaceExportDeclaration */ ; + return kind === 262 /* FunctionDeclaration */ || kind === 282 /* MissingDeclaration */ || kind === 263 /* ClassDeclaration */ || kind === 264 /* InterfaceDeclaration */ || kind === 265 /* TypeAliasDeclaration */ || kind === 266 /* EnumDeclaration */ || kind === 267 /* ModuleDeclaration */ || kind === 272 /* ImportDeclaration */ || kind === 271 /* ImportEqualsDeclaration */ || kind === 278 /* ExportDeclaration */ || kind === 277 /* ExportAssignment */ || kind === 270 /* NamespaceExportDeclaration */ ; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 249 /* BreakStatement */ || kind === 248 /* ContinueStatement */ || kind === 256 /* DebuggerStatement */ || kind === 243 /* DoStatement */ || kind === 241 /* ExpressionStatement */ || kind === 239 /* EmptyStatement */ || kind === 246 /* ForInStatement */ || kind === 247 /* ForOfStatement */ || kind === 245 /* ForStatement */ || kind === 242 /* IfStatement */ || kind === 253 /* LabeledStatement */ || kind === 250 /* ReturnStatement */ || kind === 252 /* SwitchStatement */ || kind === 254 /* ThrowStatement */ || kind === 255 /* TryStatement */ || kind === 240 /* VariableStatement */ || kind === 244 /* WhileStatement */ || kind === 251 /* WithStatement */ || kind === 355 /* NotEmittedStatement */ || kind === 359 /* EndOfDeclarationMarker */ || kind === 358 /* MergeDeclarationMarker */ ; + return kind === 252 /* BreakStatement */ || kind === 251 /* ContinueStatement */ || kind === 259 /* DebuggerStatement */ || kind === 246 /* DoStatement */ || kind === 244 /* ExpressionStatement */ || kind === 242 /* EmptyStatement */ || kind === 249 /* ForInStatement */ || kind === 250 /* ForOfStatement */ || kind === 248 /* ForStatement */ || kind === 245 /* IfStatement */ || kind === 256 /* LabeledStatement */ || kind === 253 /* ReturnStatement */ || kind === 255 /* SwitchStatement */ || kind === 257 /* ThrowStatement */ || kind === 258 /* TryStatement */ || kind === 243 /* VariableStatement */ || kind === 247 /* WhileStatement */ || kind === 254 /* WithStatement */ || kind === 359 /* NotEmittedStatement */ ; } function isDeclaration(node) { - if (node.kind === 165 /* TypeParameter */ ) return node.parent && node.parent.kind !== 348 /* JSDocTemplateTag */ || isInJSFile(node); + if (node.kind === 168 /* TypeParameter */ ) return node.parent && node.parent.kind !== 352 /* JSDocTemplateTag */ || isInJSFile(node); return isDeclarationKind(node.kind); } function isDeclarationStatement(node) { @@ -16638,62 +16699,62 @@ ${lanes.join("\n")} return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) || isBlockStatement(node); } function isBlockStatement(node) { - if (node.kind !== 238 /* Block */ ) return false; + if (node.kind !== 241 /* Block */ ) return false; if (node.parent !== void 0) { - if (node.parent.kind === 255 /* TryStatement */ || node.parent.kind === 295 /* CatchClause */ ) return false; + if (node.parent.kind === 258 /* TryStatement */ || node.parent.kind === 299 /* CatchClause */ ) return false; } return !isFunctionBlock(node); } function isStatementOrBlock(node) { const kind = node.kind; - return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) || kind === 238 /* Block */ ; + return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) || kind === 241 /* Block */ ; } function isModuleReference(node) { const kind = node.kind; - return kind === 280 /* ExternalModuleReference */ || kind === 163 /* QualifiedName */ || kind === 79 /* Identifier */ ; + return kind === 283 /* ExternalModuleReference */ || kind === 166 /* QualifiedName */ || kind === 80 /* Identifier */ ; } function isJsxTagNameExpression(node) { const kind = node.kind; - return kind === 108 /* ThisKeyword */ || kind === 79 /* Identifier */ || kind === 208 /* PropertyAccessExpression */ ; + return kind === 110 /* ThisKeyword */ || kind === 80 /* Identifier */ || kind === 211 /* PropertyAccessExpression */ || kind === 295 /* JsxNamespacedName */ ; } function isJsxChild(node) { const kind = node.kind; - return kind === 281 /* JsxElement */ || kind === 291 /* JsxExpression */ || kind === 282 /* JsxSelfClosingElement */ || kind === 11 /* JsxText */ || kind === 285 /* JsxFragment */ ; + return kind === 284 /* JsxElement */ || kind === 294 /* JsxExpression */ || kind === 285 /* JsxSelfClosingElement */ || kind === 12 /* JsxText */ || kind === 288 /* JsxFragment */ ; } function isJsxAttributeLike(node) { const kind = node.kind; - return kind === 288 /* JsxAttribute */ || kind === 290 /* JsxSpreadAttribute */ ; + return kind === 291 /* JsxAttribute */ || kind === 293 /* JsxSpreadAttribute */ ; } function isStringLiteralOrJsxExpression(node) { const kind = node.kind; - return kind === 10 /* StringLiteral */ || kind === 291 /* JsxExpression */ ; + return kind === 11 /* StringLiteral */ || kind === 294 /* JsxExpression */ ; } function isJsxOpeningLikeElement(node) { const kind = node.kind; - return kind === 283 /* JsxOpeningElement */ || kind === 282 /* JsxSelfClosingElement */ ; + return kind === 286 /* JsxOpeningElement */ || kind === 285 /* JsxSelfClosingElement */ ; } function isCaseOrDefaultClause(node) { const kind = node.kind; - return kind === 292 /* CaseClause */ || kind === 293 /* DefaultClause */ ; + return kind === 296 /* CaseClause */ || kind === 297 /* DefaultClause */ ; } function isJSDocNode(node) { - return node.kind >= 312 /* FirstJSDocNode */ && node.kind <= 353 /* LastJSDocNode */ ; + return node.kind >= 316 /* FirstJSDocNode */ && node.kind <= 357 /* LastJSDocNode */ ; } function isJSDocCommentContainingNode(node) { - return node.kind === 323 /* JSDoc */ || node.kind === 322 /* JSDocNamepathType */ || node.kind === 324 /* JSDocText */ || isJSDocLinkLike(node) || isJSDocTag(node) || isJSDocTypeLiteral(node) || isJSDocSignature(node); + return node.kind === 327 /* JSDoc */ || node.kind === 326 /* JSDocNamepathType */ || node.kind === 328 /* JSDocText */ || isJSDocLinkLike(node) || isJSDocTag(node) || isJSDocTypeLiteral(node) || isJSDocSignature(node); } function isJSDocTag(node) { - return node.kind >= 330 /* FirstJSDocTagNode */ && node.kind <= 353 /* LastJSDocTagNode */ ; + return node.kind >= 334 /* FirstJSDocTagNode */ && node.kind <= 357 /* LastJSDocTagNode */ ; } function isSetAccessor(node) { - return node.kind === 175 /* SetAccessor */ ; + return node.kind === 178 /* SetAccessor */ ; } function isGetAccessor(node) { - return node.kind === 174 /* GetAccessor */ ; + return node.kind === 177 /* GetAccessor */ ; } function hasJSDocNodes(node) { if (!canHaveJSDoc(node)) return false; - const { jsDoc: jsDoc } = node; + const { jsDoc: jsDoc } = node; return !!jsDoc && jsDoc.length > 0; } function hasType(node) { @@ -16704,22 +16765,22 @@ ${lanes.join("\n")} } function hasOnlyExpressionInitializer(node) { switch(node.kind){ - case 257 /* VariableDeclaration */ : - case 166 /* Parameter */ : - case 205 /* BindingElement */ : - case 169 /* PropertyDeclaration */ : - case 299 /* PropertyAssignment */ : - case 302 /* EnumMember */ : + case 260 /* VariableDeclaration */ : + case 169 /* Parameter */ : + case 208 /* BindingElement */ : + case 172 /* PropertyDeclaration */ : + case 303 /* PropertyAssignment */ : + case 306 /* EnumMember */ : return true; default: return false; } } function isObjectLiteralElement(node) { - return node.kind === 288 /* JsxAttribute */ || node.kind === 290 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); + return node.kind === 291 /* JsxAttribute */ || node.kind === 293 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); } function isTypeReferenceType(node) { - return node.kind === 180 /* TypeReference */ || node.kind === 230 /* ExpressionWithTypeArguments */ ; + return node.kind === 183 /* TypeReference */ || node.kind === 233 /* ExpressionWithTypeArguments */ ; } function guessIndentation(lines) { let indentation = MAX_SMI_X86; @@ -16735,10 +16796,10 @@ ${lanes.join("\n")} return indentation === MAX_SMI_X86 ? void 0 : indentation; } function isStringLiteralLike(node) { - return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */ ; + return node.kind === 11 /* StringLiteral */ || node.kind === 15 /* NoSubstitutionTemplateLiteral */ ; } function isJSDocLinkLike(node) { - return node.kind === 327 /* JSDocLink */ || node.kind === 328 /* JSDocLinkCode */ || node.kind === 329 /* JSDocLinkPlain */ ; + return node.kind === 331 /* JSDocLink */ || node.kind === 332 /* JSDocLinkCode */ || node.kind === 333 /* JSDocLinkPlain */ ; } function hasRestParameter(s) { const last2 = lastOrUndefined(s.parameters); @@ -16746,7 +16807,7 @@ ${lanes.join("\n")} } function isRestParameter(node) { const type = isJSDocParameterTag(node) ? node.typeExpression && node.typeExpression.type : node.type; - return node.dotDotDotToken !== void 0 || !!type && type.kind === 321 /* JSDocVariadicType */ ; + return node.dotDotDotToken !== void 0 || !!type && type.kind === 325 /* JSDocVariadicType */ ; } var unchangedTextChangeRange, supportedLocaleDirectories, MAX_SMI_X86; var init_utilitiesPublic = __esm({ @@ -16880,8 +16941,8 @@ ${lanes.join("\n")} return node.end - node.pos; } function getResolvedModule(sourceFile, moduleNameText, mode) { - var _a2, _b; - return (_b = (_a2 = sourceFile == null ? void 0 : sourceFile.resolvedModules) == null ? void 0 : _a2.get(moduleNameText, mode)) == null ? void 0 : _b.resolvedModule; + var _a, _b; + return (_b = (_a = sourceFile == null ? void 0 : sourceFile.resolvedModules) == null ? void 0 : _a.get(moduleNameText, mode)) == null ? void 0 : _b.resolvedModule; } function setResolvedModule(sourceFile, moduleNameText, resolvedModule, mode) { if (!sourceFile.resolvedModules) sourceFile.resolvedModules = createModeAwareCache(); @@ -16892,19 +16953,30 @@ ${lanes.join("\n")} sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, mode, resolvedTypeReferenceDirective); } function getResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, mode) { - var _a2, _b; - return (_b = (_a2 = sourceFile == null ? void 0 : sourceFile.resolvedTypeReferenceDirectiveNames) == null ? void 0 : _a2.get(typeReferenceDirectiveName, mode)) == null ? void 0 : _b.resolvedTypeReferenceDirective; + var _a, _b; + return (_b = (_a = sourceFile == null ? void 0 : sourceFile.resolvedTypeReferenceDirectiveNames) == null ? void 0 : _a.get(typeReferenceDirectiveName, mode)) == null ? void 0 : _b.resolvedTypeReferenceDirective; } function projectReferenceIsEqualTo(oldRef, newRef) { return oldRef.path === newRef.path && !oldRef.prepend === !newRef.prepend && !oldRef.circular === !newRef.circular; } function moduleResolutionIsEqualTo(oldResolution, newResolution) { - return oldResolution === newResolution || oldResolution.resolvedModule === newResolution.resolvedModule || !!oldResolution.resolvedModule && !!newResolution.resolvedModule && oldResolution.resolvedModule.isExternalLibraryImport === newResolution.resolvedModule.isExternalLibraryImport && oldResolution.resolvedModule.extension === newResolution.resolvedModule.extension && oldResolution.resolvedModule.resolvedFileName === newResolution.resolvedModule.resolvedFileName && oldResolution.resolvedModule.originalPath === newResolution.resolvedModule.originalPath && packageIdIsEqual(oldResolution.resolvedModule.packageId, newResolution.resolvedModule.packageId); + return oldResolution === newResolution || oldResolution.resolvedModule === newResolution.resolvedModule || !!oldResolution.resolvedModule && !!newResolution.resolvedModule && oldResolution.resolvedModule.isExternalLibraryImport === newResolution.resolvedModule.isExternalLibraryImport && oldResolution.resolvedModule.extension === newResolution.resolvedModule.extension && oldResolution.resolvedModule.resolvedFileName === newResolution.resolvedModule.resolvedFileName && oldResolution.resolvedModule.originalPath === newResolution.resolvedModule.originalPath && packageIdIsEqual(oldResolution.resolvedModule.packageId, newResolution.resolvedModule.packageId) && oldResolution.node10Result === newResolution.node10Result; + } + function createModuleNotFoundChain(sourceFile, host, moduleReference, mode, packageName) { + var _a, _b; + const node10Result = (_b = (_a = sourceFile.resolvedModules) == null ? void 0 : _a.get(moduleReference, mode)) == null ? void 0 : _b.node10Result; + const result = node10Result ? chainDiagnosticMessages(/*details*/ void 0, Diagnostics.There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The_1_library_may_need_to_update_its_package_json_or_typings, node10Result, node10Result.indexOf(nodeModulesPathPart + "@types/") > -1 ? `@types/${mangleScopedPackageName(packageName)}` : packageName) : host.typesPackageExists(packageName) ? chainDiagnosticMessages(/*details*/ void 0, Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageName, mangleScopedPackageName(packageName)) : host.packageBundlesTypes(packageName) ? chainDiagnosticMessages(/*details*/ void 0, Diagnostics.If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1, packageName, moduleReference) : chainDiagnosticMessages(/*details*/ void 0, Diagnostics.Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, mangleScopedPackageName(packageName)); + if (result) result.repopulateInfo = ()=>({ + moduleReference: moduleReference, + mode: mode, + packageName: packageName === moduleReference ? void 0 : packageName + }); + return result; } function packageIdIsEqual(a, b) { return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } - function packageIdToPackageName({ name: name , subModuleName: subModuleName }) { + function packageIdToPackageName({ name: name, subModuleName: subModuleName }) { return subModuleName ? `${name}/${subModuleName}` : name; } function packageIdToString(packageId) { @@ -16928,17 +17000,17 @@ ${lanes.join("\n")} } function containsParseError(node) { aggregateChildData(node); - return (node.flags & 524288 /* ThisNodeOrAnySubNodesHasError */ ) !== 0; + return (node.flags & 1048576 /* ThisNodeOrAnySubNodesHasError */ ) !== 0; } function aggregateChildData(node) { - if (!(node.flags & 1048576 /* HasAggregatedChildData */ )) { - const thisNodeOrAnySubNodesHasError = (node.flags & 131072 /* ThisNodeHasError */ ) !== 0 || forEachChild(node, containsParseError); - if (thisNodeOrAnySubNodesHasError) node.flags |= 524288 /* ThisNodeOrAnySubNodesHasError */ ; - node.flags |= 1048576 /* HasAggregatedChildData */ ; + if (!(node.flags & 2097152 /* HasAggregatedChildData */ )) { + const thisNodeOrAnySubNodesHasError = (node.flags & 262144 /* ThisNodeHasError */ ) !== 0 || forEachChild(node, containsParseError); + if (thisNodeOrAnySubNodesHasError) node.flags |= 1048576 /* ThisNodeOrAnySubNodesHasError */ ; + node.flags |= 2097152 /* HasAggregatedChildData */ ; } } function getSourceFileOfNode(node) { - while(node && node.kind !== 308 /* SourceFile */ )node = node.parent; + while(node && node.kind !== 312 /* SourceFile */ )node = node.parent; return node; } function getSourceFileOfModule(module2) { @@ -16949,11 +17021,11 @@ ${lanes.join("\n")} } function isStatementWithLocals(node) { switch(node.kind){ - case 238 /* Block */ : - case 266 /* CaseBlock */ : - case 245 /* ForStatement */ : - case 246 /* ForInStatement */ : - case 247 /* ForOfStatement */ : + case 241 /* Block */ : + case 269 /* CaseBlock */ : + case 248 /* ForStatement */ : + case 249 /* ForInStatement */ : + case 250 /* ForOfStatement */ : return true; } return false; @@ -17045,7 +17117,7 @@ ${lanes.join("\n")} function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { if (text.charCodeAt(commentPos + 1) === 47 /* slash */ && commentPos + 2 < commentEnd && text.charCodeAt(commentPos + 2) === 47 /* slash */ ) { const textSubStr = text.substring(commentPos, commentEnd); - return fullTripleSlashReferencePathRegEx.test(textSubStr) || fullTripleSlashAMDReferencePathRegEx.test(textSubStr) || fullTripleSlashReferenceTypeReferenceDirectiveRegEx.test(textSubStr) || defaultLibReferenceRegEx.test(textSubStr) ? true : false; + return fullTripleSlashReferencePathRegEx.test(textSubStr) || fullTripleSlashAMDReferencePathRegEx.test(textSubStr) || fullTripleSlashAMDModuleRegEx.test(textSubStr) || fullTripleSlashReferenceTypeReferenceDirectiveRegEx.test(textSubStr) || fullTripleSlashLibReferenceRegEx.test(textSubStr) || defaultLibReferenceRegEx.test(textSubStr) ? true : false; } return false; } @@ -17073,9 +17145,9 @@ ${lanes.join("\n")} } function getTokenPosOfNode(node, sourceFile, includeJsDoc) { if (nodeIsMissing(node)) return node.pos; - if (isJSDocNode(node) || node.kind === 11 /* JsxText */ ) return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + if (isJSDocNode(node) || node.kind === 12 /* JsxText */ ) return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); if (includeJsDoc && hasJSDocNodes(node)) return getTokenPosOfNode(node.jsDoc[0], sourceFile); - if (node.kind === 354 /* SyntaxList */ && node._children.length > 0) return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); + if (node.kind === 358 /* SyntaxList */ && node._children.length > 0) return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ false, isInJSDoc(node)); } function getNonDecoratorTokenPosOfNode(node, sourceFile) { @@ -17512,38 +17584,37 @@ ${lanes.join("\n")} })); } function getLiteralText(node, sourceFile, flags) { - var _a2; if (sourceFile && canUseOriginalText(node, flags)) return getSourceTextOfNodeFromSourceFile(sourceFile, node); switch(node.kind){ - case 10 /* StringLiteral */ : + case 11 /* StringLiteral */ : { - const escapeText = flags & 2 /* JsxAttributeEscape */ ? escapeJsxAttributeString : flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 33554432 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + const escapeText = flags & 2 /* JsxAttributeEscape */ ? escapeJsxAttributeString : flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; if (node.singleQuote) return "'" + escapeText(node.text, 39 /* singleQuote */ ) + "'"; else return '"' + escapeText(node.text, 34 /* doubleQuote */ ) + '"'; } - case 14 /* NoSubstitutionTemplateLiteral */ : - case 15 /* TemplateHead */ : - case 16 /* TemplateMiddle */ : - case 17 /* TemplateTail */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + case 16 /* TemplateHead */ : + case 17 /* TemplateMiddle */ : + case 18 /* TemplateTail */ : { - const escapeText = flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 33554432 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; - const rawText = (_a2 = node.rawText) != null ? _a2 : escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */ )); + const escapeText = flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + const rawText = node.rawText ?? escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */ )); switch(node.kind){ - case 14 /* NoSubstitutionTemplateLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : return "`" + rawText + "`"; - case 15 /* TemplateHead */ : + case 16 /* TemplateHead */ : return "`" + rawText + "${"; - case 16 /* TemplateMiddle */ : + case 17 /* TemplateMiddle */ : return "}" + rawText + "${"; - case 17 /* TemplateTail */ : + case 18 /* TemplateTail */ : return "}" + rawText + "`"; } break; } - case 8 /* NumericLiteral */ : - case 9 /* BigIntLiteral */ : + case 9 /* NumericLiteral */ : + case 10 /* BigIntLiteral */ : return node.text; - case 13 /* RegularExpressionLiteral */ : + case 14 /* RegularExpressionLiteral */ : if (flags & 4 /* TerminateUnterminatedLiterals */ && node.isUnterminated) return node.text + (node.text.charCodeAt(node.text.length - 1) === 92 /* backslash */ ? " /" : "/"); return node.text; } @@ -17551,7 +17622,10 @@ ${lanes.join("\n")} } function canUseOriginalText(node, flags) { if (nodeIsSynthesized(node) || !node.parent || flags & 4 /* TerminateUnterminatedLiterals */ && node.isUnterminated) return false; - if (isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */ ) return !!(flags & 8 /* AllowNumericSeparator */ ); + if (isNumericLiteral(node)) { + if (node.numericLiteralFlags & 26656 /* IsInvalid */ ) return false; + if (node.numericLiteralFlags & 512 /* ContainsSeparator */ ) return !!(flags & 8 /* AllowNumericSeparator */ ); + } return !isBigIntLiteral(node); } function getTextOfConstantValue(value1) { @@ -17561,17 +17635,17 @@ ${lanes.join("\n")} return getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_"); } function isBlockOrCatchScoped(declaration) { - return (getCombinedNodeFlags(declaration) & 3 /* BlockScoped */ ) !== 0 || isCatchClauseVariableDeclarationOrBindingElement(declaration); + return (getCombinedNodeFlags(declaration) & 7 /* BlockScoped */ ) !== 0 || isCatchClauseVariableDeclarationOrBindingElement(declaration); } function isCatchClauseVariableDeclarationOrBindingElement(declaration) { const node = getRootDeclaration(declaration); - return node.kind === 257 /* VariableDeclaration */ && node.parent.kind === 295 /* CatchClause */ ; + return node.kind === 260 /* VariableDeclaration */ && node.parent.kind === 299 /* CatchClause */ ; } function isAmbientModule(node) { - return isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node)); + return isModuleDeclaration(node) && (node.name.kind === 11 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } function isModuleWithStringLiteralName(node) { - return isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */ ; + return isModuleDeclaration(node) && node.name.kind === 11 /* StringLiteral */ ; } function isNonGlobalAmbientModule(node) { return isModuleDeclaration(node) && isStringLiteral(node.name); @@ -17583,35 +17657,35 @@ ${lanes.join("\n")} return isShorthandAmbientModule(moduleSymbol.valueDeclaration); } function isShorthandAmbientModule(node) { - return !!node && node.kind === 264 /* ModuleDeclaration */ && !node.body; + return !!node && node.kind === 267 /* ModuleDeclaration */ && !node.body; } function isBlockScopedContainerTopLevel(node) { - return node.kind === 308 /* SourceFile */ || node.kind === 264 /* ModuleDeclaration */ || isFunctionLikeOrClassStaticBlockDeclaration(node); + return node.kind === 312 /* SourceFile */ || node.kind === 267 /* ModuleDeclaration */ || isFunctionLikeOrClassStaticBlockDeclaration(node); } function isGlobalScopeAugmentation(module2) { - return !!(module2.flags & 1024 /* GlobalAugmentation */ ); + return !!(module2.flags & 2048 /* GlobalAugmentation */ ); } function isExternalModuleAugmentation(node) { return isAmbientModule(node) && isModuleAugmentationExternal(node); } function isModuleAugmentationExternal(node) { switch(node.parent.kind){ - case 308 /* SourceFile */ : + case 312 /* SourceFile */ : return isExternalModule(node.parent); - case 265 /* ModuleBlock */ : + case 268 /* ModuleBlock */ : return isAmbientModule(node.parent.parent) && isSourceFile(node.parent.parent.parent) && !isExternalModule(node.parent.parent.parent); } return false; } function getNonAugmentationDeclaration(symbol) { - var _a2; - return (_a2 = symbol.declarations) == null ? void 0 : _a2.find((d)=>!isExternalModuleAugmentation(d) && !(isModuleDeclaration(d) && isGlobalScopeAugmentation(d))); + var _a; + return (_a = symbol.declarations) == null ? void 0 : _a.find((d)=>!isExternalModuleAugmentation(d) && !(isModuleDeclaration(d) && isGlobalScopeAugmentation(d))); } function isCommonJSContainingModuleKind(kind) { return kind === 1 /* CommonJS */ || kind === 100 /* Node16 */ || kind === 199 /* NodeNext */ ; } function isEffectiveExternalModule(node, compilerOptions) { - return isExternalModule(node) || getIsolatedModules(compilerOptions) || isCommonJSContainingModuleKind(getEmitModuleKind(compilerOptions)) && !!node.commonJsModuleIndicator; + return isExternalModule(node) || isCommonJSContainingModuleKind(getEmitModuleKind(compilerOptions)) && !!node.commonJsModuleIndicator; } function isEffectiveStrictModeSourceFile(node, compilerOptions) { switch(node.scriptKind){ @@ -17633,28 +17707,28 @@ ${lanes.join("\n")} return false; } function isAmbientPropertyDeclaration(node) { - return !!(node.flags & 16777216 /* Ambient */ ) || hasSyntacticModifier(node, 2 /* Ambient */ ); + return !!(node.flags & 33554432 /* Ambient */ ) || hasSyntacticModifier(node, 2 /* Ambient */ ); } function isBlockScope(node, parentNode) { switch(node.kind){ - case 308 /* SourceFile */ : - case 266 /* CaseBlock */ : - case 295 /* CatchClause */ : - case 264 /* ModuleDeclaration */ : - case 245 /* ForStatement */ : - case 246 /* ForInStatement */ : - case 247 /* ForOfStatement */ : - case 173 /* Constructor */ : - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - case 169 /* PropertyDeclaration */ : - case 172 /* ClassStaticBlockDeclaration */ : + case 312 /* SourceFile */ : + case 269 /* CaseBlock */ : + case 299 /* CatchClause */ : + case 267 /* ModuleDeclaration */ : + case 248 /* ForStatement */ : + case 249 /* ForInStatement */ : + case 250 /* ForOfStatement */ : + case 176 /* Constructor */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + case 172 /* PropertyDeclaration */ : + case 175 /* ClassStaticBlockDeclaration */ : return true; - case 238 /* Block */ : + case 241 /* Block */ : return !isFunctionLikeOrClassStaticBlockDeclaration(parentNode); } return false; @@ -17662,9 +17736,9 @@ ${lanes.join("\n")} function isDeclarationWithTypeParameters(node) { Debug.type(node); switch(node.kind){ - case 341 /* JSDocCallbackTag */ : - case 349 /* JSDocTypedefTag */ : - case 326 /* JSDocSignature */ : + case 345 /* JSDocCallbackTag */ : + case 353 /* JSDocTypedefTag */ : + case 330 /* JSDocSignature */ : return true; default: assertType(node); @@ -17674,25 +17748,25 @@ ${lanes.join("\n")} function isDeclarationWithTypeParameterChildren(node) { Debug.type(node); switch(node.kind){ - case 176 /* CallSignature */ : - case 177 /* ConstructSignature */ : - case 170 /* MethodSignature */ : - case 178 /* IndexSignature */ : - case 181 /* FunctionType */ : - case 182 /* ConstructorType */ : - case 320 /* JSDocFunctionType */ : - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : - case 261 /* InterfaceDeclaration */ : - case 262 /* TypeAliasDeclaration */ : - case 348 /* JSDocTemplateTag */ : - case 259 /* FunctionDeclaration */ : - case 171 /* MethodDeclaration */ : - case 173 /* Constructor */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : + case 179 /* CallSignature */ : + case 180 /* ConstructSignature */ : + case 173 /* MethodSignature */ : + case 181 /* IndexSignature */ : + case 184 /* FunctionType */ : + case 185 /* ConstructorType */ : + case 324 /* JSDocFunctionType */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 264 /* InterfaceDeclaration */ : + case 265 /* TypeAliasDeclaration */ : + case 352 /* JSDocTemplateTag */ : + case 262 /* FunctionDeclaration */ : + case 174 /* MethodDeclaration */ : + case 176 /* Constructor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : return true; default: assertType(node); @@ -17701,8 +17775,8 @@ ${lanes.join("\n")} } function isAnyImportSyntax(node) { switch(node.kind){ - case 269 /* ImportDeclaration */ : - case 268 /* ImportEqualsDeclaration */ : + case 272 /* ImportDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : return true; default: return false; @@ -17713,15 +17787,15 @@ ${lanes.join("\n")} } function isLateVisibilityPaintedStatement(node) { switch(node.kind){ - case 269 /* ImportDeclaration */ : - case 268 /* ImportEqualsDeclaration */ : - case 240 /* VariableStatement */ : - case 260 /* ClassDeclaration */ : - case 259 /* FunctionDeclaration */ : - case 264 /* ModuleDeclaration */ : - case 262 /* TypeAliasDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 263 /* EnumDeclaration */ : + case 272 /* ImportDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : + case 243 /* VariableStatement */ : + case 263 /* ClassDeclaration */ : + case 262 /* FunctionDeclaration */ : + case 267 /* ModuleDeclaration */ : + case 265 /* TypeAliasDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 266 /* EnumDeclaration */ : return true; default: return false; @@ -17733,6 +17807,9 @@ ${lanes.join("\n")} function isAnyImportOrReExport(node) { return isAnyImportSyntax(node) || isExportDeclaration(node); } + function getEnclosingContainer(node) { + return findAncestor(node.parent, (n)=>!!(getContainerFlags(n) & 1 /* IsContainer */ )); + } function getEnclosingBlockScopeContainer(node) { return findAncestor(node.parent, (current)=>isBlockScope(current, current.parent)); } @@ -17750,21 +17827,23 @@ ${lanes.join("\n")} return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : void 0; } function isComputedNonLiteralName(name) { - return name.kind === 164 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression); + return name.kind === 167 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression); } function tryGetTextOfPropertyName(name) { - var _a2; + var _a; switch(name.kind){ - case 79 /* Identifier */ : - case 80 /* PrivateIdentifier */ : - return ((_a2 = name.emitNode) == null ? void 0 : _a2.autoGenerate) ? void 0 : name.escapedText; - case 10 /* StringLiteral */ : - case 8 /* NumericLiteral */ : - case 14 /* NoSubstitutionTemplateLiteral */ : + case 80 /* Identifier */ : + case 81 /* PrivateIdentifier */ : + return ((_a = name.emitNode) == null ? void 0 : _a.autoGenerate) ? void 0 : name.escapedText; + case 11 /* StringLiteral */ : + case 9 /* NumericLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : return escapeLeadingUnderscores(name.text); - case 164 /* ComputedPropertyName */ : + case 167 /* ComputedPropertyName */ : if (isStringOrNumericLiteralLike(name.expression)) return escapeLeadingUnderscores(name.expression.text); return void 0; + case 295 /* JsxNamespacedName */ : + return getEscapedTextOfJsxNamespacedName(name); default: return Debug.assertNever(name); } @@ -17774,33 +17853,35 @@ ${lanes.join("\n")} } function entityNameToString(name) { switch(name.kind){ - case 108 /* ThisKeyword */ : + case 110 /* ThisKeyword */ : return "this"; - case 80 /* PrivateIdentifier */ : - case 79 /* Identifier */ : + case 81 /* PrivateIdentifier */ : + case 80 /* Identifier */ : return getFullWidth(name) === 0 ? idText(name) : getTextOfNode(name); - case 163 /* QualifiedName */ : + case 166 /* QualifiedName */ : return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 208 /* PropertyAccessExpression */ : + case 211 /* PropertyAccessExpression */ : if (isIdentifier(name.name) || isPrivateIdentifier(name.name)) return entityNameToString(name.expression) + "." + entityNameToString(name.name); else return Debug.assertNever(name.name); - case 314 /* JSDocMemberName */ : + case 318 /* JSDocMemberName */ : return entityNameToString(name.left) + entityNameToString(name.right); + case 295 /* JsxNamespacedName */ : + return entityNameToString(name.namespace) + ":" + entityNameToString(name.name); default: return Debug.assertNever(name); } } - function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) { + function createDiagnosticForNode(node, message, ...args) { const sourceFile = getSourceFileOfNode(node); - return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3); + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, ...args); } - function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) { + function createDiagnosticForNodeArray(sourceFile, nodes, message, ...args) { const start = skipTrivia(sourceFile.text, nodes.pos); - return createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3); + return createFileDiagnostic(sourceFile, start, nodes.end - start, message, ...args); } - function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) { + function createDiagnosticForNodeInSourceFile(sourceFile, node, message, ...args) { const span = getErrorSpanForNode(sourceFile, node); - return createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); + return createFileDiagnostic(sourceFile, span.start, span.length, message, ...args); } function createDiagnosticForNodeFromMessageChain(sourceFile, node, messageChain, relatedInformation) { const span = getErrorSpanForNode(sourceFile, node); @@ -17860,21 +17941,21 @@ ${lanes.join("\n")} }; } function getSpanOfTokenAtPosition(sourceFile, pos) { - const scanner2 = createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ void 0, pos); + const scanner2 = createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError*/ void 0, pos); scanner2.scan(); - const start = scanner2.getTokenPos(); - return createTextSpanFromBounds(start, scanner2.getTextPos()); + const start = scanner2.getTokenStart(); + return createTextSpanFromBounds(start, scanner2.getTokenEnd()); } function scanTokenAtPosition(sourceFile, pos) { - const scanner2 = createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ void 0, pos); + const scanner2 = createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError*/ void 0, pos); scanner2.scan(); return scanner2.getToken(); } function getErrorSpanForArrowFunction(sourceFile, node) { const pos = skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 238 /* Block */ ) { - const { line: startLine } = getLineAndCharacterOfPosition(sourceFile, node.body.pos); - const { line: endLine } = getLineAndCharacterOfPosition(sourceFile, node.body.end); + if (node.body && node.body.kind === 241 /* Block */ ) { + const { line: startLine } = getLineAndCharacterOfPosition(sourceFile, node.body.pos); + const { line: endLine } = getLineAndCharacterOfPosition(sourceFile, node.body.end); if (startLine < endLine) return createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1); } return createTextSpanFromBounds(pos, node.end); @@ -17882,36 +17963,56 @@ ${lanes.join("\n")} function getErrorSpanForNode(sourceFile, node) { let errorNode = node; switch(node.kind){ - case 308 /* SourceFile */ : - const pos2 = skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); - if (pos2 === sourceFile.text.length) return createTextSpan(0, 0); - return getSpanOfTokenAtPosition(sourceFile, pos2); - case 257 /* VariableDeclaration */ : - case 205 /* BindingElement */ : - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : - case 261 /* InterfaceDeclaration */ : - case 264 /* ModuleDeclaration */ : - case 263 /* EnumDeclaration */ : - case 302 /* EnumMember */ : - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 262 /* TypeAliasDeclaration */ : - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : - case 271 /* NamespaceImport */ : + case 312 /* SourceFile */ : + { + const pos2 = skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); + if (pos2 === sourceFile.text.length) return createTextSpan(0, 0); + return getSpanOfTokenAtPosition(sourceFile, pos2); + } + case 260 /* VariableDeclaration */ : + case 208 /* BindingElement */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 264 /* InterfaceDeclaration */ : + case 267 /* ModuleDeclaration */ : + case 266 /* EnumDeclaration */ : + case 306 /* EnumMember */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 265 /* TypeAliasDeclaration */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : + case 274 /* NamespaceImport */ : errorNode = node.name; break; - case 216 /* ArrowFunction */ : + case 219 /* ArrowFunction */ : return getErrorSpanForArrowFunction(sourceFile, node); - case 292 /* CaseClause */ : - case 293 /* DefaultClause */ : - const start = skipTrivia(sourceFile.text, node.pos); - const end = node.statements.length > 0 ? node.statements[0].pos : node.end; - return createTextSpanFromBounds(start, end); + case 296 /* CaseClause */ : + case 297 /* DefaultClause */ : + { + const start = skipTrivia(sourceFile.text, node.pos); + const end = node.statements.length > 0 ? node.statements[0].pos : node.end; + return createTextSpanFromBounds(start, end); + } + case 253 /* ReturnStatement */ : + case 229 /* YieldExpression */ : + { + const pos2 = skipTrivia(sourceFile.text, node.pos); + return getSpanOfTokenAtPosition(sourceFile, pos2); + } + case 238 /* SatisfiesExpression */ : + { + const pos2 = skipTrivia(sourceFile.text, node.expression.end); + return getSpanOfTokenAtPosition(sourceFile, pos2); + } + case 357 /* JSDocSatisfiesTag */ : + { + const pos2 = skipTrivia(sourceFile.text, node.tagName.pos); + return getSpanOfTokenAtPosition(sourceFile, pos2); + } } if (errorNode === void 0) return getSpanOfTokenAtPosition(sourceFile, node.pos); Debug.assert(!isJSDoc(errorNode)); @@ -17938,26 +18039,32 @@ ${lanes.join("\n")} function isDeclarationReadonly(declaration) { return !!(getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !isParameterPropertyDeclaration(declaration, declaration.parent)); } + function isVarAwaitUsing(node) { + return (getCombinedNodeFlags(node) & 7 /* BlockScoped */ ) === 6 /* AwaitUsing */ ; + } + function isVarUsing(node) { + return (getCombinedNodeFlags(node) & 7 /* BlockScoped */ ) === 4 /* Using */ ; + } function isVarConst(node) { - return !!(getCombinedNodeFlags(node) & 2 /* Const */ ); + return (getCombinedNodeFlags(node) & 7 /* BlockScoped */ ) === 2 /* Const */ ; } function isLet(node) { - return !!(getCombinedNodeFlags(node) & 1 /* Let */ ); + return (getCombinedNodeFlags(node) & 7 /* BlockScoped */ ) === 1 /* Let */ ; } function isSuperCall(n) { - return n.kind === 210 /* CallExpression */ && n.expression.kind === 106 /* SuperKeyword */ ; + return n.kind === 213 /* CallExpression */ && n.expression.kind === 108 /* SuperKeyword */ ; } function isImportCall(n) { - return n.kind === 210 /* CallExpression */ && n.expression.kind === 100 /* ImportKeyword */ ; + return n.kind === 213 /* CallExpression */ && n.expression.kind === 102 /* ImportKeyword */ ; } function isImportMeta(n) { - return isMetaProperty(n) && n.keywordToken === 100 /* ImportKeyword */ && n.name.escapedText === "meta"; + return isMetaProperty(n) && n.keywordToken === 102 /* ImportKeyword */ && n.name.escapedText === "meta"; } function isLiteralImportTypeNode(n) { return isImportTypeNode(n) && isLiteralTypeNode(n.argument) && isStringLiteral(n.argument.literal); } function isPrologueDirective(node) { - return node.kind === 241 /* ExpressionStatement */ && node.expression.kind === 10 /* StringLiteral */ ; + return node.kind === 244 /* ExpressionStatement */ && node.expression.kind === 11 /* StringLiteral */ ; } function isCustomPrologue(node) { return !!(getEmitFlags(node) & 2097152 /* CustomPrologue */ ); @@ -17972,76 +18079,76 @@ ${lanes.join("\n")} return isCustomPrologue(node) && isVariableStatement(node) && every(node.declarationList.declarations, isHoistedVariable); } function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { - return node.kind !== 11 /* JsxText */ ? getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : void 0; + return node.kind !== 12 /* JsxText */ ? getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : void 0; } function getJSDocCommentRanges(node, text) { - const commentRanges = node.kind === 166 /* Parameter */ || node.kind === 165 /* TypeParameter */ || node.kind === 215 /* FunctionExpression */ || node.kind === 216 /* ArrowFunction */ || node.kind === 214 /* ParenthesizedExpression */ || node.kind === 257 /* VariableDeclaration */ || node.kind === 278 /* ExportSpecifier */ ? concatenate(getTrailingCommentRanges(text, node.pos), getLeadingCommentRanges(text, node.pos)) : getLeadingCommentRanges(text, node.pos); + const commentRanges = node.kind === 169 /* Parameter */ || node.kind === 168 /* TypeParameter */ || node.kind === 218 /* FunctionExpression */ || node.kind === 219 /* ArrowFunction */ || node.kind === 217 /* ParenthesizedExpression */ || node.kind === 260 /* VariableDeclaration */ || node.kind === 281 /* ExportSpecifier */ ? concatenate(getTrailingCommentRanges(text, node.pos), getLeadingCommentRanges(text, node.pos)) : getLeadingCommentRanges(text, node.pos); return filter(commentRanges, (comment)=>text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 3) !== 47 /* slash */ ); } function isPartOfTypeNode(node) { - if (179 /* FirstTypeNode */ <= node.kind && node.kind <= 202 /* LastTypeNode */ ) return true; + if (182 /* FirstTypeNode */ <= node.kind && node.kind <= 205 /* LastTypeNode */ ) return true; switch(node.kind){ - case 131 /* AnyKeyword */ : - case 157 /* UnknownKeyword */ : - case 148 /* NumberKeyword */ : - case 160 /* BigIntKeyword */ : - case 152 /* StringKeyword */ : - case 134 /* BooleanKeyword */ : - case 153 /* SymbolKeyword */ : - case 149 /* ObjectKeyword */ : - case 155 /* UndefinedKeyword */ : - case 144 /* NeverKeyword */ : + case 133 /* AnyKeyword */ : + case 159 /* UnknownKeyword */ : + case 150 /* NumberKeyword */ : + case 163 /* BigIntKeyword */ : + case 154 /* StringKeyword */ : + case 136 /* BooleanKeyword */ : + case 155 /* SymbolKeyword */ : + case 151 /* ObjectKeyword */ : + case 157 /* UndefinedKeyword */ : + case 106 /* NullKeyword */ : + case 146 /* NeverKeyword */ : return true; - case 114 /* VoidKeyword */ : - return node.parent.kind !== 219 /* VoidExpression */ ; - case 230 /* ExpressionWithTypeArguments */ : + case 116 /* VoidKeyword */ : + return node.parent.kind !== 222 /* VoidExpression */ ; + case 233 /* ExpressionWithTypeArguments */ : return isHeritageClause(node.parent) && !isExpressionWithTypeArgumentsInClassExtendsClause(node); - case 165 /* TypeParameter */ : - return node.parent.kind === 197 /* MappedType */ || node.parent.kind === 192 /* InferType */ ; - case 79 /* Identifier */ : - if (node.parent.kind === 163 /* QualifiedName */ && node.parent.right === node) node = node.parent; - else if (node.parent.kind === 208 /* PropertyAccessExpression */ && node.parent.name === node) node = node.parent; - Debug.assert(node.kind === 79 /* Identifier */ || node.kind === 163 /* QualifiedName */ || node.kind === 208 /* PropertyAccessExpression */ , "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); - case 163 /* QualifiedName */ : - case 208 /* PropertyAccessExpression */ : - case 108 /* ThisKeyword */ : + case 168 /* TypeParameter */ : + return node.parent.kind === 200 /* MappedType */ || node.parent.kind === 195 /* InferType */ ; + case 80 /* Identifier */ : + if (node.parent.kind === 166 /* QualifiedName */ && node.parent.right === node) node = node.parent; + else if (node.parent.kind === 211 /* PropertyAccessExpression */ && node.parent.name === node) node = node.parent; + Debug.assert(node.kind === 80 /* Identifier */ || node.kind === 166 /* QualifiedName */ || node.kind === 211 /* PropertyAccessExpression */ , "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + case 166 /* QualifiedName */ : + case 211 /* PropertyAccessExpression */ : + case 110 /* ThisKeyword */ : { - const { parent: parent2 } = node; - if (parent2.kind === 183 /* TypeQuery */ ) return false; - if (parent2.kind === 202 /* ImportType */ ) return !parent2.isTypeOf; - if (179 /* FirstTypeNode */ <= parent2.kind && parent2.kind <= 202 /* LastTypeNode */ ) return true; + const { parent: parent2 } = node; + if (parent2.kind === 186 /* TypeQuery */ ) return false; + if (parent2.kind === 205 /* ImportType */ ) return !parent2.isTypeOf; + if (182 /* FirstTypeNode */ <= parent2.kind && parent2.kind <= 205 /* LastTypeNode */ ) return true; switch(parent2.kind){ - case 230 /* ExpressionWithTypeArguments */ : + case 233 /* ExpressionWithTypeArguments */ : return isHeritageClause(parent2.parent) && !isExpressionWithTypeArgumentsInClassExtendsClause(parent2); - case 165 /* TypeParameter */ : + case 168 /* TypeParameter */ : return node === parent2.constraint; - case 348 /* JSDocTemplateTag */ : + case 352 /* JSDocTemplateTag */ : return node === parent2.constraint; - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : - case 166 /* Parameter */ : - case 257 /* VariableDeclaration */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : + case 169 /* Parameter */ : + case 260 /* VariableDeclaration */ : return node === parent2.type; - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - case 173 /* Constructor */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + case 176 /* Constructor */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : return node === parent2.type; - case 176 /* CallSignature */ : - case 177 /* ConstructSignature */ : - case 178 /* IndexSignature */ : + case 179 /* CallSignature */ : + case 180 /* ConstructSignature */ : + case 181 /* IndexSignature */ : return node === parent2.type; - case 213 /* TypeAssertionExpression */ : + case 216 /* TypeAssertionExpression */ : return node === parent2.type; - case 210 /* CallExpression */ : - case 211 /* NewExpression */ : + case 213 /* CallExpression */ : + case 214 /* NewExpression */ : + case 215 /* TaggedTemplateExpression */ : return contains(parent2.typeArguments, node); - case 212 /* TaggedTemplateExpression */ : - return false; } } } @@ -18058,23 +18165,23 @@ ${lanes.join("\n")} return traverse(body); function traverse(node) { switch(node.kind){ - case 250 /* ReturnStatement */ : + case 253 /* ReturnStatement */ : return visitor(node); - case 266 /* CaseBlock */ : - case 238 /* Block */ : - case 242 /* IfStatement */ : - case 243 /* DoStatement */ : - case 244 /* WhileStatement */ : - case 245 /* ForStatement */ : - case 246 /* ForInStatement */ : - case 247 /* ForOfStatement */ : - case 251 /* WithStatement */ : - case 252 /* SwitchStatement */ : - case 292 /* CaseClause */ : - case 293 /* DefaultClause */ : - case 253 /* LabeledStatement */ : - case 255 /* TryStatement */ : - case 295 /* CatchClause */ : + case 269 /* CaseBlock */ : + case 241 /* Block */ : + case 245 /* IfStatement */ : + case 246 /* DoStatement */ : + case 247 /* WhileStatement */ : + case 248 /* ForStatement */ : + case 249 /* ForInStatement */ : + case 250 /* ForOfStatement */ : + case 254 /* WithStatement */ : + case 255 /* SwitchStatement */ : + case 296 /* CaseClause */ : + case 297 /* DefaultClause */ : + case 256 /* LabeledStatement */ : + case 258 /* TryStatement */ : + case 299 /* CatchClause */ : return forEachChild(node, traverse); } } @@ -18083,19 +18190,19 @@ ${lanes.join("\n")} return traverse(body); function traverse(node) { switch(node.kind){ - case 226 /* YieldExpression */ : + case 229 /* YieldExpression */ : visitor(node); const operand = node.expression; if (operand) traverse(operand); return; - case 263 /* EnumDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 264 /* ModuleDeclaration */ : - case 262 /* TypeAliasDeclaration */ : + case 266 /* EnumDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 267 /* ModuleDeclaration */ : + case 265 /* TypeAliasDeclaration */ : return; default: if (isFunctionLike(node)) { - if (node.name && node.name.kind === 164 /* ComputedPropertyName */ ) { + if (node.name && node.name.kind === 167 /* ComputedPropertyName */ ) { traverse(node.name.expression); return; } @@ -18104,31 +18211,31 @@ ${lanes.join("\n")} } } function getRestParameterElementType(node) { - if (node && node.kind === 185 /* ArrayType */ ) return node.elementType; - else if (node && node.kind === 180 /* TypeReference */ ) return singleOrUndefined(node.typeArguments); + if (node && node.kind === 188 /* ArrayType */ ) return node.elementType; + else if (node && node.kind === 183 /* TypeReference */ ) return singleOrUndefined(node.typeArguments); else return void 0; } function getMembersOfDeclaration(node) { switch(node.kind){ - case 261 /* InterfaceDeclaration */ : - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : - case 184 /* TypeLiteral */ : + case 264 /* InterfaceDeclaration */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 187 /* TypeLiteral */ : return node.members; - case 207 /* ObjectLiteralExpression */ : + case 210 /* ObjectLiteralExpression */ : return node.properties; } } function isVariableLike(node) { if (node) switch(node.kind){ - case 205 /* BindingElement */ : - case 302 /* EnumMember */ : - case 166 /* Parameter */ : - case 299 /* PropertyAssignment */ : - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : - case 300 /* ShorthandPropertyAssignment */ : - case 257 /* VariableDeclaration */ : + case 208 /* BindingElement */ : + case 306 /* EnumMember */ : + case 169 /* Parameter */ : + case 303 /* PropertyAssignment */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : + case 304 /* ShorthandPropertyAssignment */ : + case 260 /* VariableDeclaration */ : return true; } return false; @@ -18137,7 +18244,7 @@ ${lanes.join("\n")} return isVariableLike(node) || isAccessor(node); } function isVariableDeclarationInVariableStatement(node) { - return node.parent.kind === 258 /* VariableDeclarationList */ && node.parent.parent.kind === 240 /* VariableStatement */ ; + return node.parent.kind === 261 /* VariableDeclarationList */ && node.parent.parent.kind === 243 /* VariableStatement */ ; } function isCommonJsExportedExpression(node) { if (!isInJSFile(node)) return false; @@ -18152,13 +18259,13 @@ ${lanes.join("\n")} } function introducesArgumentsExoticObject(node) { switch(node.kind){ - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 173 /* Constructor */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 176 /* Constructor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : return true; } return false; @@ -18166,18 +18273,18 @@ ${lanes.join("\n")} function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) { while(true){ if (beforeUnwrapLabelCallback) beforeUnwrapLabelCallback(node); - if (node.statement.kind !== 253 /* LabeledStatement */ ) return node.statement; + if (node.statement.kind !== 256 /* LabeledStatement */ ) return node.statement; node = node.statement; } } function isFunctionBlock(node) { - return node && node.kind === 238 /* Block */ && isFunctionLike(node.parent); + return node && node.kind === 241 /* Block */ && isFunctionLike(node.parent); } function isObjectLiteralMethod(node) { - return node && node.kind === 171 /* MethodDeclaration */ && node.parent.kind === 207 /* ObjectLiteralExpression */ ; + return node && node.kind === 174 /* MethodDeclaration */ && node.parent.kind === 210 /* ObjectLiteralExpression */ ; } function isObjectLiteralOrClassExpressionMethodOrAccessor(node) { - return (node.kind === 171 /* MethodDeclaration */ || node.kind === 174 /* GetAccessor */ || node.kind === 175 /* SetAccessor */ ) && (node.parent.kind === 207 /* ObjectLiteralExpression */ || node.parent.kind === 228 /* ClassExpression */ ); + return (node.kind === 174 /* MethodDeclaration */ || node.kind === 177 /* GetAccessor */ || node.kind === 178 /* SetAccessor */ ) && (node.parent.kind === 210 /* ObjectLiteralExpression */ || node.parent.kind === 231 /* ClassExpression */ ); } function isIdentifierTypePredicate(predicate) { return predicate && predicate.kind === 1 /* Identifier */ ; @@ -18185,17 +18292,15 @@ ${lanes.join("\n")} function isThisTypePredicate(predicate) { return predicate && predicate.kind === 0 /* This */ ; } - function getPropertyAssignment(objectLiteral, key, key2) { - return objectLiteral.properties.filter((property)=>{ - if (property.kind === 299 /* PropertyAssignment */ ) { - const propName = tryGetTextOfPropertyName(property.name); - return key === propName || !!key2 && key2 === propName; - } - return false; + function forEachPropertyAssignment(objectLiteral, key, callback, key2) { + return forEach(objectLiteral == null ? void 0 : objectLiteral.properties, (property)=>{ + if (!isPropertyAssignment(property)) return void 0; + const propName = tryGetTextOfPropertyName(property.name); + return key === propName || key2 && key2 === propName ? callback(property) : void 0; }); } function getPropertyArrayElementValue(objectLiteral, propKey, elementValue) { - return firstDefined(getPropertyAssignment(objectLiteral, propKey), (property)=>isArrayLiteralExpression(property.initializer) ? find(property.initializer.elements, (element)=>isStringLiteral(element) && element.text === elementValue) : void 0); + return forEachPropertyAssignment(objectLiteral, propKey, (property)=>isArrayLiteralExpression(property.initializer) ? find(property.initializer.elements, (element)=>isStringLiteral(element) && element.text === elementValue) : void 0); } function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { @@ -18204,11 +18309,10 @@ ${lanes.join("\n")} } } function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) { - return firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), (property)=>isArrayLiteralExpression(property.initializer) ? find(property.initializer.elements, (element)=>isStringLiteral(element) && element.text === elementValue) : void 0); + return forEachTsConfigPropArray(tsConfigSourceFile, propKey, (property)=>isArrayLiteralExpression(property.initializer) ? find(property.initializer.elements, (element)=>isStringLiteral(element) && element.text === elementValue) : void 0); } - function getTsConfigPropArray(tsConfigSourceFile, propKey) { - const jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); - return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : emptyArray; + function forEachTsConfigPropArray(tsConfigSourceFile, propKey, callback) { + return forEachPropertyAssignment(getTsConfigObjectLiteralExpression(tsConfigSourceFile), propKey, callback); } function getContainingFunction(node) { return findAncestor(node.parent, isFunctionLike); @@ -18228,55 +18332,59 @@ ${lanes.join("\n")} function getContainingFunctionOrClassStaticBlock(node) { return findAncestor(node.parent, isFunctionLikeOrClassStaticBlockDeclaration); } + function getContainingClassExcludingClassDecorators(node) { + const decorator = findAncestor(node.parent, (n)=>isClassLike(n) ? "quit" : isDecorator(n)); + return decorator && isClassLike(decorator.parent) ? getContainingClass(decorator.parent) : getContainingClass(decorator ?? node); + } function getThisContainer(node, includeArrowFunctions, includeClassComputedPropertyName) { - Debug.assert(node.kind !== 308 /* SourceFile */ ); + Debug.assert(node.kind !== 312 /* SourceFile */ ); while(true){ node = node.parent; if (!node) return Debug.fail(); switch(node.kind){ - case 164 /* ComputedPropertyName */ : + case 167 /* ComputedPropertyName */ : if (includeClassComputedPropertyName && isClassLike(node.parent.parent)) return node; node = node.parent.parent; break; - case 167 /* Decorator */ : - if (node.parent.kind === 166 /* Parameter */ && isClassElement(node.parent.parent)) node = node.parent.parent; + case 170 /* Decorator */ : + if (node.parent.kind === 169 /* Parameter */ && isClassElement(node.parent.parent)) node = node.parent.parent; else if (isClassElement(node.parent)) node = node.parent; break; - case 216 /* ArrowFunction */ : + case 219 /* ArrowFunction */ : if (!includeArrowFunctions) continue; - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 264 /* ModuleDeclaration */ : - case 172 /* ClassStaticBlockDeclaration */ : - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 173 /* Constructor */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 176 /* CallSignature */ : - case 177 /* ConstructSignature */ : - case 178 /* IndexSignature */ : - case 263 /* EnumDeclaration */ : - case 308 /* SourceFile */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 267 /* ModuleDeclaration */ : + case 175 /* ClassStaticBlockDeclaration */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 176 /* Constructor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 179 /* CallSignature */ : + case 180 /* ConstructSignature */ : + case 181 /* IndexSignature */ : + case 266 /* EnumDeclaration */ : + case 312 /* SourceFile */ : return node; } } } function isThisContainerOrFunctionBlock(node) { switch(node.kind){ - case 216 /* ArrowFunction */ : - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 169 /* PropertyDeclaration */ : + case 219 /* ArrowFunction */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 172 /* PropertyDeclaration */ : return true; - case 238 /* Block */ : + case 241 /* Block */ : switch(node.parent.kind){ - case 173 /* Constructor */ : - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 176 /* Constructor */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : return true; default: return false; @@ -18293,9 +18401,9 @@ ${lanes.join("\n")} function getNewTargetContainer(node) { const container = getThisContainer(node, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false); if (container) switch(container.kind){ - case 173 /* Constructor */ : - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : + case 176 /* Constructor */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : return container; } return void 0; @@ -18305,76 +18413,76 @@ ${lanes.join("\n")} node = node.parent; if (!node) return void 0; switch(node.kind){ - case 164 /* ComputedPropertyName */ : + case 167 /* ComputedPropertyName */ : node = node.parent; break; - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : if (!stopOnFunctions) continue; - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 173 /* Constructor */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 172 /* ClassStaticBlockDeclaration */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 176 /* Constructor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 175 /* ClassStaticBlockDeclaration */ : return node; - case 167 /* Decorator */ : - if (node.parent.kind === 166 /* Parameter */ && isClassElement(node.parent.parent)) node = node.parent.parent; + case 170 /* Decorator */ : + if (node.parent.kind === 169 /* Parameter */ && isClassElement(node.parent.parent)) node = node.parent.parent; else if (isClassElement(node.parent)) node = node.parent; break; } } } function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 215 /* FunctionExpression */ || func.kind === 216 /* ArrowFunction */ ) { + if (func.kind === 218 /* FunctionExpression */ || func.kind === 219 /* ArrowFunction */ ) { let prev = func; let parent2 = func.parent; - while(parent2.kind === 214 /* ParenthesizedExpression */ ){ + while(parent2.kind === 217 /* ParenthesizedExpression */ ){ prev = parent2; parent2 = parent2.parent; } - if (parent2.kind === 210 /* CallExpression */ && parent2.expression === prev) return parent2; + if (parent2.kind === 213 /* CallExpression */ && parent2.expression === prev) return parent2; } } function isSuperOrSuperProperty(node) { - return node.kind === 106 /* SuperKeyword */ || isSuperProperty(node); + return node.kind === 108 /* SuperKeyword */ || isSuperProperty(node); } function isSuperProperty(node) { const kind = node.kind; - return (kind === 208 /* PropertyAccessExpression */ || kind === 209 /* ElementAccessExpression */ ) && node.expression.kind === 106 /* SuperKeyword */ ; + return (kind === 211 /* PropertyAccessExpression */ || kind === 212 /* ElementAccessExpression */ ) && node.expression.kind === 108 /* SuperKeyword */ ; } function isThisProperty(node) { const kind = node.kind; - return (kind === 208 /* PropertyAccessExpression */ || kind === 209 /* ElementAccessExpression */ ) && node.expression.kind === 108 /* ThisKeyword */ ; + return (kind === 211 /* PropertyAccessExpression */ || kind === 212 /* ElementAccessExpression */ ) && node.expression.kind === 110 /* ThisKeyword */ ; } function isThisInitializedDeclaration(node) { - var _a2; - return !!node && isVariableDeclaration(node) && ((_a2 = node.initializer) == null ? void 0 : _a2.kind) === 108 /* ThisKeyword */ ; + var _a; + return !!node && isVariableDeclaration(node) && ((_a = node.initializer) == null ? void 0 : _a.kind) === 110 /* ThisKeyword */ ; } function isThisInitializedObjectBindingExpression(node) { - return !!node && (isShorthandPropertyAssignment(node) || isPropertyAssignment(node)) && isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 63 /* EqualsToken */ && node.parent.parent.right.kind === 108 /* ThisKeyword */ ; + return !!node && (isShorthandPropertyAssignment(node) || isPropertyAssignment(node)) && isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 64 /* EqualsToken */ && node.parent.parent.right.kind === 110 /* ThisKeyword */ ; } function getEntityNameFromTypeNode(node) { switch(node.kind){ - case 180 /* TypeReference */ : + case 183 /* TypeReference */ : return node.typeName; - case 230 /* ExpressionWithTypeArguments */ : + case 233 /* ExpressionWithTypeArguments */ : return isEntityNameExpression(node.expression) ? node.expression : void 0; - case 79 /* Identifier */ : - case 163 /* QualifiedName */ : + case 80 /* Identifier */ : + case 166 /* QualifiedName */ : return node; } return void 0; } function getInvokedExpression(node) { switch(node.kind){ - case 212 /* TaggedTemplateExpression */ : + case 215 /* TaggedTemplateExpression */ : return node.tag; - case 283 /* JsxOpeningElement */ : - case 282 /* JsxSelfClosingElement */ : + case 286 /* JsxOpeningElement */ : + case 285 /* JsxSelfClosingElement */ : return node.tagName; default: return node.expression; @@ -18383,19 +18491,19 @@ ${lanes.join("\n")} function nodeCanBeDecorated(useLegacyDecorators, node, parent2, grandparent) { if (useLegacyDecorators && isNamedDeclaration(node) && isPrivateIdentifier(node.name)) return false; switch(node.kind){ - case 260 /* ClassDeclaration */ : + case 263 /* ClassDeclaration */ : return true; - case 228 /* ClassExpression */ : + case 231 /* ClassExpression */ : return !useLegacyDecorators; - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : return parent2 !== void 0 && (useLegacyDecorators ? isClassDeclaration(parent2) : isClassLike(parent2) && !hasAbstractModifier(node) && !hasAmbientModifier(node)); - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 171 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 174 /* MethodDeclaration */ : return node.body !== void 0 && parent2 !== void 0 && (useLegacyDecorators ? isClassDeclaration(parent2) : isClassLike(parent2)); - case 166 /* Parameter */ : + case 169 /* Parameter */ : if (!useLegacyDecorators) return false; - return parent2 !== void 0 && parent2.body !== void 0 && (parent2.kind === 173 /* Constructor */ || parent2.kind === 171 /* MethodDeclaration */ || parent2.kind === 175 /* SetAccessor */ ) && getThisParameter(parent2) !== node && grandparent !== void 0 && grandparent.kind === 260 /* ClassDeclaration */ ; + return parent2 !== void 0 && parent2.body !== void 0 && (parent2.kind === 176 /* Constructor */ || parent2.kind === 174 /* MethodDeclaration */ || parent2.kind === 178 /* SetAccessor */ ) && getThisParameter(parent2) !== node && grandparent !== void 0 && grandparent.kind === 263 /* ClassDeclaration */ ; } return false; } @@ -18407,13 +18515,13 @@ ${lanes.join("\n")} } function childIsDecorated(useLegacyDecorators, node, parent2) { switch(node.kind){ - case 260 /* ClassDeclaration */ : + case 263 /* ClassDeclaration */ : return some(node.members, (m)=>nodeOrChildIsDecorated(useLegacyDecorators, m, node, parent2)); - case 228 /* ClassExpression */ : + case 231 /* ClassExpression */ : return !useLegacyDecorators && some(node.members, (m)=>nodeOrChildIsDecorated(useLegacyDecorators, m, node, parent2)); - case 171 /* MethodDeclaration */ : - case 175 /* SetAccessor */ : - case 173 /* Constructor */ : + case 174 /* MethodDeclaration */ : + case 178 /* SetAccessor */ : + case 176 /* Constructor */ : return some(node.parameters, (p)=>nodeIsDecorated(useLegacyDecorators, p, node, parent2)); default: return false; @@ -18427,7 +18535,7 @@ ${lanes.join("\n")} function classElementOrClassElementParameterIsDecorated(useLegacyDecorators, node, parent2) { let parameters; if (isAccessor(node)) { - const { firstAccessor: firstAccessor , secondAccessor: secondAccessor , setAccessor: setAccessor } = getAllAccessorDeclarations(parent2.members, node); + const { firstAccessor: firstAccessor, secondAccessor: secondAccessor, setAccessor: setAccessor } = getAllAccessorDeclarations(parent2.members, node); const firstAccessorWithDecorators = hasDecorators(firstAccessor) ? firstAccessor : secondAccessor && hasDecorators(secondAccessor) ? secondAccessor : void 0; if (!firstAccessorWithDecorators || node !== firstAccessorWithDecorators) return false; parameters = setAccessor == null ? void 0 : setAccessor.parameters; @@ -18442,9 +18550,9 @@ ${lanes.join("\n")} function isEmptyStringLiteral(node) { if (node.textSourceNode) { switch(node.textSourceNode.kind){ - case 10 /* StringLiteral */ : + case 11 /* StringLiteral */ : return isEmptyStringLiteral(node.textSourceNode); - case 14 /* NoSubstitutionTemplateLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : return node.text === ""; } return false; @@ -18452,130 +18560,130 @@ ${lanes.join("\n")} return node.text === ""; } function isJSXTagName(node) { - const { parent: parent2 } = node; - if (parent2.kind === 283 /* JsxOpeningElement */ || parent2.kind === 282 /* JsxSelfClosingElement */ || parent2.kind === 284 /* JsxClosingElement */ ) return parent2.tagName === node; + const { parent: parent2 } = node; + if (parent2.kind === 286 /* JsxOpeningElement */ || parent2.kind === 285 /* JsxSelfClosingElement */ || parent2.kind === 287 /* JsxClosingElement */ ) return parent2.tagName === node; return false; } function isExpressionNode(node) { switch(node.kind){ - case 106 /* SuperKeyword */ : - case 104 /* NullKeyword */ : - case 110 /* TrueKeyword */ : - case 95 /* FalseKeyword */ : - case 13 /* RegularExpressionLiteral */ : - case 206 /* ArrayLiteralExpression */ : - case 207 /* ObjectLiteralExpression */ : - case 208 /* PropertyAccessExpression */ : - case 209 /* ElementAccessExpression */ : - case 210 /* CallExpression */ : - case 211 /* NewExpression */ : - case 212 /* TaggedTemplateExpression */ : - case 231 /* AsExpression */ : - case 213 /* TypeAssertionExpression */ : - case 235 /* SatisfiesExpression */ : - case 232 /* NonNullExpression */ : - case 214 /* ParenthesizedExpression */ : - case 215 /* FunctionExpression */ : - case 228 /* ClassExpression */ : - case 216 /* ArrowFunction */ : - case 219 /* VoidExpression */ : - case 217 /* DeleteExpression */ : - case 218 /* TypeOfExpression */ : - case 221 /* PrefixUnaryExpression */ : - case 222 /* PostfixUnaryExpression */ : - case 223 /* BinaryExpression */ : - case 224 /* ConditionalExpression */ : - case 227 /* SpreadElement */ : - case 225 /* TemplateExpression */ : - case 229 /* OmittedExpression */ : - case 281 /* JsxElement */ : - case 282 /* JsxSelfClosingElement */ : - case 285 /* JsxFragment */ : - case 226 /* YieldExpression */ : - case 220 /* AwaitExpression */ : - case 233 /* MetaProperty */ : + case 108 /* SuperKeyword */ : + case 106 /* NullKeyword */ : + case 112 /* TrueKeyword */ : + case 97 /* FalseKeyword */ : + case 14 /* RegularExpressionLiteral */ : + case 209 /* ArrayLiteralExpression */ : + case 210 /* ObjectLiteralExpression */ : + case 211 /* PropertyAccessExpression */ : + case 212 /* ElementAccessExpression */ : + case 213 /* CallExpression */ : + case 214 /* NewExpression */ : + case 215 /* TaggedTemplateExpression */ : + case 234 /* AsExpression */ : + case 216 /* TypeAssertionExpression */ : + case 238 /* SatisfiesExpression */ : + case 235 /* NonNullExpression */ : + case 217 /* ParenthesizedExpression */ : + case 218 /* FunctionExpression */ : + case 231 /* ClassExpression */ : + case 219 /* ArrowFunction */ : + case 222 /* VoidExpression */ : + case 220 /* DeleteExpression */ : + case 221 /* TypeOfExpression */ : + case 224 /* PrefixUnaryExpression */ : + case 225 /* PostfixUnaryExpression */ : + case 226 /* BinaryExpression */ : + case 227 /* ConditionalExpression */ : + case 230 /* SpreadElement */ : + case 228 /* TemplateExpression */ : + case 232 /* OmittedExpression */ : + case 284 /* JsxElement */ : + case 285 /* JsxSelfClosingElement */ : + case 288 /* JsxFragment */ : + case 229 /* YieldExpression */ : + case 223 /* AwaitExpression */ : + case 236 /* MetaProperty */ : return true; - case 230 /* ExpressionWithTypeArguments */ : + case 233 /* ExpressionWithTypeArguments */ : return !isHeritageClause(node.parent) && !isJSDocAugmentsTag(node.parent); - case 163 /* QualifiedName */ : - while(node.parent.kind === 163 /* QualifiedName */ )node = node.parent; - return node.parent.kind === 183 /* TypeQuery */ || isJSDocLinkLike(node.parent) || isJSDocNameReference(node.parent) || isJSDocMemberName(node.parent) || isJSXTagName(node); - case 314 /* JSDocMemberName */ : + case 166 /* QualifiedName */ : + while(node.parent.kind === 166 /* QualifiedName */ )node = node.parent; + return node.parent.kind === 186 /* TypeQuery */ || isJSDocLinkLike(node.parent) || isJSDocNameReference(node.parent) || isJSDocMemberName(node.parent) || isJSXTagName(node); + case 318 /* JSDocMemberName */ : while(isJSDocMemberName(node.parent))node = node.parent; - return node.parent.kind === 183 /* TypeQuery */ || isJSDocLinkLike(node.parent) || isJSDocNameReference(node.parent) || isJSDocMemberName(node.parent) || isJSXTagName(node); - case 80 /* PrivateIdentifier */ : - return isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 101 /* InKeyword */ ; - case 79 /* Identifier */ : - if (node.parent.kind === 183 /* TypeQuery */ || isJSDocLinkLike(node.parent) || isJSDocNameReference(node.parent) || isJSDocMemberName(node.parent) || isJSXTagName(node)) return true; - case 8 /* NumericLiteral */ : - case 9 /* BigIntLiteral */ : - case 10 /* StringLiteral */ : - case 14 /* NoSubstitutionTemplateLiteral */ : - case 108 /* ThisKeyword */ : + return node.parent.kind === 186 /* TypeQuery */ || isJSDocLinkLike(node.parent) || isJSDocNameReference(node.parent) || isJSDocMemberName(node.parent) || isJSXTagName(node); + case 81 /* PrivateIdentifier */ : + return isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 103 /* InKeyword */ ; + case 80 /* Identifier */ : + if (node.parent.kind === 186 /* TypeQuery */ || isJSDocLinkLike(node.parent) || isJSDocNameReference(node.parent) || isJSDocMemberName(node.parent) || isJSXTagName(node)) return true; + case 9 /* NumericLiteral */ : + case 10 /* BigIntLiteral */ : + case 11 /* StringLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + case 110 /* ThisKeyword */ : return isInExpressionContext(node); default: return false; } } function isInExpressionContext(node) { - const { parent: parent2 } = node; + const { parent: parent2 } = node; switch(parent2.kind){ - case 257 /* VariableDeclaration */ : - case 166 /* Parameter */ : - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : - case 302 /* EnumMember */ : - case 299 /* PropertyAssignment */ : - case 205 /* BindingElement */ : + case 260 /* VariableDeclaration */ : + case 169 /* Parameter */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : + case 306 /* EnumMember */ : + case 303 /* PropertyAssignment */ : + case 208 /* BindingElement */ : return parent2.initializer === node; - case 241 /* ExpressionStatement */ : - case 242 /* IfStatement */ : - case 243 /* DoStatement */ : - case 244 /* WhileStatement */ : - case 250 /* ReturnStatement */ : - case 251 /* WithStatement */ : - case 252 /* SwitchStatement */ : - case 292 /* CaseClause */ : - case 254 /* ThrowStatement */ : + case 244 /* ExpressionStatement */ : + case 245 /* IfStatement */ : + case 246 /* DoStatement */ : + case 247 /* WhileStatement */ : + case 253 /* ReturnStatement */ : + case 254 /* WithStatement */ : + case 255 /* SwitchStatement */ : + case 296 /* CaseClause */ : + case 257 /* ThrowStatement */ : return parent2.expression === node; - case 245 /* ForStatement */ : + case 248 /* ForStatement */ : const forStatement = parent2; - return forStatement.initializer === node && forStatement.initializer.kind !== 258 /* VariableDeclarationList */ || forStatement.condition === node || forStatement.incrementor === node; - case 246 /* ForInStatement */ : - case 247 /* ForOfStatement */ : + return forStatement.initializer === node && forStatement.initializer.kind !== 261 /* VariableDeclarationList */ || forStatement.condition === node || forStatement.incrementor === node; + case 249 /* ForInStatement */ : + case 250 /* ForOfStatement */ : const forInStatement = parent2; - return forInStatement.initializer === node && forInStatement.initializer.kind !== 258 /* VariableDeclarationList */ || forInStatement.expression === node; - case 213 /* TypeAssertionExpression */ : - case 231 /* AsExpression */ : + return forInStatement.initializer === node && forInStatement.initializer.kind !== 261 /* VariableDeclarationList */ || forInStatement.expression === node; + case 216 /* TypeAssertionExpression */ : + case 234 /* AsExpression */ : return node === parent2.expression; - case 236 /* TemplateSpan */ : + case 239 /* TemplateSpan */ : return node === parent2.expression; - case 164 /* ComputedPropertyName */ : + case 167 /* ComputedPropertyName */ : return node === parent2.expression; - case 167 /* Decorator */ : - case 291 /* JsxExpression */ : - case 290 /* JsxSpreadAttribute */ : - case 301 /* SpreadAssignment */ : + case 170 /* Decorator */ : + case 294 /* JsxExpression */ : + case 293 /* JsxSpreadAttribute */ : + case 305 /* SpreadAssignment */ : return true; - case 230 /* ExpressionWithTypeArguments */ : + case 233 /* ExpressionWithTypeArguments */ : return parent2.expression === node && !isPartOfTypeNode(parent2); - case 300 /* ShorthandPropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : return parent2.objectAssignmentInitializer === node; - case 235 /* SatisfiesExpression */ : + case 238 /* SatisfiesExpression */ : return node === parent2.expression; default: return isExpressionNode(parent2); } } function isPartOfTypeQuery(node) { - while(node.kind === 163 /* QualifiedName */ || node.kind === 79 /* Identifier */ )node = node.parent; - return node.kind === 183 /* TypeQuery */ ; + while(node.kind === 166 /* QualifiedName */ || node.kind === 80 /* Identifier */ )node = node.parent; + return node.kind === 186 /* TypeQuery */ ; } function isNamespaceReexportDeclaration(node) { return isNamespaceExport(node) && !!node.parent.moduleSpecifier; } function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 268 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 280 /* ExternalModuleReference */ ; + return node.kind === 271 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 283 /* ExternalModuleReference */ ; } function getExternalModuleImportEqualsDeclarationExpression(node) { Debug.assert(isExternalModuleImportEqualsDeclaration(node)); @@ -18585,7 +18693,7 @@ ${lanes.join("\n")} return isVariableDeclarationInitializedToBareOrAccessedRequire(node) && getLeftmostAccessExpression(node.initializer).arguments[0]; } function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 268 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 280 /* ExternalModuleReference */ ; + return node.kind === 271 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 283 /* ExternalModuleReference */ ; } function isSourceFileJS(file) { return isInJSFile(file); @@ -18594,24 +18702,24 @@ ${lanes.join("\n")} return !isInJSFile(file); } function isInJSFile(node) { - return !!node && !!(node.flags & 262144 /* JavaScriptFile */ ); + return !!node && !!(node.flags & 524288 /* JavaScriptFile */ ); } function isInJsonFile(node) { - return !!node && !!(node.flags & 67108864 /* JsonFile */ ); + return !!node && !!(node.flags & 134217728 /* JsonFile */ ); } function isSourceFileNotJson(file) { return !isJsonSourceFile(file); } function isInJSDoc(node) { - return !!node && !!(node.flags & 8388608 /* JSDoc */ ); + return !!node && !!(node.flags & 16777216 /* JSDoc */ ); } function isJSDocIndexSignature(node) { - return isTypeReferenceNode(node) && isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && node.typeArguments && node.typeArguments.length === 2 && (node.typeArguments[0].kind === 152 /* StringKeyword */ || node.typeArguments[0].kind === 148 /* NumberKeyword */ ); + return isTypeReferenceNode(node) && isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && node.typeArguments && node.typeArguments.length === 2 && (node.typeArguments[0].kind === 154 /* StringKeyword */ || node.typeArguments[0].kind === 150 /* NumberKeyword */ ); } function isRequireCall(callExpression, requireStringLiteralLikeArgument) { - if (callExpression.kind !== 210 /* CallExpression */ ) return false; - const { expression: expression , arguments: args } = callExpression; - if (expression.kind !== 79 /* Identifier */ || expression.escapedText !== "require") return false; + if (callExpression.kind !== 213 /* CallExpression */ ) return false; + const { expression: expression, arguments: args } = callExpression; + if (expression.kind !== 80 /* Identifier */ || expression.escapedText !== "require") return false; if (args.length !== 1) return false; const arg = args[0]; return !requireStringLiteralLikeArgument || isStringLiteralLike(arg); @@ -18641,7 +18749,7 @@ ${lanes.join("\n")} return isBinaryExpression(decl) || isAccessExpression(decl) || isIdentifier(decl) || isCallExpression(decl); } function getEffectiveInitializer(node) { - if (isInJSFile(node) && node.initializer && isBinaryExpression(node.initializer) && (node.initializer.operatorToken.kind === 56 /* BarBarToken */ || node.initializer.operatorToken.kind === 60 /* QuestionQuestionToken */ ) && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) return node.initializer.right; + if (isInJSFile(node) && node.initializer && isBinaryExpression(node.initializer) && (node.initializer.operatorToken.kind === 57 /* BarBarToken */ || node.initializer.operatorToken.kind === 61 /* QuestionQuestionToken */ ) && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) return node.initializer.right; return node.initializer; } function getDeclaredExpandoInitializer(node) { @@ -18652,7 +18760,7 @@ ${lanes.join("\n")} return forEach(node.properties, (p)=>isPropertyAssignment(p) && isIdentifier(p.name) && p.name.escapedText === "value" && p.initializer && getExpandoInitializer(p.initializer, isPrototypeAssignment)); } function getAssignedExpandoInitializer(node) { - if (node && node.parent && isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 63 /* EqualsToken */ ) { + if (node && node.parent && isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 64 /* EqualsToken */ ) { const isPrototypeAssignment = isPrototypeAccess(node.parent.left); return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); } @@ -18664,33 +18772,33 @@ ${lanes.join("\n")} function getExpandoInitializer(initializer, isPrototypeAssignment) { if (isCallExpression(initializer)) { const e = skipParentheses(initializer.expression); - return e.kind === 215 /* FunctionExpression */ || e.kind === 216 /* ArrowFunction */ ? initializer : void 0; + return e.kind === 218 /* FunctionExpression */ || e.kind === 219 /* ArrowFunction */ ? initializer : void 0; } - if (initializer.kind === 215 /* FunctionExpression */ || initializer.kind === 228 /* ClassExpression */ || initializer.kind === 216 /* ArrowFunction */ ) return initializer; + if (initializer.kind === 218 /* FunctionExpression */ || initializer.kind === 231 /* ClassExpression */ || initializer.kind === 219 /* ArrowFunction */ ) return initializer; if (isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) return initializer; } function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { - const e = isBinaryExpression(initializer) && (initializer.operatorToken.kind === 56 /* BarBarToken */ || initializer.operatorToken.kind === 60 /* QuestionQuestionToken */ ) && getExpandoInitializer(initializer.right, isPrototypeAssignment); + const e = isBinaryExpression(initializer) && (initializer.operatorToken.kind === 57 /* BarBarToken */ || initializer.operatorToken.kind === 61 /* QuestionQuestionToken */ ) && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) return e; } function isDefaultedExpandoInitializer(node) { - const name = isVariableDeclaration(node.parent) ? node.parent.name : isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 63 /* EqualsToken */ ? node.parent.left : void 0; + const name = isVariableDeclaration(node.parent) ? node.parent.name : isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 64 /* EqualsToken */ ? node.parent.left : void 0; return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } function getNameOfExpando(node) { if (isBinaryExpression(node.parent)) { - const parent2 = (node.parent.operatorToken.kind === 56 /* BarBarToken */ || node.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ ) && isBinaryExpression(node.parent.parent) ? node.parent.parent : node.parent; - if (parent2.operatorToken.kind === 63 /* EqualsToken */ && isIdentifier(parent2.left)) return parent2.left; + const parent2 = (node.parent.operatorToken.kind === 57 /* BarBarToken */ || node.parent.operatorToken.kind === 61 /* QuestionQuestionToken */ ) && isBinaryExpression(node.parent.parent) ? node.parent.parent : node.parent; + if (parent2.operatorToken.kind === 64 /* EqualsToken */ && isIdentifier(parent2.left)) return parent2.left; } else if (isVariableDeclaration(node.parent)) return node.parent.name; } function isSameEntityName(name, initializer) { if (isPropertyNameLiteral(name) && isPropertyNameLiteral(initializer)) return getTextOfIdentifierOrLiteral(name) === getTextOfIdentifierOrLiteral(initializer); - if (isMemberName(name) && isLiteralLikeAccess(initializer) && (initializer.expression.kind === 108 /* ThisKeyword */ || isIdentifier(initializer.expression) && (initializer.expression.escapedText === "window" || initializer.expression.escapedText === "self" || initializer.expression.escapedText === "global"))) return isSameEntityName(name, getNameOrArgument(initializer)); + if (isMemberName(name) && isLiteralLikeAccess(initializer) && (initializer.expression.kind === 110 /* ThisKeyword */ || isIdentifier(initializer.expression) && (initializer.expression.escapedText === "window" || initializer.expression.escapedText === "self" || initializer.expression.escapedText === "global"))) return isSameEntityName(name, getNameOrArgument(initializer)); if (isLiteralLikeAccess(name) && isLiteralLikeAccess(initializer)) return getElementOrPropertyAccessName(name) === getElementOrPropertyAccessName(initializer) && isSameEntityName(name.expression, initializer.expression); return false; } function getRightMostAssignedExpression(node) { - while(isAssignmentExpression(node, /*excludeCompoundAssignments*/ true))node = node.right; + while(isAssignmentExpression(node, /*excludeCompoundAssignment*/ true))node = node.right; return node; } function isExportsIdentifier(node) { @@ -18716,10 +18824,10 @@ ${lanes.join("\n")} return isElementAccessExpression(node) && isStringOrNumericLiteralLike(node.argumentExpression); } function isBindableStaticAccessExpression(node, excludeThisKeyword) { - return isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 108 /* ThisKeyword */ || isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true)) || isBindableStaticElementAccessExpression(node, excludeThisKeyword); + return isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 110 /* ThisKeyword */ || isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true)) || isBindableStaticElementAccessExpression(node, excludeThisKeyword); } function isBindableStaticElementAccessExpression(node, excludeThisKeyword) { - return isLiteralLikeElementAccess(node) && (!excludeThisKeyword && node.expression.kind === 108 /* ThisKeyword */ || isEntityNameExpression(node.expression) || isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ true)); + return isLiteralLikeElementAccess(node) && (!excludeThisKeyword && node.expression.kind === 110 /* ThisKeyword */ || isEntityNameExpression(node.expression) || isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ true)); } function isBindableStaticNameExpression(node, excludeThisKeyword) { return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword); @@ -18736,7 +18844,7 @@ ${lanes.join("\n")} if (isBindableStaticAccessExpression(entityName) && getElementOrPropertyAccessName(entityName) === "prototype") return 9 /* ObjectDefinePrototypeProperty */ ; return 7 /* ObjectDefinePropertyValue */ ; } - if (expr.operatorToken.kind !== 63 /* EqualsToken */ || !isAccessExpression(expr.left) || isVoidZero(getRightMostAssignedExpression(expr))) return 0 /* None */ ; + if (expr.operatorToken.kind !== 64 /* EqualsToken */ || !isAccessExpression(expr.left) || isVoidZero(getRightMostAssignedExpression(expr))) return 0 /* None */ ; if (isBindableStaticNameExpression(expr.left.expression, /*excludeThisKeyword*/ true) && getElementOrPropertyAccessName(expr.left) === "prototype" && isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) return 6 /* Prototype */ ; return getAssignmentDeclarationPropertyAccessKind(expr.left); } @@ -18758,7 +18866,7 @@ ${lanes.join("\n")} return void 0; } function getAssignmentDeclarationPropertyAccessKind(lhs) { - if (lhs.expression.kind === 108 /* ThisKeyword */ ) return 4 /* ThisProperty */ ; + if (lhs.expression.kind === 110 /* ThisKeyword */ ) return 4 /* ThisProperty */ ; else if (isModuleExportsAccessExpression(lhs)) return 2 /* ModuleExports */ ; else if (isBindableStaticNameExpression(lhs.expression, /*excludeThisKeyword*/ true)) { if (isPrototypeAccess(lhs.expression)) return 3 /* PrototypeProperty */ ; @@ -18779,34 +18887,34 @@ ${lanes.join("\n")} return isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */ ; } function isSpecialPropertyDeclaration(expr) { - return isInJSFile(expr) && expr.parent && expr.parent.kind === 241 /* ExpressionStatement */ && (!isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) && !!getJSDocTypeTag(expr.parent); + return isInJSFile(expr) && expr.parent && expr.parent.kind === 244 /* ExpressionStatement */ && (!isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) && !!getJSDocTypeTag(expr.parent); } function setValueDeclaration(symbol, node) { - const { valueDeclaration: valueDeclaration } = symbol; - if (!valueDeclaration || !(node.flags & 16777216 /* Ambient */ && !isInJSFile(node) && !(valueDeclaration.flags & 16777216 /* Ambient */ )) && isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node) || valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration)) symbol.valueDeclaration = node; + const { valueDeclaration: valueDeclaration } = symbol; + if (!valueDeclaration || !(node.flags & 33554432 /* Ambient */ && !isInJSFile(node) && !(valueDeclaration.flags & 33554432 /* Ambient */ )) && isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node) || valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration)) symbol.valueDeclaration = node; } function isFunctionSymbol(symbol) { if (!symbol || !symbol.valueDeclaration) return false; const decl = symbol.valueDeclaration; - return decl.kind === 259 /* FunctionDeclaration */ || isVariableDeclaration(decl) && decl.initializer && isFunctionLike(decl.initializer); + return decl.kind === 262 /* FunctionDeclaration */ || isVariableDeclaration(decl) && decl.initializer && isFunctionLike(decl.initializer); } function tryGetModuleSpecifierFromDeclaration(node) { - var _a2, _b; + var _a, _b; switch(node.kind){ - case 257 /* VariableDeclaration */ : - case 205 /* BindingElement */ : - return (_a2 = findAncestor(node.initializer, (node2)=>isRequireCall(node2, /*requireStringLiteralLikeArgument*/ true))) == null ? void 0 : _a2.arguments[0]; - case 269 /* ImportDeclaration */ : + case 260 /* VariableDeclaration */ : + case 208 /* BindingElement */ : + return (_a = findAncestor(node.initializer, (node2)=>isRequireCall(node2, /*requireStringLiteralLikeArgument*/ true))) == null ? void 0 : _a.arguments[0]; + case 272 /* ImportDeclaration */ : return tryCast(node.moduleSpecifier, isStringLiteralLike); - case 268 /* ImportEqualsDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : return tryCast((_b = tryCast(node.moduleReference, isExternalModuleReference)) == null ? void 0 : _b.expression, isStringLiteralLike); - case 270 /* ImportClause */ : - case 277 /* NamespaceExport */ : + case 273 /* ImportClause */ : + case 280 /* NamespaceExport */ : return tryCast(node.parent.moduleSpecifier, isStringLiteralLike); - case 271 /* NamespaceImport */ : - case 278 /* ExportSpecifier */ : + case 274 /* NamespaceImport */ : + case 281 /* ExportSpecifier */ : return tryCast(node.parent.parent.moduleSpecifier, isStringLiteralLike); - case 273 /* ImportSpecifier */ : + case 276 /* ImportSpecifier */ : return tryCast(node.parent.parent.parent.moduleSpecifier, isStringLiteralLike); default: Debug.assertNever(node); @@ -18817,14 +18925,14 @@ ${lanes.join("\n")} } function tryGetImportFromModuleSpecifier(node) { switch(node.parent.kind){ - case 269 /* ImportDeclaration */ : - case 275 /* ExportDeclaration */ : + case 272 /* ImportDeclaration */ : + case 278 /* ExportDeclaration */ : return node.parent; - case 280 /* ExternalModuleReference */ : + case 283 /* ExternalModuleReference */ : return node.parent.parent; - case 210 /* CallExpression */ : - return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : void 0; - case 198 /* LiteralType */ : + case 213 /* CallExpression */ : + return isImportCall(node.parent) || isRequireCall(node.parent, /*requireStringLiteralLikeArgument*/ false) ? node.parent : void 0; + case 201 /* LiteralType */ : Debug.assert(isStringLiteral(node)); return tryCast(node.parent.parent, isImportTypeNode); default: @@ -18833,35 +18941,35 @@ ${lanes.join("\n")} } function getExternalModuleName(node) { switch(node.kind){ - case 269 /* ImportDeclaration */ : - case 275 /* ExportDeclaration */ : + case 272 /* ImportDeclaration */ : + case 278 /* ExportDeclaration */ : return node.moduleSpecifier; - case 268 /* ImportEqualsDeclaration */ : - return node.moduleReference.kind === 280 /* ExternalModuleReference */ ? node.moduleReference.expression : void 0; - case 202 /* ImportType */ : + case 271 /* ImportEqualsDeclaration */ : + return node.moduleReference.kind === 283 /* ExternalModuleReference */ ? node.moduleReference.expression : void 0; + case 205 /* ImportType */ : return isLiteralImportTypeNode(node) ? node.argument.literal : void 0; - case 210 /* CallExpression */ : + case 213 /* CallExpression */ : return node.arguments[0]; - case 264 /* ModuleDeclaration */ : - return node.name.kind === 10 /* StringLiteral */ ? node.name : void 0; + case 267 /* ModuleDeclaration */ : + return node.name.kind === 11 /* StringLiteral */ ? node.name : void 0; default: return Debug.assertNever(node); } } function getNamespaceDeclarationNode(node) { switch(node.kind){ - case 269 /* ImportDeclaration */ : + case 272 /* ImportDeclaration */ : return node.importClause && tryCast(node.importClause.namedBindings, isNamespaceImport); - case 268 /* ImportEqualsDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : return node; - case 275 /* ExportDeclaration */ : + case 278 /* ExportDeclaration */ : return node.exportClause && tryCast(node.exportClause, isNamespaceExport); default: return Debug.assertNever(node); } } function isDefaultImport(node) { - return node.kind === 269 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; + return node.kind === 272 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; } function forEachImportClauseDeclaration(node, action) { if (node.name) { @@ -18875,13 +18983,13 @@ ${lanes.join("\n")} } function hasQuestionToken(node) { if (node) switch(node.kind){ - case 166 /* Parameter */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 300 /* ShorthandPropertyAssignment */ : - case 299 /* PropertyAssignment */ : - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : + case 169 /* Parameter */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 304 /* ShorthandPropertyAssignment */ : + case 303 /* PropertyAssignment */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : return node.questionToken !== void 0; } return false; @@ -18892,25 +19000,25 @@ ${lanes.join("\n")} return !!name && name.escapedText === "new"; } function isJSDocTypeAlias(node) { - return node.kind === 349 /* JSDocTypedefTag */ || node.kind === 341 /* JSDocCallbackTag */ || node.kind === 343 /* JSDocEnumTag */ ; + return node.kind === 353 /* JSDocTypedefTag */ || node.kind === 345 /* JSDocCallbackTag */ || node.kind === 347 /* JSDocEnumTag */ ; } function isTypeAlias(node) { return isJSDocTypeAlias(node) || isTypeAliasDeclaration(node); } function getSourceOfAssignment(node) { - return isExpressionStatement(node) && isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 63 /* EqualsToken */ ? getRightMostAssignedExpression(node.expression) : void 0; + return isExpressionStatement(node) && isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 64 /* EqualsToken */ ? getRightMostAssignedExpression(node.expression) : void 0; } function getSourceOfDefaultedAssignment(node) { - return isExpressionStatement(node) && isBinaryExpression(node.expression) && getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && isBinaryExpression(node.expression.right) && (node.expression.right.operatorToken.kind === 56 /* BarBarToken */ || node.expression.right.operatorToken.kind === 60 /* QuestionQuestionToken */ ) ? node.expression.right.right : void 0; + return isExpressionStatement(node) && isBinaryExpression(node.expression) && getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && isBinaryExpression(node.expression.right) && (node.expression.right.operatorToken.kind === 57 /* BarBarToken */ || node.expression.right.operatorToken.kind === 61 /* QuestionQuestionToken */ ) ? node.expression.right.right : void 0; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch(node.kind){ - case 240 /* VariableStatement */ : + case 243 /* VariableStatement */ : const v = getSingleVariableOfVariableStatement(node); return v && v.initializer; - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : return node.initializer; - case 299 /* PropertyAssignment */ : + case 303 /* PropertyAssignment */ : return node.initializer; } } @@ -18918,24 +19026,24 @@ ${lanes.join("\n")} return isVariableStatement(node) ? firstOrUndefined(node.declarationList.declarations) : void 0; } function getNestedModuleDeclaration(node) { - return isModuleDeclaration(node) && node.body && node.body.kind === 264 /* ModuleDeclaration */ ? node.body : void 0; + return isModuleDeclaration(node) && node.body && node.body.kind === 267 /* ModuleDeclaration */ ? node.body : void 0; } function canHaveFlowNode(node) { - if (node.kind >= 240 /* FirstStatement */ && node.kind <= 256 /* LastStatement */ ) return true; + if (node.kind >= 243 /* FirstStatement */ && node.kind <= 259 /* LastStatement */ ) return true; switch(node.kind){ - case 79 /* Identifier */ : - case 108 /* ThisKeyword */ : - case 106 /* SuperKeyword */ : - case 163 /* QualifiedName */ : - case 233 /* MetaProperty */ : - case 209 /* ElementAccessExpression */ : - case 208 /* PropertyAccessExpression */ : - case 205 /* BindingElement */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 80 /* Identifier */ : + case 110 /* ThisKeyword */ : + case 108 /* SuperKeyword */ : + case 166 /* QualifiedName */ : + case 236 /* MetaProperty */ : + case 212 /* ElementAccessExpression */ : + case 211 /* PropertyAccessExpression */ : + case 208 /* BindingElement */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : return true; default: return false; @@ -18943,71 +19051,72 @@ ${lanes.join("\n")} } function canHaveJSDoc(node) { switch(node.kind){ - case 216 /* ArrowFunction */ : - case 223 /* BinaryExpression */ : - case 238 /* Block */ : - case 249 /* BreakStatement */ : - case 176 /* CallSignature */ : - case 292 /* CaseClause */ : - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : - case 172 /* ClassStaticBlockDeclaration */ : - case 173 /* Constructor */ : - case 182 /* ConstructorType */ : - case 177 /* ConstructSignature */ : - case 248 /* ContinueStatement */ : - case 256 /* DebuggerStatement */ : - case 243 /* DoStatement */ : - case 209 /* ElementAccessExpression */ : - case 239 /* EmptyStatement */ : + case 219 /* ArrowFunction */ : + case 226 /* BinaryExpression */ : + case 241 /* Block */ : + case 252 /* BreakStatement */ : + case 179 /* CallSignature */ : + case 296 /* CaseClause */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 175 /* ClassStaticBlockDeclaration */ : + case 176 /* Constructor */ : + case 185 /* ConstructorType */ : + case 180 /* ConstructSignature */ : + case 251 /* ContinueStatement */ : + case 259 /* DebuggerStatement */ : + case 246 /* DoStatement */ : + case 212 /* ElementAccessExpression */ : + case 242 /* EmptyStatement */ : case 1 /* EndOfFileToken */ : - case 263 /* EnumDeclaration */ : - case 302 /* EnumMember */ : - case 274 /* ExportAssignment */ : - case 275 /* ExportDeclaration */ : - case 278 /* ExportSpecifier */ : - case 241 /* ExpressionStatement */ : - case 246 /* ForInStatement */ : - case 247 /* ForOfStatement */ : - case 245 /* ForStatement */ : - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 181 /* FunctionType */ : - case 174 /* GetAccessor */ : - case 79 /* Identifier */ : - case 242 /* IfStatement */ : - case 269 /* ImportDeclaration */ : - case 268 /* ImportEqualsDeclaration */ : - case 178 /* IndexSignature */ : - case 261 /* InterfaceDeclaration */ : - case 320 /* JSDocFunctionType */ : - case 326 /* JSDocSignature */ : - case 253 /* LabeledStatement */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 264 /* ModuleDeclaration */ : - case 199 /* NamedTupleMember */ : - case 267 /* NamespaceExportDeclaration */ : - case 207 /* ObjectLiteralExpression */ : - case 166 /* Parameter */ : - case 214 /* ParenthesizedExpression */ : - case 208 /* PropertyAccessExpression */ : - case 299 /* PropertyAssignment */ : - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : - case 250 /* ReturnStatement */ : - case 175 /* SetAccessor */ : - case 300 /* ShorthandPropertyAssignment */ : - case 301 /* SpreadAssignment */ : - case 252 /* SwitchStatement */ : - case 254 /* ThrowStatement */ : - case 255 /* TryStatement */ : - case 262 /* TypeAliasDeclaration */ : - case 165 /* TypeParameter */ : - case 257 /* VariableDeclaration */ : - case 240 /* VariableStatement */ : - case 244 /* WhileStatement */ : - case 251 /* WithStatement */ : + case 266 /* EnumDeclaration */ : + case 306 /* EnumMember */ : + case 277 /* ExportAssignment */ : + case 278 /* ExportDeclaration */ : + case 281 /* ExportSpecifier */ : + case 244 /* ExpressionStatement */ : + case 249 /* ForInStatement */ : + case 250 /* ForOfStatement */ : + case 248 /* ForStatement */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 184 /* FunctionType */ : + case 177 /* GetAccessor */ : + case 80 /* Identifier */ : + case 245 /* IfStatement */ : + case 272 /* ImportDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : + case 181 /* IndexSignature */ : + case 264 /* InterfaceDeclaration */ : + case 324 /* JSDocFunctionType */ : + case 330 /* JSDocSignature */ : + case 256 /* LabeledStatement */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 267 /* ModuleDeclaration */ : + case 202 /* NamedTupleMember */ : + case 270 /* NamespaceExportDeclaration */ : + case 210 /* ObjectLiteralExpression */ : + case 169 /* Parameter */ : + case 217 /* ParenthesizedExpression */ : + case 211 /* PropertyAccessExpression */ : + case 303 /* PropertyAssignment */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : + case 253 /* ReturnStatement */ : + case 240 /* SemicolonClassElement */ : + case 178 /* SetAccessor */ : + case 304 /* ShorthandPropertyAssignment */ : + case 305 /* SpreadAssignment */ : + case 255 /* SwitchStatement */ : + case 257 /* ThrowStatement */ : + case 258 /* TryStatement */ : + case 265 /* TypeAliasDeclaration */ : + case 168 /* TypeParameter */ : + case 260 /* VariableDeclaration */ : + case 243 /* VariableStatement */ : + case 247 /* WhileStatement */ : + case 254 /* WithStatement */ : return true; default: return false; @@ -19019,11 +19128,11 @@ ${lanes.join("\n")} let node = hostNode; while(node && node.parent){ if (hasJSDocNodes(node)) result = addRange(result, filterOwnedJSDocTags(hostNode, last(node.jsDoc))); - if (node.kind === 166 /* Parameter */ ) { + if (node.kind === 169 /* Parameter */ ) { result = addRange(result, (noCache ? getJSDocParameterTagsNoCache : getJSDocParameterTags)(node)); break; } - if (node.kind === 165 /* TypeParameter */ ) { + if (node.kind === 168 /* TypeParameter */ ) { result = addRange(result, (noCache ? getJSDocTypeParameterTagsNoCache : getJSDocTypeParameterTags)(node)); break; } @@ -19047,8 +19156,8 @@ ${lanes.join("\n")} } function getNextJSDocCommentLocation(node) { const parent2 = node.parent; - if (parent2.kind === 299 /* PropertyAssignment */ || parent2.kind === 274 /* ExportAssignment */ || parent2.kind === 169 /* PropertyDeclaration */ || parent2.kind === 241 /* ExpressionStatement */ && node.kind === 208 /* PropertyAccessExpression */ || parent2.kind === 250 /* ReturnStatement */ || getNestedModuleDeclaration(parent2) || isBinaryExpression(node) && node.operatorToken.kind === 63 /* EqualsToken */ ) return parent2; - else if (parent2.parent && (getSingleVariableOfVariableStatement(parent2.parent) === node || isBinaryExpression(parent2) && parent2.operatorToken.kind === 63 /* EqualsToken */ )) return parent2.parent; + if (parent2.kind === 303 /* PropertyAssignment */ || parent2.kind === 277 /* ExportAssignment */ || parent2.kind === 172 /* PropertyDeclaration */ || parent2.kind === 244 /* ExpressionStatement */ && node.kind === 211 /* PropertyAccessExpression */ || parent2.kind === 253 /* ReturnStatement */ || getNestedModuleDeclaration(parent2) || isBinaryExpression(node) && node.operatorToken.kind === 64 /* EqualsToken */ ) return parent2; + else if (parent2.parent && (getSingleVariableOfVariableStatement(parent2.parent) === node || isBinaryExpression(parent2) && parent2.operatorToken.kind === 64 /* EqualsToken */ )) return parent2.parent; else if (parent2.parent && parent2.parent.parent && (getSingleVariableOfVariableStatement(parent2.parent.parent) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent2.parent.parent) === node || getSourceOfDefaultedAssignment(parent2.parent.parent))) return parent2.parent.parent; } function getParameterSymbolFromJSDoc(node) { @@ -19057,7 +19166,7 @@ ${lanes.join("\n")} const name = node.name.escapedText; const decl = getHostSignatureFromJSDoc(node); if (!decl) return void 0; - const parameter = find(decl.parameters, (p)=>p.name.kind === 79 /* Identifier */ && p.name.escapedText === name); + const parameter = find(decl.parameters, (p)=>p.name.kind === 80 /* Identifier */ && p.name.escapedText === name); return parameter && parameter.symbol; } function getEffectiveContainerForJSDocTemplateTag(node) { @@ -19087,7 +19196,7 @@ ${lanes.join("\n")} } function getTypeParameterFromJsDoc(node) { const name = node.name.escapedText; - const { typeParameters: typeParameters } = node.parent.parent.parent; + const { typeParameters: typeParameters } = node.parent.parent.parent; return typeParameters && find(typeParameters, (p)=>p.name.escapedText === name); } function hasTypeArguments(node) { @@ -19097,30 +19206,30 @@ ${lanes.join("\n")} let parent2 = node.parent; while(true){ switch(parent2.kind){ - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : const binaryOperator = parent2.operatorToken.kind; - return isAssignmentOperator(binaryOperator) && parent2.left === node ? binaryOperator === 63 /* EqualsToken */ || isLogicalOrCoalescingAssignmentOperator(binaryOperator) ? 1 /* Definite */ : 2 /* Compound */ : 0 /* None */ ; - case 221 /* PrefixUnaryExpression */ : - case 222 /* PostfixUnaryExpression */ : + return isAssignmentOperator(binaryOperator) && parent2.left === node ? binaryOperator === 64 /* EqualsToken */ || isLogicalOrCoalescingAssignmentOperator(binaryOperator) ? 1 /* Definite */ : 2 /* Compound */ : 0 /* None */ ; + case 224 /* PrefixUnaryExpression */ : + case 225 /* PostfixUnaryExpression */ : const unaryOperator = parent2.operator; - return unaryOperator === 45 /* PlusPlusToken */ || unaryOperator === 46 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */ ; - case 246 /* ForInStatement */ : - case 247 /* ForOfStatement */ : + return unaryOperator === 46 /* PlusPlusToken */ || unaryOperator === 47 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */ ; + case 249 /* ForInStatement */ : + case 250 /* ForOfStatement */ : return parent2.initializer === node ? 1 /* Definite */ : 0 /* None */ ; - case 214 /* ParenthesizedExpression */ : - case 206 /* ArrayLiteralExpression */ : - case 227 /* SpreadElement */ : - case 232 /* NonNullExpression */ : + case 217 /* ParenthesizedExpression */ : + case 209 /* ArrayLiteralExpression */ : + case 230 /* SpreadElement */ : + case 235 /* NonNullExpression */ : node = parent2; break; - case 301 /* SpreadAssignment */ : + case 305 /* SpreadAssignment */ : node = parent2.parent; break; - case 300 /* ShorthandPropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : if (parent2.name !== node) return 0 /* None */ ; node = parent2.parent; break; - case 299 /* PropertyAssignment */ : + case 303 /* PropertyAssignment */ : if (parent2.name === node) return 0 /* None */ ; node = parent2.parent; break; @@ -19135,22 +19244,22 @@ ${lanes.join("\n")} } function isNodeWithPossibleHoistedDeclaration(node) { switch(node.kind){ - case 238 /* Block */ : - case 240 /* VariableStatement */ : - case 251 /* WithStatement */ : - case 242 /* IfStatement */ : - case 252 /* SwitchStatement */ : - case 266 /* CaseBlock */ : - case 292 /* CaseClause */ : - case 293 /* DefaultClause */ : - case 253 /* LabeledStatement */ : - case 245 /* ForStatement */ : - case 246 /* ForInStatement */ : - case 247 /* ForOfStatement */ : - case 243 /* DoStatement */ : - case 244 /* WhileStatement */ : - case 255 /* TryStatement */ : - case 295 /* CatchClause */ : + case 241 /* Block */ : + case 243 /* VariableStatement */ : + case 254 /* WithStatement */ : + case 245 /* IfStatement */ : + case 255 /* SwitchStatement */ : + case 269 /* CaseBlock */ : + case 296 /* CaseClause */ : + case 297 /* DefaultClause */ : + case 256 /* LabeledStatement */ : + case 248 /* ForStatement */ : + case 249 /* ForInStatement */ : + case 250 /* ForOfStatement */ : + case 246 /* DoStatement */ : + case 247 /* WhileStatement */ : + case 258 /* TryStatement */ : + case 299 /* CatchClause */ : return true; } return false; @@ -19163,14 +19272,14 @@ ${lanes.join("\n")} return node; } function walkUpParenthesizedTypes(node) { - return walkUp(node, 193 /* ParenthesizedType */ ); + return walkUp(node, 196 /* ParenthesizedType */ ); } function walkUpParenthesizedExpressions(node) { - return walkUp(node, 214 /* ParenthesizedExpression */ ); + return walkUp(node, 217 /* ParenthesizedExpression */ ); } function walkUpParenthesizedTypesAndGetParentAndChild(node) { let child; - while(node && node.kind === 193 /* ParenthesizedType */ ){ + while(node && node.kind === 196 /* ParenthesizedType */ ){ child = node; node = node.parent; } @@ -19188,9 +19297,9 @@ ${lanes.join("\n")} return skipOuterExpressions(node, flags); } function isDeleteTarget(node) { - if (node.kind !== 208 /* PropertyAccessExpression */ && node.kind !== 209 /* ElementAccessExpression */ ) return false; + if (node.kind !== 211 /* PropertyAccessExpression */ && node.kind !== 212 /* ElementAccessExpression */ ) return false; node = walkUpParenthesizedExpressions(node.parent); - return node && node.kind === 217 /* DeleteExpression */ ; + return node && node.kind === 220 /* DeleteExpression */ ; } function isNodeDescendantOf(node, ancestor) { while(node){ @@ -19205,11 +19314,11 @@ ${lanes.join("\n")} function getDeclarationFromName(name) { const parent2 = name.parent; switch(name.kind){ - case 10 /* StringLiteral */ : - case 14 /* NoSubstitutionTemplateLiteral */ : - case 8 /* NumericLiteral */ : + case 11 /* StringLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + case 9 /* NumericLiteral */ : if (isComputedPropertyName(parent2)) return parent2.parent; - case 79 /* Identifier */ : + case 80 /* Identifier */ : if (isDeclaration(parent2)) return parent2.name === name ? parent2 : void 0; else if (isQualifiedName(parent2)) { const tag = parent2.parent; @@ -19218,59 +19327,59 @@ ${lanes.join("\n")} const binExp = parent2.parent; return isBinaryExpression(binExp) && getAssignmentDeclarationKind(binExp) !== 0 /* None */ && (binExp.left.symbol || binExp.symbol) && getNameOfDeclaration(binExp) === name ? binExp : void 0; } - case 80 /* PrivateIdentifier */ : + case 81 /* PrivateIdentifier */ : return isDeclaration(parent2) && parent2.name === name ? parent2 : void 0; default: return void 0; } } function isLiteralComputedPropertyDeclarationName(node) { - return isStringOrNumericLiteralLike(node) && node.parent.kind === 164 /* ComputedPropertyName */ && isDeclaration(node.parent.parent); + return isStringOrNumericLiteralLike(node) && node.parent.kind === 167 /* ComputedPropertyName */ && isDeclaration(node.parent.parent); } function isIdentifierName(node) { const parent2 = node.parent; switch(parent2.kind){ - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 302 /* EnumMember */ : - case 299 /* PropertyAssignment */ : - case 208 /* PropertyAccessExpression */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 306 /* EnumMember */ : + case 303 /* PropertyAssignment */ : + case 211 /* PropertyAccessExpression */ : return parent2.name === node; - case 163 /* QualifiedName */ : + case 166 /* QualifiedName */ : return parent2.right === node; - case 205 /* BindingElement */ : - case 273 /* ImportSpecifier */ : + case 208 /* BindingElement */ : + case 276 /* ImportSpecifier */ : return parent2.propertyName === node; - case 278 /* ExportSpecifier */ : - case 288 /* JsxAttribute */ : - case 282 /* JsxSelfClosingElement */ : - case 283 /* JsxOpeningElement */ : - case 284 /* JsxClosingElement */ : + case 281 /* ExportSpecifier */ : + case 291 /* JsxAttribute */ : + case 285 /* JsxSelfClosingElement */ : + case 286 /* JsxOpeningElement */ : + case 287 /* JsxClosingElement */ : return true; } return false; } function isAliasSymbolDeclaration(node) { - if (node.kind === 268 /* ImportEqualsDeclaration */ || node.kind === 267 /* NamespaceExportDeclaration */ || node.kind === 270 /* ImportClause */ && !!node.name || node.kind === 271 /* NamespaceImport */ || node.kind === 277 /* NamespaceExport */ || node.kind === 273 /* ImportSpecifier */ || node.kind === 278 /* ExportSpecifier */ || node.kind === 274 /* ExportAssignment */ && exportAssignmentIsAlias(node)) return true; - return isInJSFile(node) && (isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) || isPropertyAccessExpression(node) && isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 63 /* EqualsToken */ && isAliasableExpression(node.parent.right)); + if (node.kind === 271 /* ImportEqualsDeclaration */ || node.kind === 270 /* NamespaceExportDeclaration */ || node.kind === 273 /* ImportClause */ && !!node.name || node.kind === 274 /* NamespaceImport */ || node.kind === 280 /* NamespaceExport */ || node.kind === 276 /* ImportSpecifier */ || node.kind === 281 /* ExportSpecifier */ || node.kind === 277 /* ExportAssignment */ && exportAssignmentIsAlias(node)) return true; + return isInJSFile(node) && (isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) || isPropertyAccessExpression(node) && isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 64 /* EqualsToken */ && isAliasableExpression(node.parent.right)); } function getAliasDeclarationFromName(node) { switch(node.parent.kind){ - case 270 /* ImportClause */ : - case 273 /* ImportSpecifier */ : - case 271 /* NamespaceImport */ : - case 278 /* ExportSpecifier */ : - case 274 /* ExportAssignment */ : - case 268 /* ImportEqualsDeclaration */ : - case 277 /* NamespaceExport */ : + case 273 /* ImportClause */ : + case 276 /* ImportSpecifier */ : + case 274 /* NamespaceImport */ : + case 281 /* ExportSpecifier */ : + case 277 /* ExportAssignment */ : + case 271 /* ImportEqualsDeclaration */ : + case 280 /* NamespaceExport */ : return node.parent; - case 163 /* QualifiedName */ : + case 166 /* QualifiedName */ : do node = node.parent; - while (node.parent.kind === 163 /* QualifiedName */ ); + while (node.parent.kind === 166 /* QualifiedName */ ); return getAliasDeclarationFromName(node); } } @@ -19285,7 +19394,7 @@ ${lanes.join("\n")} return isExportAssignment(node) ? node.expression : node.right; } function getPropertyAssignmentAliasLikeExpression(node) { - return node.kind === 300 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 299 /* PropertyAssignment */ ? node.initializer : node.parent.right; + return node.kind === 304 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 303 /* PropertyAssignment */ ? node.initializer : node.parent.right; } function getEffectiveBaseTypeNode(node) { const baseType = getClassExtendsHeritageElement(node); @@ -19296,13 +19405,13 @@ ${lanes.join("\n")} return baseType; } function getClassExtendsHeritageElement(node) { - const heritageClause = getHeritageClause(node.heritageClauses, 94 /* ExtendsKeyword */ ); + const heritageClause = getHeritageClause(node.heritageClauses, 96 /* ExtendsKeyword */ ); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : void 0; } function getEffectiveImplementsTypeNodes(node) { if (isInJSFile(node)) return getJSDocImplementsTags(node).map((n)=>n.class); else { - const heritageClause = getHeritageClause(node.heritageClauses, 117 /* ImplementsKeyword */ ); + const heritageClause = getHeritageClause(node.heritageClauses, 119 /* ImplementsKeyword */ ); return heritageClause == null ? void 0 : heritageClause.types; } } @@ -19310,7 +19419,7 @@ ${lanes.join("\n")} return isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || emptyArray : isClassLike(node) ? concatenate(singleElementArray(getEffectiveBaseTypeNode(node)), getEffectiveImplementsTypeNodes(node)) || emptyArray : emptyArray; } function getInterfaceBaseTypeNodes(node) { - const heritageClause = getHeritageClause(node.heritageClauses, 94 /* ExtendsKeyword */ ); + const heritageClause = getHeritageClause(node.heritageClauses, 96 /* ExtendsKeyword */ ); return heritageClause ? heritageClause.types : void 0; } function getHeritageClause(clauses, kind) { @@ -19327,16 +19436,22 @@ ${lanes.join("\n")} return void 0; } function isKeyword(token) { - return 81 /* FirstKeyword */ <= token && token <= 162 /* LastKeyword */ ; + return 83 /* FirstKeyword */ <= token && token <= 165 /* LastKeyword */ ; + } + function isPunctuation(token) { + return 19 /* FirstPunctuation */ <= token && token <= 79 /* LastPunctuation */ ; + } + function isKeywordOrPunctuation(token) { + return isKeyword(token) || isPunctuation(token); } function isContextualKeyword(token) { - return 126 /* FirstContextualKeyword */ <= token && token <= 162 /* LastContextualKeyword */ ; + return 128 /* FirstContextualKeyword */ <= token && token <= 165 /* LastContextualKeyword */ ; } function isNonContextualKeyword(token) { return isKeyword(token) && !isContextualKeyword(token); } function isFutureReservedKeyword(token) { - return 117 /* FirstFutureReservedWord */ <= token && token <= 125 /* LastFutureReservedWord */ ; + return 119 /* FirstFutureReservedWord */ <= token && token <= 127 /* LastFutureReservedWord */ ; } function isStringANonContextualKeyword(name) { const token = stringToToken(name); @@ -19357,11 +19472,11 @@ ${lanes.join("\n")} if (!node) return 4 /* Invalid */ ; let flags = 0 /* Normal */ ; switch(node.kind){ - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 171 /* MethodDeclaration */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 174 /* MethodDeclaration */ : if (node.asteriskToken) flags |= 1 /* Generator */ ; - case 216 /* ArrowFunction */ : + case 219 /* ArrowFunction */ : if (hasSyntacticModifier(node, 512 /* Async */ )) flags |= 2 /* Async */ ; break; } @@ -19370,10 +19485,10 @@ ${lanes.join("\n")} } function isAsyncFunction(node) { switch(node.kind){ - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - case 171 /* MethodDeclaration */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + case 174 /* MethodDeclaration */ : return node.body !== void 0 && node.asteriskToken === void 0 && hasSyntacticModifier(node, 512 /* Async */ ); } return false; @@ -19382,59 +19497,61 @@ ${lanes.join("\n")} return isStringLiteralLike(node) || isNumericLiteral(node); } function isSignedNumericLiteral(node) { - return isPrefixUnaryExpression(node) && (node.operator === 39 /* PlusToken */ || node.operator === 40 /* MinusToken */ ) && isNumericLiteral(node.operand); + return isPrefixUnaryExpression(node) && (node.operator === 40 /* PlusToken */ || node.operator === 41 /* MinusToken */ ) && isNumericLiteral(node.operand); } function hasDynamicName(declaration) { const name = getNameOfDeclaration(declaration); return !!name && isDynamicName(name); } function isDynamicName(name) { - if (!(name.kind === 164 /* ComputedPropertyName */ || name.kind === 209 /* ElementAccessExpression */ )) return false; + if (!(name.kind === 167 /* ComputedPropertyName */ || name.kind === 212 /* ElementAccessExpression */ )) return false; const expr = isElementAccessExpression(name) ? skipParentheses(name.argumentExpression) : name.expression; return !isStringOrNumericLiteralLike(expr) && !isSignedNumericLiteral(expr); } function getPropertyNameForPropertyNameNode(name) { switch(name.kind){ - case 79 /* Identifier */ : - case 80 /* PrivateIdentifier */ : + case 80 /* Identifier */ : + case 81 /* PrivateIdentifier */ : return name.escapedText; - case 10 /* StringLiteral */ : - case 8 /* NumericLiteral */ : + case 11 /* StringLiteral */ : + case 9 /* NumericLiteral */ : return escapeLeadingUnderscores(name.text); - case 164 /* ComputedPropertyName */ : + case 167 /* ComputedPropertyName */ : const nameExpression = name.expression; if (isStringOrNumericLiteralLike(nameExpression)) return escapeLeadingUnderscores(nameExpression.text); else if (isSignedNumericLiteral(nameExpression)) { - if (nameExpression.operator === 40 /* MinusToken */ ) return tokenToString(nameExpression.operator) + nameExpression.operand.text; + if (nameExpression.operator === 41 /* MinusToken */ ) return tokenToString(nameExpression.operator) + nameExpression.operand.text; return nameExpression.operand.text; } return void 0; + case 295 /* JsxNamespacedName */ : + return getEscapedTextOfJsxNamespacedName(name); default: return Debug.assertNever(name); } } function isPropertyNameLiteral(node) { switch(node.kind){ - case 79 /* Identifier */ : - case 10 /* StringLiteral */ : - case 14 /* NoSubstitutionTemplateLiteral */ : - case 8 /* NumericLiteral */ : + case 80 /* Identifier */ : + case 11 /* StringLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + case 9 /* NumericLiteral */ : return true; default: return false; } } function getTextOfIdentifierOrLiteral(node) { - return isMemberName(node) ? idText(node) : node.text; + return isMemberName(node) ? idText(node) : isJsxNamespacedName(node) ? getTextOfJsxNamespacedName(node) : node.text; } function getEscapedTextOfIdentifierOrLiteral(node) { - return isMemberName(node) ? node.escapedText : escapeLeadingUnderscores(node.text); + return isMemberName(node) ? node.escapedText : isJsxNamespacedName(node) ? getEscapedTextOfJsxNamespacedName(node) : escapeLeadingUnderscores(node.text); } function getPropertyNameForUniqueESSymbol(symbol) { return `__@${getSymbolId(symbol)}@${symbol.escapedName}`; } - function getSymbolNameForPrivateIdentifier(containingClassSymbol, description2) { - return `__#${getSymbolId(containingClassSymbol)}@${description2}`; + function getSymbolNameForPrivateIdentifier(containingClassSymbol, description3) { + return `__#${getSymbolId(containingClassSymbol)}@${description3}`; } function isKnownSymbol(symbol) { return startsWith(symbol.escapedName, "__@"); @@ -19443,7 +19560,7 @@ ${lanes.join("\n")} return startsWith(symbol.escapedName, "__#"); } function isESSymbolIdentifier(node) { - return node.kind === 79 /* Identifier */ && node.escapedText === "Symbol"; + return node.kind === 80 /* Identifier */ && node.escapedText === "Symbol"; } function isProtoSetter(node) { return isIdentifier(node) ? idText(node) === "__proto__" : isStringLiteral(node) && node.text === "__proto__"; @@ -19451,11 +19568,13 @@ ${lanes.join("\n")} function isAnonymousFunctionDefinition(node, cb) { node = skipOuterExpressions(node); switch(node.kind){ - case 228 /* ClassExpression */ : - case 215 /* FunctionExpression */ : + case 231 /* ClassExpression */ : + if (classHasDeclaredOrExplicitlyAssignedName(node)) return false; + break; + case 218 /* FunctionExpression */ : if (node.name) return false; break; - case 216 /* ArrowFunction */ : + case 219 /* ArrowFunction */ : break; default: return false; @@ -19464,28 +19583,28 @@ ${lanes.join("\n")} } function isNamedEvaluationSource(node) { switch(node.kind){ - case 299 /* PropertyAssignment */ : + case 303 /* PropertyAssignment */ : return !isProtoSetter(node.name); - case 300 /* ShorthandPropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : return !!node.objectAssignmentInitializer; - case 257 /* VariableDeclaration */ : + case 260 /* VariableDeclaration */ : return isIdentifier(node.name) && !!node.initializer; - case 166 /* Parameter */ : + case 169 /* Parameter */ : return isIdentifier(node.name) && !!node.initializer && !node.dotDotDotToken; - case 205 /* BindingElement */ : + case 208 /* BindingElement */ : return isIdentifier(node.name) && !!node.initializer && !node.dotDotDotToken; - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : return !!node.initializer; - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : switch(node.operatorToken.kind){ - case 63 /* EqualsToken */ : - case 76 /* AmpersandAmpersandEqualsToken */ : - case 75 /* BarBarEqualsToken */ : - case 77 /* QuestionQuestionEqualsToken */ : + case 64 /* EqualsToken */ : + case 77 /* AmpersandAmpersandEqualsToken */ : + case 76 /* BarBarEqualsToken */ : + case 78 /* QuestionQuestionEqualsToken */ : return isIdentifier(node.left); } break; - case 274 /* ExportAssignment */ : + case 277 /* ExportAssignment */ : return true; } return false; @@ -19493,18 +19612,18 @@ ${lanes.join("\n")} function isNamedEvaluation(node, cb) { if (!isNamedEvaluationSource(node)) return false; switch(node.kind){ - case 299 /* PropertyAssignment */ : + case 303 /* PropertyAssignment */ : return isAnonymousFunctionDefinition(node.initializer, cb); - case 300 /* ShorthandPropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : return isAnonymousFunctionDefinition(node.objectAssignmentInitializer, cb); - case 257 /* VariableDeclaration */ : - case 166 /* Parameter */ : - case 205 /* BindingElement */ : - case 169 /* PropertyDeclaration */ : + case 260 /* VariableDeclaration */ : + case 169 /* Parameter */ : + case 208 /* BindingElement */ : + case 172 /* PropertyDeclaration */ : return isAnonymousFunctionDefinition(node.initializer, cb); - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : return isAnonymousFunctionDefinition(node.right, cb); - case 274 /* ExportAssignment */ : + case 277 /* ExportAssignment */ : return isAnonymousFunctionDefinition(node.expression, cb); } } @@ -19513,15 +19632,15 @@ ${lanes.join("\n")} } function isParameterDeclaration(node) { const root = getRootDeclaration(node); - return root.kind === 166 /* Parameter */ ; + return root.kind === 169 /* Parameter */ ; } function getRootDeclaration(node) { - while(node.kind === 205 /* BindingElement */ )node = node.parent.parent; + while(node.kind === 208 /* BindingElement */ )node = node.parent.parent; return node; } function nodeStartsNewLexicalEnvironment(node) { const kind = node.kind; - return kind === 173 /* Constructor */ || kind === 215 /* FunctionExpression */ || kind === 259 /* FunctionDeclaration */ || kind === 216 /* ArrowFunction */ || kind === 171 /* MethodDeclaration */ || kind === 174 /* GetAccessor */ || kind === 175 /* SetAccessor */ || kind === 264 /* ModuleDeclaration */ || kind === 308 /* SourceFile */ ; + return kind === 176 /* Constructor */ || kind === 218 /* FunctionExpression */ || kind === 262 /* FunctionDeclaration */ || kind === 219 /* ArrowFunction */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ || kind === 267 /* ModuleDeclaration */ || kind === 312 /* SourceFile */ ; } function nodeIsSynthesized(range) { return positionIsSynthesized(range.pos) || positionIsSynthesized(range.end); @@ -19531,40 +19650,40 @@ ${lanes.join("\n")} } function getExpressionAssociativity(expression) { const operator = getOperator(expression); - const hasArguments = expression.kind === 211 /* NewExpression */ && expression.arguments !== void 0; + const hasArguments = expression.kind === 214 /* NewExpression */ && expression.arguments !== void 0; return getOperatorAssociativity(expression.kind, operator, hasArguments); } function getOperatorAssociativity(kind, operator, hasArguments) { switch(kind){ - case 211 /* NewExpression */ : + case 214 /* NewExpression */ : return hasArguments ? 0 /* Left */ : 1 /* Right */ ; - case 221 /* PrefixUnaryExpression */ : - case 218 /* TypeOfExpression */ : - case 219 /* VoidExpression */ : - case 217 /* DeleteExpression */ : - case 220 /* AwaitExpression */ : - case 224 /* ConditionalExpression */ : - case 226 /* YieldExpression */ : + case 224 /* PrefixUnaryExpression */ : + case 221 /* TypeOfExpression */ : + case 222 /* VoidExpression */ : + case 220 /* DeleteExpression */ : + case 223 /* AwaitExpression */ : + case 227 /* ConditionalExpression */ : + case 229 /* YieldExpression */ : return 1 /* Right */ ; - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : switch(operator){ - case 42 /* AsteriskAsteriskToken */ : - case 63 /* EqualsToken */ : - case 64 /* PlusEqualsToken */ : - case 65 /* MinusEqualsToken */ : - case 67 /* AsteriskAsteriskEqualsToken */ : - case 66 /* AsteriskEqualsToken */ : - case 68 /* SlashEqualsToken */ : - case 69 /* PercentEqualsToken */ : - case 70 /* LessThanLessThanEqualsToken */ : - case 71 /* GreaterThanGreaterThanEqualsToken */ : - case 72 /* GreaterThanGreaterThanGreaterThanEqualsToken */ : - case 73 /* AmpersandEqualsToken */ : - case 78 /* CaretEqualsToken */ : - case 74 /* BarEqualsToken */ : - case 75 /* BarBarEqualsToken */ : - case 76 /* AmpersandAmpersandEqualsToken */ : - case 77 /* QuestionQuestionEqualsToken */ : + case 43 /* AsteriskAsteriskToken */ : + case 64 /* EqualsToken */ : + case 65 /* PlusEqualsToken */ : + case 66 /* MinusEqualsToken */ : + case 68 /* AsteriskAsteriskEqualsToken */ : + case 67 /* AsteriskEqualsToken */ : + case 69 /* SlashEqualsToken */ : + case 70 /* PercentEqualsToken */ : + case 71 /* LessThanLessThanEqualsToken */ : + case 72 /* GreaterThanGreaterThanEqualsToken */ : + case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */ : + case 74 /* AmpersandEqualsToken */ : + case 79 /* CaretEqualsToken */ : + case 75 /* BarEqualsToken */ : + case 76 /* BarBarEqualsToken */ : + case 77 /* AmpersandAmpersandEqualsToken */ : + case 78 /* QuestionQuestionEqualsToken */ : return 1 /* Right */ ; } } @@ -19572,93 +19691,93 @@ ${lanes.join("\n")} } function getExpressionPrecedence(expression) { const operator = getOperator(expression); - const hasArguments = expression.kind === 211 /* NewExpression */ && expression.arguments !== void 0; + const hasArguments = expression.kind === 214 /* NewExpression */ && expression.arguments !== void 0; return getOperatorPrecedence(expression.kind, operator, hasArguments); } function getOperator(expression) { - if (expression.kind === 223 /* BinaryExpression */ ) return expression.operatorToken.kind; - else if (expression.kind === 221 /* PrefixUnaryExpression */ || expression.kind === 222 /* PostfixUnaryExpression */ ) return expression.operator; + if (expression.kind === 226 /* BinaryExpression */ ) return expression.operatorToken.kind; + else if (expression.kind === 224 /* PrefixUnaryExpression */ || expression.kind === 225 /* PostfixUnaryExpression */ ) return expression.operator; else return expression.kind; } function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch(nodeKind){ - case 357 /* CommaListExpression */ : + case 361 /* CommaListExpression */ : return 0 /* Comma */ ; - case 227 /* SpreadElement */ : + case 230 /* SpreadElement */ : return 1 /* Spread */ ; - case 226 /* YieldExpression */ : + case 229 /* YieldExpression */ : return 2 /* Yield */ ; - case 224 /* ConditionalExpression */ : + case 227 /* ConditionalExpression */ : return 4 /* Conditional */ ; - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : switch(operatorKind){ - case 27 /* CommaToken */ : + case 28 /* CommaToken */ : return 0 /* Comma */ ; - case 63 /* EqualsToken */ : - case 64 /* PlusEqualsToken */ : - case 65 /* MinusEqualsToken */ : - case 67 /* AsteriskAsteriskEqualsToken */ : - case 66 /* AsteriskEqualsToken */ : - case 68 /* SlashEqualsToken */ : - case 69 /* PercentEqualsToken */ : - case 70 /* LessThanLessThanEqualsToken */ : - case 71 /* GreaterThanGreaterThanEqualsToken */ : - case 72 /* GreaterThanGreaterThanGreaterThanEqualsToken */ : - case 73 /* AmpersandEqualsToken */ : - case 78 /* CaretEqualsToken */ : - case 74 /* BarEqualsToken */ : - case 75 /* BarBarEqualsToken */ : - case 76 /* AmpersandAmpersandEqualsToken */ : - case 77 /* QuestionQuestionEqualsToken */ : + case 64 /* EqualsToken */ : + case 65 /* PlusEqualsToken */ : + case 66 /* MinusEqualsToken */ : + case 68 /* AsteriskAsteriskEqualsToken */ : + case 67 /* AsteriskEqualsToken */ : + case 69 /* SlashEqualsToken */ : + case 70 /* PercentEqualsToken */ : + case 71 /* LessThanLessThanEqualsToken */ : + case 72 /* GreaterThanGreaterThanEqualsToken */ : + case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */ : + case 74 /* AmpersandEqualsToken */ : + case 79 /* CaretEqualsToken */ : + case 75 /* BarEqualsToken */ : + case 76 /* BarBarEqualsToken */ : + case 77 /* AmpersandAmpersandEqualsToken */ : + case 78 /* QuestionQuestionEqualsToken */ : return 3 /* Assignment */ ; default: return getBinaryOperatorPrecedence(operatorKind); } - case 213 /* TypeAssertionExpression */ : - case 232 /* NonNullExpression */ : - case 221 /* PrefixUnaryExpression */ : - case 218 /* TypeOfExpression */ : - case 219 /* VoidExpression */ : - case 217 /* DeleteExpression */ : - case 220 /* AwaitExpression */ : + case 216 /* TypeAssertionExpression */ : + case 235 /* NonNullExpression */ : + case 224 /* PrefixUnaryExpression */ : + case 221 /* TypeOfExpression */ : + case 222 /* VoidExpression */ : + case 220 /* DeleteExpression */ : + case 223 /* AwaitExpression */ : return 16 /* Unary */ ; - case 222 /* PostfixUnaryExpression */ : + case 225 /* PostfixUnaryExpression */ : return 17 /* Update */ ; - case 210 /* CallExpression */ : + case 213 /* CallExpression */ : return 18 /* LeftHandSide */ ; - case 211 /* NewExpression */ : + case 214 /* NewExpression */ : return hasArguments ? 19 /* Member */ : 18 /* LeftHandSide */ ; - case 212 /* TaggedTemplateExpression */ : - case 208 /* PropertyAccessExpression */ : - case 209 /* ElementAccessExpression */ : - case 233 /* MetaProperty */ : + case 215 /* TaggedTemplateExpression */ : + case 211 /* PropertyAccessExpression */ : + case 212 /* ElementAccessExpression */ : + case 236 /* MetaProperty */ : return 19 /* Member */ ; - case 231 /* AsExpression */ : - case 235 /* SatisfiesExpression */ : + case 234 /* AsExpression */ : + case 238 /* SatisfiesExpression */ : return 11 /* Relational */ ; - case 108 /* ThisKeyword */ : - case 106 /* SuperKeyword */ : - case 79 /* Identifier */ : - case 80 /* PrivateIdentifier */ : - case 104 /* NullKeyword */ : - case 110 /* TrueKeyword */ : - case 95 /* FalseKeyword */ : - case 8 /* NumericLiteral */ : - case 9 /* BigIntLiteral */ : - case 10 /* StringLiteral */ : - case 206 /* ArrayLiteralExpression */ : - case 207 /* ObjectLiteralExpression */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - case 228 /* ClassExpression */ : - case 13 /* RegularExpressionLiteral */ : - case 14 /* NoSubstitutionTemplateLiteral */ : - case 225 /* TemplateExpression */ : - case 214 /* ParenthesizedExpression */ : - case 229 /* OmittedExpression */ : - case 281 /* JsxElement */ : - case 282 /* JsxSelfClosingElement */ : - case 285 /* JsxFragment */ : + case 110 /* ThisKeyword */ : + case 108 /* SuperKeyword */ : + case 80 /* Identifier */ : + case 81 /* PrivateIdentifier */ : + case 106 /* NullKeyword */ : + case 112 /* TrueKeyword */ : + case 97 /* FalseKeyword */ : + case 9 /* NumericLiteral */ : + case 10 /* BigIntLiteral */ : + case 11 /* StringLiteral */ : + case 209 /* ArrayLiteralExpression */ : + case 210 /* ObjectLiteralExpression */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + case 231 /* ClassExpression */ : + case 14 /* RegularExpressionLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + case 228 /* TemplateExpression */ : + case 217 /* ParenthesizedExpression */ : + case 232 /* OmittedExpression */ : + case 284 /* JsxElement */ : + case 285 /* JsxSelfClosingElement */ : + case 288 /* JsxFragment */ : return 20 /* Primary */ ; default: return -1 /* Invalid */ ; @@ -19666,44 +19785,44 @@ ${lanes.join("\n")} } function getBinaryOperatorPrecedence(kind) { switch(kind){ - case 60 /* QuestionQuestionToken */ : + case 61 /* QuestionQuestionToken */ : return 4 /* Coalesce */ ; - case 56 /* BarBarToken */ : + case 57 /* BarBarToken */ : return 5 /* LogicalOR */ ; - case 55 /* AmpersandAmpersandToken */ : + case 56 /* AmpersandAmpersandToken */ : return 6 /* LogicalAND */ ; - case 51 /* BarToken */ : + case 52 /* BarToken */ : return 7 /* BitwiseOR */ ; - case 52 /* CaretToken */ : + case 53 /* CaretToken */ : return 8 /* BitwiseXOR */ ; - case 50 /* AmpersandToken */ : + case 51 /* AmpersandToken */ : return 9 /* BitwiseAND */ ; - case 34 /* EqualsEqualsToken */ : - case 35 /* ExclamationEqualsToken */ : - case 36 /* EqualsEqualsEqualsToken */ : - case 37 /* ExclamationEqualsEqualsToken */ : + case 35 /* EqualsEqualsToken */ : + case 36 /* ExclamationEqualsToken */ : + case 37 /* EqualsEqualsEqualsToken */ : + case 38 /* ExclamationEqualsEqualsToken */ : return 10 /* Equality */ ; - case 29 /* LessThanToken */ : - case 31 /* GreaterThanToken */ : - case 32 /* LessThanEqualsToken */ : - case 33 /* GreaterThanEqualsToken */ : - case 102 /* InstanceOfKeyword */ : - case 101 /* InKeyword */ : - case 128 /* AsKeyword */ : - case 150 /* SatisfiesKeyword */ : + case 30 /* LessThanToken */ : + case 32 /* GreaterThanToken */ : + case 33 /* LessThanEqualsToken */ : + case 34 /* GreaterThanEqualsToken */ : + case 104 /* InstanceOfKeyword */ : + case 103 /* InKeyword */ : + case 130 /* AsKeyword */ : + case 152 /* SatisfiesKeyword */ : return 11 /* Relational */ ; - case 47 /* LessThanLessThanToken */ : - case 48 /* GreaterThanGreaterThanToken */ : - case 49 /* GreaterThanGreaterThanGreaterThanToken */ : + case 48 /* LessThanLessThanToken */ : + case 49 /* GreaterThanGreaterThanToken */ : + case 50 /* GreaterThanGreaterThanGreaterThanToken */ : return 12 /* Shift */ ; - case 39 /* PlusToken */ : - case 40 /* MinusToken */ : + case 40 /* PlusToken */ : + case 41 /* MinusToken */ : return 13 /* Additive */ ; - case 41 /* AsteriskToken */ : - case 43 /* SlashToken */ : - case 44 /* PercentToken */ : + case 42 /* AsteriskToken */ : + case 44 /* SlashToken */ : + case 45 /* PercentToken */ : return 14 /* Multiplicative */ ; - case 42 /* AsteriskAsteriskToken */ : + case 43 /* AsteriskAsteriskToken */ : return 15 /* Exponentiation */ ; } return -1; @@ -19711,9 +19830,9 @@ ${lanes.join("\n")} function getSemanticJsxChildren(children) { return filter(children, (i)=>{ switch(i.kind){ - case 291 /* JsxExpression */ : + case 294 /* JsxExpression */ : return !!i.expression; - case 11 /* JsxText */ : + case 12 /* JsxText */ : return !i.containsOnlyTriviaWhiteSpaces; default: return true; @@ -19819,7 +19938,7 @@ ${lanes.join("\n")} } function isIntrinsicJsxName(name) { const ch = name.charCodeAt(0); - return ch >= 97 /* a */ && ch <= 122 /* z */ || stringContains(name, "-") || stringContains(name, ":"); + return ch >= 97 /* a */ && ch <= 122 /* z */ || stringContains(name, "-"); } function getIndentString(level) { const singleLevel = indentStrings[1]; @@ -20081,9 +20200,9 @@ ${lanes.join("\n")} return options.outFile || options.out; } function getPathsBasePath(options, host) { - var _a2, _b; + var _a; if (!options.paths) return void 0; - return (_b = options.baseUrl) != null ? _b : Debug.checkDefined(options.pathsBasePath || ((_a2 = host.getCurrentDirectory) == null ? void 0 : _a2.call(host)), "Encountered 'paths' without a 'baseUrl', config file, or host 'getCurrentDirectory'."); + return options.baseUrl ?? Debug.checkDefined(options.pathsBasePath || ((_a = host.getCurrentDirectory) == null ? void 0 : _a.call(host)), "Encountered 'paths' without a 'baseUrl', config file, or host 'getCurrentDirectory'."); } function getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit) { const options = host.getCompilerOptions(); @@ -20126,7 +20245,7 @@ ${lanes.join("\n")} function writeFileEnsuringDirectories(path, data, writeByteOrderMark, writeFile2, createDirectory, directoryExists) { try { writeFile2(path, data, writeByteOrderMark); - } catch (e) { + } catch { ensureDirectoriesExist(getDirectoryPath(normalizePath(path)), createDirectory, directoryExists); writeFile2(path, data, writeByteOrderMark); } @@ -20161,12 +20280,15 @@ ${lanes.join("\n")} return isThisIdentifier(parameter.name); } function isThisIdentifier(node) { - return !!node && node.kind === 79 /* Identifier */ && identifierIsThisKeyword(node); + return !!node && node.kind === 80 /* Identifier */ && identifierIsThisKeyword(node); + } + function isInTypeQuery(node) { + return !!findAncestor(node, (n)=>n.kind === 186 /* TypeQuery */ ? true : n.kind === 80 /* Identifier */ || n.kind === 166 /* QualifiedName */ ? false : "quit"); } function isThisInTypeQuery(node) { if (!isThisIdentifier(node)) return false; while(isQualifiedName(node.parent) && node.parent.left === node)node = node.parent; - return node.parent.kind === 183 /* TypeQuery */ ; + return node.parent.kind === 186 /* TypeQuery */ ; } function identifierIsThisKeyword(id) { return id.escapedText === "this"; @@ -20178,8 +20300,8 @@ ${lanes.join("\n")} let setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 174 /* GetAccessor */ ) getAccessor = accessor; - else if (accessor.kind === 175 /* SetAccessor */ ) setAccessor = accessor; + if (accessor.kind === 177 /* GetAccessor */ ) getAccessor = accessor; + else if (accessor.kind === 178 /* SetAccessor */ ) setAccessor = accessor; else Debug.fail("Accessor has wrong kind"); } else forEach(declarations, (member)=>{ if (isAccessor(member) && isStatic(member) === isStatic(accessor)) { @@ -20188,8 +20310,8 @@ ${lanes.join("\n")} if (memberName === accessorName) { if (!firstAccessor) firstAccessor = member; else if (!secondAccessor) secondAccessor = member; - if (member.kind === 174 /* GetAccessor */ && !getAccessor) getAccessor = member; - if (member.kind === 175 /* SetAccessor */ && !setAccessor) setAccessor = member; + if (member.kind === 177 /* GetAccessor */ && !getAccessor) getAccessor = member; + if (member.kind === 178 /* SetAccessor */ && !setAccessor) setAccessor = member; } } }); @@ -20216,7 +20338,7 @@ ${lanes.join("\n")} return flatMap(getJSDocTags(node), (tag)=>isNonTypeAliasTemplate(tag) ? tag.typeParameters : void 0); } function isNonTypeAliasTemplate(tag) { - return isJSDocTemplateTag(tag) && !(tag.parent.kind === 323 /* JSDoc */ && (tag.parent.tags.some(isJSDocTypeAlias) || tag.parent.tags.some(isJSDocOverloadTag))); + return isJSDocTemplateTag(tag) && !(tag.parent.kind === 327 /* JSDoc */ && (tag.parent.tags.some(isJSDocTypeAlias) || tag.parent.tags.some(isJSDocOverloadTag))); } function getEffectiveSetAccessorTypeAnnotationNode(node) { const parameter = getSetAccessorValueParameter(node); @@ -20366,7 +20488,7 @@ ${lanes.join("\n")} return getSyntacticModifierFlags(node) & flags; } function getModifierFlagsWorker(node, includeJSDoc, alwaysIncludeJSDoc) { - if (node.kind >= 0 /* FirstToken */ && node.kind <= 162 /* LastToken */ ) return 0 /* None */ ; + if (node.kind >= 0 /* FirstToken */ && node.kind <= 165 /* LastToken */ ) return 0 /* None */ ; if (!(node.modifierFlagsCache & 536870912 /* HasComputedFlags */ )) node.modifierFlagsCache = getSyntacticModifierFlagsNoCache(node) | 536870912 /* HasComputedFlags */ ; if (includeJSDoc && !(node.modifierFlagsCache & 4096 /* HasComputedJSDocModifiers */ ) && (alwaysIncludeJSDoc || isInJSFile(node)) && node.parent) node.modifierFlagsCache |= getJSDocModifierFlagsNoCache(node) | 4096 /* HasComputedJSDocModifiers */ ; return node.modifierFlagsCache & -536875009; @@ -20375,7 +20497,7 @@ ${lanes.join("\n")} return getModifierFlagsWorker(node, /*includeJSDoc*/ true); } function getEffectiveModifierFlagsAlwaysIncludeJSDoc(node) { - return getModifierFlagsWorker(node, /*includeJSDOc*/ true, /*alwaysIncludeJSDOc*/ true); + return getModifierFlagsWorker(node, /*includeJSDoc*/ true, /*alwaysIncludeJSDoc*/ true); } function getSyntacticModifierFlags(node) { return getModifierFlagsWorker(node, /*includeJSDoc*/ false); @@ -20399,7 +20521,7 @@ ${lanes.join("\n")} } function getSyntacticModifierFlagsNoCache(node) { let flags = canHaveModifiers(node) ? modifiersToFlags(node.modifiers) : 0 /* None */ ; - if (node.flags & 4 /* NestedNamespace */ || node.kind === 79 /* Identifier */ && node.flags & 2048 /* IdentifierIsInJSDocNamespace */ ) flags |= 1 /* Export */ ; + if (node.flags & 8 /* NestedNamespace */ || node.kind === 80 /* Identifier */ && node.flags & 4096 /* IdentifierIsInJSDocNamespace */ ) flags |= 1 /* Export */ ; return flags; } function modifiersToFlags(modifiers) { @@ -20409,61 +20531,61 @@ ${lanes.join("\n")} } function modifierToFlag(token) { switch(token){ - case 124 /* StaticKeyword */ : + case 126 /* StaticKeyword */ : return 32 /* Static */ ; - case 123 /* PublicKeyword */ : + case 125 /* PublicKeyword */ : return 4 /* Public */ ; - case 122 /* ProtectedKeyword */ : + case 124 /* ProtectedKeyword */ : return 16 /* Protected */ ; - case 121 /* PrivateKeyword */ : + case 123 /* PrivateKeyword */ : return 8 /* Private */ ; - case 126 /* AbstractKeyword */ : + case 128 /* AbstractKeyword */ : return 256 /* Abstract */ ; - case 127 /* AccessorKeyword */ : + case 129 /* AccessorKeyword */ : return 128 /* Accessor */ ; - case 93 /* ExportKeyword */ : + case 95 /* ExportKeyword */ : return 1 /* Export */ ; - case 136 /* DeclareKeyword */ : + case 138 /* DeclareKeyword */ : return 2 /* Ambient */ ; - case 85 /* ConstKeyword */ : + case 87 /* ConstKeyword */ : return 2048 /* Const */ ; - case 88 /* DefaultKeyword */ : + case 90 /* DefaultKeyword */ : return 1024 /* Default */ ; - case 132 /* AsyncKeyword */ : + case 134 /* AsyncKeyword */ : return 512 /* Async */ ; - case 146 /* ReadonlyKeyword */ : + case 148 /* ReadonlyKeyword */ : return 64 /* Readonly */ ; - case 161 /* OverrideKeyword */ : + case 164 /* OverrideKeyword */ : return 16384 /* Override */ ; - case 101 /* InKeyword */ : + case 103 /* InKeyword */ : return 32768 /* In */ ; - case 145 /* OutKeyword */ : + case 147 /* OutKeyword */ : return 65536 /* Out */ ; - case 167 /* Decorator */ : + case 170 /* Decorator */ : return 131072 /* Decorator */ ; } return 0 /* None */ ; } function isBinaryLogicalOperator(token) { - return token === 56 /* BarBarToken */ || token === 55 /* AmpersandAmpersandToken */ ; + return token === 57 /* BarBarToken */ || token === 56 /* AmpersandAmpersandToken */ ; } function isLogicalOperator(token) { - return isBinaryLogicalOperator(token) || token === 53 /* ExclamationToken */ ; + return isBinaryLogicalOperator(token) || token === 54 /* ExclamationToken */ ; } function isLogicalOrCoalescingAssignmentOperator(token) { - return token === 75 /* BarBarEqualsToken */ || token === 76 /* AmpersandAmpersandEqualsToken */ || token === 77 /* QuestionQuestionEqualsToken */ ; + return token === 76 /* BarBarEqualsToken */ || token === 77 /* AmpersandAmpersandEqualsToken */ || token === 78 /* QuestionQuestionEqualsToken */ ; } function isLogicalOrCoalescingAssignmentExpression(expr) { return isBinaryExpression(expr) && isLogicalOrCoalescingAssignmentOperator(expr.operatorToken.kind); } function isLogicalOrCoalescingBinaryOperator(token) { - return isBinaryLogicalOperator(token) || token === 60 /* QuestionQuestionToken */ ; + return isBinaryLogicalOperator(token) || token === 61 /* QuestionQuestionToken */ ; } function isLogicalOrCoalescingBinaryExpression(expr) { return isBinaryExpression(expr) && isLogicalOrCoalescingBinaryOperator(expr.operatorToken.kind); } function isAssignmentOperator(token) { - return token >= 63 /* FirstAssignment */ && token <= 78 /* LastAssignment */ ; + return token >= 64 /* FirstAssignment */ && token <= 79 /* LastAssignment */ ; } function tryGetClassExtendingExpressionWithTypeArguments(node) { const cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); @@ -20473,7 +20595,7 @@ ${lanes.join("\n")} if (isExpressionWithTypeArguments(node)) { if (isHeritageClause(node.parent) && isClassLike(node.parent.parent)) return { class: node.parent.parent, - isImplements: node.parent.token === 117 /* ImplementsKeyword */ + isImplements: node.parent.token === 119 /* ImplementsKeyword */ }; if (isJSDocAugmentsTag(node.parent)) { const host = getEffectiveJSDocHost(node.parent); @@ -20486,7 +20608,7 @@ ${lanes.join("\n")} return void 0; } function isAssignmentExpression(node, excludeCompoundAssignment) { - return isBinaryExpression(node) && (excludeCompoundAssignment ? node.operatorToken.kind === 63 /* EqualsToken */ : isAssignmentOperator(node.operatorToken.kind)) && isLeftHandSideExpression(node.left); + return isBinaryExpression(node) && (excludeCompoundAssignment ? node.operatorToken.kind === 64 /* EqualsToken */ : isAssignmentOperator(node.operatorToken.kind)) && isLeftHandSideExpression(node.left); } function isLeftHandSideOfAssignment(node) { return isAssignmentExpression(node.parent) && node.parent.left === node; @@ -20494,7 +20616,7 @@ ${lanes.join("\n")} function isDestructuringAssignment(node) { if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { const kind = node.left.kind; - return kind === 207 /* ObjectLiteralExpression */ || kind === 206 /* ArrayLiteralExpression */ ; + return kind === 210 /* ObjectLiteralExpression */ || kind === 209 /* ArrayLiteralExpression */ ; } return false; } @@ -20502,24 +20624,24 @@ ${lanes.join("\n")} return tryGetClassExtendingExpressionWithTypeArguments(node) !== void 0; } function isEntityNameExpression(node) { - return node.kind === 79 /* Identifier */ || isPropertyAccessEntityNameExpression(node); + return node.kind === 80 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } function getFirstIdentifier(node) { switch(node.kind){ - case 79 /* Identifier */ : + case 80 /* Identifier */ : return node; - case 163 /* QualifiedName */ : + case 166 /* QualifiedName */ : do node = node.left; - while (node.kind !== 79 /* Identifier */ ); + while (node.kind !== 80 /* Identifier */ ); return node; - case 208 /* PropertyAccessExpression */ : + case 211 /* PropertyAccessExpression */ : do node = node.expression; - while (node.kind !== 79 /* Identifier */ ); + while (node.kind !== 80 /* Identifier */ ); return node; } } function isDottedName(node) { - return node.kind === 79 /* Identifier */ || node.kind === 108 /* ThisKeyword */ || node.kind === 106 /* SuperKeyword */ || node.kind === 233 /* MetaProperty */ || node.kind === 208 /* PropertyAccessExpression */ && isDottedName(node.expression) || node.kind === 214 /* ParenthesizedExpression */ && isDottedName(node.expression); + return node.kind === 80 /* Identifier */ || node.kind === 110 /* ThisKeyword */ || node.kind === 108 /* SuperKeyword */ || node.kind === 236 /* MetaProperty */ || node.kind === 211 /* PropertyAccessExpression */ && isDottedName(node.expression) || node.kind === 217 /* ParenthesizedExpression */ && isDottedName(node.expression); } function isPropertyAccessEntityNameExpression(node) { return isPropertyAccessExpression(node) && isIdentifier(node.name) && isEntityNameExpression(node.expression); @@ -20532,13 +20654,14 @@ ${lanes.join("\n")} const baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression); if (baseStr !== void 0 && isPropertyName(expr.argumentExpression)) return baseStr + "." + getPropertyNameForPropertyNameNode(expr.argumentExpression); } else if (isIdentifier(expr)) return unescapeLeadingUnderscores(expr.escapedText); + else if (isJsxNamespacedName(expr)) return getTextOfJsxNamespacedName(expr); return void 0; } function isPrototypeAccess(node) { return isBindableStaticAccessExpression(node) && getElementOrPropertyAccessName(node) === "prototype"; } function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return node.parent.kind === 163 /* QualifiedName */ && node.parent.right === node || node.parent.kind === 208 /* PropertyAccessExpression */ && node.parent.name === node; + return node.parent.kind === 166 /* QualifiedName */ && node.parent.right === node || node.parent.kind === 211 /* PropertyAccessExpression */ && node.parent.name === node || node.parent.kind === 236 /* MetaProperty */ && node.parent.name === node; } function isRightSideOfAccessExpression(node) { return isPropertyAccessExpression(node.parent) && node.parent.name === node || isElementAccessExpression(node.parent) && node.parent.argumentExpression === node; @@ -20547,10 +20670,10 @@ ${lanes.join("\n")} return isQualifiedName(node.parent) && node.parent.right === node || isPropertyAccessExpression(node.parent) && node.parent.name === node || isJSDocMemberName(node.parent) && node.parent.right === node; } function isEmptyObjectLiteral(expression) { - return expression.kind === 207 /* ObjectLiteralExpression */ && expression.properties.length === 0; + return expression.kind === 210 /* ObjectLiteralExpression */ && expression.properties.length === 0; } function isEmptyArrayLiteral(expression) { - return expression.kind === 206 /* ArrayLiteralExpression */ && expression.elements.length === 0; + return expression.kind === 209 /* ArrayLiteralExpression */ && expression.elements.length === 0; } function getLocalSymbolForExportDefault(symbol) { if (!isExportDefaultSymbol(symbol) || !symbol.declarations) return void 0; @@ -20739,7 +20862,7 @@ ${lanes.join("\n")} function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) { const startPos = skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments); const prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile); - return getLinesBetweenPositions(sourceFile, prevPos != null ? prevPos : stopPos, startPos); + return getLinesBetweenPositions(sourceFile, prevPos ?? stopPos, startPos); } function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) { const nextPos = skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments); @@ -20753,8 +20876,8 @@ ${lanes.join("\n")} function isDeclarationNameOfEnumOrNamespace(node) { const parseNode = getParseTreeNode(node); if (parseNode) switch(parseNode.parent.kind){ - case 263 /* EnumDeclaration */ : - case 264 /* ModuleDeclaration */ : + case 266 /* EnumDeclaration */ : + case 267 /* ModuleDeclaration */ : return parseNode === parseNode.parent.name; } return false; @@ -20802,35 +20925,31 @@ ${lanes.join("\n")} return accessKind(node) !== 0 /* Read */ ; } function accessKind(node) { - const { parent: parent2 } = node; - if (!parent2) return 0 /* Read */ ; - switch(parent2.kind){ - case 214 /* ParenthesizedExpression */ : + const { parent: parent2 } = node; + switch(parent2 == null ? void 0 : parent2.kind){ + case 217 /* ParenthesizedExpression */ : return accessKind(parent2); - case 222 /* PostfixUnaryExpression */ : - case 221 /* PrefixUnaryExpression */ : - const { operator: operator } = parent2; - return operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */ ; - case 223 /* BinaryExpression */ : - const { left: left , operatorToken: operatorToken } = parent2; - return left === node && isAssignmentOperator(operatorToken.kind) ? operatorToken.kind === 63 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() : 0 /* Read */ ; - case 208 /* PropertyAccessExpression */ : + case 225 /* PostfixUnaryExpression */ : + case 224 /* PrefixUnaryExpression */ : + const { operator: operator } = parent2; + return operator === 46 /* PlusPlusToken */ || operator === 47 /* MinusMinusToken */ ? 2 /* ReadWrite */ : 0 /* Read */ ; + case 226 /* BinaryExpression */ : + const { left: left, operatorToken: operatorToken } = parent2; + return left === node && isAssignmentOperator(operatorToken.kind) ? operatorToken.kind === 64 /* EqualsToken */ ? 1 /* Write */ : 2 /* ReadWrite */ : 0 /* Read */ ; + case 211 /* PropertyAccessExpression */ : return parent2.name !== node ? 0 /* Read */ : accessKind(parent2); - case 299 /* PropertyAssignment */ : + case 303 /* PropertyAssignment */ : { const parentAccess = accessKind(parent2.parent); return node === parent2.name ? reverseAccessKind(parentAccess) : parentAccess; } - case 300 /* ShorthandPropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : return node === parent2.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent2.parent); - case 206 /* ArrayLiteralExpression */ : + case 209 /* ArrayLiteralExpression */ : return accessKind(parent2); default: return 0 /* Read */ ; } - function writeOrReadWrite() { - return parent2.parent && walkUpParenthesizedExpressions(parent2.parent).kind === 241 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */ ; - } } function reverseAccessKind(a) { switch(a){ @@ -20860,7 +20979,7 @@ ${lanes.join("\n")} map2.clear(); } function mutateMapSkippingNewValues(map2, newMap, options) { - const { onDeleteValue: onDeleteValue , onExistingValue: onExistingValue } = options; + const { onDeleteValue: onDeleteValue, onExistingValue: onExistingValue } = options; map2.forEach((existingValue, key)=>{ const valueInNewMap = newMap.get(key); if (valueInNewMap === void 0) { @@ -20871,7 +20990,7 @@ ${lanes.join("\n")} } function mutateMap(map2, newMap, options) { mutateMapSkippingNewValues(map2, newMap, options); - const { createNewValue: createNewValue } = options; + const { createNewValue: createNewValue } = options; newMap.forEach((valueInNewMap, key)=>{ if (!map2.has(key)) map2.set(key, createNewValue(key, valueInNewMap)); }); @@ -20884,11 +21003,11 @@ ${lanes.join("\n")} return false; } function getClassLikeDeclarationOfSymbol(symbol) { - var _a2; - return (_a2 = symbol.declarations) == null ? void 0 : _a2.find(isClassLike); + var _a; + return (_a = symbol.declarations) == null ? void 0 : _a.find(isClassLike); } function getObjectFlags(type) { - return type.flags & 3899393 /* ObjectFlagsType */ ? type.objectFlags : 0; + return type.flags & 138117121 /* ObjectFlagsType */ ? type.objectFlags : 0; } function forSomeAncestorDirectory(directory, callback) { return !!forEachAncestorDirectory(directory, (d)=>callback(d) ? true : void 0); @@ -20896,7 +21015,7 @@ ${lanes.join("\n")} function isUMDExportSymbol(symbol) { return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && isNamespaceExportDeclaration(symbol.declarations[0]); } - function showModuleSpecifier({ moduleSpecifier: moduleSpecifier }) { + function showModuleSpecifier({ moduleSpecifier: moduleSpecifier }) { return isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier); } function getLastChild(node) { @@ -20920,14 +21039,14 @@ ${lanes.join("\n")} return isClassLike(node) || isInterfaceDeclaration(node) || isTypeLiteralNode(node); } function isTypeNodeKind(kind) { - return kind >= 179 /* FirstTypeNode */ && kind <= 202 /* LastTypeNode */ || kind === 131 /* AnyKeyword */ || kind === 157 /* UnknownKeyword */ || kind === 148 /* NumberKeyword */ || kind === 160 /* BigIntKeyword */ || kind === 149 /* ObjectKeyword */ || kind === 134 /* BooleanKeyword */ || kind === 152 /* StringKeyword */ || kind === 153 /* SymbolKeyword */ || kind === 114 /* VoidKeyword */ || kind === 155 /* UndefinedKeyword */ || kind === 144 /* NeverKeyword */ || kind === 139 /* IntrinsicKeyword */ || kind === 230 /* ExpressionWithTypeArguments */ || kind === 315 /* JSDocAllType */ || kind === 316 /* JSDocUnknownType */ || kind === 317 /* JSDocNullableType */ || kind === 318 /* JSDocNonNullableType */ || kind === 319 /* JSDocOptionalType */ || kind === 320 /* JSDocFunctionType */ || kind === 321 /* JSDocVariadicType */ ; + return kind >= 182 /* FirstTypeNode */ && kind <= 205 /* LastTypeNode */ || kind === 133 /* AnyKeyword */ || kind === 159 /* UnknownKeyword */ || kind === 150 /* NumberKeyword */ || kind === 163 /* BigIntKeyword */ || kind === 151 /* ObjectKeyword */ || kind === 136 /* BooleanKeyword */ || kind === 154 /* StringKeyword */ || kind === 155 /* SymbolKeyword */ || kind === 116 /* VoidKeyword */ || kind === 157 /* UndefinedKeyword */ || kind === 146 /* NeverKeyword */ || kind === 141 /* IntrinsicKeyword */ || kind === 233 /* ExpressionWithTypeArguments */ || kind === 319 /* JSDocAllType */ || kind === 320 /* JSDocUnknownType */ || kind === 321 /* JSDocNullableType */ || kind === 322 /* JSDocNonNullableType */ || kind === 323 /* JSDocOptionalType */ || kind === 324 /* JSDocFunctionType */ || kind === 325 /* JSDocVariadicType */ ; } function isAccessExpression(node) { - return node.kind === 208 /* PropertyAccessExpression */ || node.kind === 209 /* ElementAccessExpression */ ; + return node.kind === 211 /* PropertyAccessExpression */ || node.kind === 212 /* ElementAccessExpression */ ; } function getNameOfAccessExpression(node) { - if (node.kind === 208 /* PropertyAccessExpression */ ) return node.name; - Debug.assert(node.kind === 209 /* ElementAccessExpression */ ); + if (node.kind === 211 /* PropertyAccessExpression */ ) return node.name; + Debug.assert(node.kind === 212 /* ElementAccessExpression */ ); return node.argumentExpression; } function isBundleFileTextLike(section) { @@ -20940,7 +21059,7 @@ ${lanes.join("\n")} } } function isNamedImportsOrExports(node) { - return node.kind === 272 /* NamedImports */ || node.kind === 276 /* NamedExports */ ; + return node.kind === 275 /* NamedImports */ || node.kind === 279 /* NamedExports */ ; } function getLeftmostAccessExpression(expr) { while(isAccessExpression(expr))expr = expr.expression; @@ -20949,10 +21068,10 @@ ${lanes.join("\n")} function forEachNameInAccessChainWalkingLeft(name, action) { if (isAccessExpression(name.parent) && isRightSideOfAccessExpression(name)) return walkAccessExpression(name.parent); function walkAccessExpression(access) { - if (access.kind === 208 /* PropertyAccessExpression */ ) { + if (access.kind === 211 /* PropertyAccessExpression */ ) { const res = action(access.name); if (res !== void 0) return res; - } else if (access.kind === 209 /* ElementAccessExpression */ ) { + } else if (access.kind === 212 /* ElementAccessExpression */ ) { if (isIdentifier(access.argumentExpression) || isStringLiteralLike(access.argumentExpression)) { const res = action(access.argumentExpression); if (res !== void 0) return res; @@ -20966,26 +21085,26 @@ ${lanes.join("\n")} function getLeftmostExpression(node, stopAtCallExpressions) { while(true){ switch(node.kind){ - case 222 /* PostfixUnaryExpression */ : + case 225 /* PostfixUnaryExpression */ : node = node.operand; continue; - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : node = node.left; continue; - case 224 /* ConditionalExpression */ : + case 227 /* ConditionalExpression */ : node = node.condition; continue; - case 212 /* TaggedTemplateExpression */ : + case 215 /* TaggedTemplateExpression */ : node = node.tag; continue; - case 210 /* CallExpression */ : + case 213 /* CallExpression */ : if (stopAtCallExpressions) return node; - case 231 /* AsExpression */ : - case 209 /* ElementAccessExpression */ : - case 208 /* PropertyAccessExpression */ : - case 232 /* NonNullExpression */ : - case 356 /* PartiallyEmittedExpression */ : - case 235 /* SatisfiesExpression */ : + case 234 /* AsExpression */ : + case 212 /* ElementAccessExpression */ : + case 211 /* PropertyAccessExpression */ : + case 235 /* NonNullExpression */ : + case 360 /* PartiallyEmittedExpression */ : + case 238 /* SatisfiesExpression */ : node = node.expression; continue; } @@ -21261,8 +21380,7 @@ ${lanes.join("\n")} } } function getEmitScriptTarget(compilerOptions) { - var _a2; - return (_a2 = compilerOptions.target) != null ? _a2 : compilerOptions.module === 100 /* Node16 */ && 9 /* ES2022 */ || compilerOptions.module === 199 /* NodeNext */ && 99 /* ESNext */ || 1 /* ES5 */ ; + return compilerOptions.target ?? (compilerOptions.module === 100 /* Node16 */ && 9 /* ES2022 */ || compilerOptions.module === 199 /* NodeNext */ && 99 /* ESNext */ || 1 /* ES5 */ ); } function getEmitModuleKind(compilerOptions) { return typeof compilerOptions.module === "number" ? compilerOptions.module : getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? 5 /* ES2015 */ : 1 /* CommonJS */ ; @@ -21386,6 +21504,9 @@ ${lanes.join("\n")} function getUseDefineForClassFields(compilerOptions) { return compilerOptions.useDefineForClassFields === void 0 ? getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */ : compilerOptions.useDefineForClassFields; } + function getEmitStandardClassFields(compilerOptions) { + return compilerOptions.useDefineForClassFields !== false && getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */ ; + } function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { return optionsHaveChanges(oldOptions, newOptions, semanticDiagnosticsOptionDeclarations); } @@ -21437,11 +21558,11 @@ ${lanes.join("\n")} } }, setSymlinksFromResolutions (files, typeReferenceDirectives) { - var _a2, _b; + var _a, _b; Debug.assert(!hasProcessedResolutions); hasProcessedResolutions = true; for (const file of files){ - (_a2 = file.resolvedModules) == null || _a2.forEach((resolution)=>processResolution(this, resolution.resolvedModule)); + (_a = file.resolvedModules) == null || _a.forEach((resolution)=>processResolution(this, resolution.resolvedModule)); (_b = file.resolvedTypeReferenceDirectiveNames) == null || _b.forEach((resolution)=>processResolution(this, resolution.resolvedTypeReferenceDirective)); } typeReferenceDirectives.forEach((resolution)=>processResolution(this, resolution.resolvedTypeReferenceDirective)); @@ -21450,7 +21571,7 @@ ${lanes.join("\n")} }; function processResolution(cache, resolution) { if (!resolution || !resolution.originalPath || !resolution.resolvedFileName) return; - const { resolvedFileName: resolvedFileName , originalPath: originalPath } = resolution; + const { resolvedFileName: resolvedFileName, originalPath: originalPath } = resolution; cache.setSymlinkedFile(toPath(originalPath, cwd, getCanonicalFileName), resolvedFileName); const [commonResolved, commonOriginal] = guessDirectorySymlink(resolvedFileName, originalPath, cwd, getCanonicalFileName) || emptyArray; if (commonResolved && commonOriginal) cache.setSymlinkedDirectory(commonOriginal, { @@ -21507,7 +21628,7 @@ ${lanes.join("\n")} const pattern = spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); return pattern && `^(${pattern})${usage === "exclude" ? "($|/)" : "$"}`; } - function getSubPatternFromSpec(spec, basePath, usage, { singleAsteriskRegexFragment: singleAsteriskRegexFragment , doubleAsteriskRegexFragment: doubleAsteriskRegexFragment , replaceWildcardCharacter: replaceWildcardCharacter2 }) { + function getSubPatternFromSpec(spec, basePath, usage, { singleAsteriskRegexFragment: singleAsteriskRegexFragment, doubleAsteriskRegexFragment: doubleAsteriskRegexFragment, replaceWildcardCharacter: replaceWildcardCharacter2 }) { let subpattern = ""; let hasWrittenComponent = false; const components = getNormalizedPathComponents(spec, basePath); @@ -21549,7 +21670,7 @@ ${lanes.join("\n")} function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } - function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames2, currentDirectory) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); const absolutePath = combinePaths(currentDirectory, path); @@ -21558,31 +21679,31 @@ ${lanes.join("\n")} includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), - basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames2) }; } - function getRegexFromPattern(pattern, useCaseSensitiveFileNames) { - return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i"); + function getRegexFromPattern(pattern, useCaseSensitiveFileNames2) { + return new RegExp(pattern, useCaseSensitiveFileNames2 ? "" : "i"); } - function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) { + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames2, currentDirectory, depth, getFileSystemEntries, realpath) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); - const patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); - const includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map((pattern)=>getRegexFromPattern(pattern, useCaseSensitiveFileNames)); - const includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames); - const excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames); + const patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames2, currentDirectory); + const includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map((pattern)=>getRegexFromPattern(pattern, useCaseSensitiveFileNames2)); + const includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames2); + const excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames2); const results = includeFileRegexes ? includeFileRegexes.map(()=>[]) : [ [] ]; const visited = /* @__PURE__ */ new Map(); - const toCanonical = createGetCanonicalFileName(useCaseSensitiveFileNames); + const toCanonical = createGetCanonicalFileName(useCaseSensitiveFileNames2); for (const basePath of patterns.basePaths)visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); return flatten(results); function visitDirectory(path2, absolutePath, depth2) { const canonicalPath = toCanonical(realpath(absolutePath)); if (visited.has(canonicalPath)) return; visited.set(canonicalPath, true); - const { files: files , directories: directories } = getFileSystemEntries(path2); + const { files: files, directories: directories } = getFileSystemEntries(path2); for (const current of sort(files, compareStringsCaseSensitive)){ const name = combinePaths(path2, current); const absoluteName = combinePaths(absolutePath, current); @@ -21605,7 +21726,7 @@ ${lanes.join("\n")} } } } - function getBasePaths(path, includes, useCaseSensitiveFileNames) { + function getBasePaths(path, includes, useCaseSensitiveFileNames2) { const basePaths = [ path ]; @@ -21615,8 +21736,8 @@ ${lanes.join("\n")} const absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); includeBasePaths.push(getIncludeBasePath(absolute)); } - includeBasePaths.sort(getStringComparer(!useCaseSensitiveFileNames)); - for (const includeBasePath of includeBasePaths)if (every(basePaths, (basePath)=>!containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames))) basePaths.push(includeBasePath); + includeBasePaths.sort(getStringComparer(!useCaseSensitiveFileNames2)); + for (const includeBasePath of includeBasePaths)if (every(basePaths, (basePath)=>!containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames2))) basePaths.push(includeBasePath); } return basePaths; } @@ -21682,8 +21803,8 @@ ${lanes.join("\n")} function hasTSFileExtension(fileName) { return some(supportedTSExtensionsFlat, (extension)=>fileExtensionIs(fileName, extension)); } - function usesExtensionsOnImports({ imports: imports }, hasExtension2 = or(hasJSFileExtension, hasTSFileExtension)) { - return firstDefined(imports, ({ text: text })=>pathIsRelative(text) ? hasExtension2(text) : void 0) || false; + function usesExtensionsOnImports({ imports: imports }, hasExtension2 = or(hasJSFileExtension, hasTSFileExtension)) { + return firstDefined(imports, ({ text: text })=>pathIsRelative(text) && !fileExtensionIsOneOf(text, extensionsNotSupportingExtensionlessResolution) ? hasExtension2(text) : void 0) || false; } function getModuleSpecifierEndingPreference(preference, resolutionMode, compilerOptions, sourceFile) { if (preference === "js" || resolutionMode === 99 /* ESNext */ ) { @@ -21698,6 +21819,7 @@ ${lanes.join("\n")} let usesJsExtensions = false; const specifiers = sourceFile.imports.length ? sourceFile.imports.map((i)=>i.text) : isSourceFileJS(sourceFile) ? getRequiresAtTopOfFile(sourceFile).map((r)=>r.arguments[0].text) : emptyArray; for (const specifier of specifiers)if (pathIsRelative(specifier)) { + if (fileExtensionIsOneOf(specifier, extensionsNotSupportingExtensionlessResolution)) continue; if (hasTSFileExtension(specifier)) return 3 /* TsExtension */ ; if (hasJSFileExtension(specifier)) usesJsExtensions = true; } @@ -21886,7 +22008,7 @@ ${lanes.join("\n")} } return base10Value; } - function pseudoBigIntToString({ negative: negative , base10Value: base10Value }) { + function pseudoBigIntToString({ negative: negative, base10Value: base10Value }) { return (negative && base10Value !== "0" ? "-" : "") + base10Value; } function parseBigInt(text) { @@ -21908,41 +22030,41 @@ ${lanes.join("\n")} scanner2.setOnError(()=>success = false); scanner2.setText(s + "n"); let result = scanner2.scan(); - const negative = result === 40 /* MinusToken */ ; + const negative = result === 41 /* MinusToken */ ; if (negative) result = scanner2.scan(); const flags = scanner2.getTokenFlags(); - return success && result === 9 /* BigIntLiteral */ && scanner2.getTextPos() === s.length + 1 && !(flags & 512 /* ContainsSeparator */ ) && (!roundTripOnly || s === pseudoBigIntToString({ + return success && result === 10 /* BigIntLiteral */ && scanner2.getTokenEnd() === s.length + 1 && !(flags & 512 /* ContainsSeparator */ ) && (!roundTripOnly || s === pseudoBigIntToString({ negative: negative, base10Value: parsePseudoBigInt(scanner2.getTokenValue()) })); } function isValidTypeOnlyAliasUseSite(useSite) { - return !!(useSite.flags & 16777216 /* Ambient */ ) || isPartOfTypeQuery(useSite) || isIdentifierInNonEmittingHeritageClause(useSite) || isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite) || !(isExpressionNode(useSite) || isShorthandPropertyNameUseSite(useSite)); + return !!(useSite.flags & 33554432 /* Ambient */ ) || isPartOfTypeQuery(useSite) || isIdentifierInNonEmittingHeritageClause(useSite) || isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite) || !(isExpressionNode(useSite) || isShorthandPropertyNameUseSite(useSite)); } function isShorthandPropertyNameUseSite(useSite) { return isIdentifier(useSite) && isShorthandPropertyAssignment(useSite.parent) && useSite.parent.name === useSite; } function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) { - while(node.kind === 79 /* Identifier */ || node.kind === 208 /* PropertyAccessExpression */ )node = node.parent; - if (node.kind !== 164 /* ComputedPropertyName */ ) return false; + while(node.kind === 80 /* Identifier */ || node.kind === 211 /* PropertyAccessExpression */ )node = node.parent; + if (node.kind !== 167 /* ComputedPropertyName */ ) return false; if (hasSyntacticModifier(node.parent, 256 /* Abstract */ )) return true; const containerKind = node.parent.parent.kind; - return containerKind === 261 /* InterfaceDeclaration */ || containerKind === 184 /* TypeLiteral */ ; + return containerKind === 264 /* InterfaceDeclaration */ || containerKind === 187 /* TypeLiteral */ ; } function isIdentifierInNonEmittingHeritageClause(node) { - if (node.kind !== 79 /* Identifier */ ) return false; + if (node.kind !== 80 /* Identifier */ ) return false; const heritageClause = findAncestor(node.parent, (parent2)=>{ switch(parent2.kind){ - case 294 /* HeritageClause */ : + case 298 /* HeritageClause */ : return true; - case 208 /* PropertyAccessExpression */ : - case 230 /* ExpressionWithTypeArguments */ : + case 211 /* PropertyAccessExpression */ : + case 233 /* ExpressionWithTypeArguments */ : return false; default: return "quit"; } }); - return (heritageClause == null ? void 0 : heritageClause.token) === 117 /* ImplementsKeyword */ || (heritageClause == null ? void 0 : heritageClause.parent.kind) === 261 /* InterfaceDeclaration */ ; + return (heritageClause == null ? void 0 : heritageClause.token) === 119 /* ImplementsKeyword */ || (heritageClause == null ? void 0 : heritageClause.parent.kind) === 264 /* InterfaceDeclaration */ ; } function isIdentifierTypeReference(node) { return isTypeReferenceNode(node) && isIdentifier(node.typeName); @@ -22020,7 +22142,7 @@ ${lanes.join("\n")} node = parent2; continue; } - if (isBinaryExpression(parent2) && parent2.operatorToken.kind === 27 /* CommaToken */ ) { + if (isBinaryExpression(parent2) && parent2.operatorToken.kind === 28 /* CommaToken */ ) { if (node === parent2.left) return true; node = parent2; continue; @@ -22034,70 +22156,70 @@ ${lanes.join("\n")} function getContainingNodeArray(node) { if (!node.parent) return void 0; switch(node.kind){ - case 165 /* TypeParameter */ : - const { parent: parent3 } = node; - return parent3.kind === 192 /* InferType */ ? void 0 : parent3.typeParameters; - case 166 /* Parameter */ : + case 168 /* TypeParameter */ : + const { parent: parent3 } = node; + return parent3.kind === 195 /* InferType */ ? void 0 : parent3.typeParameters; + case 169 /* Parameter */ : return node.parent.parameters; - case 201 /* TemplateLiteralTypeSpan */ : + case 204 /* TemplateLiteralTypeSpan */ : return node.parent.templateSpans; - case 236 /* TemplateSpan */ : + case 239 /* TemplateSpan */ : return node.parent.templateSpans; - case 167 /* Decorator */ : + case 170 /* Decorator */ : { - const { parent: parent4 } = node; + const { parent: parent4 } = node; return canHaveDecorators(parent4) ? parent4.modifiers : void 0; } - case 294 /* HeritageClause */ : + case 298 /* HeritageClause */ : return node.parent.heritageClauses; } - const { parent: parent2 } = node; + const { parent: parent2 } = node; if (isJSDocTag(node)) return isJSDocTypeLiteral(node.parent) ? void 0 : node.parent.tags; switch(parent2.kind){ - case 184 /* TypeLiteral */ : - case 261 /* InterfaceDeclaration */ : + case 187 /* TypeLiteral */ : + case 264 /* InterfaceDeclaration */ : return isTypeElement(node) ? parent2.members : void 0; - case 189 /* UnionType */ : - case 190 /* IntersectionType */ : + case 192 /* UnionType */ : + case 193 /* IntersectionType */ : return parent2.types; - case 186 /* TupleType */ : - case 206 /* ArrayLiteralExpression */ : - case 357 /* CommaListExpression */ : - case 272 /* NamedImports */ : - case 276 /* NamedExports */ : + case 189 /* TupleType */ : + case 209 /* ArrayLiteralExpression */ : + case 361 /* CommaListExpression */ : + case 275 /* NamedImports */ : + case 279 /* NamedExports */ : return parent2.elements; - case 207 /* ObjectLiteralExpression */ : - case 289 /* JsxAttributes */ : + case 210 /* ObjectLiteralExpression */ : + case 292 /* JsxAttributes */ : return parent2.properties; - case 210 /* CallExpression */ : - case 211 /* NewExpression */ : + case 213 /* CallExpression */ : + case 214 /* NewExpression */ : return isTypeNode(node) ? parent2.typeArguments : parent2.expression === node ? void 0 : parent2.arguments; - case 281 /* JsxElement */ : - case 285 /* JsxFragment */ : + case 284 /* JsxElement */ : + case 288 /* JsxFragment */ : return isJsxChild(node) ? parent2.children : void 0; - case 283 /* JsxOpeningElement */ : - case 282 /* JsxSelfClosingElement */ : + case 286 /* JsxOpeningElement */ : + case 285 /* JsxSelfClosingElement */ : return isTypeNode(node) ? parent2.typeArguments : void 0; - case 238 /* Block */ : - case 292 /* CaseClause */ : - case 293 /* DefaultClause */ : - case 265 /* ModuleBlock */ : + case 241 /* Block */ : + case 296 /* CaseClause */ : + case 297 /* DefaultClause */ : + case 268 /* ModuleBlock */ : return parent2.statements; - case 266 /* CaseBlock */ : + case 269 /* CaseBlock */ : return parent2.clauses; - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : return isClassElement(node) ? parent2.members : void 0; - case 263 /* EnumDeclaration */ : + case 266 /* EnumDeclaration */ : return isEnumMember(node) ? parent2.members : void 0; - case 308 /* SourceFile */ : + case 312 /* SourceFile */ : return parent2.statements; } } function hasContextSensitiveParameters(node) { if (!node.typeParameters) { if (some(node.parameters, (p)=>!getEffectiveTypeAnnotationNode(p))) return true; - if (node.kind !== 216 /* ArrowFunction */ ) { + if (node.kind !== 219 /* ArrowFunction */ ) { const parameter = firstOrUndefined(node.parameters); if (!(parameter && parameterIsThisKeyword(parameter))) return true; } @@ -22108,14 +22230,14 @@ ${lanes.join("\n")} return name === "Infinity" || name === "-Infinity" || name === "NaN"; } function isCatchClauseVariableDeclaration(node) { - return node.kind === 257 /* VariableDeclaration */ && node.parent.kind === 295 /* CatchClause */ ; + return node.kind === 260 /* VariableDeclaration */ && node.parent.kind === 299 /* CatchClause */ ; } function isParameterOrCatchClauseVariable(symbol) { const declaration = symbol.valueDeclaration && getRootDeclaration(symbol.valueDeclaration); return !!declaration && (isParameter(declaration) || isCatchClauseVariableDeclaration(declaration)); } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 215 /* FunctionExpression */ || node.kind === 216 /* ArrowFunction */ ; + return node.kind === 218 /* FunctionExpression */ || node.kind === 219 /* ArrowFunction */ ; } function escapeSnippetText(text) { return text.replace(/\$/gm, ()=>"\\$"); @@ -22178,24 +22300,24 @@ ${lanes.join("\n")} } : void 0; } function getParameterTypeNode(parameter) { - var _a2; - return parameter.kind === 344 /* JSDocParameterTag */ ? (_a2 = parameter.typeExpression) == null ? void 0 : _a2.type : parameter.type; + var _a; + return parameter.kind === 348 /* JSDocParameterTag */ ? (_a = parameter.typeExpression) == null ? void 0 : _a.type : parameter.type; } function isTypeDeclaration(node) { switch(node.kind){ - case 165 /* TypeParameter */ : - case 260 /* ClassDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 262 /* TypeAliasDeclaration */ : - case 263 /* EnumDeclaration */ : - case 349 /* JSDocTypedefTag */ : - case 341 /* JSDocCallbackTag */ : - case 343 /* JSDocEnumTag */ : + case 168 /* TypeParameter */ : + case 263 /* ClassDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 265 /* TypeAliasDeclaration */ : + case 266 /* EnumDeclaration */ : + case 353 /* JSDocTypedefTag */ : + case 345 /* JSDocCallbackTag */ : + case 347 /* JSDocEnumTag */ : return true; - case 270 /* ImportClause */ : + case 273 /* ImportClause */ : return node.isTypeOnly; - case 273 /* ImportSpecifier */ : - case 278 /* ExportSpecifier */ : + case 276 /* ImportSpecifier */ : + case 281 /* ExportSpecifier */ : return node.parent.parent.isTypeOnly; default: return false; @@ -22206,8 +22328,8 @@ ${lanes.join("\n")} } function isOptionalJSDocPropertyLikeTag(node) { if (!isJSDocPropertyLikeTag(node)) return false; - const { isBracketed: isBracketed , typeExpression: typeExpression } = node; - return isBracketed || !!typeExpression && typeExpression.type.kind === 319 /* JSDocOptionalType */ ; + const { isBracketed: isBracketed, typeExpression: typeExpression } = node; + return isBracketed || !!typeExpression && typeExpression.type.kind === 323 /* JSDocOptionalType */ ; } function canUsePropertyAccess(name, languageVersion) { if (name.length === 0) return false; @@ -22215,22 +22337,22 @@ ${lanes.join("\n")} return firstChar === 35 /* hash */ ? name.length > 1 && isIdentifierStart(name.charCodeAt(1), languageVersion) : isIdentifierStart(firstChar, languageVersion); } function hasTabstop(node) { - var _a2; - return ((_a2 = getSnippetElement(node)) == null ? void 0 : _a2.kind) === 0 /* TabStop */ ; + var _a; + return ((_a = getSnippetElement(node)) == null ? void 0 : _a.kind) === 0 /* TabStop */ ; } function isJSDocOptionalParameter(node) { return isInJSFile(node) && // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType - (node.type && node.type.kind === 319 /* JSDocOptionalType */ || getJSDocParameterTags(node).some(({ isBracketed: isBracketed , typeExpression: typeExpression })=>isBracketed || !!typeExpression && typeExpression.type.kind === 319 /* JSDocOptionalType */ )); + (node.type && node.type.kind === 323 /* JSDocOptionalType */ || getJSDocParameterTags(node).some(({ isBracketed: isBracketed, typeExpression: typeExpression })=>isBracketed || !!typeExpression && typeExpression.type.kind === 323 /* JSDocOptionalType */ )); } function isOptionalDeclaration(declaration) { switch(declaration.kind){ - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : return !!declaration.questionToken; - case 166 /* Parameter */ : + case 169 /* Parameter */ : return !!declaration.questionToken || isJSDocOptionalParameter(declaration); - case 351 /* JSDocPropertyTag */ : - case 344 /* JSDocParameterTag */ : + case 355 /* JSDocPropertyTag */ : + case 348 /* JSDocParameterTag */ : return isOptionalJSDocPropertyLikeTag(declaration); default: return false; @@ -22238,7 +22360,7 @@ ${lanes.join("\n")} } function isNonNullAccess(node) { const kind = node.kind; - return (kind === 208 /* PropertyAccessExpression */ || kind === 209 /* ElementAccessExpression */ ) && isNonNullExpression(node.expression); + return (kind === 211 /* PropertyAccessExpression */ || kind === 212 /* ElementAccessExpression */ ) && isNonNullExpression(node.expression); } function isJSDocSatisfiesExpression(node) { return isInJSFile(node) && isParenthesizedExpression(node) && hasJSDocNodes(node) && !!getJSDocSatisfiesTag(node); @@ -22250,7 +22372,34 @@ ${lanes.join("\n")} const tag = getJSDocSatisfiesTag(node); return tag && tag.typeExpression && tag.typeExpression.type; } - var resolvingEmptyArray, externalHelpersModuleNameText, defaultMaximumTruncationLength, noTruncationMaximumTruncationLength, stringWriter, GetLiteralTextFlags, fullTripleSlashReferencePathRegEx, fullTripleSlashReferenceTypeReferenceDirectiveRegEx, fullTripleSlashAMDReferencePathRegEx, defaultLibReferenceRegEx, AssignmentKind, FunctionFlags, Associativity, OperatorPrecedence, templateSubstitutionRegExp, doubleQuoteEscapedCharsRegExp, singleQuoteEscapedCharsRegExp, backtickQuoteEscapedCharsRegExp, escapedCharsMap, nonAsciiCharacters, jsxDoubleQuoteEscapedCharsRegExp, jsxSingleQuoteEscapedCharsRegExp, jsxEscapedCharsMap, indentStrings, base64Digits, carriageReturnLineFeed, lineFeed, objectAllocator, objectAllocatorPatchers, localizedDiagnosticMessages, reservedCharacterPattern, wildcardCharCodes, commonPackageFolders, implicitExcludePathRegexPattern, filesMatcher, directoriesMatcher, excludeMatcher, wildcardMatchers, supportedTSExtensions, supportedTSExtensionsFlat, supportedTSExtensionsWithJson, supportedTSExtensionsForExtractExtension, supportedJSExtensions, supportedJSExtensionsFlat, allSupportedExtensions, allSupportedExtensionsWithJson, supportedDeclarationExtensions, supportedTSImplementationExtensions, ModuleSpecifierEnding, extensionsToRemove, emptyFileSystemEntries; + function getEscapedTextOfJsxAttributeName(node) { + return isIdentifier(node) ? node.escapedText : getEscapedTextOfJsxNamespacedName(node); + } + function getTextOfJsxAttributeName(node) { + return isIdentifier(node) ? idText(node) : getTextOfJsxNamespacedName(node); + } + function isJsxAttributeName(node) { + const kind = node.kind; + return kind === 80 /* Identifier */ || kind === 295 /* JsxNamespacedName */ ; + } + function getEscapedTextOfJsxNamespacedName(node) { + return `${node.namespace.escapedText}:${idText(node.name)}`; + } + function getTextOfJsxNamespacedName(node) { + return `${idText(node.namespace)}:${idText(node.name)}`; + } + function intrinsicTagNameToString(node) { + return isIdentifier(node) ? idText(node) : getTextOfJsxNamespacedName(node); + } + function isTypeUsableAsPropertyName(type) { + return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */ ); + } + function getPropertyNameFromType(type) { + if (type.flags & 8192 /* UniqueESSymbol */ ) return type.escapedName; + if (type.flags & 384 /* NumberLiteral */ ) return escapeLeadingUnderscores("" + type.value); + return Debug.fail(); + } + var resolvingEmptyArray, externalHelpersModuleNameText, defaultMaximumTruncationLength, noTruncationMaximumTruncationLength, stringWriter, GetLiteralTextFlags, fullTripleSlashReferencePathRegEx, fullTripleSlashReferenceTypeReferenceDirectiveRegEx, fullTripleSlashLibReferenceRegEx, fullTripleSlashAMDReferencePathRegEx, fullTripleSlashAMDModuleRegEx, defaultLibReferenceRegEx, AssignmentKind, FunctionFlags, Associativity, OperatorPrecedence, templateSubstitutionRegExp, doubleQuoteEscapedCharsRegExp, singleQuoteEscapedCharsRegExp, backtickQuoteEscapedCharsRegExp, escapedCharsMap, nonAsciiCharacters, jsxDoubleQuoteEscapedCharsRegExp, jsxSingleQuoteEscapedCharsRegExp, jsxEscapedCharsMap, indentStrings, base64Digits, carriageReturnLineFeed, lineFeed, objectAllocator, objectAllocatorPatchers, localizedDiagnosticMessages, reservedCharacterPattern, wildcardCharCodes, commonPackageFolders, implicitExcludePathRegexPattern, filesMatcher, directoriesMatcher, excludeMatcher, wildcardMatchers, supportedTSExtensions, supportedTSExtensionsFlat, supportedTSExtensionsWithJson, supportedTSExtensionsForExtractExtension, supportedJSExtensions, supportedJSExtensionsFlat, allSupportedExtensions, allSupportedExtensionsWithJson, supportedDeclarationExtensions, supportedTSImplementationExtensions, extensionsNotSupportingExtensionlessResolution, ModuleSpecifierEnding, extensionsToRemove, emptyFileSystemEntries; var init_utilities = __esm({ "src/compiler/utilities.ts" () { "use strict"; @@ -22270,7 +22419,9 @@ ${lanes.join("\n")} })(GetLiteralTextFlags || {}); fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; + fullTripleSlashLibReferenceRegEx = /^(\/\/\/\s*/; fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; + fullTripleSlashAMDModuleRegEx = /^\/\/\/\s*/; defaultLibReferenceRegEx = /^(\/\/\/\s*/; AssignmentKind = /* @__PURE__ */ ((AssignmentKind2)=>{ AssignmentKind2[AssignmentKind2["None"] = 0] = "None"; @@ -22320,9 +22471,9 @@ ${lanes.join("\n")} return OperatorPrecedence2; })(OperatorPrecedence || {}); templateSubstitutionRegExp = /\$\{/g; - doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - backtickQuoteEscapedCharsRegExp = /\r\n|[\\\`\u0000-\u001f\t\v\f\b\r\u2028\u2029\u0085]/g; + doubleQuoteEscapedCharsRegExp = /[\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + singleQuoteEscapedCharsRegExp = /[\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + backtickQuoteEscapedCharsRegExp = /\r\n|[\\`\u0000-\u001f\t\v\f\b\r\u2028\u2029\u0085]/g; escapedCharsMap = new Map(Object.entries({ " ": "\\t", "\v": "\\v", @@ -22343,8 +22494,8 @@ ${lanes.join("\n")} "\r\n": "\\r\\n" })); nonAsciiCharacters = /[^\u0000-\u007F]/g; - jsxDoubleQuoteEscapedCharsRegExp = /[\"\u0000-\u001f\u2028\u2029\u0085]/g; - jsxSingleQuoteEscapedCharsRegExp = /[\'\u0000-\u001f\u2028\u2029\u0085]/g; + jsxDoubleQuoteEscapedCharsRegExp = /["\u0000-\u001f\u2028\u2029\u0085]/g; + jsxSingleQuoteEscapedCharsRegExp = /['\u0000-\u001f\u2028\u2029\u0085]/g; jsxEscapedCharsMap = new Map(Object.entries({ '"': """, "'": "'" @@ -22368,7 +22519,7 @@ ${lanes.join("\n")} getSourceMapSourceConstructor: ()=>SourceMapSource }; objectAllocatorPatchers = []; - reservedCharacterPattern = /[^\w\s\/]/g; + reservedCharacterPattern = /[^\w\s/]/g; wildcardCharCodes = [ 42 /* asterisk */ , 63 /* question */ @@ -22439,9 +22590,7 @@ ${lanes.join("\n")} ".cts" /* Cts */ , ".mts" /* Mts */ , ".ts" /* Ts */ , - ".tsx" /* Tsx */ , - ".cts" /* Cts */ , - ".mts" /* Mts */ + ".tsx" /* Tsx */ ]; supportedJSExtensions = [ [ @@ -22492,6 +22641,14 @@ ${lanes.join("\n")} ".mts" /* Mts */ , ".tsx" /* Tsx */ ]; + extensionsNotSupportingExtensionlessResolution = [ + ".mts" /* Mts */ , + ".d.mts" /* Dmts */ , + ".mjs" /* Mjs */ , + ".cts" /* Cts */ , + ".d.cts" /* Dcts */ , + ".cjs" /* Cjs */ + ]; ModuleSpecifierEnding = /* @__PURE__ */ ((ModuleSpecifierEnding2)=>{ ModuleSpecifierEnding2[ModuleSpecifierEnding2["Minimal"] = 0] = "Minimal"; ModuleSpecifierEnding2[ModuleSpecifierEnding2["Index"] = 1] = "Index"; @@ -22610,14 +22767,14 @@ ${lanes.join("\n")} return parenthesizerRule; } function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { - const binaryOperatorPrecedence = getOperatorPrecedence(223 /* BinaryExpression */ , binaryOperator); - const binaryOperatorAssociativity = getOperatorAssociativity(223 /* BinaryExpression */ , binaryOperator); + const binaryOperatorPrecedence = getOperatorPrecedence(226 /* BinaryExpression */ , binaryOperator); + const binaryOperatorAssociativity = getOperatorAssociativity(226 /* BinaryExpression */ , binaryOperator); const emittedOperand = skipPartiallyEmittedExpressions(operand); - if (!isLeftSideOfBinary && operand.kind === 216 /* ArrowFunction */ && binaryOperatorPrecedence > 3 /* Assignment */ ) return true; + if (!isLeftSideOfBinary && operand.kind === 219 /* ArrowFunction */ && binaryOperatorPrecedence > 3 /* Assignment */ ) return true; const operandPrecedence = getExpressionPrecedence(emittedOperand); switch(compareValues(operandPrecedence, binaryOperatorPrecedence)){ case -1 /* LessThan */ : - if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 /* Right */ && operand.kind === 226 /* YieldExpression */ ) return false; + if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 /* Right */ && operand.kind === 229 /* YieldExpression */ ) return false; return true; case 1 /* GreaterThan */ : return false; @@ -22626,7 +22783,7 @@ ${lanes.join("\n")} else { if (isBinaryExpression(emittedOperand) && emittedOperand.operatorToken.kind === binaryOperator) { if (operatorHasAssociativeProperty(binaryOperator)) return false; - if (binaryOperator === 39 /* PlusToken */ ) { + if (binaryOperator === 40 /* PlusToken */ ) { const leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */ ; if (isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) return false; } @@ -22637,12 +22794,12 @@ ${lanes.join("\n")} } } function operatorHasAssociativeProperty(binaryOperator) { - return binaryOperator === 41 /* AsteriskToken */ || binaryOperator === 51 /* BarToken */ || binaryOperator === 50 /* AmpersandToken */ || binaryOperator === 52 /* CaretToken */ || binaryOperator === 27 /* CommaToken */ ; + return binaryOperator === 42 /* AsteriskToken */ || binaryOperator === 52 /* BarToken */ || binaryOperator === 51 /* AmpersandToken */ || binaryOperator === 53 /* CaretToken */ || binaryOperator === 28 /* CommaToken */ ; } function getLiteralKindOfBinaryPlusOperand(node) { node = skipPartiallyEmittedExpressions(node); if (isLiteralKind(node.kind)) return node.kind; - if (node.kind === 223 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */ ) { + if (node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 40 /* PlusToken */ ) { if (node.cachedLiteralKind !== void 0) return node.cachedLiteralKind; const leftKind = getLiteralKindOfBinaryPlusOperand(node.left); const literalKind = isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(node.right) ? leftKind : 0 /* Unknown */ ; @@ -22653,7 +22810,7 @@ ${lanes.join("\n")} } function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { const skipped = skipPartiallyEmittedExpressions(operand); - if (skipped.kind === 214 /* ParenthesizedExpression */ ) return operand; + if (skipped.kind === 217 /* ParenthesizedExpression */ ) return operand; return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) ? factory2.createParenthesizedExpression(operand) : operand; } function parenthesizeLeftSideOfBinary(binaryOperator, leftSide) { @@ -22666,7 +22823,7 @@ ${lanes.join("\n")} return isCommaSequence(expression) ? factory2.createParenthesizedExpression(expression) : expression; } function parenthesizeConditionOfConditionalExpression(condition) { - const conditionalPrecedence = getOperatorPrecedence(224 /* ConditionalExpression */ , 57 /* QuestionToken */ ); + const conditionalPrecedence = getOperatorPrecedence(227 /* ConditionalExpression */ , 58 /* QuestionToken */ ); const emittedCondition = skipPartiallyEmittedExpressions(condition); const conditionPrecedence = getExpressionPrecedence(emittedCondition); if (compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */ ) return factory2.createParenthesizedExpression(condition); @@ -22679,9 +22836,9 @@ ${lanes.join("\n")} function parenthesizeExpressionOfExportDefault(expression) { const check = skipPartiallyEmittedExpressions(expression); let needsParens = isCommaSequence(check); - if (!needsParens) switch(getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind){ - case 228 /* ClassExpression */ : - case 215 /* FunctionExpression */ : + if (!needsParens) switch(getLeftmostExpression(check, /*stopAtCallExpressions*/ false).kind){ + case 231 /* ClassExpression */ : + case 218 /* FunctionExpression */ : needsParens = true; } return needsParens ? factory2.createParenthesizedExpression(expression) : expression; @@ -22689,16 +22846,16 @@ ${lanes.join("\n")} function parenthesizeExpressionOfNew(expression) { const leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); switch(leftmostExpr.kind){ - case 210 /* CallExpression */ : + case 213 /* CallExpression */ : return factory2.createParenthesizedExpression(expression); - case 211 /* NewExpression */ : + case 214 /* NewExpression */ : return !leftmostExpr.arguments ? factory2.createParenthesizedExpression(expression) : expression; } return parenthesizeLeftSideOfAccess(expression); } function parenthesizeLeftSideOfAccess(expression, optionalChain) { const emittedExpression = skipPartiallyEmittedExpressions(expression); - if (isLeftHandSideExpression(emittedExpression) && (emittedExpression.kind !== 211 /* NewExpression */ || emittedExpression.arguments) && (optionalChain || !isOptionalChain(emittedExpression))) return expression; + if (isLeftHandSideExpression(emittedExpression) && (emittedExpression.kind !== 214 /* NewExpression */ || emittedExpression.arguments) && (optionalChain || !isOptionalChain(emittedExpression))) return expression; return setTextRange(factory2.createParenthesizedExpression(expression), expression); } function parenthesizeOperandOfPostfixUnary(operand) { @@ -22714,7 +22871,7 @@ ${lanes.join("\n")} function parenthesizeExpressionForDisallowedComma(expression) { const emittedExpression = skipPartiallyEmittedExpressions(expression); const expressionPrecedence = getExpressionPrecedence(emittedExpression); - const commaPrecedence = getOperatorPrecedence(223 /* BinaryExpression */ , 27 /* CommaToken */ ); + const commaPrecedence = getOperatorPrecedence(226 /* BinaryExpression */ , 28 /* CommaToken */ ); return expressionPrecedence > commaPrecedence ? expression : setTextRange(factory2.createParenthesizedExpression(expression), expression); } function parenthesizeExpressionOfExpressionStatement(expression) { @@ -22722,39 +22879,39 @@ ${lanes.join("\n")} if (isCallExpression(emittedExpression)) { const callee = emittedExpression.expression; const kind = skipPartiallyEmittedExpressions(callee).kind; - if (kind === 215 /* FunctionExpression */ || kind === 216 /* ArrowFunction */ ) { + if (kind === 218 /* FunctionExpression */ || kind === 219 /* ArrowFunction */ ) { const updated = factory2.updateCallExpression(emittedExpression, setTextRange(factory2.createParenthesizedExpression(callee), callee), emittedExpression.typeArguments, emittedExpression.arguments); return factory2.restoreOuterExpressions(expression, updated, 8 /* PartiallyEmittedExpressions */ ); } } const leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; - if (leftmostExpressionKind === 207 /* ObjectLiteralExpression */ || leftmostExpressionKind === 215 /* FunctionExpression */ ) return setTextRange(factory2.createParenthesizedExpression(expression), expression); + if (leftmostExpressionKind === 210 /* ObjectLiteralExpression */ || leftmostExpressionKind === 218 /* FunctionExpression */ ) return setTextRange(factory2.createParenthesizedExpression(expression), expression); return expression; } function parenthesizeConciseBodyOfArrowFunction(body) { - if (!isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 207 /* ObjectLiteralExpression */ )) return setTextRange(factory2.createParenthesizedExpression(body), body); + if (!isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 210 /* ObjectLiteralExpression */ )) return setTextRange(factory2.createParenthesizedExpression(body), body); return body; } function parenthesizeCheckTypeOfConditionalType(checkType) { switch(checkType.kind){ - case 181 /* FunctionType */ : - case 182 /* ConstructorType */ : - case 191 /* ConditionalType */ : + case 184 /* FunctionType */ : + case 185 /* ConstructorType */ : + case 194 /* ConditionalType */ : return factory2.createParenthesizedType(checkType); } return checkType; } function parenthesizeExtendsTypeOfConditionalType(extendsType) { switch(extendsType.kind){ - case 191 /* ConditionalType */ : + case 194 /* ConditionalType */ : return factory2.createParenthesizedType(extendsType); } return extendsType; } function parenthesizeConstituentTypeOfUnionType(type) { switch(type.kind){ - case 189 /* UnionType */ : - case 190 /* IntersectionType */ : + case 192 /* UnionType */ : + case 193 /* IntersectionType */ : return factory2.createParenthesizedType(type); } return parenthesizeCheckTypeOfConditionalType(type); @@ -22764,8 +22921,8 @@ ${lanes.join("\n")} } function parenthesizeConstituentTypeOfIntersectionType(type) { switch(type.kind){ - case 189 /* UnionType */ : - case 190 /* IntersectionType */ : + case 192 /* UnionType */ : + case 193 /* IntersectionType */ : return factory2.createParenthesizedType(type); } return parenthesizeConstituentTypeOfUnionType(type); @@ -22775,23 +22932,23 @@ ${lanes.join("\n")} } function parenthesizeOperandOfTypeOperator(type) { switch(type.kind){ - case 190 /* IntersectionType */ : + case 193 /* IntersectionType */ : return factory2.createParenthesizedType(type); } return parenthesizeConstituentTypeOfIntersectionType(type); } function parenthesizeOperandOfReadonlyTypeOperator(type) { switch(type.kind){ - case 195 /* TypeOperator */ : + case 198 /* TypeOperator */ : return factory2.createParenthesizedType(type); } return parenthesizeOperandOfTypeOperator(type); } function parenthesizeNonArrayTypeOfPostfixType(type) { switch(type.kind){ - case 192 /* InferType */ : - case 195 /* TypeOperator */ : - case 183 /* TypeQuery */ : + case 195 /* InferType */ : + case 198 /* TypeOperator */ : + case 186 /* TypeQuery */ : return factory2.createParenthesizedType(type); } return parenthesizeOperandOfTypeOperator(type); @@ -22871,6 +23028,7 @@ ${lanes.join("\n")} return { convertToFunctionBlock: convertToFunctionBlock, convertToFunctionExpression: convertToFunctionExpression, + convertToClassExpression: convertToClassExpression, convertToArrayAssignmentElement: convertToArrayAssignmentElement, convertToObjectAssignmentElement: convertToObjectAssignmentElement, convertToAssignmentPattern: convertToAssignmentPattern, @@ -22889,8 +23047,17 @@ ${lanes.join("\n")} return body; } function convertToFunctionExpression(node) { + var _a; if (!node.body) return Debug.fail(`Cannot convert a FunctionDeclaration without a body`); - const updated = factory2.createFunctionExpression(getModifiers(node), node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); + const updated = factory2.createFunctionExpression((_a = getModifiers(node)) == null ? void 0 : _a.filter((modifier)=>!isExportModifier(modifier) && !isDefaultModifier(modifier)), node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); + setOriginalNode(updated, node); + setTextRange(updated, node); + if (getStartsOnNewLine(node)) setStartsOnNewLine(updated, /*newLine*/ true); + return updated; + } + function convertToClassExpression(node) { + var _a; + const updated = factory2.createClassExpression((_a = node.modifiers) == null ? void 0 : _a.filter((modifier)=>!isExportModifier(modifier) && !isDefaultModifier(modifier)), node.name, node.typeParameters, node.heritageClauses, node.members); setOriginalNode(updated, node); setTextRange(updated, node); if (getStartsOnNewLine(node)) setStartsOnNewLine(updated, /*newLine*/ true); @@ -22924,11 +23091,11 @@ ${lanes.join("\n")} } function convertToAssignmentPattern(node) { switch(node.kind){ - case 204 /* ArrayBindingPattern */ : - case 206 /* ArrayLiteralExpression */ : + case 207 /* ArrayBindingPattern */ : + case 209 /* ArrayLiteralExpression */ : return convertToArrayAssignmentPattern(node); - case 203 /* ObjectBindingPattern */ : - case 207 /* ObjectLiteralExpression */ : + case 206 /* ObjectBindingPattern */ : + case 210 /* ObjectLiteralExpression */ : return convertToObjectAssignmentPattern(node); } } @@ -22953,6 +23120,7 @@ ${lanes.join("\n")} nullNodeConverters = { convertToFunctionBlock: notImplemented, convertToFunctionExpression: notImplemented, + convertToClassExpression: notImplemented, convertToArrayAssignmentElement: notImplemented, convertToObjectAssignmentElement: notImplemented, convertToAssignmentPattern: notImplemented, @@ -23264,40 +23432,40 @@ ${lanes.join("\n")} updateExternalModuleReference: updateExternalModuleReference, // lazily load factory members for JSDoc types with similar structure get createJSDocAllType () { - return getJSDocPrimaryTypeCreateFunction(315 /* JSDocAllType */ ); + return getJSDocPrimaryTypeCreateFunction(319 /* JSDocAllType */ ); }, get createJSDocUnknownType () { - return getJSDocPrimaryTypeCreateFunction(316 /* JSDocUnknownType */ ); + return getJSDocPrimaryTypeCreateFunction(320 /* JSDocUnknownType */ ); }, get createJSDocNonNullableType () { - return getJSDocPrePostfixUnaryTypeCreateFunction(318 /* JSDocNonNullableType */ ); + return getJSDocPrePostfixUnaryTypeCreateFunction(322 /* JSDocNonNullableType */ ); }, get updateJSDocNonNullableType () { - return getJSDocPrePostfixUnaryTypeUpdateFunction(318 /* JSDocNonNullableType */ ); + return getJSDocPrePostfixUnaryTypeUpdateFunction(322 /* JSDocNonNullableType */ ); }, get createJSDocNullableType () { - return getJSDocPrePostfixUnaryTypeCreateFunction(317 /* JSDocNullableType */ ); + return getJSDocPrePostfixUnaryTypeCreateFunction(321 /* JSDocNullableType */ ); }, get updateJSDocNullableType () { - return getJSDocPrePostfixUnaryTypeUpdateFunction(317 /* JSDocNullableType */ ); + return getJSDocPrePostfixUnaryTypeUpdateFunction(321 /* JSDocNullableType */ ); }, get createJSDocOptionalType () { - return getJSDocUnaryTypeCreateFunction(319 /* JSDocOptionalType */ ); + return getJSDocUnaryTypeCreateFunction(323 /* JSDocOptionalType */ ); }, get updateJSDocOptionalType () { - return getJSDocUnaryTypeUpdateFunction(319 /* JSDocOptionalType */ ); + return getJSDocUnaryTypeUpdateFunction(323 /* JSDocOptionalType */ ); }, get createJSDocVariadicType () { - return getJSDocUnaryTypeCreateFunction(321 /* JSDocVariadicType */ ); + return getJSDocUnaryTypeCreateFunction(325 /* JSDocVariadicType */ ); }, get updateJSDocVariadicType () { - return getJSDocUnaryTypeUpdateFunction(321 /* JSDocVariadicType */ ); + return getJSDocUnaryTypeUpdateFunction(325 /* JSDocVariadicType */ ); }, get createJSDocNamepathType () { - return getJSDocUnaryTypeCreateFunction(322 /* JSDocNamepathType */ ); + return getJSDocUnaryTypeCreateFunction(326 /* JSDocNamepathType */ ); }, get updateJSDocNamepathType () { - return getJSDocUnaryTypeUpdateFunction(322 /* JSDocNamepathType */ ); + return getJSDocUnaryTypeUpdateFunction(326 /* JSDocNamepathType */ ); }, createJSDocFunctionType: createJSDocFunctionType, updateJSDocFunctionType: updateJSDocFunctionType, @@ -23337,82 +23505,82 @@ ${lanes.join("\n")} updateJSDocLinkPlain: updateJSDocLinkPlain, // lazily load factory members for JSDoc tags with similar structure get createJSDocTypeTag () { - return getJSDocTypeLikeTagCreateFunction(347 /* JSDocTypeTag */ ); + return getJSDocTypeLikeTagCreateFunction(351 /* JSDocTypeTag */ ); }, get updateJSDocTypeTag () { - return getJSDocTypeLikeTagUpdateFunction(347 /* JSDocTypeTag */ ); + return getJSDocTypeLikeTagUpdateFunction(351 /* JSDocTypeTag */ ); }, get createJSDocReturnTag () { - return getJSDocTypeLikeTagCreateFunction(345 /* JSDocReturnTag */ ); + return getJSDocTypeLikeTagCreateFunction(349 /* JSDocReturnTag */ ); }, get updateJSDocReturnTag () { - return getJSDocTypeLikeTagUpdateFunction(345 /* JSDocReturnTag */ ); + return getJSDocTypeLikeTagUpdateFunction(349 /* JSDocReturnTag */ ); }, get createJSDocThisTag () { - return getJSDocTypeLikeTagCreateFunction(346 /* JSDocThisTag */ ); + return getJSDocTypeLikeTagCreateFunction(350 /* JSDocThisTag */ ); }, get updateJSDocThisTag () { - return getJSDocTypeLikeTagUpdateFunction(346 /* JSDocThisTag */ ); + return getJSDocTypeLikeTagUpdateFunction(350 /* JSDocThisTag */ ); }, get createJSDocAuthorTag () { - return getJSDocSimpleTagCreateFunction(333 /* JSDocAuthorTag */ ); + return getJSDocSimpleTagCreateFunction(337 /* JSDocAuthorTag */ ); }, get updateJSDocAuthorTag () { - return getJSDocSimpleTagUpdateFunction(333 /* JSDocAuthorTag */ ); + return getJSDocSimpleTagUpdateFunction(337 /* JSDocAuthorTag */ ); }, get createJSDocClassTag () { - return getJSDocSimpleTagCreateFunction(335 /* JSDocClassTag */ ); + return getJSDocSimpleTagCreateFunction(339 /* JSDocClassTag */ ); }, get updateJSDocClassTag () { - return getJSDocSimpleTagUpdateFunction(335 /* JSDocClassTag */ ); + return getJSDocSimpleTagUpdateFunction(339 /* JSDocClassTag */ ); }, get createJSDocPublicTag () { - return getJSDocSimpleTagCreateFunction(336 /* JSDocPublicTag */ ); + return getJSDocSimpleTagCreateFunction(340 /* JSDocPublicTag */ ); }, get updateJSDocPublicTag () { - return getJSDocSimpleTagUpdateFunction(336 /* JSDocPublicTag */ ); + return getJSDocSimpleTagUpdateFunction(340 /* JSDocPublicTag */ ); }, get createJSDocPrivateTag () { - return getJSDocSimpleTagCreateFunction(337 /* JSDocPrivateTag */ ); + return getJSDocSimpleTagCreateFunction(341 /* JSDocPrivateTag */ ); }, get updateJSDocPrivateTag () { - return getJSDocSimpleTagUpdateFunction(337 /* JSDocPrivateTag */ ); + return getJSDocSimpleTagUpdateFunction(341 /* JSDocPrivateTag */ ); }, get createJSDocProtectedTag () { - return getJSDocSimpleTagCreateFunction(338 /* JSDocProtectedTag */ ); + return getJSDocSimpleTagCreateFunction(342 /* JSDocProtectedTag */ ); }, get updateJSDocProtectedTag () { - return getJSDocSimpleTagUpdateFunction(338 /* JSDocProtectedTag */ ); + return getJSDocSimpleTagUpdateFunction(342 /* JSDocProtectedTag */ ); }, get createJSDocReadonlyTag () { - return getJSDocSimpleTagCreateFunction(339 /* JSDocReadonlyTag */ ); + return getJSDocSimpleTagCreateFunction(343 /* JSDocReadonlyTag */ ); }, get updateJSDocReadonlyTag () { - return getJSDocSimpleTagUpdateFunction(339 /* JSDocReadonlyTag */ ); + return getJSDocSimpleTagUpdateFunction(343 /* JSDocReadonlyTag */ ); }, get createJSDocOverrideTag () { - return getJSDocSimpleTagCreateFunction(340 /* JSDocOverrideTag */ ); + return getJSDocSimpleTagCreateFunction(344 /* JSDocOverrideTag */ ); }, get updateJSDocOverrideTag () { - return getJSDocSimpleTagUpdateFunction(340 /* JSDocOverrideTag */ ); + return getJSDocSimpleTagUpdateFunction(344 /* JSDocOverrideTag */ ); }, get createJSDocDeprecatedTag () { - return getJSDocSimpleTagCreateFunction(334 /* JSDocDeprecatedTag */ ); + return getJSDocSimpleTagCreateFunction(338 /* JSDocDeprecatedTag */ ); }, get updateJSDocDeprecatedTag () { - return getJSDocSimpleTagUpdateFunction(334 /* JSDocDeprecatedTag */ ); + return getJSDocSimpleTagUpdateFunction(338 /* JSDocDeprecatedTag */ ); }, get createJSDocThrowsTag () { - return getJSDocTypeLikeTagCreateFunction(352 /* JSDocThrowsTag */ ); + return getJSDocTypeLikeTagCreateFunction(356 /* JSDocThrowsTag */ ); }, get updateJSDocThrowsTag () { - return getJSDocTypeLikeTagUpdateFunction(352 /* JSDocThrowsTag */ ); + return getJSDocTypeLikeTagUpdateFunction(356 /* JSDocThrowsTag */ ); }, get createJSDocSatisfiesTag () { - return getJSDocTypeLikeTagCreateFunction(353 /* JSDocSatisfiesTag */ ); + return getJSDocTypeLikeTagCreateFunction(357 /* JSDocSatisfiesTag */ ); }, get updateJSDocSatisfiesTag () { - return getJSDocTypeLikeTagUpdateFunction(353 /* JSDocSatisfiesTag */ ); + return getJSDocTypeLikeTagUpdateFunction(357 /* JSDocSatisfiesTag */ ); }, createJSDocEnumTag: createJSDocEnumTag, updateJSDocEnumTag: updateJSDocEnumTag, @@ -23444,6 +23612,8 @@ ${lanes.join("\n")} updateJsxSpreadAttribute: updateJsxSpreadAttribute, createJsxExpression: createJsxExpression, updateJsxExpression: updateJsxExpression, + createJsxNamespacedName: createJsxNamespacedName, + updateJsxNamespacedName: updateJsxNamespacedName, createCaseClause: createCaseClause, updateCaseClause: updateCaseClause, createDefaultClause: createDefaultClause, @@ -23478,107 +23648,105 @@ ${lanes.join("\n")} updatePartiallyEmittedExpression: updatePartiallyEmittedExpression, createCommaListExpression: createCommaListExpression, updateCommaListExpression: updateCommaListExpression, - createEndOfDeclarationMarker: createEndOfDeclarationMarker, - createMergeDeclarationMarker: createMergeDeclarationMarker, createSyntheticReferenceExpression: createSyntheticReferenceExpression, updateSyntheticReferenceExpression: updateSyntheticReferenceExpression, cloneNode: cloneNode, // Lazily load factory methods for common operator factories and utilities get createComma () { - return getBinaryCreateFunction(27 /* CommaToken */ ); + return getBinaryCreateFunction(28 /* CommaToken */ ); }, get createAssignment () { - return getBinaryCreateFunction(63 /* EqualsToken */ ); + return getBinaryCreateFunction(64 /* EqualsToken */ ); }, get createLogicalOr () { - return getBinaryCreateFunction(56 /* BarBarToken */ ); + return getBinaryCreateFunction(57 /* BarBarToken */ ); }, get createLogicalAnd () { - return getBinaryCreateFunction(55 /* AmpersandAmpersandToken */ ); + return getBinaryCreateFunction(56 /* AmpersandAmpersandToken */ ); }, get createBitwiseOr () { - return getBinaryCreateFunction(51 /* BarToken */ ); + return getBinaryCreateFunction(52 /* BarToken */ ); }, get createBitwiseXor () { - return getBinaryCreateFunction(52 /* CaretToken */ ); + return getBinaryCreateFunction(53 /* CaretToken */ ); }, get createBitwiseAnd () { - return getBinaryCreateFunction(50 /* AmpersandToken */ ); + return getBinaryCreateFunction(51 /* AmpersandToken */ ); }, get createStrictEquality () { - return getBinaryCreateFunction(36 /* EqualsEqualsEqualsToken */ ); + return getBinaryCreateFunction(37 /* EqualsEqualsEqualsToken */ ); }, get createStrictInequality () { - return getBinaryCreateFunction(37 /* ExclamationEqualsEqualsToken */ ); + return getBinaryCreateFunction(38 /* ExclamationEqualsEqualsToken */ ); }, get createEquality () { - return getBinaryCreateFunction(34 /* EqualsEqualsToken */ ); + return getBinaryCreateFunction(35 /* EqualsEqualsToken */ ); }, get createInequality () { - return getBinaryCreateFunction(35 /* ExclamationEqualsToken */ ); + return getBinaryCreateFunction(36 /* ExclamationEqualsToken */ ); }, get createLessThan () { - return getBinaryCreateFunction(29 /* LessThanToken */ ); + return getBinaryCreateFunction(30 /* LessThanToken */ ); }, get createLessThanEquals () { - return getBinaryCreateFunction(32 /* LessThanEqualsToken */ ); + return getBinaryCreateFunction(33 /* LessThanEqualsToken */ ); }, get createGreaterThan () { - return getBinaryCreateFunction(31 /* GreaterThanToken */ ); + return getBinaryCreateFunction(32 /* GreaterThanToken */ ); }, get createGreaterThanEquals () { - return getBinaryCreateFunction(33 /* GreaterThanEqualsToken */ ); + return getBinaryCreateFunction(34 /* GreaterThanEqualsToken */ ); }, get createLeftShift () { - return getBinaryCreateFunction(47 /* LessThanLessThanToken */ ); + return getBinaryCreateFunction(48 /* LessThanLessThanToken */ ); }, get createRightShift () { - return getBinaryCreateFunction(48 /* GreaterThanGreaterThanToken */ ); + return getBinaryCreateFunction(49 /* GreaterThanGreaterThanToken */ ); }, get createUnsignedRightShift () { - return getBinaryCreateFunction(49 /* GreaterThanGreaterThanGreaterThanToken */ ); + return getBinaryCreateFunction(50 /* GreaterThanGreaterThanGreaterThanToken */ ); }, get createAdd () { - return getBinaryCreateFunction(39 /* PlusToken */ ); + return getBinaryCreateFunction(40 /* PlusToken */ ); }, get createSubtract () { - return getBinaryCreateFunction(40 /* MinusToken */ ); + return getBinaryCreateFunction(41 /* MinusToken */ ); }, get createMultiply () { - return getBinaryCreateFunction(41 /* AsteriskToken */ ); + return getBinaryCreateFunction(42 /* AsteriskToken */ ); }, get createDivide () { - return getBinaryCreateFunction(43 /* SlashToken */ ); + return getBinaryCreateFunction(44 /* SlashToken */ ); }, get createModulo () { - return getBinaryCreateFunction(44 /* PercentToken */ ); + return getBinaryCreateFunction(45 /* PercentToken */ ); }, get createExponent () { - return getBinaryCreateFunction(42 /* AsteriskAsteriskToken */ ); + return getBinaryCreateFunction(43 /* AsteriskAsteriskToken */ ); }, get createPrefixPlus () { - return getPrefixUnaryCreateFunction(39 /* PlusToken */ ); + return getPrefixUnaryCreateFunction(40 /* PlusToken */ ); }, get createPrefixMinus () { - return getPrefixUnaryCreateFunction(40 /* MinusToken */ ); + return getPrefixUnaryCreateFunction(41 /* MinusToken */ ); }, get createPrefixIncrement () { - return getPrefixUnaryCreateFunction(45 /* PlusPlusToken */ ); + return getPrefixUnaryCreateFunction(46 /* PlusPlusToken */ ); }, get createPrefixDecrement () { - return getPrefixUnaryCreateFunction(46 /* MinusMinusToken */ ); + return getPrefixUnaryCreateFunction(47 /* MinusMinusToken */ ); }, get createBitwiseNot () { - return getPrefixUnaryCreateFunction(54 /* TildeToken */ ); + return getPrefixUnaryCreateFunction(55 /* TildeToken */ ); }, get createLogicalNot () { - return getPrefixUnaryCreateFunction(53 /* ExclamationToken */ ); + return getPrefixUnaryCreateFunction(54 /* ExclamationToken */ ); }, get createPostfixIncrement () { - return getPostfixUnaryCreateFunction(45 /* PlusPlusToken */ ); + return getPostfixUnaryCreateFunction(46 /* PlusPlusToken */ ); }, get createPostfixDecrement () { - return getPostfixUnaryCreateFunction(46 /* MinusMinusToken */ ); + return getPostfixUnaryCreateFunction(47 /* MinusMinusToken */ ); }, createImmediatelyInvokedFunctionExpression: // Compound nodes createImmediatelyInvokedFunctionExpression, @@ -23587,6 +23755,7 @@ ${lanes.join("\n")} createExportDefault: createExportDefault, createExternalModuleExport: createExternalModuleExport, createTypeCheck: createTypeCheck, + createIsNotTypeCheck: createIsNotTypeCheck, createMethodCall: createMethodCall, createGlobalMethodCall: createGlobalMethodCall, createFunctionBindCall: createFunctionBindCall, @@ -23618,7 +23787,8 @@ ${lanes.join("\n")} ensureUseStrict: ensureUseStrict, liftToBlock: liftToBlock, mergeLexicalEnvironment: mergeLexicalEnvironment, - updateModifiers: updateModifiers + updateModifiers: updateModifiers, + updateModifierLike: updateModifierLike }; forEach(nodeFactoryPatchers, (fn)=>fn(factory2)); return factory2; @@ -23662,20 +23832,20 @@ ${lanes.join("\n")} return update(updated, original); } function createNumericLiteral(value1, numericLiteralFlags = 0 /* None */ ) { - const node = createBaseDeclaration(8 /* NumericLiteral */ ); + const node = createBaseDeclaration(9 /* NumericLiteral */ ); node.text = typeof value1 === "number" ? value1 + "" : value1; node.numericLiteralFlags = numericLiteralFlags; if (numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */ ) node.transformFlags |= 1024 /* ContainsES2015 */ ; return node; } function createBigIntLiteral(value1) { - const node = createBaseToken(9 /* BigIntLiteral */ ); + const node = createBaseToken(10 /* BigIntLiteral */ ); node.text = typeof value1 === "string" ? value1 : pseudoBigIntToString(value1) + "n"; - node.transformFlags |= 4 /* ContainsESNext */ ; + node.transformFlags |= 32 /* ContainsES2020 */ ; return node; } function createBaseStringLiteral(text, isSingleQuote) { - const node = createBaseDeclaration(10 /* StringLiteral */ ); + const node = createBaseDeclaration(11 /* StringLiteral */ ); node.text = text; node.singleQuote = isSingleQuote; return node; @@ -23692,30 +23862,30 @@ ${lanes.join("\n")} return node; } function createRegularExpressionLiteral(text) { - const node = createBaseToken(13 /* RegularExpressionLiteral */ ); + const node = createBaseToken(14 /* RegularExpressionLiteral */ ); node.text = text; return node; } function createLiteralLikeNode(kind, text) { switch(kind){ - case 8 /* NumericLiteral */ : + case 9 /* NumericLiteral */ : return createNumericLiteral(text, /*numericLiteralFlags*/ 0); - case 9 /* BigIntLiteral */ : + case 10 /* BigIntLiteral */ : return createBigIntLiteral(text); - case 10 /* StringLiteral */ : + case 11 /* StringLiteral */ : return createStringLiteral(text, /*isSingleQuote*/ void 0); - case 11 /* JsxText */ : + case 12 /* JsxText */ : return createJsxText(text, /*containsOnlyTriviaWhiteSpaces*/ false); - case 12 /* JsxTextAllWhiteSpaces */ : + case 13 /* JsxTextAllWhiteSpaces */ : return createJsxText(text, /*containsOnlyTriviaWhiteSpaces*/ true); - case 13 /* RegularExpressionLiteral */ : + case 14 /* RegularExpressionLiteral */ : return createRegularExpressionLiteral(text); - case 14 /* NoSubstitutionTemplateLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : return createTemplateLiteralLikeNode(kind, text, /*rawText*/ void 0, /*templateFlags*/ 0); } } function createBaseIdentifier(escapedText) { - const node = baseFactory2.createBaseIdentifierNode(79 /* Identifier */ ); + const node = baseFactory2.createBaseIdentifierNode(80 /* Identifier */ ); node.escapedText = escapedText; node.jsDoc = void 0; node.flowNode = void 0; @@ -23735,11 +23905,11 @@ ${lanes.join("\n")} } function createIdentifier(text, originalKeywordKind, hasExtendedUnicodeEscape) { if (originalKeywordKind === void 0 && text) originalKeywordKind = stringToToken(text); - if (originalKeywordKind === 79 /* Identifier */ ) originalKeywordKind = void 0; + if (originalKeywordKind === 80 /* Identifier */ ) originalKeywordKind = void 0; const node = createBaseIdentifier(escapeLeadingUnderscores(text)); - if (hasExtendedUnicodeEscape) node.flags |= 128 /* IdentifierHasExtendedUnicodeEscape */ ; + if (hasExtendedUnicodeEscape) node.flags |= 256 /* IdentifierHasExtendedUnicodeEscape */ ; if (node.escapedText === "await") node.transformFlags |= 67108864 /* ContainsPossibleTopLevelAwait */ ; - if (node.flags & 128 /* IdentifierHasExtendedUnicodeEscape */ ) node.transformFlags |= 1024 /* ContainsES2015 */ ; + if (node.flags & 256 /* IdentifierHasExtendedUnicodeEscape */ ) node.transformFlags |= 1024 /* ContainsES2015 */ ; return node; } function createTempVariable(recordTempVariable, reservedInNestedScopes, prefix, suffix) { @@ -23768,7 +23938,7 @@ ${lanes.join("\n")} return name; } function createBasePrivateIdentifier(escapedText) { - const node = baseFactory2.createBasePrivateIdentifierNode(80 /* PrivateIdentifier */ ); + const node = baseFactory2.createBasePrivateIdentifierNode(81 /* PrivateIdentifier */ ); node.escapedText = escapedText; node.transformFlags |= 16777216 /* ContainsClassFields */ ; return node; @@ -23791,7 +23961,7 @@ ${lanes.join("\n")} function createUniquePrivateName(text, prefix, suffix) { if (text && !startsWith(text, "#")) Debug.fail("First character of private identifier must be #: " + text); const autoGenerateFlags = 8 /* ReservedInNestedScopes */ | (text ? 3 /* Unique */ : 1 /* Auto */ ); - return createBaseGeneratedPrivateIdentifier(text != null ? text : "", autoGenerateFlags, prefix, suffix); + return createBaseGeneratedPrivateIdentifier(text ?? "", autoGenerateFlags, prefix, suffix); } function getGeneratedPrivateNameForNode(node, prefix, suffix) { const text = isMemberName(node) ? formatGeneratedName(/*privateName*/ true, prefix, node, suffix, idText) : `#generated@${getNodeId(node)}`; @@ -23804,50 +23974,53 @@ ${lanes.join("\n")} return baseFactory2.createBaseTokenNode(kind); } function createToken(token) { - Debug.assert(token >= 0 /* FirstToken */ && token <= 162 /* LastToken */ , "Invalid token"); - Debug.assert(token <= 14 /* FirstTemplateToken */ || token >= 17 /* LastTemplateToken */ , "Invalid token. Use 'createTemplateLiteralLikeNode' to create template literals."); - Debug.assert(token <= 8 /* FirstLiteralToken */ || token >= 14 /* LastLiteralToken */ , "Invalid token. Use 'createLiteralLikeNode' to create literals."); - Debug.assert(token !== 79 /* Identifier */ , "Invalid token. Use 'createIdentifier' to create identifiers"); + Debug.assert(token >= 0 /* FirstToken */ && token <= 165 /* LastToken */ , "Invalid token"); + Debug.assert(token <= 15 /* FirstTemplateToken */ || token >= 18 /* LastTemplateToken */ , "Invalid token. Use 'createTemplateLiteralLikeNode' to create template literals."); + Debug.assert(token <= 9 /* FirstLiteralToken */ || token >= 15 /* LastLiteralToken */ , "Invalid token. Use 'createLiteralLikeNode' to create literals."); + Debug.assert(token !== 80 /* Identifier */ , "Invalid token. Use 'createIdentifier' to create identifiers"); const node = createBaseToken(token); let transformFlags = 0 /* None */ ; switch(token){ - case 132 /* AsyncKeyword */ : + case 134 /* AsyncKeyword */ : transformFlags = 384 /* ContainsES2018 */ ; break; - case 123 /* PublicKeyword */ : - case 121 /* PrivateKeyword */ : - case 122 /* ProtectedKeyword */ : - case 146 /* ReadonlyKeyword */ : - case 126 /* AbstractKeyword */ : - case 136 /* DeclareKeyword */ : - case 85 /* ConstKeyword */ : - case 131 /* AnyKeyword */ : - case 148 /* NumberKeyword */ : - case 160 /* BigIntKeyword */ : - case 144 /* NeverKeyword */ : - case 149 /* ObjectKeyword */ : - case 101 /* InKeyword */ : - case 145 /* OutKeyword */ : - case 161 /* OverrideKeyword */ : - case 152 /* StringKeyword */ : - case 134 /* BooleanKeyword */ : - case 153 /* SymbolKeyword */ : - case 114 /* VoidKeyword */ : - case 157 /* UnknownKeyword */ : - case 155 /* UndefinedKeyword */ : + case 160 /* UsingKeyword */ : + transformFlags = 4 /* ContainsESNext */ ; + break; + case 125 /* PublicKeyword */ : + case 123 /* PrivateKeyword */ : + case 124 /* ProtectedKeyword */ : + case 148 /* ReadonlyKeyword */ : + case 128 /* AbstractKeyword */ : + case 138 /* DeclareKeyword */ : + case 87 /* ConstKeyword */ : + case 133 /* AnyKeyword */ : + case 150 /* NumberKeyword */ : + case 163 /* BigIntKeyword */ : + case 146 /* NeverKeyword */ : + case 151 /* ObjectKeyword */ : + case 103 /* InKeyword */ : + case 147 /* OutKeyword */ : + case 164 /* OverrideKeyword */ : + case 154 /* StringKeyword */ : + case 136 /* BooleanKeyword */ : + case 155 /* SymbolKeyword */ : + case 116 /* VoidKeyword */ : + case 159 /* UnknownKeyword */ : + case 157 /* UndefinedKeyword */ : transformFlags = 1 /* ContainsTypeScript */ ; break; - case 106 /* SuperKeyword */ : + case 108 /* SuperKeyword */ : transformFlags = 134218752 /* ContainsLexicalSuper */ ; node.flowNode = void 0; break; - case 124 /* StaticKeyword */ : + case 126 /* StaticKeyword */ : transformFlags = 1024 /* ContainsES2015 */ ; break; - case 127 /* AccessorKeyword */ : + case 129 /* AccessorKeyword */ : transformFlags = 16777216 /* ContainsClassFields */ ; break; - case 108 /* ThisKeyword */ : + case 110 /* ThisKeyword */ : transformFlags = 16384 /* ContainsLexicalThis */ ; node.flowNode = void 0; break; @@ -23856,44 +24029,44 @@ ${lanes.join("\n")} return node; } function createSuper() { - return createToken(106 /* SuperKeyword */ ); + return createToken(108 /* SuperKeyword */ ); } function createThis() { - return createToken(108 /* ThisKeyword */ ); + return createToken(110 /* ThisKeyword */ ); } function createNull() { - return createToken(104 /* NullKeyword */ ); + return createToken(106 /* NullKeyword */ ); } function createTrue() { - return createToken(110 /* TrueKeyword */ ); + return createToken(112 /* TrueKeyword */ ); } function createFalse() { - return createToken(95 /* FalseKeyword */ ); + return createToken(97 /* FalseKeyword */ ); } function createModifier(kind) { return createToken(kind); } function createModifiersFromModifierFlags(flags2) { const result = []; - if (flags2 & 1 /* Export */ ) result.push(createModifier(93 /* ExportKeyword */ )); - if (flags2 & 2 /* Ambient */ ) result.push(createModifier(136 /* DeclareKeyword */ )); - if (flags2 & 1024 /* Default */ ) result.push(createModifier(88 /* DefaultKeyword */ )); - if (flags2 & 2048 /* Const */ ) result.push(createModifier(85 /* ConstKeyword */ )); - if (flags2 & 4 /* Public */ ) result.push(createModifier(123 /* PublicKeyword */ )); - if (flags2 & 8 /* Private */ ) result.push(createModifier(121 /* PrivateKeyword */ )); - if (flags2 & 16 /* Protected */ ) result.push(createModifier(122 /* ProtectedKeyword */ )); - if (flags2 & 256 /* Abstract */ ) result.push(createModifier(126 /* AbstractKeyword */ )); - if (flags2 & 32 /* Static */ ) result.push(createModifier(124 /* StaticKeyword */ )); - if (flags2 & 16384 /* Override */ ) result.push(createModifier(161 /* OverrideKeyword */ )); - if (flags2 & 64 /* Readonly */ ) result.push(createModifier(146 /* ReadonlyKeyword */ )); - if (flags2 & 128 /* Accessor */ ) result.push(createModifier(127 /* AccessorKeyword */ )); - if (flags2 & 512 /* Async */ ) result.push(createModifier(132 /* AsyncKeyword */ )); - if (flags2 & 32768 /* In */ ) result.push(createModifier(101 /* InKeyword */ )); - if (flags2 & 65536 /* Out */ ) result.push(createModifier(145 /* OutKeyword */ )); + if (flags2 & 1 /* Export */ ) result.push(createModifier(95 /* ExportKeyword */ )); + if (flags2 & 2 /* Ambient */ ) result.push(createModifier(138 /* DeclareKeyword */ )); + if (flags2 & 1024 /* Default */ ) result.push(createModifier(90 /* DefaultKeyword */ )); + if (flags2 & 2048 /* Const */ ) result.push(createModifier(87 /* ConstKeyword */ )); + if (flags2 & 4 /* Public */ ) result.push(createModifier(125 /* PublicKeyword */ )); + if (flags2 & 8 /* Private */ ) result.push(createModifier(123 /* PrivateKeyword */ )); + if (flags2 & 16 /* Protected */ ) result.push(createModifier(124 /* ProtectedKeyword */ )); + if (flags2 & 256 /* Abstract */ ) result.push(createModifier(128 /* AbstractKeyword */ )); + if (flags2 & 32 /* Static */ ) result.push(createModifier(126 /* StaticKeyword */ )); + if (flags2 & 16384 /* Override */ ) result.push(createModifier(164 /* OverrideKeyword */ )); + if (flags2 & 64 /* Readonly */ ) result.push(createModifier(148 /* ReadonlyKeyword */ )); + if (flags2 & 128 /* Accessor */ ) result.push(createModifier(129 /* AccessorKeyword */ )); + if (flags2 & 512 /* Async */ ) result.push(createModifier(134 /* AsyncKeyword */ )); + if (flags2 & 32768 /* In */ ) result.push(createModifier(103 /* InKeyword */ )); + if (flags2 & 65536 /* Out */ ) result.push(createModifier(147 /* OutKeyword */ )); return result.length ? result : void 0; } function createQualifiedName(left, right) { - const node = createBaseNode(163 /* QualifiedName */ ); + const node = createBaseNode(166 /* QualifiedName */ ); node.left = left; node.right = asName(right); node.transformFlags |= propagateChildFlags(node.left) | propagateIdentifierNameFlags(node.right); @@ -23904,7 +24077,7 @@ ${lanes.join("\n")} return node.left !== left || node.right !== right ? update(createQualifiedName(left, right), node) : node; } function createComputedPropertyName(expression) { - const node = createBaseNode(164 /* ComputedPropertyName */ ); + const node = createBaseNode(167 /* ComputedPropertyName */ ); node.expression = parenthesizerRules().parenthesizeExpressionOfComputedPropertyName(expression); node.transformFlags |= propagateChildFlags(node.expression) | 132096 /* ContainsComputedPropertyName */ ; return node; @@ -23913,7 +24086,7 @@ ${lanes.join("\n")} return node.expression !== expression ? update(createComputedPropertyName(expression), node) : node; } function createTypeParameterDeclaration(modifiers, name, constraint, defaultType) { - const node = createBaseDeclaration(165 /* TypeParameter */ ); + const node = createBaseDeclaration(168 /* TypeParameter */ ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.constraint = constraint; @@ -23927,8 +24100,7 @@ ${lanes.join("\n")} return node.modifiers !== modifiers || node.name !== name || node.constraint !== constraint || node.default !== defaultType ? update(createTypeParameterDeclaration(modifiers, name, constraint, defaultType), node) : node; } function createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var _a2, _b; - const node = createBaseDeclaration(166 /* Parameter */ ); + const node = createBaseDeclaration(169 /* Parameter */ ); node.modifiers = asNodeArray(modifiers); node.dotDotDotToken = dotDotDotToken; node.name = asName(name); @@ -23936,7 +24108,7 @@ ${lanes.join("\n")} node.type = type; node.initializer = asInitializer(initializer); if (isThisIdentifier(node.name)) node.transformFlags = 1 /* ContainsTypeScript */ ; - else node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.dotDotDotToken) | propagateNameFlags(node.name) | propagateChildFlags(node.questionToken) | propagateChildFlags(node.initializer) | (((_a2 = node.questionToken) != null ? _a2 : node.type) ? 1 /* ContainsTypeScript */ : 0 /* None */ ) | (((_b = node.dotDotDotToken) != null ? _b : node.initializer) ? 1024 /* ContainsES2015 */ : 0 /* None */ ) | (modifiersToFlags(node.modifiers) & 16476 /* ParameterPropertyModifier */ ? 8192 /* ContainsTypeScriptClassSyntax */ : 0 /* None */ ); + else node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.dotDotDotToken) | propagateNameFlags(node.name) | propagateChildFlags(node.questionToken) | propagateChildFlags(node.initializer) | (node.questionToken ?? node.type ? 1 /* ContainsTypeScript */ : 0 /* None */ ) | (node.dotDotDotToken ?? node.initializer ? 1024 /* ContainsES2015 */ : 0 /* None */ ) | (modifiersToFlags(node.modifiers) & 16476 /* ParameterPropertyModifier */ ? 8192 /* ContainsTypeScriptClassSyntax */ : 0 /* None */ ); node.jsDoc = void 0; return node; } @@ -23944,7 +24116,7 @@ ${lanes.join("\n")} return node.modifiers !== modifiers || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer ? update(createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer), node) : node; } function createDecorator(expression) { - const node = createBaseNode(167 /* Decorator */ ); + const node = createBaseNode(170 /* Decorator */ ); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.transformFlags |= propagateChildFlags(node.expression) | 33562625 /* ContainsDecorators */ ; return node; @@ -23953,7 +24125,7 @@ ${lanes.join("\n")} return node.expression !== expression ? update(createDecorator(expression), node) : node; } function createPropertySignature(modifiers, name, questionToken, type) { - const node = createBaseDeclaration(168 /* PropertySignature */ ); + const node = createBaseDeclaration(171 /* PropertySignature */ ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.type = type; @@ -23971,14 +24143,14 @@ ${lanes.join("\n")} return update(updated, original); } function createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer) { - const node = createBaseDeclaration(169 /* PropertyDeclaration */ ); + const node = createBaseDeclaration(172 /* PropertyDeclaration */ ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.questionToken = questionOrExclamationToken && isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : void 0; node.exclamationToken = questionOrExclamationToken && isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : void 0; node.type = type; node.initializer = asInitializer(initializer); - const isAmbient = node.flags & 16777216 /* Ambient */ || modifiersToFlags(node.modifiers) & 2 /* Ambient */ ; + const isAmbient = node.flags & 33554432 /* Ambient */ || modifiersToFlags(node.modifiers) & 2 /* Ambient */ ; node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildFlags(node.initializer) | (isAmbient || node.questionToken || node.exclamationToken || node.type ? 1 /* ContainsTypeScript */ : 0 /* None */ ) | (isComputedPropertyName(node.name) || modifiersToFlags(node.modifiers) & 32 /* Static */ && node.initializer ? 8192 /* ContainsTypeScriptClassSyntax */ : 0 /* None */ ) | 16777216 /* ContainsClassFields */ ; node.jsDoc = void 0; return node; @@ -23987,7 +24159,7 @@ ${lanes.join("\n")} return node.modifiers !== modifiers || node.name !== name || node.questionToken !== (questionOrExclamationToken !== void 0 && isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : void 0) || node.exclamationToken !== (questionOrExclamationToken !== void 0 && isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : void 0) || node.type !== type || node.initializer !== initializer ? update(createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer), node) : node; } function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) { - const node = createBaseDeclaration(170 /* MethodSignature */ ); + const node = createBaseDeclaration(173 /* MethodSignature */ ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.questionToken = questionToken; @@ -24005,7 +24177,7 @@ ${lanes.join("\n")} return node.modifiers !== modifiers || node.name !== name || node.questionToken !== questionToken || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? finishUpdateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node) : node; } function createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - const node = createBaseDeclaration(171 /* MethodDeclaration */ ); + const node = createBaseDeclaration(174 /* MethodDeclaration */ ); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; node.name = asName(name); @@ -24039,7 +24211,7 @@ ${lanes.join("\n")} return update(updated, original); } function createClassStaticBlockDeclaration(body) { - const node = createBaseDeclaration(172 /* ClassStaticBlockDeclaration */ ); + const node = createBaseDeclaration(175 /* ClassStaticBlockDeclaration */ ); node.body = body; node.transformFlags = propagateChildFlags(body) | 16777216 /* ContainsClassFields */ ; node.modifiers = void 0; @@ -24058,7 +24230,7 @@ ${lanes.join("\n")} return update(updated, original); } function createConstructorDeclaration(modifiers, parameters, body) { - const node = createBaseDeclaration(173 /* Constructor */ ); + const node = createBaseDeclaration(176 /* Constructor */ ); node.modifiers = asNodeArray(modifiers); node.parameters = createNodeArray(parameters); node.body = body; @@ -24084,7 +24256,7 @@ ${lanes.join("\n")} return finishUpdateBaseSignatureDeclaration(updated, original); } function createGetAccessorDeclaration(modifiers, name, parameters, type, body) { - const node = createBaseDeclaration(174 /* GetAccessor */ ); + const node = createBaseDeclaration(177 /* GetAccessor */ ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.parameters = createNodeArray(parameters); @@ -24110,7 +24282,7 @@ ${lanes.join("\n")} return finishUpdateBaseSignatureDeclaration(updated, original); } function createSetAccessorDeclaration(modifiers, name, parameters, body) { - const node = createBaseDeclaration(175 /* SetAccessor */ ); + const node = createBaseDeclaration(178 /* SetAccessor */ ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.parameters = createNodeArray(parameters); @@ -24139,7 +24311,7 @@ ${lanes.join("\n")} return finishUpdateBaseSignatureDeclaration(updated, original); } function createCallSignature(typeParameters, parameters, type) { - const node = createBaseDeclaration(176 /* CallSignature */ ); + const node = createBaseDeclaration(179 /* CallSignature */ ); node.typeParameters = asNodeArray(typeParameters); node.parameters = asNodeArray(parameters); node.type = type; @@ -24154,7 +24326,7 @@ ${lanes.join("\n")} return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? finishUpdateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node) : node; } function createConstructSignature(typeParameters, parameters, type) { - const node = createBaseDeclaration(177 /* ConstructSignature */ ); + const node = createBaseDeclaration(180 /* ConstructSignature */ ); node.typeParameters = asNodeArray(typeParameters); node.parameters = asNodeArray(parameters); node.type = type; @@ -24169,7 +24341,7 @@ ${lanes.join("\n")} return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? finishUpdateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node) : node; } function createIndexSignature(modifiers, parameters, type) { - const node = createBaseDeclaration(178 /* IndexSignature */ ); + const node = createBaseDeclaration(181 /* IndexSignature */ ); node.modifiers = asNodeArray(modifiers); node.parameters = asNodeArray(parameters); node.type = type; @@ -24184,7 +24356,7 @@ ${lanes.join("\n")} return node.parameters !== parameters || node.type !== type || node.modifiers !== modifiers ? finishUpdateBaseSignatureDeclaration(createIndexSignature(modifiers, parameters, type), node) : node; } function createTemplateLiteralTypeSpan(type, literal) { - const node = createBaseNode(201 /* TemplateLiteralTypeSpan */ ); + const node = createBaseNode(204 /* TemplateLiteralTypeSpan */ ); node.type = type; node.literal = literal; node.transformFlags = 1 /* ContainsTypeScript */ ; @@ -24197,7 +24369,7 @@ ${lanes.join("\n")} return createToken(kind); } function createTypePredicateNode(assertsModifier, parameterName, type) { - const node = createBaseNode(179 /* TypePredicate */ ); + const node = createBaseNode(182 /* TypePredicate */ ); node.assertsModifier = assertsModifier; node.parameterName = asName(parameterName); node.type = type; @@ -24208,7 +24380,7 @@ ${lanes.join("\n")} return node.assertsModifier !== assertsModifier || node.parameterName !== parameterName || node.type !== type ? update(createTypePredicateNode(assertsModifier, parameterName, type), node) : node; } function createTypeReferenceNode(typeName, typeArguments) { - const node = createBaseNode(180 /* TypeReference */ ); + const node = createBaseNode(183 /* TypeReference */ ); node.typeName = asName(typeName); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(createNodeArray(typeArguments)); node.transformFlags = 1 /* ContainsTypeScript */ ; @@ -24218,7 +24390,7 @@ ${lanes.join("\n")} return node.typeName !== typeName || node.typeArguments !== typeArguments ? update(createTypeReferenceNode(typeName, typeArguments), node) : node; } function createFunctionTypeNode(typeParameters, parameters, type) { - const node = createBaseDeclaration(181 /* FunctionType */ ); + const node = createBaseDeclaration(184 /* FunctionType */ ); node.typeParameters = asNodeArray(typeParameters); node.parameters = asNodeArray(parameters); node.type = type; @@ -24241,7 +24413,7 @@ ${lanes.join("\n")} return args.length === 4 ? createConstructorTypeNode1(...args) : args.length === 3 ? createConstructorTypeNode2(...args) : Debug.fail("Incorrect number of arguments specified."); } function createConstructorTypeNode1(modifiers, typeParameters, parameters, type) { - const node = createBaseDeclaration(182 /* ConstructorType */ ); + const node = createBaseDeclaration(185 /* ConstructorType */ ); node.modifiers = asNodeArray(modifiers); node.typeParameters = asNodeArray(typeParameters); node.parameters = asNodeArray(parameters); @@ -24266,7 +24438,7 @@ ${lanes.join("\n")} return updateConstructorTypeNode1(node, node.modifiers, typeParameters, parameters, type); } function createTypeQueryNode(exprName, typeArguments) { - const node = createBaseNode(183 /* TypeQuery */ ); + const node = createBaseNode(186 /* TypeQuery */ ); node.exprName = exprName; node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.transformFlags = 1 /* ContainsTypeScript */ ; @@ -24276,7 +24448,7 @@ ${lanes.join("\n")} return node.exprName !== exprName || node.typeArguments !== typeArguments ? update(createTypeQueryNode(exprName, typeArguments), node) : node; } function createTypeLiteralNode(members) { - const node = createBaseDeclaration(184 /* TypeLiteral */ ); + const node = createBaseDeclaration(187 /* TypeLiteral */ ); node.members = createNodeArray(members); node.transformFlags = 1 /* ContainsTypeScript */ ; return node; @@ -24285,7 +24457,7 @@ ${lanes.join("\n")} return node.members !== members ? update(createTypeLiteralNode(members), node) : node; } function createArrayTypeNode(elementType) { - const node = createBaseNode(185 /* ArrayType */ ); + const node = createBaseNode(188 /* ArrayType */ ); node.elementType = parenthesizerRules().parenthesizeNonArrayTypeOfPostfixType(elementType); node.transformFlags = 1 /* ContainsTypeScript */ ; return node; @@ -24294,7 +24466,7 @@ ${lanes.join("\n")} return node.elementType !== elementType ? update(createArrayTypeNode(elementType), node) : node; } function createTupleTypeNode(elements) { - const node = createBaseNode(186 /* TupleType */ ); + const node = createBaseNode(189 /* TupleType */ ); node.elements = createNodeArray(parenthesizerRules().parenthesizeElementTypesOfTupleType(elements)); node.transformFlags = 1 /* ContainsTypeScript */ ; return node; @@ -24303,7 +24475,7 @@ ${lanes.join("\n")} return node.elements !== elements ? update(createTupleTypeNode(elements), node) : node; } function createNamedTupleMember(dotDotDotToken, name, questionToken, type) { - const node = createBaseDeclaration(199 /* NamedTupleMember */ ); + const node = createBaseDeclaration(202 /* NamedTupleMember */ ); node.dotDotDotToken = dotDotDotToken; node.name = name; node.questionToken = questionToken; @@ -24316,7 +24488,7 @@ ${lanes.join("\n")} return node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.questionToken !== questionToken || node.type !== type ? update(createNamedTupleMember(dotDotDotToken, name, questionToken, type), node) : node; } function createOptionalTypeNode(type) { - const node = createBaseNode(187 /* OptionalType */ ); + const node = createBaseNode(190 /* OptionalType */ ); node.type = parenthesizerRules().parenthesizeTypeOfOptionalType(type); node.transformFlags = 1 /* ContainsTypeScript */ ; return node; @@ -24325,7 +24497,7 @@ ${lanes.join("\n")} return node.type !== type ? update(createOptionalTypeNode(type), node) : node; } function createRestTypeNode(type) { - const node = createBaseNode(188 /* RestType */ ); + const node = createBaseNode(191 /* RestType */ ); node.type = type; node.transformFlags = 1 /* ContainsTypeScript */ ; return node; @@ -24343,19 +24515,19 @@ ${lanes.join("\n")} return node.types !== types ? update(createUnionOrIntersectionTypeNode(node.kind, types, parenthesize), node) : node; } function createUnionTypeNode(types) { - return createUnionOrIntersectionTypeNode(189 /* UnionType */ , types, parenthesizerRules().parenthesizeConstituentTypesOfUnionType); + return createUnionOrIntersectionTypeNode(192 /* UnionType */ , types, parenthesizerRules().parenthesizeConstituentTypesOfUnionType); } function updateUnionTypeNode(node, types) { return updateUnionOrIntersectionTypeNode(node, types, parenthesizerRules().parenthesizeConstituentTypesOfUnionType); } function createIntersectionTypeNode(types) { - return createUnionOrIntersectionTypeNode(190 /* IntersectionType */ , types, parenthesizerRules().parenthesizeConstituentTypesOfIntersectionType); + return createUnionOrIntersectionTypeNode(193 /* IntersectionType */ , types, parenthesizerRules().parenthesizeConstituentTypesOfIntersectionType); } function updateIntersectionTypeNode(node, types) { return updateUnionOrIntersectionTypeNode(node, types, parenthesizerRules().parenthesizeConstituentTypesOfIntersectionType); } function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { - const node = createBaseNode(191 /* ConditionalType */ ); + const node = createBaseNode(194 /* ConditionalType */ ); node.checkType = parenthesizerRules().parenthesizeCheckTypeOfConditionalType(checkType); node.extendsType = parenthesizerRules().parenthesizeExtendsTypeOfConditionalType(extendsType); node.trueType = trueType; @@ -24369,7 +24541,7 @@ ${lanes.join("\n")} return node.checkType !== checkType || node.extendsType !== extendsType || node.trueType !== trueType || node.falseType !== falseType ? update(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node) : node; } function createInferTypeNode(typeParameter) { - const node = createBaseNode(192 /* InferType */ ); + const node = createBaseNode(195 /* InferType */ ); node.typeParameter = typeParameter; node.transformFlags = 1 /* ContainsTypeScript */ ; return node; @@ -24378,7 +24550,7 @@ ${lanes.join("\n")} return node.typeParameter !== typeParameter ? update(createInferTypeNode(typeParameter), node) : node; } function createTemplateLiteralType(head, templateSpans) { - const node = createBaseNode(200 /* TemplateLiteralType */ ); + const node = createBaseNode(203 /* TemplateLiteralType */ ); node.head = head; node.templateSpans = createNodeArray(templateSpans); node.transformFlags = 1 /* ContainsTypeScript */ ; @@ -24388,7 +24560,7 @@ ${lanes.join("\n")} return node.head !== head || node.templateSpans !== templateSpans ? update(createTemplateLiteralType(head, templateSpans), node) : node; } function createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf = false) { - const node = createBaseNode(202 /* ImportType */ ); + const node = createBaseNode(205 /* ImportType */ ); node.argument = argument; node.assertions = assertions; node.qualifier = qualifier; @@ -24401,7 +24573,7 @@ ${lanes.join("\n")} return node.argument !== argument || node.assertions !== assertions || node.qualifier !== qualifier || node.typeArguments !== typeArguments || node.isTypeOf !== isTypeOf ? update(createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf), node) : node; } function createParenthesizedType(type) { - const node = createBaseNode(193 /* ParenthesizedType */ ); + const node = createBaseNode(196 /* ParenthesizedType */ ); node.type = type; node.transformFlags = 1 /* ContainsTypeScript */ ; return node; @@ -24410,14 +24582,14 @@ ${lanes.join("\n")} return node.type !== type ? update(createParenthesizedType(type), node) : node; } function createThisTypeNode() { - const node = createBaseNode(194 /* ThisType */ ); + const node = createBaseNode(197 /* ThisType */ ); node.transformFlags = 1 /* ContainsTypeScript */ ; return node; } function createTypeOperatorNode(operator, type) { - const node = createBaseNode(195 /* TypeOperator */ ); + const node = createBaseNode(198 /* TypeOperator */ ); node.operator = operator; - node.type = operator === 146 /* ReadonlyKeyword */ ? parenthesizerRules().parenthesizeOperandOfReadonlyTypeOperator(type) : parenthesizerRules().parenthesizeOperandOfTypeOperator(type); + node.type = operator === 148 /* ReadonlyKeyword */ ? parenthesizerRules().parenthesizeOperandOfReadonlyTypeOperator(type) : parenthesizerRules().parenthesizeOperandOfTypeOperator(type); node.transformFlags = 1 /* ContainsTypeScript */ ; return node; } @@ -24425,7 +24597,7 @@ ${lanes.join("\n")} return node.type !== type ? update(createTypeOperatorNode(node.operator, type), node) : node; } function createIndexedAccessTypeNode(objectType, indexType) { - const node = createBaseNode(196 /* IndexedAccessType */ ); + const node = createBaseNode(199 /* IndexedAccessType */ ); node.objectType = parenthesizerRules().parenthesizeNonArrayTypeOfPostfixType(objectType); node.indexType = indexType; node.transformFlags = 1 /* ContainsTypeScript */ ; @@ -24435,7 +24607,7 @@ ${lanes.join("\n")} return node.objectType !== objectType || node.indexType !== indexType ? update(createIndexedAccessTypeNode(objectType, indexType), node) : node; } function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members) { - const node = createBaseDeclaration(197 /* MappedType */ ); + const node = createBaseDeclaration(200 /* MappedType */ ); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.nameType = nameType; @@ -24451,7 +24623,7 @@ ${lanes.join("\n")} return node.readonlyToken !== readonlyToken || node.typeParameter !== typeParameter || node.nameType !== nameType || node.questionToken !== questionToken || node.type !== type || node.members !== members ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), node) : node; } function createLiteralTypeNode(literal) { - const node = createBaseNode(198 /* LiteralType */ ); + const node = createBaseNode(201 /* LiteralType */ ); node.literal = literal; node.transformFlags = 1 /* ContainsTypeScript */ ; return node; @@ -24460,7 +24632,7 @@ ${lanes.join("\n")} return node.literal !== literal ? update(createLiteralTypeNode(literal), node) : node; } function createObjectBindingPattern(elements) { - const node = createBaseNode(203 /* ObjectBindingPattern */ ); + const node = createBaseNode(206 /* ObjectBindingPattern */ ); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements) | 525312 /* ContainsBindingPattern */ ; if (node.transformFlags & 32768 /* ContainsRestOrSpread */ ) node.transformFlags |= 65664 /* ContainsObjectRestOrSpread */ ; @@ -24470,7 +24642,7 @@ ${lanes.join("\n")} return node.elements !== elements ? update(createObjectBindingPattern(elements), node) : node; } function createArrayBindingPattern(elements) { - const node = createBaseNode(204 /* ArrayBindingPattern */ ); + const node = createBaseNode(207 /* ArrayBindingPattern */ ); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements) | 525312 /* ContainsBindingPattern */ ; return node; @@ -24479,7 +24651,7 @@ ${lanes.join("\n")} return node.elements !== elements ? update(createArrayBindingPattern(elements), node) : node; } function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - const node = createBaseDeclaration(205 /* BindingElement */ ); + const node = createBaseDeclaration(208 /* BindingElement */ ); node.dotDotDotToken = dotDotDotToken; node.propertyName = asName(propertyName); node.name = asName(name); @@ -24492,7 +24664,7 @@ ${lanes.join("\n")} return node.propertyName !== propertyName || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.initializer !== initializer ? update(createBindingElement(dotDotDotToken, propertyName, name, initializer), node) : node; } function createArrayLiteralExpression(elements, multiLine) { - const node = createBaseNode(206 /* ArrayLiteralExpression */ ); + const node = createBaseNode(209 /* ArrayLiteralExpression */ ); const lastElement = elements && lastOrUndefined(elements); const elementsArray = createNodeArray(elements, lastElement && isOmittedExpression(lastElement) ? true : void 0); node.elements = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(elementsArray); @@ -24504,7 +24676,7 @@ ${lanes.join("\n")} return node.elements !== elements ? update(createArrayLiteralExpression(elements, node.multiLine), node) : node; } function createObjectLiteralExpression(properties, multiLine) { - const node = createBaseDeclaration(207 /* ObjectLiteralExpression */ ); + const node = createBaseDeclaration(210 /* ObjectLiteralExpression */ ); node.properties = createNodeArray(properties); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.properties); @@ -24515,7 +24687,7 @@ ${lanes.join("\n")} return node.properties !== properties ? update(createObjectLiteralExpression(properties, node.multiLine), node) : node; } function createBasePropertyAccessExpression(expression, questionDotToken, name) { - const node = createBaseDeclaration(208 /* PropertyAccessExpression */ ); + const node = createBaseDeclaration(211 /* PropertyAccessExpression */ ); node.expression = expression; node.questionDotToken = questionDotToken; node.name = name; @@ -24535,16 +24707,16 @@ ${lanes.join("\n")} } function createPropertyAccessChain(expression, questionDotToken, name) { const node = createBasePropertyAccessExpression(parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true), questionDotToken, asName(name)); - node.flags |= 32 /* OptionalChain */ ; + node.flags |= 64 /* OptionalChain */ ; node.transformFlags |= 32 /* ContainsES2020 */ ; return node; } function updatePropertyAccessChain(node, expression, questionDotToken, name) { - Debug.assert(!!(node.flags & 32 /* OptionalChain */ ), "Cannot update a PropertyAccessExpression using updatePropertyAccessChain. Use updatePropertyAccess instead."); + Debug.assert(!!(node.flags & 64 /* OptionalChain */ ), "Cannot update a PropertyAccessExpression using updatePropertyAccessChain. Use updatePropertyAccess instead."); return node.expression !== expression || node.questionDotToken !== questionDotToken || node.name !== name ? update(createPropertyAccessChain(expression, questionDotToken, name), node) : node; } function createBaseElementAccessExpression(expression, questionDotToken, argumentExpression) { - const node = createBaseDeclaration(209 /* ElementAccessExpression */ ); + const node = createBaseDeclaration(212 /* ElementAccessExpression */ ); node.expression = expression; node.questionDotToken = questionDotToken; node.argumentExpression = argumentExpression; @@ -24564,16 +24736,16 @@ ${lanes.join("\n")} } function createElementAccessChain(expression, questionDotToken, index) { const node = createBaseElementAccessExpression(parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true), questionDotToken, asExpression(index)); - node.flags |= 32 /* OptionalChain */ ; + node.flags |= 64 /* OptionalChain */ ; node.transformFlags |= 32 /* ContainsES2020 */ ; return node; } function updateElementAccessChain(node, expression, questionDotToken, argumentExpression) { - Debug.assert(!!(node.flags & 32 /* OptionalChain */ ), "Cannot update a ElementAccessExpression using updateElementAccessChain. Use updateElementAccess instead."); + Debug.assert(!!(node.flags & 64 /* OptionalChain */ ), "Cannot update a ElementAccessExpression using updateElementAccessChain. Use updateElementAccess instead."); return node.expression !== expression || node.questionDotToken !== questionDotToken || node.argumentExpression !== argumentExpression ? update(createElementAccessChain(expression, questionDotToken, argumentExpression), node) : node; } function createBaseCallExpression(expression, questionDotToken, typeArguments, argumentsArray) { - const node = createBaseDeclaration(210 /* CallExpression */ ); + const node = createBaseDeclaration(213 /* CallExpression */ ); node.expression = expression; node.questionDotToken = questionDotToken; node.typeArguments = typeArguments; @@ -24594,16 +24766,16 @@ ${lanes.join("\n")} } function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) { const node = createBaseCallExpression(parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true), questionDotToken, asNodeArray(typeArguments), parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray))); - node.flags |= 32 /* OptionalChain */ ; + node.flags |= 64 /* OptionalChain */ ; node.transformFlags |= 32 /* ContainsES2020 */ ; return node; } function updateCallChain(node, expression, questionDotToken, typeArguments, argumentsArray) { - Debug.assert(!!(node.flags & 32 /* OptionalChain */ ), "Cannot update a CallExpression using updateCallChain. Use updateCall instead."); + Debug.assert(!!(node.flags & 64 /* OptionalChain */ ), "Cannot update a CallExpression using updateCallChain. Use updateCall instead."); return node.expression !== expression || node.questionDotToken !== questionDotToken || node.typeArguments !== typeArguments || node.arguments !== argumentsArray ? update(createCallChain(expression, questionDotToken, typeArguments, argumentsArray), node) : node; } function createNewExpression(expression, typeArguments, argumentsArray) { - const node = createBaseDeclaration(211 /* NewExpression */ ); + const node = createBaseDeclaration(214 /* NewExpression */ ); node.expression = parenthesizerRules().parenthesizeExpressionOfNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(argumentsArray) : void 0; @@ -24615,7 +24787,7 @@ ${lanes.join("\n")} return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray ? update(createNewExpression(expression, typeArguments, argumentsArray), node) : node; } function createTaggedTemplateExpression(tag, typeArguments, template) { - const node = createBaseNode(212 /* TaggedTemplateExpression */ ); + const node = createBaseNode(215 /* TaggedTemplateExpression */ ); node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag, /*optionalChain*/ false); node.typeArguments = asNodeArray(typeArguments); node.template = template; @@ -24628,7 +24800,7 @@ ${lanes.join("\n")} return node.tag !== tag || node.typeArguments !== typeArguments || node.template !== template ? update(createTaggedTemplateExpression(tag, typeArguments, template), node) : node; } function createTypeAssertion(type, expression) { - const node = createBaseNode(213 /* TypeAssertionExpression */ ); + const node = createBaseNode(216 /* TypeAssertionExpression */ ); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.type = type; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.type) | 1 /* ContainsTypeScript */ ; @@ -24638,7 +24810,7 @@ ${lanes.join("\n")} return node.type !== type || node.expression !== expression ? update(createTypeAssertion(type, expression), node) : node; } function createParenthesizedExpression(expression) { - const node = createBaseNode(214 /* ParenthesizedExpression */ ); + const node = createBaseNode(217 /* ParenthesizedExpression */ ); node.expression = expression; node.transformFlags = propagateChildFlags(node.expression); node.jsDoc = void 0; @@ -24648,7 +24820,7 @@ ${lanes.join("\n")} return node.expression !== expression ? update(createParenthesizedExpression(expression), node) : node; } function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - const node = createBaseDeclaration(215 /* FunctionExpression */ ); + const node = createBaseDeclaration(218 /* FunctionExpression */ ); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; node.name = asName(name); @@ -24673,12 +24845,12 @@ ${lanes.join("\n")} return node.name !== name || node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body ? finishUpdateBaseSignatureDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node; } function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - const node = createBaseDeclaration(216 /* ArrowFunction */ ); + const node = createBaseDeclaration(219 /* ArrowFunction */ ); node.modifiers = asNodeArray(modifiers); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken != null ? equalsGreaterThanToken : createToken(38 /* EqualsGreaterThanToken */ ); + node.equalsGreaterThanToken = equalsGreaterThanToken ?? createToken(39 /* EqualsGreaterThanToken */ ); node.body = parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body); const isAsync = modifiersToFlags(node.modifiers) & 512 /* Async */ ; node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | propagateChildFlags(node.equalsGreaterThanToken) | propagateChildFlags(node.body) & -67108865 /* ContainsPossibleTopLevelAwait */ | (node.typeParameters || node.type ? 1 /* ContainsTypeScript */ : 0 /* None */ ) | (isAsync ? 16640 /* ContainsLexicalThis */ : 0 /* None */ ) | 1024 /* ContainsES2015 */ ; @@ -24695,7 +24867,7 @@ ${lanes.join("\n")} return node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.equalsGreaterThanToken !== equalsGreaterThanToken || node.body !== body ? finishUpdateBaseSignatureDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) : node; } function createDeleteExpression(expression) { - const node = createBaseNode(217 /* DeleteExpression */ ); + const node = createBaseNode(220 /* DeleteExpression */ ); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -24704,7 +24876,7 @@ ${lanes.join("\n")} return node.expression !== expression ? update(createDeleteExpression(expression), node) : node; } function createTypeOfExpression(expression) { - const node = createBaseNode(218 /* TypeOfExpression */ ); + const node = createBaseNode(221 /* TypeOfExpression */ ); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -24713,7 +24885,7 @@ ${lanes.join("\n")} return node.expression !== expression ? update(createTypeOfExpression(expression), node) : node; } function createVoidExpression(expression) { - const node = createBaseNode(219 /* VoidExpression */ ); + const node = createBaseNode(222 /* VoidExpression */ ); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -24722,7 +24894,7 @@ ${lanes.join("\n")} return node.expression !== expression ? update(createVoidExpression(expression), node) : node; } function createAwaitExpression(expression) { - const node = createBaseNode(220 /* AwaitExpression */ ); + const node = createBaseNode(223 /* AwaitExpression */ ); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression) | 2097536 /* ContainsAwait */ ; return node; @@ -24731,18 +24903,18 @@ ${lanes.join("\n")} return node.expression !== expression ? update(createAwaitExpression(expression), node) : node; } function createPrefixUnaryExpression(operator, operand) { - const node = createBaseNode(221 /* PrefixUnaryExpression */ ); + const node = createBaseNode(224 /* PrefixUnaryExpression */ ); node.operator = operator; node.operand = parenthesizerRules().parenthesizeOperandOfPrefixUnary(operand); node.transformFlags |= propagateChildFlags(node.operand); - if ((operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */ ) && isIdentifier(node.operand) && !isGeneratedIdentifier(node.operand) && !isLocalName(node.operand)) node.transformFlags |= 268435456 /* ContainsUpdateExpressionForIdentifier */ ; + if ((operator === 46 /* PlusPlusToken */ || operator === 47 /* MinusMinusToken */ ) && isIdentifier(node.operand) && !isGeneratedIdentifier(node.operand) && !isLocalName(node.operand)) node.transformFlags |= 268435456 /* ContainsUpdateExpressionForIdentifier */ ; return node; } function updatePrefixUnaryExpression(node, operand) { return node.operand !== operand ? update(createPrefixUnaryExpression(node.operator, operand), node) : node; } function createPostfixUnaryExpression(operand, operator) { - const node = createBaseNode(222 /* PostfixUnaryExpression */ ); + const node = createBaseNode(225 /* PostfixUnaryExpression */ ); node.operator = operator; node.operand = parenthesizerRules().parenthesizeOperandOfPostfixUnary(operand); node.transformFlags |= propagateChildFlags(node.operand); @@ -24753,20 +24925,20 @@ ${lanes.join("\n")} return node.operand !== operand ? update(createPostfixUnaryExpression(operand, node.operator), node) : node; } function createBinaryExpression(left, operator, right) { - const node = createBaseDeclaration(223 /* BinaryExpression */ ); + const node = createBaseDeclaration(226 /* BinaryExpression */ ); const operatorToken = asToken(operator); const operatorKind = operatorToken.kind; node.left = parenthesizerRules().parenthesizeLeftSideOfBinary(operatorKind, left); node.operatorToken = operatorToken; node.right = parenthesizerRules().parenthesizeRightSideOfBinary(operatorKind, node.left, right); node.transformFlags |= propagateChildFlags(node.left) | propagateChildFlags(node.operatorToken) | propagateChildFlags(node.right); - if (operatorKind === 60 /* QuestionQuestionToken */ ) node.transformFlags |= 32 /* ContainsES2020 */ ; - else if (operatorKind === 63 /* EqualsToken */ ) { + if (operatorKind === 61 /* QuestionQuestionToken */ ) node.transformFlags |= 32 /* ContainsES2020 */ ; + else if (operatorKind === 64 /* EqualsToken */ ) { if (isObjectLiteralExpression(node.left)) node.transformFlags |= 5248 /* ContainsDestructuringAssignment */ | propagateAssignmentPatternFlags(node.left); else if (isArrayLiteralExpression(node.left)) node.transformFlags |= 5120 /* ContainsDestructuringAssignment */ | propagateAssignmentPatternFlags(node.left); - } else if (operatorKind === 42 /* AsteriskAsteriskToken */ || operatorKind === 67 /* AsteriskAsteriskEqualsToken */ ) node.transformFlags |= 512 /* ContainsES2016 */ ; + } else if (operatorKind === 43 /* AsteriskAsteriskToken */ || operatorKind === 68 /* AsteriskAsteriskEqualsToken */ ) node.transformFlags |= 512 /* ContainsES2016 */ ; else if (isLogicalOrCoalescingAssignmentOperator(operatorKind)) node.transformFlags |= 16 /* ContainsES2021 */ ; - if (operatorKind === 101 /* InKeyword */ && isPrivateIdentifier(node.left)) node.transformFlags |= 536870912 /* ContainsPrivateIdentifierInExpression */ ; + if (operatorKind === 103 /* InKeyword */ && isPrivateIdentifier(node.left)) node.transformFlags |= 536870912 /* ContainsPrivateIdentifierInExpression */ ; node.jsDoc = void 0; return node; } @@ -24777,11 +24949,11 @@ ${lanes.join("\n")} return node.left !== left || node.operatorToken !== operator || node.right !== right ? update(createBinaryExpression(left, operator, right), node) : node; } function createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse) { - const node = createBaseNode(224 /* ConditionalExpression */ ); + const node = createBaseNode(227 /* ConditionalExpression */ ); node.condition = parenthesizerRules().parenthesizeConditionOfConditionalExpression(condition); - node.questionToken = questionToken != null ? questionToken : createToken(57 /* QuestionToken */ ); + node.questionToken = questionToken ?? createToken(58 /* QuestionToken */ ); node.whenTrue = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenTrue); - node.colonToken = colonToken != null ? colonToken : createToken(58 /* ColonToken */ ); + node.colonToken = colonToken ?? createToken(59 /* ColonToken */ ); node.whenFalse = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenFalse); node.transformFlags |= propagateChildFlags(node.condition) | propagateChildFlags(node.questionToken) | propagateChildFlags(node.whenTrue) | propagateChildFlags(node.colonToken) | propagateChildFlags(node.whenFalse); return node; @@ -24790,7 +24962,7 @@ ${lanes.join("\n")} return node.condition !== condition || node.questionToken !== questionToken || node.whenTrue !== whenTrue || node.colonToken !== colonToken || node.whenFalse !== whenFalse ? update(createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse), node) : node; } function createTemplateExpression(head, templateSpans) { - const node = createBaseNode(225 /* TemplateExpression */ ); + const node = createBaseNode(228 /* TemplateExpression */ ); node.head = head; node.templateSpans = createNodeArray(templateSpans); node.transformFlags |= propagateChildFlags(node.head) | propagateChildrenFlags(node.templateSpans) | 1024 /* ContainsES2015 */ ; @@ -24800,7 +24972,7 @@ ${lanes.join("\n")} return node.head !== head || node.templateSpans !== templateSpans ? update(createTemplateExpression(head, templateSpans), node) : node; } function checkTemplateLiteralLikeNode(kind, text, rawText, templateFlags = 0 /* None */ ) { - Debug.assert(!(templateFlags & -2049 /* TemplateLiteralLikeFlags */ ), "Unsupported template flags."); + Debug.assert(!(templateFlags & -7177 /* TemplateLiteralLikeFlags */ ), "Unsupported template flags."); let cooked = void 0; if (rawText !== void 0 && rawText !== text) { cooked = getCookedText(kind, rawText); @@ -24821,7 +24993,7 @@ ${lanes.join("\n")} const node = createBaseToken(kind); node.text = text; node.rawText = rawText; - node.templateFlags = templateFlags & 2048 /* TemplateLiteralLikeFlags */ ; + node.templateFlags = templateFlags & 7176 /* TemplateLiteralLikeFlags */ ; node.transformFlags = getTransformFlagsOfTemplateLiteralLike(node.templateFlags); return node; } @@ -24829,33 +25001,33 @@ ${lanes.join("\n")} const node = createBaseDeclaration(kind); node.text = text; node.rawText = rawText; - node.templateFlags = templateFlags & 2048 /* TemplateLiteralLikeFlags */ ; + node.templateFlags = templateFlags & 7176 /* TemplateLiteralLikeFlags */ ; node.transformFlags = getTransformFlagsOfTemplateLiteralLike(node.templateFlags); return node; } function createTemplateLiteralLikeNode(kind, text, rawText, templateFlags) { - if (kind === 14 /* NoSubstitutionTemplateLiteral */ ) return createTemplateLiteralLikeDeclaration(kind, text, rawText, templateFlags); + if (kind === 15 /* NoSubstitutionTemplateLiteral */ ) return createTemplateLiteralLikeDeclaration(kind, text, rawText, templateFlags); return createTemplateLiteralLikeToken(kind, text, rawText, templateFlags); } function createTemplateHead(text, rawText, templateFlags) { - text = checkTemplateLiteralLikeNode(15 /* TemplateHead */ , text, rawText, templateFlags); - return createTemplateLiteralLikeNode(15 /* TemplateHead */ , text, rawText, templateFlags); + text = checkTemplateLiteralLikeNode(16 /* TemplateHead */ , text, rawText, templateFlags); + return createTemplateLiteralLikeNode(16 /* TemplateHead */ , text, rawText, templateFlags); } function createTemplateMiddle(text, rawText, templateFlags) { - text = checkTemplateLiteralLikeNode(15 /* TemplateHead */ , text, rawText, templateFlags); - return createTemplateLiteralLikeNode(16 /* TemplateMiddle */ , text, rawText, templateFlags); + text = checkTemplateLiteralLikeNode(16 /* TemplateHead */ , text, rawText, templateFlags); + return createTemplateLiteralLikeNode(17 /* TemplateMiddle */ , text, rawText, templateFlags); } function createTemplateTail(text, rawText, templateFlags) { - text = checkTemplateLiteralLikeNode(15 /* TemplateHead */ , text, rawText, templateFlags); - return createTemplateLiteralLikeNode(17 /* TemplateTail */ , text, rawText, templateFlags); + text = checkTemplateLiteralLikeNode(16 /* TemplateHead */ , text, rawText, templateFlags); + return createTemplateLiteralLikeNode(18 /* TemplateTail */ , text, rawText, templateFlags); } function createNoSubstitutionTemplateLiteral(text, rawText, templateFlags) { - text = checkTemplateLiteralLikeNode(15 /* TemplateHead */ , text, rawText, templateFlags); - return createTemplateLiteralLikeDeclaration(14 /* NoSubstitutionTemplateLiteral */ , text, rawText, templateFlags); + text = checkTemplateLiteralLikeNode(16 /* TemplateHead */ , text, rawText, templateFlags); + return createTemplateLiteralLikeDeclaration(15 /* NoSubstitutionTemplateLiteral */ , text, rawText, templateFlags); } function createYieldExpression(asteriskToken, expression) { Debug.assert(!asteriskToken || !!expression, "A `YieldExpression` with an asteriskToken must have an expression."); - const node = createBaseNode(226 /* YieldExpression */ ); + const node = createBaseNode(229 /* YieldExpression */ ); node.expression = expression && parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.asteriskToken = asteriskToken; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.asteriskToken) | 1049728 /* ContainsYield */ ; @@ -24865,7 +25037,7 @@ ${lanes.join("\n")} return node.expression !== expression || node.asteriskToken !== asteriskToken ? update(createYieldExpression(asteriskToken, expression), node) : node; } function createSpreadElement(expression) { - const node = createBaseNode(227 /* SpreadElement */ ); + const node = createBaseNode(230 /* SpreadElement */ ); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.transformFlags |= propagateChildFlags(node.expression) | 33792 /* ContainsRestOrSpread */ ; return node; @@ -24874,7 +25046,7 @@ ${lanes.join("\n")} return node.expression !== expression ? update(createSpreadElement(expression), node) : node; } function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { - const node = createBaseDeclaration(228 /* ClassExpression */ ); + const node = createBaseDeclaration(231 /* ClassExpression */ ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.typeParameters = asNodeArray(typeParameters); @@ -24888,10 +25060,10 @@ ${lanes.join("\n")} return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members ? update(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node) : node; } function createOmittedExpression() { - return createBaseNode(229 /* OmittedExpression */ ); + return createBaseNode(232 /* OmittedExpression */ ); } function createExpressionWithTypeArguments(expression, typeArguments) { - const node = createBaseNode(230 /* ExpressionWithTypeArguments */ ); + const node = createBaseNode(233 /* ExpressionWithTypeArguments */ ); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | 1024 /* ContainsES2015 */ ; @@ -24901,7 +25073,7 @@ ${lanes.join("\n")} return node.expression !== expression || node.typeArguments !== typeArguments ? update(createExpressionWithTypeArguments(expression, typeArguments), node) : node; } function createAsExpression(expression, type) { - const node = createBaseNode(231 /* AsExpression */ ); + const node = createBaseNode(234 /* AsExpression */ ); node.expression = expression; node.type = type; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.type) | 1 /* ContainsTypeScript */ ; @@ -24911,7 +25083,7 @@ ${lanes.join("\n")} return node.expression !== expression || node.type !== type ? update(createAsExpression(expression, type), node) : node; } function createNonNullExpression(expression) { - const node = createBaseNode(232 /* NonNullExpression */ ); + const node = createBaseNode(235 /* NonNullExpression */ ); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* ContainsTypeScript */ ; return node; @@ -24921,7 +25093,7 @@ ${lanes.join("\n")} return node.expression !== expression ? update(createNonNullExpression(expression), node) : node; } function createSatisfiesExpression(expression, type) { - const node = createBaseNode(235 /* SatisfiesExpression */ ); + const node = createBaseNode(238 /* SatisfiesExpression */ ); node.expression = expression; node.type = type; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.type) | 1 /* ContainsTypeScript */ ; @@ -24931,27 +25103,27 @@ ${lanes.join("\n")} return node.expression !== expression || node.type !== type ? update(createSatisfiesExpression(expression, type), node) : node; } function createNonNullChain(expression) { - const node = createBaseNode(232 /* NonNullExpression */ ); - node.flags |= 32 /* OptionalChain */ ; + const node = createBaseNode(235 /* NonNullExpression */ ); + node.flags |= 64 /* OptionalChain */ ; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* ContainsTypeScript */ ; return node; } function updateNonNullChain(node, expression) { - Debug.assert(!!(node.flags & 32 /* OptionalChain */ ), "Cannot update a NonNullExpression using updateNonNullChain. Use updateNonNullExpression instead."); + Debug.assert(!!(node.flags & 64 /* OptionalChain */ ), "Cannot update a NonNullExpression using updateNonNullChain. Use updateNonNullExpression instead."); return node.expression !== expression ? update(createNonNullChain(expression), node) : node; } function createMetaProperty(keywordToken, name) { - const node = createBaseNode(233 /* MetaProperty */ ); + const node = createBaseNode(236 /* MetaProperty */ ); node.keywordToken = keywordToken; node.name = name; node.transformFlags |= propagateChildFlags(node.name); switch(keywordToken){ - case 103 /* NewKeyword */ : + case 105 /* NewKeyword */ : node.transformFlags |= 1024 /* ContainsES2015 */ ; break; - case 100 /* ImportKeyword */ : - node.transformFlags |= 4 /* ContainsESNext */ ; + case 102 /* ImportKeyword */ : + node.transformFlags |= 32 /* ContainsES2020 */ ; break; default: return Debug.assertNever(keywordToken); @@ -24963,7 +25135,7 @@ ${lanes.join("\n")} return node.name !== name ? update(createMetaProperty(node.keywordToken, name), node) : node; } function createTemplateSpan(expression, literal) { - const node = createBaseNode(236 /* TemplateSpan */ ); + const node = createBaseNode(239 /* TemplateSpan */ ); node.expression = expression; node.literal = literal; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.literal) | 1024 /* ContainsES2015 */ ; @@ -24973,12 +25145,12 @@ ${lanes.join("\n")} return node.expression !== expression || node.literal !== literal ? update(createTemplateSpan(expression, literal), node) : node; } function createSemicolonClassElement() { - const node = createBaseNode(237 /* SemicolonClassElement */ ); + const node = createBaseNode(240 /* SemicolonClassElement */ ); node.transformFlags |= 1024 /* ContainsES2015 */ ; return node; } function createBlock(statements, multiLine) { - const node = createBaseNode(238 /* Block */ ); + const node = createBaseNode(241 /* Block */ ); node.statements = createNodeArray(statements); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.statements); @@ -24991,7 +25163,7 @@ ${lanes.join("\n")} return node.statements !== statements ? update(createBlock(statements, node.multiLine), node) : node; } function createVariableStatement(modifiers, declarationList) { - const node = createBaseNode(240 /* VariableStatement */ ); + const node = createBaseNode(243 /* VariableStatement */ ); node.modifiers = asNodeArray(modifiers); node.declarationList = isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.declarationList); @@ -25004,12 +25176,12 @@ ${lanes.join("\n")} return node.modifiers !== modifiers || node.declarationList !== declarationList ? update(createVariableStatement(modifiers, declarationList), node) : node; } function createEmptyStatement() { - const node = createBaseNode(239 /* EmptyStatement */ ); + const node = createBaseNode(242 /* EmptyStatement */ ); node.jsDoc = void 0; return node; } function createExpressionStatement(expression) { - const node = createBaseNode(241 /* ExpressionStatement */ ); + const node = createBaseNode(244 /* ExpressionStatement */ ); node.expression = parenthesizerRules().parenthesizeExpressionOfExpressionStatement(expression); node.transformFlags |= propagateChildFlags(node.expression); node.jsDoc = void 0; @@ -25020,7 +25192,7 @@ ${lanes.join("\n")} return node.expression !== expression ? update(createExpressionStatement(expression), node) : node; } function createIfStatement(expression, thenStatement, elseStatement) { - const node = createBaseNode(242 /* IfStatement */ ); + const node = createBaseNode(245 /* IfStatement */ ); node.expression = expression; node.thenStatement = asEmbeddedStatement(thenStatement); node.elseStatement = asEmbeddedStatement(elseStatement); @@ -25033,7 +25205,7 @@ ${lanes.join("\n")} return node.expression !== expression || node.thenStatement !== thenStatement || node.elseStatement !== elseStatement ? update(createIfStatement(expression, thenStatement, elseStatement), node) : node; } function createDoStatement(statement, expression) { - const node = createBaseNode(243 /* DoStatement */ ); + const node = createBaseNode(246 /* DoStatement */ ); node.statement = asEmbeddedStatement(statement); node.expression = expression; node.transformFlags |= propagateChildFlags(node.statement) | propagateChildFlags(node.expression); @@ -25045,7 +25217,7 @@ ${lanes.join("\n")} return node.statement !== statement || node.expression !== expression ? update(createDoStatement(statement, expression), node) : node; } function createWhileStatement(expression, statement) { - const node = createBaseNode(244 /* WhileStatement */ ); + const node = createBaseNode(247 /* WhileStatement */ ); node.expression = expression; node.statement = asEmbeddedStatement(statement); node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.statement); @@ -25057,7 +25229,7 @@ ${lanes.join("\n")} return node.expression !== expression || node.statement !== statement ? update(createWhileStatement(expression, statement), node) : node; } function createForStatement(initializer, condition, incrementor, statement) { - const node = createBaseNode(245 /* ForStatement */ ); + const node = createBaseNode(248 /* ForStatement */ ); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -25073,7 +25245,7 @@ ${lanes.join("\n")} return node.initializer !== initializer || node.condition !== condition || node.incrementor !== incrementor || node.statement !== statement ? update(createForStatement(initializer, condition, incrementor, statement), node) : node; } function createForInStatement(initializer, expression, statement) { - const node = createBaseNode(246 /* ForInStatement */ ); + const node = createBaseNode(249 /* ForInStatement */ ); node.initializer = initializer; node.expression = expression; node.statement = asEmbeddedStatement(statement); @@ -25088,7 +25260,7 @@ ${lanes.join("\n")} return node.initializer !== initializer || node.expression !== expression || node.statement !== statement ? update(createForInStatement(initializer, expression, statement), node) : node; } function createForOfStatement(awaitModifier, initializer, expression, statement) { - const node = createBaseNode(247 /* ForOfStatement */ ); + const node = createBaseNode(250 /* ForOfStatement */ ); node.awaitModifier = awaitModifier; node.initializer = initializer; node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); @@ -25105,7 +25277,7 @@ ${lanes.join("\n")} return node.awaitModifier !== awaitModifier || node.initializer !== initializer || node.expression !== expression || node.statement !== statement ? update(createForOfStatement(awaitModifier, initializer, expression, statement), node) : node; } function createContinueStatement(label) { - const node = createBaseNode(248 /* ContinueStatement */ ); + const node = createBaseNode(251 /* ContinueStatement */ ); node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | 4194304 /* ContainsHoistedDeclarationOrCompletion */ ; node.jsDoc = void 0; @@ -25116,7 +25288,7 @@ ${lanes.join("\n")} return node.label !== label ? update(createContinueStatement(label), node) : node; } function createBreakStatement(label) { - const node = createBaseNode(249 /* BreakStatement */ ); + const node = createBaseNode(252 /* BreakStatement */ ); node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | 4194304 /* ContainsHoistedDeclarationOrCompletion */ ; node.jsDoc = void 0; @@ -25127,7 +25299,7 @@ ${lanes.join("\n")} return node.label !== label ? update(createBreakStatement(label), node) : node; } function createReturnStatement(expression) { - const node = createBaseNode(250 /* ReturnStatement */ ); + const node = createBaseNode(253 /* ReturnStatement */ ); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression) | 4194432 /* ContainsHoistedDeclarationOrCompletion */ ; node.jsDoc = void 0; @@ -25138,7 +25310,7 @@ ${lanes.join("\n")} return node.expression !== expression ? update(createReturnStatement(expression), node) : node; } function createWithStatement(expression, statement) { - const node = createBaseNode(251 /* WithStatement */ ); + const node = createBaseNode(254 /* WithStatement */ ); node.expression = expression; node.statement = asEmbeddedStatement(statement); node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.statement); @@ -25150,7 +25322,7 @@ ${lanes.join("\n")} return node.expression !== expression || node.statement !== statement ? update(createWithStatement(expression, statement), node) : node; } function createSwitchStatement(expression, caseBlock) { - const node = createBaseNode(252 /* SwitchStatement */ ); + const node = createBaseNode(255 /* SwitchStatement */ ); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.caseBlock = caseBlock; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.caseBlock); @@ -25163,7 +25335,7 @@ ${lanes.join("\n")} return node.expression !== expression || node.caseBlock !== caseBlock ? update(createSwitchStatement(expression, caseBlock), node) : node; } function createLabeledStatement(label, statement) { - const node = createBaseNode(253 /* LabeledStatement */ ); + const node = createBaseNode(256 /* LabeledStatement */ ); node.label = asName(label); node.statement = asEmbeddedStatement(statement); node.transformFlags |= propagateChildFlags(node.label) | propagateChildFlags(node.statement); @@ -25175,7 +25347,7 @@ ${lanes.join("\n")} return node.label !== label || node.statement !== statement ? update(createLabeledStatement(label, statement), node) : node; } function createThrowStatement(expression) { - const node = createBaseNode(254 /* ThrowStatement */ ); + const node = createBaseNode(257 /* ThrowStatement */ ); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); node.jsDoc = void 0; @@ -25186,7 +25358,7 @@ ${lanes.join("\n")} return node.expression !== expression ? update(createThrowStatement(expression), node) : node; } function createTryStatement(tryBlock, catchClause, finallyBlock) { - const node = createBaseNode(255 /* TryStatement */ ); + const node = createBaseNode(258 /* TryStatement */ ); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -25199,19 +25371,18 @@ ${lanes.join("\n")} return node.tryBlock !== tryBlock || node.catchClause !== catchClause || node.finallyBlock !== finallyBlock ? update(createTryStatement(tryBlock, catchClause, finallyBlock), node) : node; } function createDebuggerStatement() { - const node = createBaseNode(256 /* DebuggerStatement */ ); + const node = createBaseNode(259 /* DebuggerStatement */ ); node.jsDoc = void 0; node.flowNode = void 0; return node; } function createVariableDeclaration(name, exclamationToken, type, initializer) { - var _a2; - const node = createBaseDeclaration(257 /* VariableDeclaration */ ); + const node = createBaseDeclaration(260 /* VariableDeclaration */ ); node.name = asName(name); node.exclamationToken = exclamationToken; node.type = type; node.initializer = asInitializer(initializer); - node.transformFlags |= propagateNameFlags(node.name) | propagateChildFlags(node.initializer) | (((_a2 = node.exclamationToken) != null ? _a2 : node.type) ? 1 /* ContainsTypeScript */ : 0 /* None */ ); + node.transformFlags |= propagateNameFlags(node.name) | propagateChildFlags(node.initializer) | (node.exclamationToken ?? node.type ? 1 /* ContainsTypeScript */ : 0 /* None */ ); node.jsDoc = void 0; return node; } @@ -25219,18 +25390,19 @@ ${lanes.join("\n")} return node.name !== name || node.type !== type || node.exclamationToken !== exclamationToken || node.initializer !== initializer ? update(createVariableDeclaration(name, exclamationToken, type, initializer), node) : node; } function createVariableDeclarationList(declarations, flags2 = 0 /* None */ ) { - const node = createBaseNode(258 /* VariableDeclarationList */ ); - node.flags |= flags2 & 3 /* BlockScoped */ ; + const node = createBaseNode(261 /* VariableDeclarationList */ ); + node.flags |= flags2 & 7 /* BlockScoped */ ; node.declarations = createNodeArray(declarations); node.transformFlags |= propagateChildrenFlags(node.declarations) | 4194304 /* ContainsHoistedDeclarationOrCompletion */ ; - if (flags2 & 3 /* BlockScoped */ ) node.transformFlags |= 263168 /* ContainsBlockScopedBinding */ ; + if (flags2 & 7 /* BlockScoped */ ) node.transformFlags |= 263168 /* ContainsBlockScopedBinding */ ; + if (flags2 & 4 /* Using */ ) node.transformFlags |= 4 /* ContainsESNext */ ; return node; } function updateVariableDeclarationList(node, declarations) { return node.declarations !== declarations ? update(createVariableDeclarationList(declarations, node.flags), node) : node; } function createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - const node = createBaseDeclaration(259 /* FunctionDeclaration */ ); + const node = createBaseDeclaration(262 /* FunctionDeclaration */ ); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; node.name = asName(name); @@ -25263,7 +25435,7 @@ ${lanes.join("\n")} return finishUpdateBaseSignatureDeclaration(updated, original); } function createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members) { - const node = createBaseDeclaration(260 /* ClassDeclaration */ ); + const node = createBaseDeclaration(263 /* ClassDeclaration */ ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.typeParameters = asNodeArray(typeParameters); @@ -25281,7 +25453,7 @@ ${lanes.join("\n")} return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members ? update(createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node; } function createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members) { - const node = createBaseDeclaration(261 /* InterfaceDeclaration */ ); + const node = createBaseDeclaration(264 /* InterfaceDeclaration */ ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.typeParameters = asNodeArray(typeParameters); @@ -25295,7 +25467,7 @@ ${lanes.join("\n")} return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members ? update(createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node; } function createTypeAliasDeclaration(modifiers, name, typeParameters, type) { - const node = createBaseDeclaration(262 /* TypeAliasDeclaration */ ); + const node = createBaseDeclaration(265 /* TypeAliasDeclaration */ ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.typeParameters = asNodeArray(typeParameters); @@ -25310,7 +25482,7 @@ ${lanes.join("\n")} return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.type !== type ? update(createTypeAliasDeclaration(modifiers, name, typeParameters, type), node) : node; } function createEnumDeclaration(modifiers, name, members) { - const node = createBaseDeclaration(263 /* EnumDeclaration */ ); + const node = createBaseDeclaration(266 /* EnumDeclaration */ ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.members = createNodeArray(members); @@ -25323,9 +25495,9 @@ ${lanes.join("\n")} return node.modifiers !== modifiers || node.name !== name || node.members !== members ? update(createEnumDeclaration(modifiers, name, members), node) : node; } function createModuleDeclaration(modifiers, name, body, flags2 = 0 /* None */ ) { - const node = createBaseDeclaration(264 /* ModuleDeclaration */ ); + const node = createBaseDeclaration(267 /* ModuleDeclaration */ ); node.modifiers = asNodeArray(modifiers); - node.flags |= flags2 & 1044 /* GlobalAugmentation */ ; + node.flags |= flags2 & 2088 /* GlobalAugmentation */ ; node.name = name; node.body = body; if (modifiersToFlags(node.modifiers) & 2 /* Ambient */ ) node.transformFlags = 1 /* ContainsTypeScript */ ; @@ -25340,7 +25512,7 @@ ${lanes.join("\n")} return node.modifiers !== modifiers || node.name !== name || node.body !== body ? update(createModuleDeclaration(modifiers, name, body, node.flags), node) : node; } function createModuleBlock(statements) { - const node = createBaseNode(265 /* ModuleBlock */ ); + const node = createBaseNode(268 /* ModuleBlock */ ); node.statements = createNodeArray(statements); node.transformFlags |= propagateChildrenFlags(node.statements); node.jsDoc = void 0; @@ -25350,7 +25522,7 @@ ${lanes.join("\n")} return node.statements !== statements ? update(createModuleBlock(statements), node) : node; } function createCaseBlock(clauses) { - const node = createBaseNode(266 /* CaseBlock */ ); + const node = createBaseNode(269 /* CaseBlock */ ); node.clauses = createNodeArray(clauses); node.transformFlags |= propagateChildrenFlags(node.clauses); node.locals = void 0; @@ -25361,7 +25533,7 @@ ${lanes.join("\n")} return node.clauses !== clauses ? update(createCaseBlock(clauses), node) : node; } function createNamespaceExportDeclaration(name) { - const node = createBaseDeclaration(267 /* NamespaceExportDeclaration */ ); + const node = createBaseDeclaration(270 /* NamespaceExportDeclaration */ ); node.name = asName(name); node.transformFlags |= propagateIdentifierNameFlags(node.name) | 1 /* ContainsTypeScript */ ; node.modifiers = void 0; @@ -25376,7 +25548,7 @@ ${lanes.join("\n")} return update(updated, original); } function createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference) { - const node = createBaseDeclaration(268 /* ImportEqualsDeclaration */ ); + const node = createBaseDeclaration(271 /* ImportEqualsDeclaration */ ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.isTypeOnly = isTypeOnly; @@ -25391,7 +25563,7 @@ ${lanes.join("\n")} return node.modifiers !== modifiers || node.isTypeOnly !== isTypeOnly || node.name !== name || node.moduleReference !== moduleReference ? update(createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference), node) : node; } function createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause) { - const node = createBaseNode(269 /* ImportDeclaration */ ); + const node = createBaseNode(272 /* ImportDeclaration */ ); node.modifiers = asNodeArray(modifiers); node.importClause = importClause; node.moduleSpecifier = moduleSpecifier; @@ -25405,7 +25577,7 @@ ${lanes.join("\n")} return node.modifiers !== modifiers || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier || node.assertClause !== assertClause ? update(createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause), node) : node; } function createImportClause(isTypeOnly, name, namedBindings) { - const node = createBaseDeclaration(270 /* ImportClause */ ); + const node = createBaseDeclaration(273 /* ImportClause */ ); node.isTypeOnly = isTypeOnly; node.name = name; node.namedBindings = namedBindings; @@ -25418,7 +25590,7 @@ ${lanes.join("\n")} return node.isTypeOnly !== isTypeOnly || node.name !== name || node.namedBindings !== namedBindings ? update(createImportClause(isTypeOnly, name, namedBindings), node) : node; } function createAssertClause(elements, multiLine) { - const node = createBaseNode(296 /* AssertClause */ ); + const node = createBaseNode(300 /* AssertClause */ ); node.elements = createNodeArray(elements); node.multiLine = multiLine; node.transformFlags |= 4 /* ContainsESNext */ ; @@ -25428,7 +25600,7 @@ ${lanes.join("\n")} return node.elements !== elements || node.multiLine !== multiLine ? update(createAssertClause(elements, multiLine), node) : node; } function createAssertEntry(name, value1) { - const node = createBaseNode(297 /* AssertEntry */ ); + const node = createBaseNode(301 /* AssertEntry */ ); node.name = name; node.value = value1; node.transformFlags |= 4 /* ContainsESNext */ ; @@ -25438,7 +25610,7 @@ ${lanes.join("\n")} return node.name !== name || node.value !== value1 ? update(createAssertEntry(name, value1), node) : node; } function createImportTypeAssertionContainer(clause, multiLine) { - const node = createBaseNode(298 /* ImportTypeAssertionContainer */ ); + const node = createBaseNode(302 /* ImportTypeAssertionContainer */ ); node.assertClause = clause; node.multiLine = multiLine; return node; @@ -25447,7 +25619,7 @@ ${lanes.join("\n")} return node.assertClause !== clause || node.multiLine !== multiLine ? update(createImportTypeAssertionContainer(clause, multiLine), node) : node; } function createNamespaceImport(name) { - const node = createBaseDeclaration(271 /* NamespaceImport */ ); + const node = createBaseDeclaration(274 /* NamespaceImport */ ); node.name = name; node.transformFlags |= propagateChildFlags(node.name); node.transformFlags &= -67108865 /* ContainsPossibleTopLevelAwait */ ; @@ -25457,9 +25629,9 @@ ${lanes.join("\n")} return node.name !== name ? update(createNamespaceImport(name), node) : node; } function createNamespaceExport(name) { - const node = createBaseDeclaration(277 /* NamespaceExport */ ); + const node = createBaseDeclaration(280 /* NamespaceExport */ ); node.name = name; - node.transformFlags |= propagateChildFlags(node.name) | 4 /* ContainsESNext */ ; + node.transformFlags |= propagateChildFlags(node.name) | 32 /* ContainsES2020 */ ; node.transformFlags &= -67108865 /* ContainsPossibleTopLevelAwait */ ; return node; } @@ -25467,7 +25639,7 @@ ${lanes.join("\n")} return node.name !== name ? update(createNamespaceExport(name), node) : node; } function createNamedImports(elements) { - const node = createBaseNode(272 /* NamedImports */ ); + const node = createBaseNode(275 /* NamedImports */ ); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); node.transformFlags &= -67108865 /* ContainsPossibleTopLevelAwait */ ; @@ -25477,7 +25649,7 @@ ${lanes.join("\n")} return node.elements !== elements ? update(createNamedImports(elements), node) : node; } function createImportSpecifier(isTypeOnly, propertyName, name) { - const node = createBaseDeclaration(273 /* ImportSpecifier */ ); + const node = createBaseDeclaration(276 /* ImportSpecifier */ ); node.isTypeOnly = isTypeOnly; node.propertyName = propertyName; node.name = name; @@ -25489,10 +25661,10 @@ ${lanes.join("\n")} return node.isTypeOnly !== isTypeOnly || node.propertyName !== propertyName || node.name !== name ? update(createImportSpecifier(isTypeOnly, propertyName, name), node) : node; } function createExportAssignment2(modifiers, isExportEquals, expression) { - const node = createBaseDeclaration(274 /* ExportAssignment */ ); + const node = createBaseDeclaration(277 /* ExportAssignment */ ); node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; - node.expression = isExportEquals ? parenthesizerRules().parenthesizeRightSideOfBinary(63 /* EqualsToken */ , /*leftSide*/ void 0, expression) : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression); + node.expression = isExportEquals ? parenthesizerRules().parenthesizeRightSideOfBinary(64 /* EqualsToken */ , /*leftSide*/ void 0, expression) : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression); node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.expression); node.transformFlags &= -67108865 /* ContainsPossibleTopLevelAwait */ ; node.jsDoc = void 0; @@ -25502,7 +25674,7 @@ ${lanes.join("\n")} return node.modifiers !== modifiers || node.expression !== expression ? update(createExportAssignment2(modifiers, node.isExportEquals, expression), node) : node; } function createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { - const node = createBaseDeclaration(275 /* ExportDeclaration */ ); + const node = createBaseDeclaration(278 /* ExportDeclaration */ ); node.modifiers = asNodeArray(modifiers); node.isTypeOnly = isTypeOnly; node.exportClause = exportClause; @@ -25523,7 +25695,7 @@ ${lanes.join("\n")} return update(updated, original); } function createNamedExports(elements) { - const node = createBaseNode(276 /* NamedExports */ ); + const node = createBaseNode(279 /* NamedExports */ ); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); node.transformFlags &= -67108865 /* ContainsPossibleTopLevelAwait */ ; @@ -25533,7 +25705,7 @@ ${lanes.join("\n")} return node.elements !== elements ? update(createNamedExports(elements), node) : node; } function createExportSpecifier(isTypeOnly, propertyName, name) { - const node = createBaseNode(278 /* ExportSpecifier */ ); + const node = createBaseNode(281 /* ExportSpecifier */ ); node.isTypeOnly = isTypeOnly; node.propertyName = asName(propertyName); node.name = asName(name); @@ -25546,12 +25718,12 @@ ${lanes.join("\n")} return node.isTypeOnly !== isTypeOnly || node.propertyName !== propertyName || node.name !== name ? update(createExportSpecifier(isTypeOnly, propertyName, name), node) : node; } function createMissingDeclaration() { - const node = createBaseDeclaration(279 /* MissingDeclaration */ ); + const node = createBaseDeclaration(282 /* MissingDeclaration */ ); node.jsDoc = void 0; return node; } function createExternalModuleReference(expression) { - const node = createBaseNode(280 /* ExternalModuleReference */ ); + const node = createBaseNode(283 /* ExternalModuleReference */ ); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); node.transformFlags &= -67108865 /* ContainsPossibleTopLevelAwait */ ; @@ -25580,7 +25752,7 @@ ${lanes.join("\n")} return node.type !== type ? update(createJSDocUnaryTypeWorker(kind, type), node) : node; } function createJSDocFunctionType(parameters, type) { - const node = createBaseDeclaration(320 /* JSDocFunctionType */ ); + const node = createBaseDeclaration(324 /* JSDocFunctionType */ ); node.parameters = asNodeArray(parameters); node.type = type; node.transformFlags = propagateChildrenFlags(node.parameters) | (node.type ? 1 /* ContainsTypeScript */ : 0 /* None */ ); @@ -25594,7 +25766,7 @@ ${lanes.join("\n")} return node.parameters !== parameters || node.type !== type ? update(createJSDocFunctionType(parameters, type), node) : node; } function createJSDocTypeLiteral(propertyTags, isArrayType = false) { - const node = createBaseDeclaration(325 /* JSDocTypeLiteral */ ); + const node = createBaseDeclaration(329 /* JSDocTypeLiteral */ ); node.jsDocPropertyTags = asNodeArray(propertyTags); node.isArrayType = isArrayType; return node; @@ -25603,7 +25775,7 @@ ${lanes.join("\n")} return node.jsDocPropertyTags !== propertyTags || node.isArrayType !== isArrayType ? update(createJSDocTypeLiteral(propertyTags, isArrayType), node) : node; } function createJSDocTypeExpression(type) { - const node = createBaseNode(312 /* JSDocTypeExpression */ ); + const node = createBaseNode(316 /* JSDocTypeExpression */ ); node.type = type; return node; } @@ -25611,7 +25783,7 @@ ${lanes.join("\n")} return node.type !== type ? update(createJSDocTypeExpression(type), node) : node; } function createJSDocSignature(typeParameters, parameters, type) { - const node = createBaseDeclaration(326 /* JSDocSignature */ ); + const node = createBaseDeclaration(330 /* JSDocSignature */ ); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); node.type = type; @@ -25640,7 +25812,7 @@ ${lanes.join("\n")} return node; } function createJSDocTemplateTag(tagName, constraint, typeParameters, comment) { - const node = createBaseJSDocTag(348 /* JSDocTemplateTag */ , tagName != null ? tagName : createIdentifier("template"), comment); + const node = createBaseJSDocTag(352 /* JSDocTemplateTag */ , tagName ?? createIdentifier("template"), comment); node.constraint = constraint; node.typeParameters = createNodeArray(typeParameters); return node; @@ -25649,7 +25821,7 @@ ${lanes.join("\n")} return node.tagName !== tagName || node.constraint !== constraint || node.typeParameters !== typeParameters || node.comment !== comment ? update(createJSDocTemplateTag(tagName, constraint, typeParameters, comment), node) : node; } function createJSDocTypedefTag(tagName, typeExpression, fullName, comment) { - const node = createBaseJSDocTagDeclaration(349 /* JSDocTypedefTag */ , tagName != null ? tagName : createIdentifier("typedef"), comment); + const node = createBaseJSDocTagDeclaration(353 /* JSDocTypedefTag */ , tagName ?? createIdentifier("typedef"), comment); node.typeExpression = typeExpression; node.fullName = fullName; node.name = getJSDocTypeAliasName(fullName); @@ -25661,7 +25833,7 @@ ${lanes.join("\n")} return node.tagName !== tagName || node.typeExpression !== typeExpression || node.fullName !== fullName || node.comment !== comment ? update(createJSDocTypedefTag(tagName, typeExpression, fullName, comment), node) : node; } function createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) { - const node = createBaseJSDocTagDeclaration(344 /* JSDocParameterTag */ , tagName != null ? tagName : createIdentifier("param"), comment); + const node = createBaseJSDocTagDeclaration(348 /* JSDocParameterTag */ , tagName ?? createIdentifier("param"), comment); node.typeExpression = typeExpression; node.name = name; node.isNameFirst = !!isNameFirst; @@ -25672,7 +25844,7 @@ ${lanes.join("\n")} return node.tagName !== tagName || node.name !== name || node.isBracketed !== isBracketed || node.typeExpression !== typeExpression || node.isNameFirst !== isNameFirst || node.comment !== comment ? update(createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node) : node; } function createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) { - const node = createBaseJSDocTagDeclaration(351 /* JSDocPropertyTag */ , tagName != null ? tagName : createIdentifier("prop"), comment); + const node = createBaseJSDocTagDeclaration(355 /* JSDocPropertyTag */ , tagName ?? createIdentifier("prop"), comment); node.typeExpression = typeExpression; node.name = name; node.isNameFirst = !!isNameFirst; @@ -25683,7 +25855,7 @@ ${lanes.join("\n")} return node.tagName !== tagName || node.name !== name || node.isBracketed !== isBracketed || node.typeExpression !== typeExpression || node.isNameFirst !== isNameFirst || node.comment !== comment ? update(createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node) : node; } function createJSDocCallbackTag(tagName, typeExpression, fullName, comment) { - const node = createBaseJSDocTagDeclaration(341 /* JSDocCallbackTag */ , tagName != null ? tagName : createIdentifier("callback"), comment); + const node = createBaseJSDocTagDeclaration(345 /* JSDocCallbackTag */ , tagName ?? createIdentifier("callback"), comment); node.typeExpression = typeExpression; node.fullName = fullName; node.name = getJSDocTypeAliasName(fullName); @@ -25695,7 +25867,7 @@ ${lanes.join("\n")} return node.tagName !== tagName || node.typeExpression !== typeExpression || node.fullName !== fullName || node.comment !== comment ? update(createJSDocCallbackTag(tagName, typeExpression, fullName, comment), node) : node; } function createJSDocOverloadTag(tagName, typeExpression, comment) { - const node = createBaseJSDocTag(342 /* JSDocOverloadTag */ , tagName != null ? tagName : createIdentifier("overload"), comment); + const node = createBaseJSDocTag(346 /* JSDocOverloadTag */ , tagName ?? createIdentifier("overload"), comment); node.typeExpression = typeExpression; return node; } @@ -25703,7 +25875,7 @@ ${lanes.join("\n")} return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment ? update(createJSDocOverloadTag(tagName, typeExpression, comment), node) : node; } function createJSDocAugmentsTag(tagName, className, comment) { - const node = createBaseJSDocTag(331 /* JSDocAugmentsTag */ , tagName != null ? tagName : createIdentifier("augments"), comment); + const node = createBaseJSDocTag(335 /* JSDocAugmentsTag */ , tagName ?? createIdentifier("augments"), comment); node.class = className; return node; } @@ -25711,12 +25883,12 @@ ${lanes.join("\n")} return node.tagName !== tagName || node.class !== className || node.comment !== comment ? update(createJSDocAugmentsTag(tagName, className, comment), node) : node; } function createJSDocImplementsTag(tagName, className, comment) { - const node = createBaseJSDocTag(332 /* JSDocImplementsTag */ , tagName != null ? tagName : createIdentifier("implements"), comment); + const node = createBaseJSDocTag(336 /* JSDocImplementsTag */ , tagName ?? createIdentifier("implements"), comment); node.class = className; return node; } function createJSDocSeeTag(tagName, name, comment) { - const node = createBaseJSDocTag(350 /* JSDocSeeTag */ , tagName != null ? tagName : createIdentifier("see"), comment); + const node = createBaseJSDocTag(354 /* JSDocSeeTag */ , tagName ?? createIdentifier("see"), comment); node.name = name; return node; } @@ -25724,7 +25896,7 @@ ${lanes.join("\n")} return node.tagName !== tagName || node.name !== name || node.comment !== comment ? update(createJSDocSeeTag(tagName, name, comment), node) : node; } function createJSDocNameReference(name) { - const node = createBaseNode(313 /* JSDocNameReference */ ); + const node = createBaseNode(317 /* JSDocNameReference */ ); node.name = name; return node; } @@ -25732,7 +25904,7 @@ ${lanes.join("\n")} return node.name !== name ? update(createJSDocNameReference(name), node) : node; } function createJSDocMemberName(left, right) { - const node = createBaseNode(314 /* JSDocMemberName */ ); + const node = createBaseNode(318 /* JSDocMemberName */ ); node.left = left; node.right = right; node.transformFlags |= propagateChildFlags(node.left) | propagateChildFlags(node.right); @@ -25742,7 +25914,7 @@ ${lanes.join("\n")} return node.left !== left || node.right !== right ? update(createJSDocMemberName(left, right), node) : node; } function createJSDocLink(name, text) { - const node = createBaseNode(327 /* JSDocLink */ ); + const node = createBaseNode(331 /* JSDocLink */ ); node.name = name; node.text = text; return node; @@ -25751,7 +25923,7 @@ ${lanes.join("\n")} return node.name !== name ? update(createJSDocLink(name, text), node) : node; } function createJSDocLinkCode(name, text) { - const node = createBaseNode(328 /* JSDocLinkCode */ ); + const node = createBaseNode(332 /* JSDocLinkCode */ ); node.name = name; node.text = text; return node; @@ -25760,7 +25932,7 @@ ${lanes.join("\n")} return node.name !== name ? update(createJSDocLinkCode(name, text), node) : node; } function createJSDocLinkPlain(name, text) { - const node = createBaseNode(329 /* JSDocLinkPlain */ ); + const node = createBaseNode(333 /* JSDocLinkPlain */ ); node.name = name; node.text = text; return node; @@ -25772,14 +25944,14 @@ ${lanes.join("\n")} return node.tagName !== tagName || node.class !== className || node.comment !== comment ? update(createJSDocImplementsTag(tagName, className, comment), node) : node; } function createJSDocSimpleTagWorker(kind, tagName, comment) { - const node = createBaseJSDocTag(kind, tagName != null ? tagName : createIdentifier(getDefaultTagNameForKind(kind)), comment); + const node = createBaseJSDocTag(kind, tagName ?? createIdentifier(getDefaultTagNameForKind(kind)), comment); return node; } function updateJSDocSimpleTagWorker(kind, node, tagName = getDefaultTagName(node), comment) { return node.tagName !== tagName || node.comment !== comment ? update(createJSDocSimpleTagWorker(kind, tagName, comment), node) : node; } function createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment) { - const node = createBaseJSDocTag(kind, tagName != null ? tagName : createIdentifier(getDefaultTagNameForKind(kind)), comment); + const node = createBaseJSDocTag(kind, tagName ?? createIdentifier(getDefaultTagNameForKind(kind)), comment); node.typeExpression = typeExpression; return node; } @@ -25787,14 +25959,14 @@ ${lanes.join("\n")} return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment ? update(createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment), node) : node; } function createJSDocUnknownTag(tagName, comment) { - const node = createBaseJSDocTag(330 /* JSDocTag */ , tagName, comment); + const node = createBaseJSDocTag(334 /* JSDocTag */ , tagName, comment); return node; } function updateJSDocUnknownTag(node, tagName, comment) { return node.tagName !== tagName || node.comment !== comment ? update(createJSDocUnknownTag(tagName, comment), node) : node; } function createJSDocEnumTag(tagName, typeExpression, comment) { - const node = createBaseJSDocTagDeclaration(343 /* JSDocEnumTag */ , tagName != null ? tagName : createIdentifier(getDefaultTagNameForKind(343 /* JSDocEnumTag */ )), comment); + const node = createBaseJSDocTagDeclaration(347 /* JSDocEnumTag */ , tagName ?? createIdentifier(getDefaultTagNameForKind(347 /* JSDocEnumTag */ )), comment); node.typeExpression = typeExpression; node.locals = void 0; node.nextContainer = void 0; @@ -25804,7 +25976,7 @@ ${lanes.join("\n")} return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment ? update(createJSDocEnumTag(tagName, typeExpression, comment), node) : node; } function createJSDocText(text) { - const node = createBaseNode(324 /* JSDocText */ ); + const node = createBaseNode(328 /* JSDocText */ ); node.text = text; return node; } @@ -25812,7 +25984,7 @@ ${lanes.join("\n")} return node.text !== text ? update(createJSDocText(text), node) : node; } function createJSDocComment(comment, tags) { - const node = createBaseNode(323 /* JSDoc */ ); + const node = createBaseNode(327 /* JSDoc */ ); node.comment = comment; node.tags = asNodeArray(tags); return node; @@ -25821,7 +25993,7 @@ ${lanes.join("\n")} return node.comment !== comment || node.tags !== tags ? update(createJSDocComment(comment, tags), node) : node; } function createJsxElement(openingElement, children, closingElement) { - const node = createBaseNode(281 /* JsxElement */ ); + const node = createBaseNode(284 /* JsxElement */ ); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -25832,7 +26004,7 @@ ${lanes.join("\n")} return node.openingElement !== openingElement || node.children !== children || node.closingElement !== closingElement ? update(createJsxElement(openingElement, children, closingElement), node) : node; } function createJsxSelfClosingElement(tagName, typeArguments, attributes) { - const node = createBaseNode(282 /* JsxSelfClosingElement */ ); + const node = createBaseNode(285 /* JsxSelfClosingElement */ ); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -25844,7 +26016,7 @@ ${lanes.join("\n")} return node.tagName !== tagName || node.typeArguments !== typeArguments || node.attributes !== attributes ? update(createJsxSelfClosingElement(tagName, typeArguments, attributes), node) : node; } function createJsxOpeningElement(tagName, typeArguments, attributes) { - const node = createBaseNode(283 /* JsxOpeningElement */ ); + const node = createBaseNode(286 /* JsxOpeningElement */ ); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -25856,7 +26028,7 @@ ${lanes.join("\n")} return node.tagName !== tagName || node.typeArguments !== typeArguments || node.attributes !== attributes ? update(createJsxOpeningElement(tagName, typeArguments, attributes), node) : node; } function createJsxClosingElement(tagName) { - const node = createBaseNode(284 /* JsxClosingElement */ ); + const node = createBaseNode(287 /* JsxClosingElement */ ); node.tagName = tagName; node.transformFlags |= propagateChildFlags(node.tagName) | 2 /* ContainsJsx */ ; return node; @@ -25865,7 +26037,7 @@ ${lanes.join("\n")} return node.tagName !== tagName ? update(createJsxClosingElement(tagName), node) : node; } function createJsxFragment(openingFragment, children, closingFragment) { - const node = createBaseNode(285 /* JsxFragment */ ); + const node = createBaseNode(288 /* JsxFragment */ ); node.openingFragment = openingFragment; node.children = createNodeArray(children); node.closingFragment = closingFragment; @@ -25876,7 +26048,7 @@ ${lanes.join("\n")} return node.openingFragment !== openingFragment || node.children !== children || node.closingFragment !== closingFragment ? update(createJsxFragment(openingFragment, children, closingFragment), node) : node; } function createJsxText(text, containsOnlyTriviaWhiteSpaces) { - const node = createBaseNode(11 /* JsxText */ ); + const node = createBaseNode(12 /* JsxText */ ); node.text = text; node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces; node.transformFlags |= 2 /* ContainsJsx */ ; @@ -25886,17 +26058,17 @@ ${lanes.join("\n")} return node.text !== text || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces ? update(createJsxText(text, containsOnlyTriviaWhiteSpaces), node) : node; } function createJsxOpeningFragment() { - const node = createBaseNode(286 /* JsxOpeningFragment */ ); + const node = createBaseNode(289 /* JsxOpeningFragment */ ); node.transformFlags |= 2 /* ContainsJsx */ ; return node; } function createJsxJsxClosingFragment() { - const node = createBaseNode(287 /* JsxClosingFragment */ ); + const node = createBaseNode(290 /* JsxClosingFragment */ ); node.transformFlags |= 2 /* ContainsJsx */ ; return node; } function createJsxAttribute(name, initializer) { - const node = createBaseDeclaration(288 /* JsxAttribute */ ); + const node = createBaseDeclaration(291 /* JsxAttribute */ ); node.name = name; node.initializer = initializer; node.transformFlags |= propagateChildFlags(node.name) | propagateChildFlags(node.initializer) | 2 /* ContainsJsx */ ; @@ -25906,7 +26078,7 @@ ${lanes.join("\n")} return node.name !== name || node.initializer !== initializer ? update(createJsxAttribute(name, initializer), node) : node; } function createJsxAttributes(properties) { - const node = createBaseDeclaration(289 /* JsxAttributes */ ); + const node = createBaseDeclaration(292 /* JsxAttributes */ ); node.properties = createNodeArray(properties); node.transformFlags |= propagateChildrenFlags(node.properties) | 2 /* ContainsJsx */ ; return node; @@ -25915,7 +26087,7 @@ ${lanes.join("\n")} return node.properties !== properties ? update(createJsxAttributes(properties), node) : node; } function createJsxSpreadAttribute(expression) { - const node = createBaseNode(290 /* JsxSpreadAttribute */ ); + const node = createBaseNode(293 /* JsxSpreadAttribute */ ); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression) | 2 /* ContainsJsx */ ; return node; @@ -25924,7 +26096,7 @@ ${lanes.join("\n")} return node.expression !== expression ? update(createJsxSpreadAttribute(expression), node) : node; } function createJsxExpression(dotDotDotToken, expression) { - const node = createBaseNode(291 /* JsxExpression */ ); + const node = createBaseNode(294 /* JsxExpression */ ); node.dotDotDotToken = dotDotDotToken; node.expression = expression; node.transformFlags |= propagateChildFlags(node.dotDotDotToken) | propagateChildFlags(node.expression) | 2 /* ContainsJsx */ ; @@ -25933,8 +26105,18 @@ ${lanes.join("\n")} function updateJsxExpression(node, expression) { return node.expression !== expression ? update(createJsxExpression(node.dotDotDotToken, expression), node) : node; } + function createJsxNamespacedName(namespace, name) { + const node = createBaseNode(295 /* JsxNamespacedName */ ); + node.namespace = namespace; + node.name = name; + node.transformFlags |= propagateChildFlags(node.namespace) | propagateChildFlags(node.name) | 2 /* ContainsJsx */ ; + return node; + } + function updateJsxNamespacedName(node, namespace, name) { + return node.namespace !== namespace || node.name !== name ? update(createJsxNamespacedName(namespace, name), node) : node; + } function createCaseClause(expression, statements) { - const node = createBaseNode(292 /* CaseClause */ ); + const node = createBaseNode(296 /* CaseClause */ ); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.statements = createNodeArray(statements); node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.statements); @@ -25945,7 +26127,7 @@ ${lanes.join("\n")} return node.expression !== expression || node.statements !== statements ? update(createCaseClause(expression, statements), node) : node; } function createDefaultClause(statements) { - const node = createBaseNode(293 /* DefaultClause */ ); + const node = createBaseNode(297 /* DefaultClause */ ); node.statements = createNodeArray(statements); node.transformFlags = propagateChildrenFlags(node.statements); return node; @@ -25954,15 +26136,15 @@ ${lanes.join("\n")} return node.statements !== statements ? update(createDefaultClause(statements), node) : node; } function createHeritageClause(token, types) { - const node = createBaseNode(294 /* HeritageClause */ ); + const node = createBaseNode(298 /* HeritageClause */ ); node.token = token; node.types = createNodeArray(types); node.transformFlags |= propagateChildrenFlags(node.types); switch(token){ - case 94 /* ExtendsKeyword */ : + case 96 /* ExtendsKeyword */ : node.transformFlags |= 1024 /* ContainsES2015 */ ; break; - case 117 /* ImplementsKeyword */ : + case 119 /* ImplementsKeyword */ : node.transformFlags |= 1 /* ContainsTypeScript */ ; break; default: @@ -25974,7 +26156,7 @@ ${lanes.join("\n")} return node.types !== types ? update(createHeritageClause(node.token, types), node) : node; } function createCatchClause(variableDeclaration, block) { - const node = createBaseNode(295 /* CatchClause */ ); + const node = createBaseNode(299 /* CatchClause */ ); node.variableDeclaration = asVariableDeclaration(variableDeclaration); node.block = block; node.transformFlags |= propagateChildFlags(node.variableDeclaration) | propagateChildFlags(node.block) | (!variableDeclaration ? 64 /* ContainsES2019 */ : 0 /* None */ ); @@ -25986,7 +26168,7 @@ ${lanes.join("\n")} return node.variableDeclaration !== variableDeclaration || node.block !== block ? update(createCatchClause(variableDeclaration, block), node) : node; } function createPropertyAssignment(name, initializer) { - const node = createBaseDeclaration(299 /* PropertyAssignment */ ); + const node = createBaseDeclaration(303 /* PropertyAssignment */ ); node.name = asName(name); node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); node.transformFlags |= propagateNameFlags(node.name) | propagateChildFlags(node.initializer); @@ -26008,7 +26190,7 @@ ${lanes.join("\n")} return update(updated, original); } function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - const node = createBaseDeclaration(300 /* ShorthandPropertyAssignment */ ); + const node = createBaseDeclaration(304 /* ShorthandPropertyAssignment */ ); node.name = asName(name); node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer); node.transformFlags |= propagateIdentifierNameFlags(node.name) | propagateChildFlags(node.objectAssignmentInitializer) | 1024 /* ContainsES2015 */ ; @@ -26032,7 +26214,7 @@ ${lanes.join("\n")} return update(updated, original); } function createSpreadAssignment(expression) { - const node = createBaseDeclaration(301 /* SpreadAssignment */ ); + const node = createBaseDeclaration(305 /* SpreadAssignment */ ); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.transformFlags |= propagateChildFlags(node.expression) | 65664 /* ContainsObjectRestOrSpread */ ; node.jsDoc = void 0; @@ -26042,7 +26224,7 @@ ${lanes.join("\n")} return node.expression !== expression ? update(createSpreadAssignment(expression), node) : node; } function createEnumMember(name, initializer) { - const node = createBaseDeclaration(302 /* EnumMember */ ); + const node = createBaseDeclaration(306 /* EnumMember */ ); node.name = asName(name); node.initializer = initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); node.transformFlags |= propagateChildFlags(node.name) | propagateChildFlags(node.initializer) | 1 /* ContainsTypeScript */ ; @@ -26053,7 +26235,7 @@ ${lanes.join("\n")} return node.name !== name || node.initializer !== initializer ? update(createEnumMember(name, initializer), node) : node; } function createSourceFile2(statements, endOfFileToken, flags2) { - const node = baseFactory2.createBaseSourceFileNode(308 /* SourceFile */ ); + const node = baseFactory2.createBaseSourceFileNode(312 /* SourceFile */ ); node.statements = createNodeArray(statements); node.endOfFileToken = endOfFileToken; node.flags |= flags2; @@ -26123,7 +26305,7 @@ ${lanes.join("\n")} } function cloneRedirectedSourceFile(source) { const node = createRedirectedSourceFile(source.redirectInfo); - node.flags |= source.flags & -9 /* Synthesized */ ; + node.flags |= source.flags & -17 /* Synthesized */ ; node.fileName = source.fileName; node.path = source.path; node.resolvedPath = source.resolvedPath; @@ -26134,8 +26316,8 @@ ${lanes.join("\n")} return node; } function cloneSourceFileWorker(source) { - const node = baseFactory2.createBaseSourceFileNode(308 /* SourceFile */ ); - node.flags |= source.flags & -9 /* Synthesized */ ; + const node = baseFactory2.createBaseSourceFileNode(312 /* SourceFile */ ); + node.flags |= source.flags & -17 /* Synthesized */ ; for(const p in source){ if (hasProperty(node, p) || !hasProperty(source, p)) continue; if (p === "emitNode") { @@ -26166,7 +26348,7 @@ ${lanes.join("\n")} return node.statements !== statements || node.isDeclarationFile !== isDeclarationFile || node.referencedFiles !== referencedFiles || node.typeReferenceDirectives !== typeReferenceDirectives || node.hasNoDefaultLib !== hasNoDefaultLib || node.libReferenceDirectives !== libReferenceDirectives ? update(cloneSourceFileWithChanges(node, statements, isDeclarationFile, referencedFiles, typeReferenceDirectives, hasNoDefaultLib, libReferenceDirectives), node) : node; } function createBundle(sourceFiles, prepends = emptyArray) { - const node = createBaseNode(309 /* Bundle */ ); + const node = createBaseNode(313 /* Bundle */ ); node.prepends = prepends; node.sourceFiles = sourceFiles; node.syntheticFileReferences = void 0; @@ -26179,7 +26361,7 @@ ${lanes.join("\n")} return node.sourceFiles !== sourceFiles || node.prepends !== prepends ? update(createBundle(sourceFiles, prepends), node) : node; } function createUnparsedSource(prologues, syntheticReferences, texts) { - const node = createBaseNode(310 /* UnparsedSource */ ); + const node = createBaseNode(314 /* UnparsedSource */ ); node.prologues = prologues; node.syntheticReferences = syntheticReferences; node.texts = texts; @@ -26196,48 +26378,48 @@ ${lanes.join("\n")} return node; } function createUnparsedPrologue(data) { - return createBaseUnparsedNode(303 /* UnparsedPrologue */ , data); + return createBaseUnparsedNode(307 /* UnparsedPrologue */ , data); } function createUnparsedPrepend(data, texts) { - const node = createBaseUnparsedNode(304 /* UnparsedPrepend */ , data); + const node = createBaseUnparsedNode(308 /* UnparsedPrepend */ , data); node.texts = texts; return node; } function createUnparsedTextLike(data, internal) { - return createBaseUnparsedNode(internal ? 306 /* UnparsedInternalText */ : 305 /* UnparsedText */ , data); + return createBaseUnparsedNode(internal ? 310 /* UnparsedInternalText */ : 309 /* UnparsedText */ , data); } function createUnparsedSyntheticReference(section) { - const node = createBaseNode(307 /* UnparsedSyntheticReference */ ); + const node = createBaseNode(311 /* UnparsedSyntheticReference */ ); node.data = section.data; node.section = section; return node; } function createInputFiles2() { - const node = createBaseNode(311 /* InputFiles */ ); + const node = createBaseNode(315 /* InputFiles */ ); node.javascriptText = ""; node.declarationText = ""; return node; } function createSyntheticExpression(type, isSpread = false, tupleNameSource) { - const node = createBaseNode(234 /* SyntheticExpression */ ); + const node = createBaseNode(237 /* SyntheticExpression */ ); node.type = type; node.isSpread = isSpread; node.tupleNameSource = tupleNameSource; return node; } function createSyntaxList3(children) { - const node = createBaseNode(354 /* SyntaxList */ ); + const node = createBaseNode(358 /* SyntaxList */ ); node._children = children; return node; } function createNotEmittedStatement(original) { - const node = createBaseNode(355 /* NotEmittedStatement */ ); + const node = createBaseNode(359 /* NotEmittedStatement */ ); node.original = original; setTextRange(node, original); return node; } function createPartiallyEmittedExpression(expression, original) { - const node = createBaseNode(356 /* PartiallyEmittedExpression */ ); + const node = createBaseNode(360 /* PartiallyEmittedExpression */ ); node.expression = expression; node.original = original; node.transformFlags |= propagateChildFlags(node.expression) | 1 /* ContainsTypeScript */ ; @@ -26258,7 +26440,7 @@ ${lanes.join("\n")} return node; } function createCommaListExpression(elements) { - const node = createBaseNode(357 /* CommaListExpression */ ); + const node = createBaseNode(361 /* CommaListExpression */ ); node.elements = createNodeArray(sameFlatMap(elements, flattenCommaElements)); node.transformFlags |= propagateChildrenFlags(node.elements); return node; @@ -26266,20 +26448,8 @@ ${lanes.join("\n")} function updateCommaListExpression(node, elements) { return node.elements !== elements ? update(createCommaListExpression(elements), node) : node; } - function createEndOfDeclarationMarker(original) { - const node = createBaseNode(359 /* EndOfDeclarationMarker */ ); - node.emitNode = {}; - node.original = original; - return node; - } - function createMergeDeclarationMarker(original) { - const node = createBaseNode(358 /* MergeDeclarationMarker */ ); - node.emitNode = {}; - node.original = original; - return node; - } function createSyntheticReferenceExpression(expression, thisArg) { - const node = createBaseNode(360 /* SyntheticReferenceExpression */ ); + const node = createBaseNode(362 /* SyntheticReferenceExpression */ ); node.expression = expression; node.thisArg = thisArg; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.thisArg); @@ -26290,7 +26460,7 @@ ${lanes.join("\n")} } function cloneGeneratedIdentifier(node) { const clone2 = createBaseIdentifier(node.escapedText); - clone2.flags |= node.flags & -9 /* Synthesized */ ; + clone2.flags |= node.flags & -17 /* Synthesized */ ; clone2.transformFlags = node.transformFlags; setOriginalNode(clone2, node); setIdentifierAutoGenerate(clone2, { @@ -26300,7 +26470,7 @@ ${lanes.join("\n")} } function cloneIdentifier(node) { const clone2 = createBaseIdentifier(node.escapedText); - clone2.flags |= node.flags & -9 /* Synthesized */ ; + clone2.flags |= node.flags & -17 /* Synthesized */ ; clone2.jsDoc = node.jsDoc; clone2.flowNode = node.flowNode; clone2.symbol = node.symbol; @@ -26312,7 +26482,7 @@ ${lanes.join("\n")} } function cloneGeneratedPrivateIdentifier(node) { const clone2 = createBasePrivateIdentifier(node.escapedText); - clone2.flags |= node.flags & -9 /* Synthesized */ ; + clone2.flags |= node.flags & -17 /* Synthesized */ ; clone2.transformFlags = node.transformFlags; setOriginalNode(clone2, node); setIdentifierAutoGenerate(clone2, { @@ -26322,7 +26492,7 @@ ${lanes.join("\n")} } function clonePrivateIdentifier(node) { const clone2 = createBasePrivateIdentifier(node.escapedText); - clone2.flags |= node.flags & -9 /* Synthesized */ ; + clone2.flags |= node.flags & -17 /* Synthesized */ ; clone2.transformFlags = node.transformFlags; setOriginalNode(clone2, node); return clone2; @@ -26335,7 +26505,7 @@ ${lanes.join("\n")} if (isGeneratedPrivateIdentifier(node)) return cloneGeneratedPrivateIdentifier(node); if (isPrivateIdentifier(node)) return clonePrivateIdentifier(node); const clone2 = !isNodeKind(node.kind) ? baseFactory2.createBaseTokenNode(node.kind) : baseFactory2.createBaseNode(node.kind); - clone2.flags |= node.flags & -9 /* Synthesized */ ; + clone2.flags |= node.flags & -17 /* Synthesized */ ; clone2.transformFlags = node.transformFlags; setOriginalNode(clone2, node); for(const key in node){ @@ -26370,7 +26540,10 @@ ${lanes.join("\n")} ])); } function createTypeCheck(value1, tag) { - return tag === "undefined" ? factory2.createStrictEquality(value1, createVoidZero()) : factory2.createStrictEquality(createTypeOfExpression(value1), createStringLiteral(tag)); + return tag === "null" ? factory2.createStrictEquality(value1, createNull()) : tag === "undefined" ? factory2.createStrictEquality(value1, createVoidZero()) : factory2.createStrictEquality(createTypeOfExpression(value1), createStringLiteral(tag)); + } + function createIsNotTypeCheck(value1, tag) { + return tag === "null" ? factory2.createStrictInequality(value1, createNull()) : tag === "undefined" ? factory2.createStrictInequality(value1, createVoidZero()) : factory2.createStrictInequality(createTypeOfExpression(value1), createStringLiteral(tag)); } function createMethodCall(object, methodName, argumentsList) { if (isCallChain(object)) return createCallChain(createPropertyAccessChain(object, /*questionDotToken*/ void 0, methodName), /*questionDotToken*/ void 0, /*typeArguments*/ void 0, argumentsList); @@ -26460,17 +26633,17 @@ ${lanes.join("\n")} } function updateOuterExpression(outerExpression, expression) { switch(outerExpression.kind){ - case 214 /* ParenthesizedExpression */ : + case 217 /* ParenthesizedExpression */ : return updateParenthesizedExpression(outerExpression, expression); - case 213 /* TypeAssertionExpression */ : + case 216 /* TypeAssertionExpression */ : return updateTypeAssertion(outerExpression, outerExpression.type, expression); - case 231 /* AsExpression */ : + case 234 /* AsExpression */ : return updateAsExpression(outerExpression, expression, outerExpression.type); - case 235 /* SatisfiesExpression */ : + case 238 /* SatisfiesExpression */ : return updateSatisfiesExpression(outerExpression, expression, outerExpression.type); - case 232 /* NonNullExpression */ : + case 235 /* NonNullExpression */ : return updateNonNullExpression(outerExpression, expression); - case 356 /* PartiallyEmittedExpression */ : + case 360 /* PartiallyEmittedExpression */ : return updatePartiallyEmittedExpression(outerExpression, expression); } } @@ -26490,18 +26663,18 @@ ${lanes.join("\n")} function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { const target = skipParentheses(node); switch(target.kind){ - case 79 /* Identifier */ : + case 80 /* Identifier */ : return cacheIdentifiers; - case 108 /* ThisKeyword */ : - case 8 /* NumericLiteral */ : - case 9 /* BigIntLiteral */ : - case 10 /* StringLiteral */ : + case 110 /* ThisKeyword */ : + case 9 /* NumericLiteral */ : + case 10 /* BigIntLiteral */ : + case 11 /* StringLiteral */ : return false; - case 206 /* ArrayLiteralExpression */ : + case 209 /* ArrayLiteralExpression */ : const elements = target.elements; if (elements.length === 0) return false; return true; - case 207 /* ObjectLiteralExpression */ : + case 210 /* ObjectLiteralExpression */ : return target.properties.length > 0; default: return true; @@ -26560,8 +26733,8 @@ ${lanes.join("\n")} function inlineExpressions(expressions) { return expressions.length > 10 ? createCommaListExpression(expressions) : reduceLeft(expressions, factory2.createComma); } - function getName(node, allowComments, allowSourceMaps, emitFlags = 0) { - const nodeName = getNameOfDeclaration(node); + function getName(node, allowComments, allowSourceMaps, emitFlags = 0, ignoreAssignedName) { + const nodeName = ignoreAssignedName ? node && getNonAssignedNameOfDeclaration(node) : getNameOfDeclaration(node); if (nodeName && isIdentifier(nodeName) && !isGeneratedIdentifier(nodeName)) { const name = setParent(setTextRange(cloneNode(nodeName), nodeName), nodeName.parent); emitFlags |= getEmitFlags(nodeName); @@ -26575,8 +26748,8 @@ ${lanes.join("\n")} function getInternalName(node, allowComments, allowSourceMaps) { return getName(node, allowComments, allowSourceMaps, 98304 /* InternalName */ ); } - function getLocalName(node, allowComments, allowSourceMaps) { - return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */ ); + function getLocalName(node, allowComments, allowSourceMaps, ignoreAssignedName) { + return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */ , ignoreAssignedName); } function getExportName(node, allowComments, allowSourceMaps) { return getName(node, allowComments, allowSourceMaps, 16384 /* ExportName */ ); @@ -26681,11 +26854,13 @@ ${lanes.join("\n")} return statements; } function updateModifiers(node, modifiers) { - var _a2; let modifierArray; if (typeof modifiers === "number") modifierArray = createModifiersFromModifierFlags(modifiers); else modifierArray = modifiers; - return isTypeParameterDeclaration(node) ? updateTypeParameterDeclaration(node, modifierArray, node.name, node.constraint, node.default) : isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : isConstructorTypeNode(node) ? updateConstructorTypeNode1(node, modifierArray, node.typeParameters, node.parameters, node.type) : isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : isPropertyDeclaration(node) ? updatePropertyDeclaration2(node, modifierArray, node.name, (_a2 = node.questionToken) != null ? _a2 : 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, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : isConstructorDeclaration(node) ? updateConstructorDeclaration(node, modifierArray, node.parameters, node.body) : isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : isIndexSignatureDeclaration(node) ? updateIndexSignature(node, 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, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : isFunctionDeclaration(node) ? updateFunctionDeclaration(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, modifierArray, node.name, node.typeParameters, node.type) : isEnumDeclaration(node) ? updateEnumDeclaration(node, modifierArray, node.name, node.members) : isModuleDeclaration(node) ? updateModuleDeclaration(node, modifierArray, node.name, node.body) : isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : isImportDeclaration(node) ? updateImportDeclaration(node, modifierArray, node.importClause, node.moduleSpecifier, node.assertClause) : isExportAssignment(node) ? updateExportAssignment(node, modifierArray, node.expression) : isExportDeclaration(node) ? updateExportDeclaration(node, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) : Debug.assertNever(node); + return isTypeParameterDeclaration(node) ? updateTypeParameterDeclaration(node, modifierArray, node.name, node.constraint, node.default) : isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : isConstructorTypeNode(node) ? updateConstructorTypeNode1(node, modifierArray, node.typeParameters, node.parameters, node.type) : isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : isPropertyDeclaration(node) ? updatePropertyDeclaration2(node, 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, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : isConstructorDeclaration(node) ? updateConstructorDeclaration(node, modifierArray, node.parameters, node.body) : isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : isIndexSignatureDeclaration(node) ? updateIndexSignature(node, 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, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : isFunctionDeclaration(node) ? updateFunctionDeclaration(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, modifierArray, node.name, node.typeParameters, node.type) : isEnumDeclaration(node) ? updateEnumDeclaration(node, modifierArray, node.name, node.members) : isModuleDeclaration(node) ? updateModuleDeclaration(node, modifierArray, node.name, node.body) : isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : isImportDeclaration(node) ? updateImportDeclaration(node, modifierArray, node.importClause, node.moduleSpecifier, node.assertClause) : isExportAssignment(node) ? updateExportAssignment(node, modifierArray, node.expression) : isExportDeclaration(node) ? updateExportDeclaration(node, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) : Debug.assertNever(node); + } + function updateModifierLike(node, modifierArray) { + return isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : isPropertyDeclaration(node) ? updatePropertyDeclaration2(node, modifierArray, node.name, node.questionToken ?? node.exclamationToken, node.type, node.initializer) : isMethodDeclaration(node) ? updateMethodDeclaration(node, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : isClassExpression(node) ? updateClassExpression(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : Debug.assertNever(node); } function asNodeArray(array) { return array ? createNodeArray(array) : void 0; @@ -26723,43 +26898,43 @@ ${lanes.join("\n")} } function getDefaultTagNameForKind(kind) { switch(kind){ - case 347 /* JSDocTypeTag */ : + case 351 /* JSDocTypeTag */ : return "type"; - case 345 /* JSDocReturnTag */ : + case 349 /* JSDocReturnTag */ : return "returns"; - case 346 /* JSDocThisTag */ : + case 350 /* JSDocThisTag */ : return "this"; - case 343 /* JSDocEnumTag */ : + case 347 /* JSDocEnumTag */ : return "enum"; - case 333 /* JSDocAuthorTag */ : + case 337 /* JSDocAuthorTag */ : return "author"; - case 335 /* JSDocClassTag */ : + case 339 /* JSDocClassTag */ : return "class"; - case 336 /* JSDocPublicTag */ : + case 340 /* JSDocPublicTag */ : return "public"; - case 337 /* JSDocPrivateTag */ : + case 341 /* JSDocPrivateTag */ : return "private"; - case 338 /* JSDocProtectedTag */ : + case 342 /* JSDocProtectedTag */ : return "protected"; - case 339 /* JSDocReadonlyTag */ : + case 343 /* JSDocReadonlyTag */ : return "readonly"; - case 340 /* JSDocOverrideTag */ : + case 344 /* JSDocOverrideTag */ : return "override"; - case 348 /* JSDocTemplateTag */ : + case 352 /* JSDocTemplateTag */ : return "template"; - case 349 /* JSDocTypedefTag */ : + case 353 /* JSDocTypedefTag */ : return "typedef"; - case 344 /* JSDocParameterTag */ : + case 348 /* JSDocParameterTag */ : return "param"; - case 351 /* JSDocPropertyTag */ : + case 355 /* JSDocPropertyTag */ : return "prop"; - case 341 /* JSDocCallbackTag */ : + case 345 /* JSDocCallbackTag */ : return "callback"; - case 342 /* JSDocOverloadTag */ : + case 346 /* JSDocOverloadTag */ : return "overload"; - case 331 /* JSDocAugmentsTag */ : + case 335 /* JSDocAugmentsTag */ : return "augments"; - case 332 /* JSDocImplementsTag */ : + case 336 /* JSDocImplementsTag */ : return "implements"; default: return Debug.fail(`Unsupported kind: ${Debug.formatSyntaxKind(kind)}`); @@ -26768,31 +26943,31 @@ ${lanes.join("\n")} function getCookedText(kind, rawText) { if (!rawTextScanner) rawTextScanner = createScanner(99 /* Latest */ , /*skipTrivia*/ false, 0 /* Standard */ ); switch(kind){ - case 14 /* NoSubstitutionTemplateLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : rawTextScanner.setText("`" + rawText + "`"); break; - case 15 /* TemplateHead */ : + case 16 /* TemplateHead */ : rawTextScanner.setText("`" + rawText + "${"); break; - case 16 /* TemplateMiddle */ : + case 17 /* TemplateMiddle */ : rawTextScanner.setText("}" + rawText + "${"); break; - case 17 /* TemplateTail */ : + case 18 /* TemplateTail */ : rawTextScanner.setText("}" + rawText + "`"); break; } let token = rawTextScanner.scan(); - if (token === 19 /* CloseBraceToken */ ) token = rawTextScanner.reScanTemplateToken(/*isTaggedTemplate*/ false); + if (token === 20 /* CloseBraceToken */ ) token = rawTextScanner.reScanTemplateToken(/*isTaggedTemplate*/ false); if (rawTextScanner.isUnterminated()) { rawTextScanner.setText(void 0); return invalidValueSentinel; } let tokenValue; switch(token){ - case 14 /* NoSubstitutionTemplateLiteral */ : - case 15 /* TemplateHead */ : - case 16 /* TemplateMiddle */ : - case 17 /* TemplateTail */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + case 16 /* TemplateHead */ : + case 17 /* TemplateMiddle */ : + case 18 /* TemplateTail */ : tokenValue = rawTextScanner.getTokenValue(); break; } @@ -26826,75 +27001,75 @@ ${lanes.join("\n")} children.transformFlags = subtreeFlags; } function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 179 /* FirstTypeNode */ && kind <= 202 /* LastTypeNode */ ) return -2 /* TypeExcludes */ ; + if (kind >= 182 /* FirstTypeNode */ && kind <= 205 /* LastTypeNode */ ) return -2 /* TypeExcludes */ ; switch(kind){ - case 210 /* CallExpression */ : - case 211 /* NewExpression */ : - case 206 /* ArrayLiteralExpression */ : + case 213 /* CallExpression */ : + case 214 /* NewExpression */ : + case 209 /* ArrayLiteralExpression */ : return -2147450880 /* ArrayLiteralOrCallOrNewExcludes */ ; - case 264 /* ModuleDeclaration */ : + case 267 /* ModuleDeclaration */ : return -1941676032 /* ModuleExcludes */ ; - case 166 /* Parameter */ : + case 169 /* Parameter */ : return -2147483648 /* ParameterExcludes */ ; - case 216 /* ArrowFunction */ : + case 219 /* ArrowFunction */ : return -2072174592 /* ArrowFunctionExcludes */ ; - case 215 /* FunctionExpression */ : - case 259 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 262 /* FunctionDeclaration */ : return -1937940480 /* FunctionExcludes */ ; - case 258 /* VariableDeclarationList */ : + case 261 /* VariableDeclarationList */ : return -2146893824 /* VariableDeclarationListExcludes */ ; - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : return -2147344384 /* ClassExcludes */ ; - case 173 /* Constructor */ : + case 176 /* Constructor */ : return -1937948672 /* ConstructorExcludes */ ; - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : return -2013249536 /* PropertyExcludes */ ; - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : return -2005057536 /* MethodOrAccessorExcludes */ ; - case 131 /* AnyKeyword */ : - case 148 /* NumberKeyword */ : - case 160 /* BigIntKeyword */ : - case 144 /* NeverKeyword */ : - case 152 /* StringKeyword */ : - case 149 /* ObjectKeyword */ : - case 134 /* BooleanKeyword */ : - case 153 /* SymbolKeyword */ : - case 114 /* VoidKeyword */ : - case 165 /* TypeParameter */ : - case 168 /* PropertySignature */ : - case 170 /* MethodSignature */ : - case 176 /* CallSignature */ : - case 177 /* ConstructSignature */ : - case 178 /* IndexSignature */ : - case 261 /* InterfaceDeclaration */ : - case 262 /* TypeAliasDeclaration */ : + case 133 /* AnyKeyword */ : + case 150 /* NumberKeyword */ : + case 163 /* BigIntKeyword */ : + case 146 /* NeverKeyword */ : + case 154 /* StringKeyword */ : + case 151 /* ObjectKeyword */ : + case 136 /* BooleanKeyword */ : + case 155 /* SymbolKeyword */ : + case 116 /* VoidKeyword */ : + case 168 /* TypeParameter */ : + case 171 /* PropertySignature */ : + case 173 /* MethodSignature */ : + case 179 /* CallSignature */ : + case 180 /* ConstructSignature */ : + case 181 /* IndexSignature */ : + case 264 /* InterfaceDeclaration */ : + case 265 /* TypeAliasDeclaration */ : return -2 /* TypeExcludes */ ; - case 207 /* ObjectLiteralExpression */ : + case 210 /* ObjectLiteralExpression */ : return -2147278848 /* ObjectLiteralExcludes */ ; - case 295 /* CatchClause */ : + case 299 /* CatchClause */ : return -2147418112 /* CatchClauseExcludes */ ; - case 203 /* ObjectBindingPattern */ : - case 204 /* ArrayBindingPattern */ : + case 206 /* ObjectBindingPattern */ : + case 207 /* ArrayBindingPattern */ : return -2147450880 /* BindingPatternExcludes */ ; - case 213 /* TypeAssertionExpression */ : - case 235 /* SatisfiesExpression */ : - case 231 /* AsExpression */ : - case 356 /* PartiallyEmittedExpression */ : - case 214 /* ParenthesizedExpression */ : - case 106 /* SuperKeyword */ : + case 216 /* TypeAssertionExpression */ : + case 238 /* SatisfiesExpression */ : + case 234 /* AsExpression */ : + case 360 /* PartiallyEmittedExpression */ : + case 217 /* ParenthesizedExpression */ : + case 108 /* SuperKeyword */ : return -2147483648 /* OuterExpressionExcludes */ ; - case 208 /* PropertyAccessExpression */ : - case 209 /* ElementAccessExpression */ : + case 211 /* PropertyAccessExpression */ : + case 212 /* ElementAccessExpression */ : return -2147483648 /* PropertyAccessExcludes */ ; default: return -2147483648 /* NodeExcludes */ ; } } function makeSynthetic(node) { - node.flags |= 8 /* Synthesized */ ; + node.flags |= 16 /* Synthesized */ ; return node; } function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) { @@ -26941,7 +27116,7 @@ ${lanes.join("\n")} }); } else { Debug.assert(!oldFileOfCurrentEmit); - node.text = text != null ? text : ""; + node.text = text ?? ""; node.sourceMapText = sourceMapText; } return node; @@ -27006,7 +27181,7 @@ ${lanes.join("\n")} let prependTexts; for (const text of section.texts)if (!stripInternal || text.kind !== "internal" /* Internal */ ) prependTexts = append(prependTexts, setTextRange(factory.createUnparsedTextLike(text.data, text.kind === "internal" /* Internal */ ), text)); prependChildren = addRange(prependChildren, prependTexts); - texts = append(texts, factory.createUnparsedPrepend(section.data, prependTexts != null ? prependTexts : emptyArray)); + texts = append(texts, factory.createUnparsedPrepend(section.data, prependTexts ?? emptyArray)); break; case "internal" /* Internal */ : if (stripInternal) { @@ -27026,7 +27201,7 @@ ${lanes.join("\n")} textNode ]; } - const node = parseNodeFactory.createUnparsedSource(prologues != null ? prologues : emptyArray, /*syntheticReferences*/ void 0, texts); + const node = parseNodeFactory.createUnparsedSource(prologues ?? emptyArray, /*syntheticReferences*/ void 0, texts); setEachParent(prologues, node); setEachParent(texts, node); setEachParent(prependChildren, node); @@ -27060,7 +27235,7 @@ ${lanes.join("\n")} default: Debug.assertNever(section); } - const node = factory.createUnparsedSource(emptyArray, syntheticReferences, texts != null ? texts : emptyArray); + const node = factory.createUnparsedSource(emptyArray, syntheticReferences, texts ?? emptyArray); setEachParent(syntheticReferences, node); setEachParent(texts, node); node.helpers = map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, (name)=>getAllUnscopedEmitHelpers().get(name)); @@ -27093,12 +27268,11 @@ ${lanes.join("\n")} }; let buildInfo; const getAndCacheBuildInfo = ()=>{ - var _a2, _b; if (buildInfo === void 0 && buildInfoPath) { - if (host == null ? void 0 : host.getBuildInfo) buildInfo = (_a2 = host.getBuildInfo(buildInfoPath, options.configFilePath)) != null ? _a2 : false; + if (host == null ? void 0 : host.getBuildInfo) buildInfo = host.getBuildInfo(buildInfoPath, options.configFilePath) ?? false; else { const result = textGetter(buildInfoPath); - buildInfo = result !== void 0 ? (_b = getBuildInfo(buildInfoPath, result)) != null ? _b : false : false; + buildInfo = result !== void 0 ? getBuildInfo(buildInfoPath, result) ?? false : false; } } return buildInfo || void 0; @@ -27143,20 +27317,22 @@ ${lanes.join("\n")} return new (SourceMapSource2 || (SourceMapSource2 = objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia2); } function setOriginalNode(node, original) { - node.original = original; - if (original) { - const emitNode = original.emitNode; - if (emitNode) node.emitNode = mergeEmitNode(emitNode, node.emitNode); + if (node.original !== original) { + node.original = original; + if (original) { + const emitNode = original.emitNode; + if (emitNode) node.emitNode = mergeEmitNode(emitNode, node.emitNode); + } } return node; } function mergeEmitNode(sourceEmitNode, destEmitNode) { - const { flags: flags , internalFlags: internalFlags , leadingComments: leadingComments , trailingComments: trailingComments , commentRange: commentRange , sourceMapRange: sourceMapRange , tokenSourceMapRanges: tokenSourceMapRanges , constantValue: constantValue , helpers: helpers , startsOnNewLine: startsOnNewLine , snippetElement: snippetElement } = sourceEmitNode; + const { flags: flags, internalFlags: internalFlags, leadingComments: leadingComments, trailingComments: trailingComments, commentRange: commentRange, sourceMapRange: sourceMapRange, tokenSourceMapRanges: tokenSourceMapRanges, constantValue: constantValue, helpers: helpers, startsOnNewLine: startsOnNewLine, snippetElement: snippetElement, classThis: classThis, assignedName: assignedName } = sourceEmitNode; if (!destEmitNode) destEmitNode = {}; - if (leadingComments) destEmitNode.leadingComments = addRange(leadingComments.slice(), destEmitNode.leadingComments); - if (trailingComments) destEmitNode.trailingComments = addRange(trailingComments.slice(), destEmitNode.trailingComments); if (flags) destEmitNode.flags = flags; if (internalFlags) destEmitNode.internalFlags = internalFlags & -9 /* Immutable */ ; + if (leadingComments) destEmitNode.leadingComments = addRange(leadingComments.slice(), destEmitNode.leadingComments); + if (trailingComments) destEmitNode.trailingComments = addRange(trailingComments.slice(), destEmitNode.trailingComments); if (commentRange) destEmitNode.commentRange = commentRange; if (sourceMapRange) destEmitNode.sourceMapRange = sourceMapRange; if (tokenSourceMapRanges) destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); @@ -27164,6 +27340,8 @@ ${lanes.join("\n")} if (helpers) for (const helper of helpers)destEmitNode.helpers = appendIfUnique(destEmitNode.helpers, helper); if (startsOnNewLine !== void 0) destEmitNode.startsOnNewLine = startsOnNewLine; if (snippetElement !== void 0) destEmitNode.snippetElement = snippetElement; + if (classThis) destEmitNode.classThis = classThis; + if (assignedName) destEmitNode.assignedName = assignedName; return destEmitNode; } function mergeTokenSourceMapRanges(sourceRanges, destRanges) { @@ -27200,15 +27378,14 @@ ${lanes.join("\n")} }); // src/compiler/factory/emitNode.ts function getOrCreateEmitNode(node) { - var _a2; if (!node.emitNode) { if (isParseTreeNode(node)) { - if (node.kind === 308 /* SourceFile */ ) return node.emitNode = { + if (node.kind === 312 /* SourceFile */ ) return node.emitNode = { annotatedNodes: [ node ] }; - const sourceFile = (_a2 = getSourceFileOfNode(getParseTreeNode(getSourceFileOfNode(node)))) != null ? _a2 : Debug.fail("Could not determine parsed source file."); + const sourceFile = getSourceFileOfNode(getParseTreeNode(getSourceFileOfNode(node))) ?? Debug.fail("Could not determine parsed source file."); getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); } node.emitNode = {}; @@ -27216,8 +27393,8 @@ ${lanes.join("\n")} return node.emitNode; } function disposeEmitNodes(sourceFile) { - var _a2, _b; - const annotatedNodes = (_b = (_a2 = getSourceFileOfNode(getParseTreeNode(sourceFile))) == null ? void 0 : _a2.emitNode) == null ? void 0 : _b.annotatedNodes; + var _a, _b; + const annotatedNodes = (_b = (_a = getSourceFileOfNode(getParseTreeNode(sourceFile))) == null ? void 0 : _a.emitNode) == null ? void 0 : _b.annotatedNodes; if (annotatedNodes) for (const node of annotatedNodes)node.emitNode = void 0; } function removeAllComments(node) { @@ -27246,43 +27423,42 @@ ${lanes.join("\n")} return node; } function getSourceMapRange(node) { - var _a2, _b; - return (_b = (_a2 = node.emitNode) == null ? void 0 : _a2.sourceMapRange) != null ? _b : node; + var _a; + return ((_a = node.emitNode) == null ? void 0 : _a.sourceMapRange) ?? node; } function setSourceMapRange(node, range) { getOrCreateEmitNode(node).sourceMapRange = range; return node; } function getTokenSourceMapRange(node, token) { - var _a2, _b; - return (_b = (_a2 = node.emitNode) == null ? void 0 : _a2.tokenSourceMapRanges) == null ? void 0 : _b[token]; + var _a, _b; + return (_b = (_a = node.emitNode) == null ? void 0 : _a.tokenSourceMapRanges) == null ? void 0 : _b[token]; } function setTokenSourceMapRange(node, token, range) { - var _a2; const emitNode = getOrCreateEmitNode(node); - const tokenSourceMapRanges = (_a2 = emitNode.tokenSourceMapRanges) != null ? _a2 : emitNode.tokenSourceMapRanges = []; + const tokenSourceMapRanges = emitNode.tokenSourceMapRanges ?? (emitNode.tokenSourceMapRanges = []); tokenSourceMapRanges[token] = range; return node; } function getStartsOnNewLine(node) { - var _a2; - return (_a2 = node.emitNode) == null ? void 0 : _a2.startsOnNewLine; + var _a; + return (_a = node.emitNode) == null ? void 0 : _a.startsOnNewLine; } function setStartsOnNewLine(node, newLine) { getOrCreateEmitNode(node).startsOnNewLine = newLine; return node; } function getCommentRange(node) { - var _a2, _b; - return (_b = (_a2 = node.emitNode) == null ? void 0 : _a2.commentRange) != null ? _b : node; + var _a; + return ((_a = node.emitNode) == null ? void 0 : _a.commentRange) ?? node; } function setCommentRange(node, range) { getOrCreateEmitNode(node).commentRange = range; return node; } function getSyntheticLeadingComments(node) { - var _a2; - return (_a2 = node.emitNode) == null ? void 0 : _a2.leadingComments; + var _a; + return (_a = node.emitNode) == null ? void 0 : _a.leadingComments; } function setSyntheticLeadingComments(node, comments) { getOrCreateEmitNode(node).leadingComments = comments; @@ -27298,8 +27474,8 @@ ${lanes.join("\n")} })); } function getSyntheticTrailingComments(node) { - var _a2; - return (_a2 = node.emitNode) == null ? void 0 : _a2.trailingComments; + var _a; + return (_a = node.emitNode) == null ? void 0 : _a.trailingComments; } function setSyntheticTrailingComments(node, comments) { getOrCreateEmitNode(node).trailingComments = comments; @@ -27323,8 +27499,8 @@ ${lanes.join("\n")} return node; } function getConstantValue(node) { - var _a2; - return (_a2 = node.emitNode) == null ? void 0 : _a2.constantValue; + var _a; + return (_a = node.emitNode) == null ? void 0 : _a.constantValue; } function setConstantValue(node, value1) { const emitNode = getOrCreateEmitNode(node); @@ -27344,14 +27520,14 @@ ${lanes.join("\n")} return node; } function removeEmitHelper(node, helper) { - var _a2; - const helpers = (_a2 = node.emitNode) == null ? void 0 : _a2.helpers; + var _a; + const helpers = (_a = node.emitNode) == null ? void 0 : _a.helpers; if (helpers) return orderedRemoveItem(helpers, helper); return false; } function getEmitHelpers(node) { - var _a2; - return (_a2 = node.emitNode) == null ? void 0 : _a2.helpers; + var _a; + return (_a = node.emitNode) == null ? void 0 : _a.helpers; } function moveEmitHelpers(source, target, predicate) { const sourceEmitNode = source.emitNode; @@ -27369,8 +27545,8 @@ ${lanes.join("\n")} if (helpersRemoved > 0) sourceEmitHelpers.length -= helpersRemoved; } function getSnippetElement(node) { - var _a2; - return (_a2 = node.emitNode) == null ? void 0 : _a2.snippetElement; + var _a; + return (_a = node.emitNode) == null ? void 0 : _a.snippetElement; } function setSnippetElement(node, snippet) { const emitNode = getOrCreateEmitNode(node); @@ -27387,32 +27563,32 @@ ${lanes.join("\n")} return node; } function getTypeNode(node) { - var _a2; - return (_a2 = node.emitNode) == null ? void 0 : _a2.typeNode; + var _a; + return (_a = node.emitNode) == null ? void 0 : _a.typeNode; } function setIdentifierTypeArguments(node, typeArguments) { getOrCreateEmitNode(node).identifierTypeArguments = typeArguments; return node; } function getIdentifierTypeArguments(node) { - var _a2; - return (_a2 = node.emitNode) == null ? void 0 : _a2.identifierTypeArguments; + var _a; + return (_a = node.emitNode) == null ? void 0 : _a.identifierTypeArguments; } function setIdentifierAutoGenerate(node, autoGenerate) { getOrCreateEmitNode(node).autoGenerate = autoGenerate; return node; } function getIdentifierAutoGenerate(node) { - var _a2; - return (_a2 = node.emitNode) == null ? void 0 : _a2.autoGenerate; + var _a; + return (_a = node.emitNode) == null ? void 0 : _a.autoGenerate; } function setIdentifierGeneratedImportReference(node, value1) { getOrCreateEmitNode(node).generatedImportReference = value1; return node; } function getIdentifierGeneratedImportReference(node) { - var _a2; - return (_a2 = node.emitNode) == null ? void 0 : _a2.generatedImportReference; + var _a; + return (_a = node.emitNode) == null ? void 0 : _a.generatedImportReference; } var init_emitNode = __esm({ "src/compiler/factory/emitNode.ts" () { @@ -27464,7 +27640,10 @@ ${lanes.join("\n")} createClassPrivateFieldGetHelper: // Class Fields Helpers createClassPrivateFieldGetHelper, createClassPrivateFieldSetHelper: createClassPrivateFieldSetHelper, - createClassPrivateFieldInHelper: createClassPrivateFieldInHelper + createClassPrivateFieldInHelper: createClassPrivateFieldInHelper, + createAddDisposableResourceHelper: // 'using' helpers + createAddDisposableResourceHelper, + createDisposeResourcesHelper: createDisposeResourcesHelper }; function getUnscopedHelperName(name) { return setEmitFlags(factory2.createIdentifier(name), 8196 /* AdviseOnEmitNode */ ); @@ -27495,10 +27674,12 @@ ${lanes.join("\n")} ]), location); } function createESDecorateClassContextObject(contextIn) { - return factory2.createObjectLiteralExpression([ + const properties = [ factory2.createPropertyAssignment(factory2.createIdentifier("kind"), factory2.createStringLiteral("class")), - factory2.createPropertyAssignment(factory2.createIdentifier("name"), contextIn.name) - ]); + factory2.createPropertyAssignment(factory2.createIdentifier("name"), contextIn.name), + factory2.createPropertyAssignment(factory2.createIdentifier("metadata"), contextIn.metadata) + ]; + return factory2.createObjectLiteralExpression(properties); } function createESDecorateClassElementAccessGetMethod(elementName) { const accessor = elementName.computed ? factory2.createElementAccessExpression(factory2.createIdentifier("obj"), elementName.name) : factory2.createPropertyAccessExpression(factory2.createIdentifier("obj"), elementName.name); @@ -27519,7 +27700,7 @@ ${lanes.join("\n")} const propertyName = elementName.computed ? elementName.name : isIdentifier(elementName.name) ? factory2.createStringLiteralFromNode(elementName.name) : elementName.name; return factory2.createPropertyAssignment("has", factory2.createArrowFunction(/*modifiers*/ void 0, /*typeParameters*/ void 0, [ factory2.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, factory2.createIdentifier("obj")) - ], /*type*/ void 0, /*equalsGreaterThanToken*/ void 0, factory2.createBinaryExpression(propertyName, 101 /* InKeyword */ , factory2.createIdentifier("obj")))); + ], /*type*/ void 0, /*equalsGreaterThanToken*/ void 0, factory2.createBinaryExpression(propertyName, 103 /* InKeyword */ , factory2.createIdentifier("obj")))); } function createESDecorateClassElementAccessObject(name, access) { const properties = []; @@ -27529,13 +27710,15 @@ ${lanes.join("\n")} return factory2.createObjectLiteralExpression(properties); } function createESDecorateClassElementContextObject(contextIn) { - return factory2.createObjectLiteralExpression([ + const properties = [ factory2.createPropertyAssignment(factory2.createIdentifier("kind"), factory2.createStringLiteral(contextIn.kind)), factory2.createPropertyAssignment(factory2.createIdentifier("name"), contextIn.name.computed ? contextIn.name.name : factory2.createStringLiteralFromNode(contextIn.name.name)), factory2.createPropertyAssignment(factory2.createIdentifier("static"), contextIn.static ? factory2.createTrue() : factory2.createFalse()), factory2.createPropertyAssignment(factory2.createIdentifier("private"), contextIn.private ? factory2.createTrue() : factory2.createFalse()), - factory2.createPropertyAssignment(factory2.createIdentifier("access"), createESDecorateClassElementAccessObject(contextIn.name, contextIn.access)) - ]); + factory2.createPropertyAssignment(factory2.createIdentifier("access"), createESDecorateClassElementAccessObject(contextIn.name, contextIn.access)), + factory2.createPropertyAssignment(factory2.createIdentifier("metadata"), contextIn.metadata) + ]; + return factory2.createObjectLiteralExpression(properties); } function createESDecorateContextObject(contextIn) { return contextIn.kind === "class" ? createESDecorateClassContextObject(contextIn) : createESDecorateClassElementContextObject(contextIn); @@ -27543,8 +27726,8 @@ ${lanes.join("\n")} function createESDecorateHelper(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { context.requestEmitHelper(esDecorateHelper); return factory2.createCallExpression(getUnscopedHelperName("__esDecorate"), /*typeArguments*/ void 0, [ - ctor != null ? ctor : factory2.createNull(), - descriptorIn != null ? descriptorIn : factory2.createNull(), + ctor ?? factory2.createNull(), + descriptorIn ?? factory2.createNull(), decorators, createESDecorateContextObject(contextIn), initializers, @@ -27618,7 +27801,7 @@ ${lanes.join("\n")} } function createAwaiterHelper(hasLexicalThis, hasLexicalArguments, promiseConstructor, body) { context.requestEmitHelper(awaiterHelper); - const generatorFunc = factory2.createFunctionExpression(/*modifiers*/ void 0, factory2.createToken(41 /* AsteriskToken */ ), /*name*/ void 0, /*typeParameters*/ void 0, /*parameters*/ [], /*type*/ void 0, body); + const generatorFunc = factory2.createFunctionExpression(/*modifiers*/ void 0, factory2.createToken(42 /* AsteriskToken */ ), /*name*/ void 0, /*typeParameters*/ void 0, /*parameters*/ [], /*type*/ void 0, body); (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 1572864 /* ReuseTempVariableScope */ ; return factory2.createCallExpression(getUnscopedHelperName("__awaiter"), /*typeArguments*/ void 0, [ hasLexicalThis ? factory2.createThis() : factory2.createVoidZero(), @@ -27759,11 +27942,25 @@ ${lanes.join("\n")} } function createClassPrivateFieldInHelper(state, receiver) { context.requestEmitHelper(classPrivateFieldInHelper); - return factory2.createCallExpression(getUnscopedHelperName("__classPrivateFieldIn"), /* typeArguments*/ void 0, [ + return factory2.createCallExpression(getUnscopedHelperName("__classPrivateFieldIn"), /*typeArguments*/ void 0, [ state, receiver ]); } + function createAddDisposableResourceHelper(envBinding, value1, async) { + context.requestEmitHelper(addDisposableResourceHelper); + return factory2.createCallExpression(getUnscopedHelperName("__addDisposableResource"), /*typeArguments*/ void 0, [ + envBinding, + value1, + async ? factory2.createTrue() : factory2.createFalse() + ]); + } + function createDisposeResourcesHelper(envBinding) { + context.requestEmitHelper(disposeResourcesHelper); + return factory2.createCallExpression(getUnscopedHelperName("__disposeResources"), /*typeArguments*/ void 0, [ + envBinding + ]); + } } function compareEmitHelpers(x, y) { if (x === y) return 0 /* EqualTo */ ; @@ -27812,13 +28009,15 @@ ${lanes.join("\n")} classPrivateFieldSetHelper, classPrivateFieldInHelper, createBindingHelper, - setModuleDefaultHelper + setModuleDefaultHelper, + addDisposableResourceHelper, + disposeResourcesHelper ], (helper)=>helper.name)); } function isCallToHelper(firstSegment, helperName) { return isCallExpression(firstSegment) && isIdentifier(firstSegment.expression) && (getEmitFlags(firstSegment.expression) & 8192 /* HelperName */ ) !== 0 && firstSegment.expression.escapedText === helperName; } - var PrivateIdentifierKind, decorateHelper, metadataHelper, paramHelper, esDecorateHelper, runInitializersHelper, assignHelper, awaitHelper, asyncGeneratorHelper, asyncDelegator, asyncValues, restHelper, awaiterHelper, extendsHelper, templateObjectHelper, readHelper, spreadArrayHelper, propKeyHelper, setFunctionNameHelper, valuesHelper, generatorHelper, createBindingHelper, setModuleDefaultHelper, importStarHelper, importDefaultHelper, exportStarHelper, classPrivateFieldGetHelper, classPrivateFieldSetHelper, classPrivateFieldInHelper, allUnscopedEmitHelpers, asyncSuperHelper, advancedAsyncSuperHelper; + var PrivateIdentifierKind, decorateHelper, metadataHelper, paramHelper, esDecorateHelper, runInitializersHelper, assignHelper, awaitHelper, asyncGeneratorHelper, asyncDelegator, asyncValues, restHelper, awaiterHelper, extendsHelper, templateObjectHelper, readHelper, spreadArrayHelper, propKeyHelper, setFunctionNameHelper, valuesHelper, generatorHelper, createBindingHelper, setModuleDefaultHelper, importStarHelper, importDefaultHelper, exportStarHelper, classPrivateFieldGetHelper, classPrivateFieldSetHelper, classPrivateFieldInHelper, addDisposableResourceHelper, disposeResourcesHelper, allUnscopedEmitHelpers, asyncSuperHelper, advancedAsyncSuperHelper; var init_emitHelpers = __esm({ "src/compiler/factory/emitHelpers.ts" () { "use strict"; @@ -27885,10 +28084,10 @@ ${lanes.join("\n")} if (result === null || typeof result !== "object") throw new TypeError("Object expected"); if (_ = accept(result.get)) descriptor.get = _; if (_ = accept(result.set)) descriptor.set = _; - if (_ = accept(result.init)) initializers.push(_); + if (_ = accept(result.init)) initializers.unshift(_); } else if (_ = accept(result)) { - if (kind === "field") initializers.push(_); + if (kind === "field") initializers.unshift(_); else descriptor[key] = _; } } @@ -28258,6 +28457,63 @@ ${lanes.join("\n")} 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); };` + }; + addDisposableResourceHelper = { + name: "typescript:addDisposableResource", + importName: "__addDisposableResource", + scoped: false, + text: ` + var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + env.stack.push({ value: value, dispose: dispose, async: async }); + } + else if (async) { + env.stack.push({ async: true }); + } + return value; + };` + }; + disposeResourcesHelper = { + name: "typescript:disposeResources", + importName: "__disposeResources", + scoped: false, + text: ` + var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { + return function (env) { + function fail(e) { + env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + function next() { + while (env.stack.length) { + var rec = env.stack.pop(); + try { + var result = rec.dispose && rec.dispose.call(rec.value); + if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + } + catch (e) { + fail(e); + } + } + if (env.hasError) throw env.error; + } + return next(); + }; + })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + });` }; asyncSuperHelper = { name: "typescript:async-super", @@ -28278,682 +28534,679 @@ ${lanes.join("\n")} }); // src/compiler/factory/nodeTests.ts function isNumericLiteral(node) { - return node.kind === 8 /* NumericLiteral */ ; + return node.kind === 9 /* NumericLiteral */ ; } function isBigIntLiteral(node) { - return node.kind === 9 /* BigIntLiteral */ ; + return node.kind === 10 /* BigIntLiteral */ ; } function isStringLiteral(node) { - return node.kind === 10 /* StringLiteral */ ; + return node.kind === 11 /* StringLiteral */ ; } function isJsxText(node) { - return node.kind === 11 /* JsxText */ ; + return node.kind === 12 /* JsxText */ ; } function isRegularExpressionLiteral(node) { - return node.kind === 13 /* RegularExpressionLiteral */ ; + return node.kind === 14 /* RegularExpressionLiteral */ ; } function isNoSubstitutionTemplateLiteral(node) { - return node.kind === 14 /* NoSubstitutionTemplateLiteral */ ; + return node.kind === 15 /* NoSubstitutionTemplateLiteral */ ; } function isTemplateHead(node) { - return node.kind === 15 /* TemplateHead */ ; + return node.kind === 16 /* TemplateHead */ ; } function isTemplateMiddle(node) { - return node.kind === 16 /* TemplateMiddle */ ; + return node.kind === 17 /* TemplateMiddle */ ; } function isTemplateTail(node) { - return node.kind === 17 /* TemplateTail */ ; + return node.kind === 18 /* TemplateTail */ ; } function isDotDotDotToken(node) { - return node.kind === 25 /* DotDotDotToken */ ; + return node.kind === 26 /* DotDotDotToken */ ; } function isCommaToken(node) { - return node.kind === 27 /* CommaToken */ ; + return node.kind === 28 /* CommaToken */ ; } function isPlusToken(node) { - return node.kind === 39 /* PlusToken */ ; + return node.kind === 40 /* PlusToken */ ; } function isMinusToken(node) { - return node.kind === 40 /* MinusToken */ ; + return node.kind === 41 /* MinusToken */ ; } function isAsteriskToken(node) { - return node.kind === 41 /* AsteriskToken */ ; + return node.kind === 42 /* AsteriskToken */ ; } function isExclamationToken(node) { - return node.kind === 53 /* ExclamationToken */ ; + return node.kind === 54 /* ExclamationToken */ ; } function isQuestionToken(node) { - return node.kind === 57 /* QuestionToken */ ; + return node.kind === 58 /* QuestionToken */ ; } function isColonToken(node) { - return node.kind === 58 /* ColonToken */ ; + return node.kind === 59 /* ColonToken */ ; } function isQuestionDotToken(node) { - return node.kind === 28 /* QuestionDotToken */ ; + return node.kind === 29 /* QuestionDotToken */ ; } function isEqualsGreaterThanToken(node) { - return node.kind === 38 /* EqualsGreaterThanToken */ ; + return node.kind === 39 /* EqualsGreaterThanToken */ ; } function isIdentifier(node) { - return node.kind === 79 /* Identifier */ ; + return node.kind === 80 /* Identifier */ ; } function isPrivateIdentifier(node) { - return node.kind === 80 /* PrivateIdentifier */ ; + return node.kind === 81 /* PrivateIdentifier */ ; } function isExportModifier(node) { - return node.kind === 93 /* ExportKeyword */ ; + return node.kind === 95 /* ExportKeyword */ ; } function isDefaultModifier(node) { - return node.kind === 88 /* DefaultKeyword */ ; + return node.kind === 90 /* DefaultKeyword */ ; } function isAsyncModifier(node) { - return node.kind === 132 /* AsyncKeyword */ ; + return node.kind === 134 /* AsyncKeyword */ ; } function isAssertsKeyword(node) { - return node.kind === 129 /* AssertsKeyword */ ; + return node.kind === 131 /* AssertsKeyword */ ; } function isAwaitKeyword(node) { - return node.kind === 133 /* AwaitKeyword */ ; + return node.kind === 135 /* AwaitKeyword */ ; } function isReadonlyKeyword(node) { - return node.kind === 146 /* ReadonlyKeyword */ ; + return node.kind === 148 /* ReadonlyKeyword */ ; } function isStaticModifier(node) { - return node.kind === 124 /* StaticKeyword */ ; + return node.kind === 126 /* StaticKeyword */ ; } function isAbstractModifier(node) { - return node.kind === 126 /* AbstractKeyword */ ; + return node.kind === 128 /* AbstractKeyword */ ; } function isOverrideModifier(node) { - return node.kind === 161 /* OverrideKeyword */ ; + return node.kind === 164 /* OverrideKeyword */ ; } function isAccessorModifier(node) { - return node.kind === 127 /* AccessorKeyword */ ; + return node.kind === 129 /* AccessorKeyword */ ; } function isSuperKeyword(node) { - return node.kind === 106 /* SuperKeyword */ ; + return node.kind === 108 /* SuperKeyword */ ; } function isImportKeyword(node) { - return node.kind === 100 /* ImportKeyword */ ; + return node.kind === 102 /* ImportKeyword */ ; } function isCaseKeyword(node) { - return node.kind === 82 /* CaseKeyword */ ; + return node.kind === 84 /* CaseKeyword */ ; } function isQualifiedName(node) { - return node.kind === 163 /* QualifiedName */ ; + return node.kind === 166 /* QualifiedName */ ; } function isComputedPropertyName(node) { - return node.kind === 164 /* ComputedPropertyName */ ; + return node.kind === 167 /* ComputedPropertyName */ ; } function isTypeParameterDeclaration(node) { - return node.kind === 165 /* TypeParameter */ ; + return node.kind === 168 /* TypeParameter */ ; } function isParameter(node) { - return node.kind === 166 /* Parameter */ ; + return node.kind === 169 /* Parameter */ ; } function isDecorator(node) { - return node.kind === 167 /* Decorator */ ; + return node.kind === 170 /* Decorator */ ; } function isPropertySignature(node) { - return node.kind === 168 /* PropertySignature */ ; + return node.kind === 171 /* PropertySignature */ ; } function isPropertyDeclaration(node) { - return node.kind === 169 /* PropertyDeclaration */ ; + return node.kind === 172 /* PropertyDeclaration */ ; } function isMethodSignature(node) { - return node.kind === 170 /* MethodSignature */ ; + return node.kind === 173 /* MethodSignature */ ; } function isMethodDeclaration(node) { - return node.kind === 171 /* MethodDeclaration */ ; + return node.kind === 174 /* MethodDeclaration */ ; } function isClassStaticBlockDeclaration(node) { - return node.kind === 172 /* ClassStaticBlockDeclaration */ ; + return node.kind === 175 /* ClassStaticBlockDeclaration */ ; } function isConstructorDeclaration(node) { - return node.kind === 173 /* Constructor */ ; + return node.kind === 176 /* Constructor */ ; } function isGetAccessorDeclaration(node) { - return node.kind === 174 /* GetAccessor */ ; + return node.kind === 177 /* GetAccessor */ ; } function isSetAccessorDeclaration(node) { - return node.kind === 175 /* SetAccessor */ ; + return node.kind === 178 /* SetAccessor */ ; } function isCallSignatureDeclaration(node) { - return node.kind === 176 /* CallSignature */ ; + return node.kind === 179 /* CallSignature */ ; } function isConstructSignatureDeclaration(node) { - return node.kind === 177 /* ConstructSignature */ ; + return node.kind === 180 /* ConstructSignature */ ; } function isIndexSignatureDeclaration(node) { - return node.kind === 178 /* IndexSignature */ ; + return node.kind === 181 /* IndexSignature */ ; } function isTypePredicateNode(node) { - return node.kind === 179 /* TypePredicate */ ; + return node.kind === 182 /* TypePredicate */ ; } function isTypeReferenceNode(node) { - return node.kind === 180 /* TypeReference */ ; + return node.kind === 183 /* TypeReference */ ; } function isFunctionTypeNode(node) { - return node.kind === 181 /* FunctionType */ ; + return node.kind === 184 /* FunctionType */ ; } function isConstructorTypeNode(node) { - return node.kind === 182 /* ConstructorType */ ; + return node.kind === 185 /* ConstructorType */ ; } function isTypeQueryNode(node) { - return node.kind === 183 /* TypeQuery */ ; + return node.kind === 186 /* TypeQuery */ ; } function isTypeLiteralNode(node) { - return node.kind === 184 /* TypeLiteral */ ; + return node.kind === 187 /* TypeLiteral */ ; } function isArrayTypeNode(node) { - return node.kind === 185 /* ArrayType */ ; + return node.kind === 188 /* ArrayType */ ; } function isTupleTypeNode(node) { - return node.kind === 186 /* TupleType */ ; + return node.kind === 189 /* TupleType */ ; } function isNamedTupleMember(node) { - return node.kind === 199 /* NamedTupleMember */ ; + return node.kind === 202 /* NamedTupleMember */ ; } function isOptionalTypeNode(node) { - return node.kind === 187 /* OptionalType */ ; + return node.kind === 190 /* OptionalType */ ; } function isRestTypeNode(node) { - return node.kind === 188 /* RestType */ ; + return node.kind === 191 /* RestType */ ; } function isUnionTypeNode(node) { - return node.kind === 189 /* UnionType */ ; + return node.kind === 192 /* UnionType */ ; } function isIntersectionTypeNode(node) { - return node.kind === 190 /* IntersectionType */ ; + return node.kind === 193 /* IntersectionType */ ; } function isConditionalTypeNode(node) { - return node.kind === 191 /* ConditionalType */ ; + return node.kind === 194 /* ConditionalType */ ; } function isInferTypeNode(node) { - return node.kind === 192 /* InferType */ ; + return node.kind === 195 /* InferType */ ; } function isParenthesizedTypeNode(node) { - return node.kind === 193 /* ParenthesizedType */ ; + return node.kind === 196 /* ParenthesizedType */ ; } function isThisTypeNode(node) { - return node.kind === 194 /* ThisType */ ; + return node.kind === 197 /* ThisType */ ; } function isTypeOperatorNode(node) { - return node.kind === 195 /* TypeOperator */ ; + return node.kind === 198 /* TypeOperator */ ; } function isIndexedAccessTypeNode(node) { - return node.kind === 196 /* IndexedAccessType */ ; + return node.kind === 199 /* IndexedAccessType */ ; } function isMappedTypeNode(node) { - return node.kind === 197 /* MappedType */ ; + return node.kind === 200 /* MappedType */ ; } function isLiteralTypeNode(node) { - return node.kind === 198 /* LiteralType */ ; + return node.kind === 201 /* LiteralType */ ; } function isImportTypeNode(node) { - return node.kind === 202 /* ImportType */ ; + return node.kind === 205 /* ImportType */ ; } function isTemplateLiteralTypeSpan(node) { - return node.kind === 201 /* TemplateLiteralTypeSpan */ ; + return node.kind === 204 /* TemplateLiteralTypeSpan */ ; } function isTemplateLiteralTypeNode(node) { - return node.kind === 200 /* TemplateLiteralType */ ; + return node.kind === 203 /* TemplateLiteralType */ ; } function isObjectBindingPattern(node) { - return node.kind === 203 /* ObjectBindingPattern */ ; + return node.kind === 206 /* ObjectBindingPattern */ ; } function isArrayBindingPattern(node) { - return node.kind === 204 /* ArrayBindingPattern */ ; + return node.kind === 207 /* ArrayBindingPattern */ ; } function isBindingElement(node) { - return node.kind === 205 /* BindingElement */ ; + return node.kind === 208 /* BindingElement */ ; } function isArrayLiteralExpression(node) { - return node.kind === 206 /* ArrayLiteralExpression */ ; + return node.kind === 209 /* ArrayLiteralExpression */ ; } function isObjectLiteralExpression(node) { - return node.kind === 207 /* ObjectLiteralExpression */ ; + return node.kind === 210 /* ObjectLiteralExpression */ ; } function isPropertyAccessExpression(node) { - return node.kind === 208 /* PropertyAccessExpression */ ; + return node.kind === 211 /* PropertyAccessExpression */ ; } function isElementAccessExpression(node) { - return node.kind === 209 /* ElementAccessExpression */ ; + return node.kind === 212 /* ElementAccessExpression */ ; } function isCallExpression(node) { - return node.kind === 210 /* CallExpression */ ; + return node.kind === 213 /* CallExpression */ ; } function isNewExpression(node) { - return node.kind === 211 /* NewExpression */ ; + return node.kind === 214 /* NewExpression */ ; } function isTaggedTemplateExpression(node) { - return node.kind === 212 /* TaggedTemplateExpression */ ; + return node.kind === 215 /* TaggedTemplateExpression */ ; } function isTypeAssertionExpression(node) { - return node.kind === 213 /* TypeAssertionExpression */ ; + return node.kind === 216 /* TypeAssertionExpression */ ; } function isParenthesizedExpression(node) { - return node.kind === 214 /* ParenthesizedExpression */ ; + return node.kind === 217 /* ParenthesizedExpression */ ; } function isFunctionExpression(node) { - return node.kind === 215 /* FunctionExpression */ ; + return node.kind === 218 /* FunctionExpression */ ; } function isArrowFunction(node) { - return node.kind === 216 /* ArrowFunction */ ; + return node.kind === 219 /* ArrowFunction */ ; } function isDeleteExpression(node) { - return node.kind === 217 /* DeleteExpression */ ; + return node.kind === 220 /* DeleteExpression */ ; } function isTypeOfExpression(node) { - return node.kind === 218 /* TypeOfExpression */ ; + return node.kind === 221 /* TypeOfExpression */ ; } function isVoidExpression(node) { - return node.kind === 219 /* VoidExpression */ ; + return node.kind === 222 /* VoidExpression */ ; } function isAwaitExpression(node) { - return node.kind === 220 /* AwaitExpression */ ; + return node.kind === 223 /* AwaitExpression */ ; } function isPrefixUnaryExpression(node) { - return node.kind === 221 /* PrefixUnaryExpression */ ; + return node.kind === 224 /* PrefixUnaryExpression */ ; } function isPostfixUnaryExpression(node) { - return node.kind === 222 /* PostfixUnaryExpression */ ; + return node.kind === 225 /* PostfixUnaryExpression */ ; } function isBinaryExpression(node) { - return node.kind === 223 /* BinaryExpression */ ; + return node.kind === 226 /* BinaryExpression */ ; } function isConditionalExpression(node) { - return node.kind === 224 /* ConditionalExpression */ ; + return node.kind === 227 /* ConditionalExpression */ ; } function isTemplateExpression(node) { - return node.kind === 225 /* TemplateExpression */ ; + return node.kind === 228 /* TemplateExpression */ ; } function isYieldExpression(node) { - return node.kind === 226 /* YieldExpression */ ; + return node.kind === 229 /* YieldExpression */ ; } function isSpreadElement(node) { - return node.kind === 227 /* SpreadElement */ ; + return node.kind === 230 /* SpreadElement */ ; } function isClassExpression(node) { - return node.kind === 228 /* ClassExpression */ ; + return node.kind === 231 /* ClassExpression */ ; } function isOmittedExpression(node) { - return node.kind === 229 /* OmittedExpression */ ; + return node.kind === 232 /* OmittedExpression */ ; } function isExpressionWithTypeArguments(node) { - return node.kind === 230 /* ExpressionWithTypeArguments */ ; + return node.kind === 233 /* ExpressionWithTypeArguments */ ; } function isAsExpression(node) { - return node.kind === 231 /* AsExpression */ ; + return node.kind === 234 /* AsExpression */ ; } function isSatisfiesExpression(node) { - return node.kind === 235 /* SatisfiesExpression */ ; + return node.kind === 238 /* SatisfiesExpression */ ; } function isNonNullExpression(node) { - return node.kind === 232 /* NonNullExpression */ ; + return node.kind === 235 /* NonNullExpression */ ; } function isMetaProperty(node) { - return node.kind === 233 /* MetaProperty */ ; + return node.kind === 236 /* MetaProperty */ ; } function isSyntheticExpression(node) { - return node.kind === 234 /* SyntheticExpression */ ; + return node.kind === 237 /* SyntheticExpression */ ; } function isPartiallyEmittedExpression(node) { - return node.kind === 356 /* PartiallyEmittedExpression */ ; + return node.kind === 360 /* PartiallyEmittedExpression */ ; } function isCommaListExpression(node) { - return node.kind === 357 /* CommaListExpression */ ; + return node.kind === 361 /* CommaListExpression */ ; } function isTemplateSpan(node) { - return node.kind === 236 /* TemplateSpan */ ; + return node.kind === 239 /* TemplateSpan */ ; } function isSemicolonClassElement(node) { - return node.kind === 237 /* SemicolonClassElement */ ; + return node.kind === 240 /* SemicolonClassElement */ ; } function isBlock(node) { - return node.kind === 238 /* Block */ ; + return node.kind === 241 /* Block */ ; } function isVariableStatement(node) { - return node.kind === 240 /* VariableStatement */ ; + return node.kind === 243 /* VariableStatement */ ; } function isEmptyStatement(node) { - return node.kind === 239 /* EmptyStatement */ ; + return node.kind === 242 /* EmptyStatement */ ; } function isExpressionStatement(node) { - return node.kind === 241 /* ExpressionStatement */ ; + return node.kind === 244 /* ExpressionStatement */ ; } function isIfStatement(node) { - return node.kind === 242 /* IfStatement */ ; + return node.kind === 245 /* IfStatement */ ; } function isDoStatement(node) { - return node.kind === 243 /* DoStatement */ ; + return node.kind === 246 /* DoStatement */ ; } function isWhileStatement(node) { - return node.kind === 244 /* WhileStatement */ ; + return node.kind === 247 /* WhileStatement */ ; } function isForStatement(node) { - return node.kind === 245 /* ForStatement */ ; + return node.kind === 248 /* ForStatement */ ; } function isForInStatement(node) { - return node.kind === 246 /* ForInStatement */ ; + return node.kind === 249 /* ForInStatement */ ; } function isForOfStatement(node) { - return node.kind === 247 /* ForOfStatement */ ; + return node.kind === 250 /* ForOfStatement */ ; } function isContinueStatement(node) { - return node.kind === 248 /* ContinueStatement */ ; + return node.kind === 251 /* ContinueStatement */ ; } function isBreakStatement(node) { - return node.kind === 249 /* BreakStatement */ ; + return node.kind === 252 /* BreakStatement */ ; } function isReturnStatement(node) { - return node.kind === 250 /* ReturnStatement */ ; + return node.kind === 253 /* ReturnStatement */ ; } function isWithStatement(node) { - return node.kind === 251 /* WithStatement */ ; + return node.kind === 254 /* WithStatement */ ; } function isSwitchStatement(node) { - return node.kind === 252 /* SwitchStatement */ ; + return node.kind === 255 /* SwitchStatement */ ; } function isLabeledStatement(node) { - return node.kind === 253 /* LabeledStatement */ ; + return node.kind === 256 /* LabeledStatement */ ; } function isThrowStatement(node) { - return node.kind === 254 /* ThrowStatement */ ; + return node.kind === 257 /* ThrowStatement */ ; } function isTryStatement(node) { - return node.kind === 255 /* TryStatement */ ; + return node.kind === 258 /* TryStatement */ ; } function isDebuggerStatement(node) { - return node.kind === 256 /* DebuggerStatement */ ; + return node.kind === 259 /* DebuggerStatement */ ; } function isVariableDeclaration(node) { - return node.kind === 257 /* VariableDeclaration */ ; + return node.kind === 260 /* VariableDeclaration */ ; } function isVariableDeclarationList(node) { - return node.kind === 258 /* VariableDeclarationList */ ; + return node.kind === 261 /* VariableDeclarationList */ ; } function isFunctionDeclaration(node) { - return node.kind === 259 /* FunctionDeclaration */ ; + return node.kind === 262 /* FunctionDeclaration */ ; } function isClassDeclaration(node) { - return node.kind === 260 /* ClassDeclaration */ ; + return node.kind === 263 /* ClassDeclaration */ ; } function isInterfaceDeclaration(node) { - return node.kind === 261 /* InterfaceDeclaration */ ; + return node.kind === 264 /* InterfaceDeclaration */ ; } function isTypeAliasDeclaration(node) { - return node.kind === 262 /* TypeAliasDeclaration */ ; + return node.kind === 265 /* TypeAliasDeclaration */ ; } function isEnumDeclaration(node) { - return node.kind === 263 /* EnumDeclaration */ ; + return node.kind === 266 /* EnumDeclaration */ ; } function isModuleDeclaration(node) { - return node.kind === 264 /* ModuleDeclaration */ ; + return node.kind === 267 /* ModuleDeclaration */ ; } function isModuleBlock(node) { - return node.kind === 265 /* ModuleBlock */ ; + return node.kind === 268 /* ModuleBlock */ ; } function isCaseBlock(node) { - return node.kind === 266 /* CaseBlock */ ; + return node.kind === 269 /* CaseBlock */ ; } function isNamespaceExportDeclaration(node) { - return node.kind === 267 /* NamespaceExportDeclaration */ ; + return node.kind === 270 /* NamespaceExportDeclaration */ ; } function isImportEqualsDeclaration(node) { - return node.kind === 268 /* ImportEqualsDeclaration */ ; + return node.kind === 271 /* ImportEqualsDeclaration */ ; } function isImportDeclaration(node) { - return node.kind === 269 /* ImportDeclaration */ ; + return node.kind === 272 /* ImportDeclaration */ ; } function isImportClause(node) { - return node.kind === 270 /* ImportClause */ ; + return node.kind === 273 /* ImportClause */ ; } function isImportTypeAssertionContainer(node) { - return node.kind === 298 /* ImportTypeAssertionContainer */ ; + return node.kind === 302 /* ImportTypeAssertionContainer */ ; } function isAssertClause(node) { - return node.kind === 296 /* AssertClause */ ; + return node.kind === 300 /* AssertClause */ ; } function isAssertEntry(node) { - return node.kind === 297 /* AssertEntry */ ; + return node.kind === 301 /* AssertEntry */ ; } function isNamespaceImport(node) { - return node.kind === 271 /* NamespaceImport */ ; + return node.kind === 274 /* NamespaceImport */ ; } function isNamespaceExport(node) { - return node.kind === 277 /* NamespaceExport */ ; + return node.kind === 280 /* NamespaceExport */ ; } function isNamedImports(node) { - return node.kind === 272 /* NamedImports */ ; + return node.kind === 275 /* NamedImports */ ; } function isImportSpecifier(node) { - return node.kind === 273 /* ImportSpecifier */ ; + return node.kind === 276 /* ImportSpecifier */ ; } function isExportAssignment(node) { - return node.kind === 274 /* ExportAssignment */ ; + return node.kind === 277 /* ExportAssignment */ ; } function isExportDeclaration(node) { - return node.kind === 275 /* ExportDeclaration */ ; + return node.kind === 278 /* ExportDeclaration */ ; } function isNamedExports(node) { - return node.kind === 276 /* NamedExports */ ; + return node.kind === 279 /* NamedExports */ ; } function isExportSpecifier(node) { - return node.kind === 278 /* ExportSpecifier */ ; + return node.kind === 281 /* ExportSpecifier */ ; } function isMissingDeclaration(node) { - return node.kind === 279 /* MissingDeclaration */ ; + return node.kind === 282 /* MissingDeclaration */ ; } function isNotEmittedStatement(node) { - return node.kind === 355 /* NotEmittedStatement */ ; + return node.kind === 359 /* NotEmittedStatement */ ; } function isSyntheticReference(node) { - return node.kind === 360 /* SyntheticReferenceExpression */ ; - } - function isMergeDeclarationMarker(node) { - return node.kind === 358 /* MergeDeclarationMarker */ ; - } - function isEndOfDeclarationMarker(node) { - return node.kind === 359 /* EndOfDeclarationMarker */ ; + return node.kind === 362 /* SyntheticReferenceExpression */ ; } function isExternalModuleReference(node) { - return node.kind === 280 /* ExternalModuleReference */ ; + return node.kind === 283 /* ExternalModuleReference */ ; } function isJsxElement(node) { - return node.kind === 281 /* JsxElement */ ; + return node.kind === 284 /* JsxElement */ ; } function isJsxSelfClosingElement(node) { - return node.kind === 282 /* JsxSelfClosingElement */ ; + return node.kind === 285 /* JsxSelfClosingElement */ ; } function isJsxOpeningElement(node) { - return node.kind === 283 /* JsxOpeningElement */ ; + return node.kind === 286 /* JsxOpeningElement */ ; } function isJsxClosingElement(node) { - return node.kind === 284 /* JsxClosingElement */ ; + return node.kind === 287 /* JsxClosingElement */ ; } function isJsxFragment(node) { - return node.kind === 285 /* JsxFragment */ ; + return node.kind === 288 /* JsxFragment */ ; } function isJsxOpeningFragment(node) { - return node.kind === 286 /* JsxOpeningFragment */ ; + return node.kind === 289 /* JsxOpeningFragment */ ; } function isJsxClosingFragment(node) { - return node.kind === 287 /* JsxClosingFragment */ ; + return node.kind === 290 /* JsxClosingFragment */ ; } function isJsxAttribute(node) { - return node.kind === 288 /* JsxAttribute */ ; + return node.kind === 291 /* JsxAttribute */ ; } function isJsxAttributes(node) { - return node.kind === 289 /* JsxAttributes */ ; + return node.kind === 292 /* JsxAttributes */ ; } function isJsxSpreadAttribute(node) { - return node.kind === 290 /* JsxSpreadAttribute */ ; + return node.kind === 293 /* JsxSpreadAttribute */ ; } function isJsxExpression(node) { - return node.kind === 291 /* JsxExpression */ ; + return node.kind === 294 /* JsxExpression */ ; + } + function isJsxNamespacedName(node) { + return node.kind === 295 /* JsxNamespacedName */ ; } function isCaseClause(node) { - return node.kind === 292 /* CaseClause */ ; + return node.kind === 296 /* CaseClause */ ; } function isDefaultClause(node) { - return node.kind === 293 /* DefaultClause */ ; + return node.kind === 297 /* DefaultClause */ ; } function isHeritageClause(node) { - return node.kind === 294 /* HeritageClause */ ; + return node.kind === 298 /* HeritageClause */ ; } function isCatchClause(node) { - return node.kind === 295 /* CatchClause */ ; + return node.kind === 299 /* CatchClause */ ; } function isPropertyAssignment(node) { - return node.kind === 299 /* PropertyAssignment */ ; + return node.kind === 303 /* PropertyAssignment */ ; } function isShorthandPropertyAssignment(node) { - return node.kind === 300 /* ShorthandPropertyAssignment */ ; + return node.kind === 304 /* ShorthandPropertyAssignment */ ; } function isSpreadAssignment(node) { - return node.kind === 301 /* SpreadAssignment */ ; + return node.kind === 305 /* SpreadAssignment */ ; } function isEnumMember(node) { - return node.kind === 302 /* EnumMember */ ; + return node.kind === 306 /* EnumMember */ ; } function isUnparsedPrepend(node) { - return node.kind === 304 /* UnparsedPrepend */ ; + return node.kind === 308 /* UnparsedPrepend */ ; } function isSourceFile(node) { - return node.kind === 308 /* SourceFile */ ; + return node.kind === 312 /* SourceFile */ ; } function isBundle(node) { - return node.kind === 309 /* Bundle */ ; + return node.kind === 313 /* Bundle */ ; } function isUnparsedSource(node) { - return node.kind === 310 /* UnparsedSource */ ; + return node.kind === 314 /* UnparsedSource */ ; } function isJSDocTypeExpression(node) { - return node.kind === 312 /* JSDocTypeExpression */ ; + return node.kind === 316 /* JSDocTypeExpression */ ; } function isJSDocNameReference(node) { - return node.kind === 313 /* JSDocNameReference */ ; + return node.kind === 317 /* JSDocNameReference */ ; } function isJSDocMemberName(node) { - return node.kind === 314 /* JSDocMemberName */ ; + return node.kind === 318 /* JSDocMemberName */ ; } function isJSDocLink(node) { - return node.kind === 327 /* JSDocLink */ ; + return node.kind === 331 /* JSDocLink */ ; } function isJSDocLinkCode(node) { - return node.kind === 328 /* JSDocLinkCode */ ; + return node.kind === 332 /* JSDocLinkCode */ ; } function isJSDocLinkPlain(node) { - return node.kind === 329 /* JSDocLinkPlain */ ; + return node.kind === 333 /* JSDocLinkPlain */ ; } function isJSDocAllType(node) { - return node.kind === 315 /* JSDocAllType */ ; + return node.kind === 319 /* JSDocAllType */ ; } function isJSDocUnknownType(node) { - return node.kind === 316 /* JSDocUnknownType */ ; + return node.kind === 320 /* JSDocUnknownType */ ; } function isJSDocNullableType(node) { - return node.kind === 317 /* JSDocNullableType */ ; + return node.kind === 321 /* JSDocNullableType */ ; } function isJSDocNonNullableType(node) { - return node.kind === 318 /* JSDocNonNullableType */ ; + return node.kind === 322 /* JSDocNonNullableType */ ; } function isJSDocOptionalType(node) { - return node.kind === 319 /* JSDocOptionalType */ ; + return node.kind === 323 /* JSDocOptionalType */ ; } function isJSDocFunctionType(node) { - return node.kind === 320 /* JSDocFunctionType */ ; + return node.kind === 324 /* JSDocFunctionType */ ; } function isJSDocVariadicType(node) { - return node.kind === 321 /* JSDocVariadicType */ ; + return node.kind === 325 /* JSDocVariadicType */ ; } function isJSDocNamepathType(node) { - return node.kind === 322 /* JSDocNamepathType */ ; + return node.kind === 326 /* JSDocNamepathType */ ; } function isJSDoc(node) { - return node.kind === 323 /* JSDoc */ ; + return node.kind === 327 /* JSDoc */ ; } function isJSDocTypeLiteral(node) { - return node.kind === 325 /* JSDocTypeLiteral */ ; + return node.kind === 329 /* JSDocTypeLiteral */ ; } function isJSDocSignature(node) { - return node.kind === 326 /* JSDocSignature */ ; + return node.kind === 330 /* JSDocSignature */ ; } function isJSDocAugmentsTag(node) { - return node.kind === 331 /* JSDocAugmentsTag */ ; + return node.kind === 335 /* JSDocAugmentsTag */ ; } function isJSDocAuthorTag(node) { - return node.kind === 333 /* JSDocAuthorTag */ ; + return node.kind === 337 /* JSDocAuthorTag */ ; } function isJSDocClassTag(node) { - return node.kind === 335 /* JSDocClassTag */ ; + return node.kind === 339 /* JSDocClassTag */ ; } function isJSDocCallbackTag(node) { - return node.kind === 341 /* JSDocCallbackTag */ ; + return node.kind === 345 /* JSDocCallbackTag */ ; } function isJSDocPublicTag(node) { - return node.kind === 336 /* JSDocPublicTag */ ; + return node.kind === 340 /* JSDocPublicTag */ ; } function isJSDocPrivateTag(node) { - return node.kind === 337 /* JSDocPrivateTag */ ; + return node.kind === 341 /* JSDocPrivateTag */ ; } function isJSDocProtectedTag(node) { - return node.kind === 338 /* JSDocProtectedTag */ ; + return node.kind === 342 /* JSDocProtectedTag */ ; } function isJSDocReadonlyTag(node) { - return node.kind === 339 /* JSDocReadonlyTag */ ; + return node.kind === 343 /* JSDocReadonlyTag */ ; } function isJSDocOverrideTag(node) { - return node.kind === 340 /* JSDocOverrideTag */ ; + return node.kind === 344 /* JSDocOverrideTag */ ; } function isJSDocOverloadTag(node) { - return node.kind === 342 /* JSDocOverloadTag */ ; + return node.kind === 346 /* JSDocOverloadTag */ ; } function isJSDocDeprecatedTag(node) { - return node.kind === 334 /* JSDocDeprecatedTag */ ; + return node.kind === 338 /* JSDocDeprecatedTag */ ; } function isJSDocSeeTag(node) { - return node.kind === 350 /* JSDocSeeTag */ ; + return node.kind === 354 /* JSDocSeeTag */ ; } function isJSDocEnumTag(node) { - return node.kind === 343 /* JSDocEnumTag */ ; + return node.kind === 347 /* JSDocEnumTag */ ; } function isJSDocParameterTag(node) { - return node.kind === 344 /* JSDocParameterTag */ ; + return node.kind === 348 /* JSDocParameterTag */ ; } function isJSDocReturnTag(node) { - return node.kind === 345 /* JSDocReturnTag */ ; + return node.kind === 349 /* JSDocReturnTag */ ; } function isJSDocThisTag(node) { - return node.kind === 346 /* JSDocThisTag */ ; + return node.kind === 350 /* JSDocThisTag */ ; } function isJSDocTypeTag(node) { - return node.kind === 347 /* JSDocTypeTag */ ; + return node.kind === 351 /* JSDocTypeTag */ ; } function isJSDocTemplateTag(node) { - return node.kind === 348 /* JSDocTemplateTag */ ; + return node.kind === 352 /* JSDocTemplateTag */ ; } function isJSDocTypedefTag(node) { - return node.kind === 349 /* JSDocTypedefTag */ ; + return node.kind === 353 /* JSDocTypedefTag */ ; } function isJSDocUnknownTag(node) { - return node.kind === 330 /* JSDocTag */ ; + return node.kind === 334 /* JSDocTag */ ; } function isJSDocPropertyTag(node) { - return node.kind === 351 /* JSDocPropertyTag */ ; + return node.kind === 355 /* JSDocPropertyTag */ ; } function isJSDocImplementsTag(node) { - return node.kind === 332 /* JSDocImplementsTag */ ; + return node.kind === 336 /* JSDocImplementsTag */ ; } function isJSDocSatisfiesTag(node) { - return node.kind === 353 /* JSDocSatisfiesTag */ ; + return node.kind === 357 /* JSDocSatisfiesTag */ ; } function isJSDocThrowsTag(node) { - return node.kind === 352 /* JSDocThrowsTag */ ; + return node.kind === 356 /* JSDocThrowsTag */ ; } function isSyntaxList(n) { - return n.kind === 354 /* SyntaxList */ ; + return n.kind === 358 /* SyntaxList */ ; } var init_nodeTests = __esm({ "src/compiler/factory/nodeTests.ts" () { @@ -29057,7 +29310,7 @@ ${lanes.join("\n")} else return setParent(setTextRange(factory2.cloneNode(memberName), memberName), memberName.parent); } function createExpressionForAccessorDeclaration(factory2, properties, property, receiver, multiLine) { - const { firstAccessor: firstAccessor , getAccessor: getAccessor , setAccessor: setAccessor } = getAllAccessorDeclarations(properties, property); + const { firstAccessor: firstAccessor, getAccessor: getAccessor, setAccessor: setAccessor } = getAllAccessorDeclarations(properties, property); if (property === firstAccessor) return setTextRange(factory2.createObjectDefinePropertyCall(receiver, createExpressionForPropertyName(factory2, property.name), factory2.createPropertyDescriptor({ enumerable: factory2.createFalse(), configurable: true, @@ -29078,20 +29331,20 @@ ${lanes.join("\n")} function createExpressionForObjectLiteralElementLike(factory2, node, property, receiver) { if (property.name && isPrivateIdentifier(property.name)) Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals."); switch(property.kind){ - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : return createExpressionForAccessorDeclaration(factory2, node.properties, property, receiver, !!node.multiLine); - case 299 /* PropertyAssignment */ : + case 303 /* PropertyAssignment */ : return createExpressionForPropertyAssignment(factory2, property, receiver); - case 300 /* ShorthandPropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : return createExpressionForShorthandPropertyAssignment(factory2, property, receiver); - case 171 /* MethodDeclaration */ : + case 174 /* MethodDeclaration */ : return createExpressionForMethodDeclaration(factory2, property, receiver); } } function expandPreOrPostfixIncrementOrDecrementExpression(factory2, node, expression, recordTempVariable, resultVariable) { const operator = node.operator; - Debug.assert(operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */ , "Expected 'node' to be a pre- or post-increment or pre- or post-decrement expression"); + Debug.assert(operator === 46 /* PlusPlusToken */ || operator === 47 /* MinusMinusToken */ , "Expected 'node' to be a pre- or post-increment or pre- or post-decrement expression"); const temp = factory2.createTempVariable(recordTempVariable); expression = factory2.createAssignment(temp, expression); setTextRange(expression, node.operand); @@ -29134,7 +29387,7 @@ ${lanes.join("\n")} return firstStatement !== void 0 && isPrologueDirective(firstStatement) && isUseStrictPrologue(firstStatement); } function isCommaExpression(node) { - return node.kind === 223 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ; + return node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 28 /* CommaToken */ ; } function isCommaSequence(node) { return isCommaExpression(node) || isCommaListExpression(node); @@ -29149,17 +29402,17 @@ ${lanes.join("\n")} } function isOuterExpression(node, kinds = 15 /* All */ ) { switch(node.kind){ - case 214 /* ParenthesizedExpression */ : + case 217 /* ParenthesizedExpression */ : if (kinds & 16 /* ExcludeJSDocTypeAssertion */ && isJSDocTypeAssertion(node)) return false; return (kinds & 1 /* Parentheses */ ) !== 0; - case 213 /* TypeAssertionExpression */ : - case 231 /* AsExpression */ : - case 230 /* ExpressionWithTypeArguments */ : - case 235 /* SatisfiesExpression */ : + case 216 /* TypeAssertionExpression */ : + case 234 /* AsExpression */ : + case 233 /* ExpressionWithTypeArguments */ : + case 238 /* SatisfiesExpression */ : return (kinds & 2 /* TypeAssertions */ ) !== 0; - case 232 /* NonNullExpression */ : + case 235 /* NonNullExpression */ : return (kinds & 4 /* NonNullAssertions */ ) !== 0; - case 356 /* PartiallyEmittedExpression */ : + case 360 /* PartiallyEmittedExpression */ : return (kinds & 8 /* PartiallyEmittedExpressions */ ) !== 0; } return false; @@ -29251,8 +29504,8 @@ ${lanes.join("\n")} const name = namespaceDeclaration.name; return isGeneratedIdentifier(name) ? name : factory2.createIdentifier(getSourceTextOfNodeFromSourceFile(sourceFile, name) || idText(name)); } - if (node.kind === 269 /* ImportDeclaration */ && node.importClause) return factory2.getGeneratedNameForNode(node); - if (node.kind === 275 /* ExportDeclaration */ && node.moduleSpecifier) return factory2.getGeneratedNameForNode(node); + if (node.kind === 272 /* ImportDeclaration */ && node.importClause) return factory2.getGeneratedNameForNode(node); + if (node.kind === 278 /* ExportDeclaration */ && node.moduleSpecifier) return factory2.getGeneratedNameForNode(node); return void 0; } function getExternalModuleNameLiteral(factory2, importNode, sourceFile, host, resolver, compilerOptions) { @@ -29287,11 +29540,11 @@ ${lanes.join("\n")} if (isDeclarationBindingElement(bindingElement)) return bindingElement.name; if (isObjectLiteralElementLike(bindingElement)) { switch(bindingElement.kind){ - case 299 /* PropertyAssignment */ : + case 303 /* PropertyAssignment */ : return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); - case 300 /* ShorthandPropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : return bindingElement.name; - case 301 /* SpreadAssignment */ : + case 305 /* SpreadAssignment */ : return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } return void 0; @@ -29302,11 +29555,11 @@ ${lanes.join("\n")} } function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { switch(bindingElement.kind){ - case 166 /* Parameter */ : - case 205 /* BindingElement */ : + case 169 /* Parameter */ : + case 208 /* BindingElement */ : return bindingElement.dotDotDotToken; - case 227 /* SpreadElement */ : - case 301 /* SpreadAssignment */ : + case 230 /* SpreadElement */ : + case 305 /* SpreadAssignment */ : return bindingElement; } return void 0; @@ -29318,21 +29571,21 @@ ${lanes.join("\n")} } function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch(bindingElement.kind){ - case 205 /* BindingElement */ : + case 208 /* BindingElement */ : if (bindingElement.propertyName) { const propertyName = bindingElement.propertyName; if (isPrivateIdentifier(propertyName)) return Debug.failBadSyntaxKind(propertyName); return isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) ? propertyName.expression : propertyName; } break; - case 299 /* PropertyAssignment */ : + case 303 /* PropertyAssignment */ : if (bindingElement.name) { const propertyName = bindingElement.name; if (isPrivateIdentifier(propertyName)) return Debug.failBadSyntaxKind(propertyName); return isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) ? propertyName.expression : propertyName; } break; - case 301 /* SpreadAssignment */ : + case 305 /* SpreadAssignment */ : if (bindingElement.name && isPrivateIdentifier(bindingElement.name)) return Debug.failBadSyntaxKind(bindingElement.name); return bindingElement.name; } @@ -29341,15 +29594,15 @@ ${lanes.join("\n")} } function isStringOrNumericLiteral(node) { const kind = node.kind; - return kind === 10 /* StringLiteral */ || kind === 8 /* NumericLiteral */ ; + return kind === 11 /* StringLiteral */ || kind === 9 /* NumericLiteral */ ; } function getElementsOfBindingOrAssignmentPattern(name) { switch(name.kind){ - case 203 /* ObjectBindingPattern */ : - case 204 /* ArrayBindingPattern */ : - case 206 /* ArrayLiteralExpression */ : + case 206 /* ObjectBindingPattern */ : + case 207 /* ArrayBindingPattern */ : + case 209 /* ArrayLiteralExpression */ : return name.elements; - case 207 /* ObjectLiteralExpression */ : + case 210 /* ObjectLiteralExpression */ : return name.properties; } } @@ -29364,19 +29617,19 @@ ${lanes.join("\n")} } function canHaveIllegalType(node) { const kind = node.kind; - return kind === 173 /* Constructor */ || kind === 175 /* SetAccessor */ ; + return kind === 176 /* Constructor */ || kind === 178 /* SetAccessor */ ; } function canHaveIllegalTypeParameters(node) { const kind = node.kind; - return kind === 173 /* Constructor */ || kind === 174 /* GetAccessor */ || kind === 175 /* SetAccessor */ ; + return kind === 176 /* Constructor */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ ; } function canHaveIllegalDecorators(node) { const kind = node.kind; - return kind === 299 /* PropertyAssignment */ || kind === 300 /* ShorthandPropertyAssignment */ || kind === 259 /* FunctionDeclaration */ || kind === 173 /* Constructor */ || kind === 178 /* IndexSignature */ || kind === 172 /* ClassStaticBlockDeclaration */ || kind === 279 /* MissingDeclaration */ || kind === 240 /* VariableStatement */ || kind === 261 /* InterfaceDeclaration */ || kind === 262 /* TypeAliasDeclaration */ || kind === 263 /* EnumDeclaration */ || kind === 264 /* ModuleDeclaration */ || kind === 268 /* ImportEqualsDeclaration */ || kind === 269 /* ImportDeclaration */ || kind === 267 /* NamespaceExportDeclaration */ || kind === 275 /* ExportDeclaration */ || kind === 274 /* ExportAssignment */ ; + return kind === 303 /* PropertyAssignment */ || kind === 304 /* ShorthandPropertyAssignment */ || kind === 262 /* FunctionDeclaration */ || kind === 176 /* Constructor */ || kind === 181 /* IndexSignature */ || kind === 175 /* ClassStaticBlockDeclaration */ || kind === 282 /* MissingDeclaration */ || kind === 243 /* VariableStatement */ || kind === 264 /* InterfaceDeclaration */ || kind === 265 /* TypeAliasDeclaration */ || kind === 266 /* EnumDeclaration */ || kind === 267 /* ModuleDeclaration */ || kind === 271 /* ImportEqualsDeclaration */ || kind === 272 /* ImportDeclaration */ || kind === 270 /* NamespaceExportDeclaration */ || kind === 278 /* ExportDeclaration */ || kind === 277 /* ExportAssignment */ ; } function canHaveIllegalModifiers(node) { const kind = node.kind; - return kind === 172 /* ClassStaticBlockDeclaration */ || kind === 299 /* PropertyAssignment */ || kind === 300 /* ShorthandPropertyAssignment */ || kind === 279 /* MissingDeclaration */ || kind === 267 /* NamespaceExportDeclaration */ ; + return kind === 175 /* ClassStaticBlockDeclaration */ || kind === 303 /* PropertyAssignment */ || kind === 304 /* ShorthandPropertyAssignment */ || kind === 282 /* MissingDeclaration */ || kind === 270 /* NamespaceExportDeclaration */ ; } function isQuestionOrExclamationToken(node) { return isQuestionToken(node) || isExclamationToken(node); @@ -29395,58 +29648,58 @@ ${lanes.join("\n")} } function isLiteralTypeLikeExpression(node) { const kind = node.kind; - return kind === 104 /* NullKeyword */ || kind === 110 /* TrueKeyword */ || kind === 95 /* FalseKeyword */ || isLiteralExpression(node) || isPrefixUnaryExpression(node); + return kind === 106 /* NullKeyword */ || kind === 112 /* TrueKeyword */ || kind === 97 /* FalseKeyword */ || isLiteralExpression(node) || isPrefixUnaryExpression(node); } function isExponentiationOperator(kind) { - return kind === 42 /* AsteriskAsteriskToken */ ; + return kind === 43 /* AsteriskAsteriskToken */ ; } function isMultiplicativeOperator(kind) { - return kind === 41 /* AsteriskToken */ || kind === 43 /* SlashToken */ || kind === 44 /* PercentToken */ ; + return kind === 42 /* AsteriskToken */ || kind === 44 /* SlashToken */ || kind === 45 /* PercentToken */ ; } function isMultiplicativeOperatorOrHigher(kind) { return isExponentiationOperator(kind) || isMultiplicativeOperator(kind); } function isAdditiveOperator(kind) { - return kind === 39 /* PlusToken */ || kind === 40 /* MinusToken */ ; + return kind === 40 /* PlusToken */ || kind === 41 /* MinusToken */ ; } function isAdditiveOperatorOrHigher(kind) { return isAdditiveOperator(kind) || isMultiplicativeOperatorOrHigher(kind); } function isShiftOperator(kind) { - return kind === 47 /* LessThanLessThanToken */ || kind === 48 /* GreaterThanGreaterThanToken */ || kind === 49 /* GreaterThanGreaterThanGreaterThanToken */ ; + return kind === 48 /* LessThanLessThanToken */ || kind === 49 /* GreaterThanGreaterThanToken */ || kind === 50 /* GreaterThanGreaterThanGreaterThanToken */ ; } function isShiftOperatorOrHigher(kind) { return isShiftOperator(kind) || isAdditiveOperatorOrHigher(kind); } function isRelationalOperator(kind) { - return kind === 29 /* LessThanToken */ || kind === 32 /* LessThanEqualsToken */ || kind === 31 /* GreaterThanToken */ || kind === 33 /* GreaterThanEqualsToken */ || kind === 102 /* InstanceOfKeyword */ || kind === 101 /* InKeyword */ ; + return kind === 30 /* LessThanToken */ || kind === 33 /* LessThanEqualsToken */ || kind === 32 /* GreaterThanToken */ || kind === 34 /* GreaterThanEqualsToken */ || kind === 104 /* InstanceOfKeyword */ || kind === 103 /* InKeyword */ ; } function isRelationalOperatorOrHigher(kind) { return isRelationalOperator(kind) || isShiftOperatorOrHigher(kind); } function isEqualityOperator(kind) { - return kind === 34 /* EqualsEqualsToken */ || kind === 36 /* EqualsEqualsEqualsToken */ || kind === 35 /* ExclamationEqualsToken */ || kind === 37 /* ExclamationEqualsEqualsToken */ ; + return kind === 35 /* EqualsEqualsToken */ || kind === 37 /* EqualsEqualsEqualsToken */ || kind === 36 /* ExclamationEqualsToken */ || kind === 38 /* ExclamationEqualsEqualsToken */ ; } function isEqualityOperatorOrHigher(kind) { return isEqualityOperator(kind) || isRelationalOperatorOrHigher(kind); } function isBitwiseOperator(kind) { - return kind === 50 /* AmpersandToken */ || kind === 51 /* BarToken */ || kind === 52 /* CaretToken */ ; + return kind === 51 /* AmpersandToken */ || kind === 52 /* BarToken */ || kind === 53 /* CaretToken */ ; } function isBitwiseOperatorOrHigher(kind) { return isBitwiseOperator(kind) || isEqualityOperatorOrHigher(kind); } function isLogicalOperator2(kind) { - return kind === 55 /* AmpersandAmpersandToken */ || kind === 56 /* BarBarToken */ ; + return kind === 56 /* AmpersandAmpersandToken */ || kind === 57 /* BarBarToken */ ; } function isLogicalOperatorOrHigher(kind) { return isLogicalOperator2(kind) || isBitwiseOperatorOrHigher(kind); } function isAssignmentOperatorOrHigher(kind) { - return kind === 60 /* QuestionQuestionToken */ || isLogicalOperatorOrHigher(kind) || isAssignmentOperator(kind); + return kind === 61 /* QuestionQuestionToken */ || isLogicalOperatorOrHigher(kind) || isAssignmentOperator(kind); } function isBinaryOperator(kind) { - return isAssignmentOperatorOrHigher(kind) || kind === 27 /* CommaToken */ ; + return isAssignmentOperatorOrHigher(kind) || kind === 28 /* CommaToken */ ; } function isBinaryOperatorToken(node) { return isBinaryOperator(node.kind); @@ -29474,7 +29727,7 @@ ${lanes.join("\n")} } } function isExportOrDefaultKeywordKind(kind) { - return kind === 93 /* ExportKeyword */ || kind === 88 /* DefaultKeyword */ ; + return kind === 95 /* ExportKeyword */ || kind === 90 /* DefaultKeyword */ ; } function isExportOrDefaultModifier(node) { const kind = node.kind; @@ -29490,7 +29743,7 @@ ${lanes.join("\n")} return setTextRange(factory2.createNodeArray([], nodes.hasTrailingComma), nodes); } function getNodeForGeneratedName(name) { - var _a2; + var _a; const autoGenerate = name.emitNode.autoGenerate; if (autoGenerate.flags & 4 /* Node */ ) { const autoGenerateId = autoGenerate.id; @@ -29498,7 +29751,7 @@ ${lanes.join("\n")} let original = node.original; while(original){ node = original; - const autoGenerate2 = (_a2 = node.emitNode) == null ? void 0 : _a2.autoGenerate; + const autoGenerate2 = (_a = node.emitNode) == null ? void 0 : _a.autoGenerate; if (isMemberName(node) && (autoGenerate2 === void 0 || !!(autoGenerate2.flags & 4 /* Node */ ) && autoGenerate2.id !== autoGenerateId)) break; original = node.original; } @@ -29524,16 +29777,16 @@ ${lanes.join("\n")} function createAccessorPropertyBackingField(factory2, node, modifiers, initializer) { return factory2.updatePropertyDeclaration(node, modifiers, factory2.getGeneratedPrivateNameForNode(node.name, /*prefix*/ void 0, "_accessor_storage"), /*questionOrExclamationToken*/ void 0, /*type*/ void 0, initializer); } - function createAccessorPropertyGetRedirector(factory2, node, modifiers, name) { + function createAccessorPropertyGetRedirector(factory2, node, modifiers, name, receiver = factory2.createThis()) { return factory2.createGetAccessorDeclaration(modifiers, name, [], /*type*/ void 0, factory2.createBlock([ - factory2.createReturnStatement(factory2.createPropertyAccessExpression(factory2.createThis(), factory2.getGeneratedPrivateNameForNode(node.name, /*prefix*/ void 0, "_accessor_storage"))) + factory2.createReturnStatement(factory2.createPropertyAccessExpression(receiver, factory2.getGeneratedPrivateNameForNode(node.name, /*prefix*/ void 0, "_accessor_storage"))) ])); } - function createAccessorPropertySetRedirector(factory2, node, modifiers, name) { + function createAccessorPropertySetRedirector(factory2, node, modifiers, name, receiver = factory2.createThis()) { return factory2.createSetAccessorDeclaration(modifiers, name, [ - factory2.createParameterDeclaration(/*modifiers*/ void 0, /*dotdotDotToken*/ void 0, "value") + factory2.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, "value") ], factory2.createBlock([ - factory2.createExpressionStatement(factory2.createAssignment(factory2.createPropertyAccessExpression(factory2.createThis(), factory2.getGeneratedPrivateNameForNode(node.name, /*prefix*/ void 0, "_accessor_storage")), factory2.createIdentifier("value"))) + factory2.createExpressionStatement(factory2.createAssignment(factory2.createPropertyAccessExpression(receiver, factory2.getGeneratedPrivateNameForNode(node.name, /*prefix*/ void 0, "_accessor_storage")), factory2.createIdentifier("value"))) ])); } function findComputedPropertyNameCacheAssignment(name) { @@ -29697,11 +29950,11 @@ ${lanes.join("\n")} } function canHaveModifiers(node) { const kind = node.kind; - return kind === 165 /* TypeParameter */ || kind === 166 /* Parameter */ || kind === 168 /* PropertySignature */ || kind === 169 /* PropertyDeclaration */ || kind === 170 /* MethodSignature */ || kind === 171 /* MethodDeclaration */ || kind === 173 /* Constructor */ || kind === 174 /* GetAccessor */ || kind === 175 /* SetAccessor */ || kind === 178 /* IndexSignature */ || kind === 182 /* ConstructorType */ || kind === 215 /* FunctionExpression */ || kind === 216 /* ArrowFunction */ || kind === 228 /* ClassExpression */ || kind === 240 /* VariableStatement */ || kind === 259 /* FunctionDeclaration */ || kind === 260 /* ClassDeclaration */ || kind === 261 /* InterfaceDeclaration */ || kind === 262 /* TypeAliasDeclaration */ || kind === 263 /* EnumDeclaration */ || kind === 264 /* ModuleDeclaration */ || kind === 268 /* ImportEqualsDeclaration */ || kind === 269 /* ImportDeclaration */ || kind === 274 /* ExportAssignment */ || kind === 275 /* ExportDeclaration */ ; + return kind === 168 /* TypeParameter */ || kind === 169 /* Parameter */ || kind === 171 /* PropertySignature */ || kind === 172 /* PropertyDeclaration */ || kind === 173 /* MethodSignature */ || kind === 174 /* MethodDeclaration */ || kind === 176 /* Constructor */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ || kind === 181 /* IndexSignature */ || kind === 185 /* ConstructorType */ || kind === 218 /* FunctionExpression */ || kind === 219 /* ArrowFunction */ || kind === 231 /* ClassExpression */ || kind === 243 /* VariableStatement */ || kind === 262 /* FunctionDeclaration */ || kind === 263 /* ClassDeclaration */ || kind === 264 /* InterfaceDeclaration */ || kind === 265 /* TypeAliasDeclaration */ || kind === 266 /* EnumDeclaration */ || kind === 267 /* ModuleDeclaration */ || kind === 271 /* ImportEqualsDeclaration */ || kind === 272 /* ImportDeclaration */ || kind === 277 /* ExportAssignment */ || kind === 278 /* ExportDeclaration */ ; } function canHaveDecorators(node) { const kind = node.kind; - return kind === 166 /* Parameter */ || kind === 169 /* PropertyDeclaration */ || kind === 171 /* MethodDeclaration */ || kind === 174 /* GetAccessor */ || kind === 175 /* SetAccessor */ || kind === 228 /* ClassExpression */ || kind === 260 /* ClassDeclaration */ ; + return kind === 169 /* Parameter */ || kind === 172 /* PropertyDeclaration */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ || kind === 231 /* ClassExpression */ || kind === 263 /* ClassDeclaration */ ; } var init_utilitiesPublic2 = __esm({ "src/compiler/factory/utilitiesPublic.ts" () { @@ -29729,10 +29982,10 @@ ${lanes.join("\n")} return forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) || getImportMetaIfNecessary(sourceFile); } function isAnExternalModuleIndicatorNode(node) { - return canHaveModifiers(node) && hasModifierOfKind(node, 93 /* ExportKeyword */ ) || isImportEqualsDeclaration(node) && isExternalModuleReference(node.moduleReference) || isImportDeclaration(node) || isExportAssignment(node) || isExportDeclaration(node) ? node : void 0; + return canHaveModifiers(node) && hasModifierOfKind(node, 95 /* ExportKeyword */ ) || isImportEqualsDeclaration(node) && isExternalModuleReference(node.moduleReference) || isImportDeclaration(node) || isExportAssignment(node) || isExportDeclaration(node) ? node : void 0; } function getImportMetaIfNecessary(sourceFile) { - return sourceFile.flags & 4194304 /* PossiblyContainsImportMeta */ ? walkTreeForImportMeta(sourceFile) : void 0; + return sourceFile.flags & 8388608 /* PossiblyContainsImportMeta */ ? walkTreeForImportMeta(sourceFile) : void 0; } function walkTreeForImportMeta(node) { return isImportMeta2(node) ? node : forEachChild(node, walkTreeForImportMeta); @@ -29741,7 +29994,7 @@ ${lanes.join("\n")} return some(node.modifiers, (m)=>m.kind === kind); } function isImportMeta2(node) { - return isMetaProperty(node) && node.keywordToken === 100 /* ImportKeyword */ && node.name.escapedText === "meta"; + return isMetaProperty(node) && node.keywordToken === 102 /* ImportKeyword */ && node.name.escapedText === "meta"; } function forEachChildInCallOrConstructSignature(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type); @@ -29796,7 +30049,7 @@ ${lanes.join("\n")} return visitNode2(cbNode, node.expression); } function forEachChild(node, cbNode, cbNodes) { - if (node === void 0 || node.kind <= 162 /* LastToken */ ) return; + if (node === void 0 || node.kind <= 165 /* LastToken */ ) return; const fn = forEachChildTable[node.kind]; return fn === void 0 ? void 0 : fn(node, cbNode, cbNodes); } @@ -29825,7 +30078,7 @@ ${lanes.join("\n")} if (res === "skip") continue; return res; } - if (current.kind >= 163 /* FirstNode */ ) for (const child of gatherPossibleChildren(current)){ + if (current.kind >= 166 /* FirstNode */ ) for (const child of gatherPossibleChildren(current)){ queue.push(child); parents.push(current); } @@ -29844,14 +30097,14 @@ ${lanes.join("\n")} sourceFile.externalModuleIndicator = isFileProbablyExternalModule(sourceFile); } function createSourceFile(fileName, sourceText, languageVersionOrOptions, setParentNodes = false, scriptKind) { - var _a2, _b; - (_a2 = tracing) == null || _a2.push(tracing.Phase.Parse, "createSourceFile", { + var _a, _b, _c, _d; + (_a = tracing) == null || _a.push(tracing.Phase.Parse, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); mark("beforeParse"); let result; - perfLogger.logStartParseSourceFile(fileName); - const { languageVersion: languageVersion , setExternalModuleIndicator: overrideSetExternalModuleIndicator , impliedNodeFormat: format } = typeof languageVersionOrOptions === "object" ? languageVersionOrOptions : { + (_b = perfLogger) == null || _b.logStartParseSourceFile(fileName); + const { languageVersion: languageVersion, setExternalModuleIndicator: overrideSetExternalModuleIndicator, impliedNodeFormat: format } = typeof languageVersionOrOptions === "object" ? languageVersionOrOptions : { languageVersion: languageVersionOrOptions }; if (languageVersion === 100 /* JSON */ ) result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ void 0, setParentNodes, 6 /* JSON */ , noop); @@ -29862,10 +30115,10 @@ ${lanes.join("\n")} }; result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ void 0, setParentNodes, scriptKind, setIndicator); } - perfLogger.logStopParseSourceFile(); + (_c = perfLogger) == null || _c.logStopParseSourceFile(); mark("afterParse"); measure("Parse", "beforeParse", "afterParse"); - (_b = tracing) == null || _b.pop(); + (_d = tracing) == null || _d.pop(); return result; } function parseIsolatedEntityName(text, languageVersion) { @@ -29879,7 +30132,7 @@ ${lanes.join("\n")} } function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks = false) { const newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); - newSourceFile.flags |= sourceFile.flags & 6291456 /* PermanentlySetIncrementalFlags */ ; + newSourceFile.flags |= sourceFile.flags & 12582912 /* PermanentlySetIncrementalFlags */ ; return newSourceFile; } function parseIsolatedJSDocComment(content, start, length2) { @@ -29935,7 +30188,7 @@ ${lanes.join("\n")} const typeReferenceDirectives = context.typeReferenceDirectives; const libReferenceDirectives = context.libReferenceDirectives; forEach(toArray(entryOrList), (arg)=>{ - const { types: types , lib: lib , path: path , ["resolution-mode"]: res } = arg.arguments; + const { types: types, lib: lib, path: path, ["resolution-mode"]: res } = arg.arguments; if (arg.arguments["no-default-lib"]) context.hasNoDefaultLib = true; else if (types) { const parsed = parseResolutionMode(res, types.pos, types.end, reportDiagnostic); @@ -30080,8 +30333,9 @@ ${lanes.join("\n")} } function tagNamesAreEquivalent(lhs, rhs) { if (lhs.kind !== rhs.kind) return false; - if (lhs.kind === 79 /* Identifier */ ) return lhs.escapedText === rhs.escapedText; - if (lhs.kind === 108 /* ThisKeyword */ ) return true; + if (lhs.kind === 80 /* Identifier */ ) return lhs.escapedText === rhs.escapedText; + if (lhs.kind === 110 /* ThisKeyword */ ) return true; + if (lhs.kind === 295 /* JsxNamespacedName */ ) return lhs.namespace.escapedText === rhs.namespace.escapedText && lhs.name.escapedText === rhs.name.escapedText; return lhs.name.escapedText === rhs.name.escapedText && tagNamesAreEquivalent(lhs.expression, rhs.expression); } var NodeConstructor, TokenConstructor, IdentifierConstructor, PrivateIdentifierConstructor, SourceFileConstructor, parseBaseNodeFactory, parseNodeFactory, forEachChildTable, Parser, IncrementalParser, namedArgRegExCache, tripleSlashXMLCommentStartRegEx, singleLinePragmaRegEx; @@ -30089,7 +30343,6 @@ ${lanes.join("\n")} "src/compiler/parser.ts" () { "use strict"; init_ts2(); - init_ts2(); init_ts_performance(); parseBaseNodeFactory = { createBaseSourceFileNode: (kind)=>new (SourceFileConstructor || (SourceFileConstructor = objectAllocator.getSourceFileConstructor()))(kind, -1, -1), @@ -30100,429 +30353,432 @@ ${lanes.join("\n")} }; parseNodeFactory = createNodeFactory(1 /* NoParenthesizerRules */ , parseBaseNodeFactory); forEachChildTable = { - [163 /* QualifiedName */ ]: function forEachChildInQualifiedName(node, cbNode, _cbNodes) { + [166 /* QualifiedName */ ]: function forEachChildInQualifiedName(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.left) || visitNode2(cbNode, node.right); }, - [165 /* TypeParameter */ ]: function forEachChildInTypeParameter(node, cbNode, cbNodes) { + [168 /* TypeParameter */ ]: function forEachChildInTypeParameter(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.constraint) || visitNode2(cbNode, node.default) || visitNode2(cbNode, node.expression); }, - [300 /* ShorthandPropertyAssignment */ ]: function forEachChildInShorthandPropertyAssignment(node, cbNode, cbNodes) { + [304 /* ShorthandPropertyAssignment */ ]: function forEachChildInShorthandPropertyAssignment(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.exclamationToken) || visitNode2(cbNode, node.equalsToken) || visitNode2(cbNode, node.objectAssignmentInitializer); }, - [301 /* SpreadAssignment */ ]: function forEachChildInSpreadAssignment(node, cbNode, _cbNodes) { + [305 /* SpreadAssignment */ ]: function forEachChildInSpreadAssignment(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression); }, - [166 /* Parameter */ ]: function forEachChildInParameter(node, cbNode, cbNodes) { + [169 /* Parameter */ ]: function forEachChildInParameter(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.dotDotDotToken) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.initializer); }, - [169 /* PropertyDeclaration */ ]: function forEachChildInPropertyDeclaration(node, cbNode, cbNodes) { + [172 /* PropertyDeclaration */ ]: function forEachChildInPropertyDeclaration(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.exclamationToken) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.initializer); }, - [168 /* PropertySignature */ ]: function forEachChildInPropertySignature(node, cbNode, cbNodes) { + [171 /* PropertySignature */ ]: function forEachChildInPropertySignature(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.initializer); }, - [299 /* PropertyAssignment */ ]: function forEachChildInPropertyAssignment(node, cbNode, cbNodes) { + [303 /* PropertyAssignment */ ]: function forEachChildInPropertyAssignment(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.exclamationToken) || visitNode2(cbNode, node.initializer); }, - [257 /* VariableDeclaration */ ]: function forEachChildInVariableDeclaration(node, cbNode, _cbNodes) { + [260 /* VariableDeclaration */ ]: function forEachChildInVariableDeclaration(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.name) || visitNode2(cbNode, node.exclamationToken) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.initializer); }, - [205 /* BindingElement */ ]: function forEachChildInBindingElement(node, cbNode, _cbNodes) { + [208 /* BindingElement */ ]: function forEachChildInBindingElement(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.dotDotDotToken) || visitNode2(cbNode, node.propertyName) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.initializer); }, - [178 /* IndexSignature */ ]: function forEachChildInIndexSignature(node, cbNode, cbNodes) { + [181 /* IndexSignature */ ]: function forEachChildInIndexSignature(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type); }, - [182 /* ConstructorType */ ]: function forEachChildInConstructorType(node, cbNode, cbNodes) { + [185 /* ConstructorType */ ]: function forEachChildInConstructorType(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type); }, - [181 /* FunctionType */ ]: function forEachChildInFunctionType(node, cbNode, cbNodes) { + [184 /* FunctionType */ ]: function forEachChildInFunctionType(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type); }, - [176 /* CallSignature */ ]: forEachChildInCallOrConstructSignature, - [177 /* ConstructSignature */ ]: forEachChildInCallOrConstructSignature, - [171 /* MethodDeclaration */ ]: function forEachChildInMethodDeclaration(node, cbNode, cbNodes) { + [179 /* CallSignature */ ]: forEachChildInCallOrConstructSignature, + [180 /* ConstructSignature */ ]: forEachChildInCallOrConstructSignature, + [174 /* MethodDeclaration */ ]: function forEachChildInMethodDeclaration(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.asteriskToken) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.body); }, - [170 /* MethodSignature */ ]: function forEachChildInMethodSignature(node, cbNode, cbNodes) { + [173 /* MethodSignature */ ]: function forEachChildInMethodSignature(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type); }, - [173 /* Constructor */ ]: function forEachChildInConstructor(node, cbNode, cbNodes) { + [176 /* Constructor */ ]: function forEachChildInConstructor(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.body); }, - [174 /* GetAccessor */ ]: function forEachChildInGetAccessor(node, cbNode, cbNodes) { + [177 /* GetAccessor */ ]: function forEachChildInGetAccessor(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.body); }, - [175 /* SetAccessor */ ]: function forEachChildInSetAccessor(node, cbNode, cbNodes) { + [178 /* SetAccessor */ ]: function forEachChildInSetAccessor(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.body); }, - [259 /* FunctionDeclaration */ ]: function forEachChildInFunctionDeclaration(node, cbNode, cbNodes) { + [262 /* FunctionDeclaration */ ]: function forEachChildInFunctionDeclaration(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.asteriskToken) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.body); }, - [215 /* FunctionExpression */ ]: function forEachChildInFunctionExpression(node, cbNode, cbNodes) { + [218 /* FunctionExpression */ ]: function forEachChildInFunctionExpression(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.asteriskToken) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.body); }, - [216 /* ArrowFunction */ ]: function forEachChildInArrowFunction(node, cbNode, cbNodes) { + [219 /* ArrowFunction */ ]: function forEachChildInArrowFunction(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.equalsGreaterThanToken) || visitNode2(cbNode, node.body); }, - [172 /* ClassStaticBlockDeclaration */ ]: function forEachChildInClassStaticBlockDeclaration(node, cbNode, cbNodes) { + [175 /* ClassStaticBlockDeclaration */ ]: function forEachChildInClassStaticBlockDeclaration(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.body); }, - [180 /* TypeReference */ ]: function forEachChildInTypeReference(node, cbNode, cbNodes) { + [183 /* TypeReference */ ]: function forEachChildInTypeReference(node, cbNode, cbNodes) { return visitNode2(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments); }, - [179 /* TypePredicate */ ]: function forEachChildInTypePredicate(node, cbNode, _cbNodes) { + [182 /* TypePredicate */ ]: function forEachChildInTypePredicate(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.assertsModifier) || visitNode2(cbNode, node.parameterName) || visitNode2(cbNode, node.type); }, - [183 /* TypeQuery */ ]: function forEachChildInTypeQuery(node, cbNode, cbNodes) { + [186 /* TypeQuery */ ]: function forEachChildInTypeQuery(node, cbNode, cbNodes) { return visitNode2(cbNode, node.exprName) || visitNodes(cbNode, cbNodes, node.typeArguments); }, - [184 /* TypeLiteral */ ]: function forEachChildInTypeLiteral(node, cbNode, cbNodes) { + [187 /* TypeLiteral */ ]: function forEachChildInTypeLiteral(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.members); }, - [185 /* ArrayType */ ]: function forEachChildInArrayType(node, cbNode, _cbNodes) { + [188 /* ArrayType */ ]: function forEachChildInArrayType(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.elementType); }, - [186 /* TupleType */ ]: function forEachChildInTupleType(node, cbNode, cbNodes) { + [189 /* TupleType */ ]: function forEachChildInTupleType(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.elements); }, - [189 /* UnionType */ ]: forEachChildInUnionOrIntersectionType, - [190 /* IntersectionType */ ]: forEachChildInUnionOrIntersectionType, - [191 /* ConditionalType */ ]: function forEachChildInConditionalType(node, cbNode, _cbNodes) { + [192 /* UnionType */ ]: forEachChildInUnionOrIntersectionType, + [193 /* IntersectionType */ ]: forEachChildInUnionOrIntersectionType, + [194 /* ConditionalType */ ]: function forEachChildInConditionalType(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.checkType) || visitNode2(cbNode, node.extendsType) || visitNode2(cbNode, node.trueType) || visitNode2(cbNode, node.falseType); }, - [192 /* InferType */ ]: function forEachChildInInferType(node, cbNode, _cbNodes) { + [195 /* InferType */ ]: function forEachChildInInferType(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.typeParameter); }, - [202 /* ImportType */ ]: function forEachChildInImportType(node, cbNode, cbNodes) { + [205 /* ImportType */ ]: function forEachChildInImportType(node, cbNode, cbNodes) { return visitNode2(cbNode, node.argument) || visitNode2(cbNode, node.assertions) || visitNode2(cbNode, node.qualifier) || visitNodes(cbNode, cbNodes, node.typeArguments); }, - [298 /* ImportTypeAssertionContainer */ ]: function forEachChildInImportTypeAssertionContainer(node, cbNode, _cbNodes) { + [302 /* ImportTypeAssertionContainer */ ]: function forEachChildInImportTypeAssertionContainer(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.assertClause); }, - [193 /* ParenthesizedType */ ]: forEachChildInParenthesizedTypeOrTypeOperator, - [195 /* TypeOperator */ ]: forEachChildInParenthesizedTypeOrTypeOperator, - [196 /* IndexedAccessType */ ]: function forEachChildInIndexedAccessType(node, cbNode, _cbNodes) { + [196 /* ParenthesizedType */ ]: forEachChildInParenthesizedTypeOrTypeOperator, + [198 /* TypeOperator */ ]: forEachChildInParenthesizedTypeOrTypeOperator, + [199 /* IndexedAccessType */ ]: function forEachChildInIndexedAccessType(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.objectType) || visitNode2(cbNode, node.indexType); }, - [197 /* MappedType */ ]: function forEachChildInMappedType(node, cbNode, cbNodes) { + [200 /* MappedType */ ]: function forEachChildInMappedType(node, cbNode, cbNodes) { return visitNode2(cbNode, node.readonlyToken) || visitNode2(cbNode, node.typeParameter) || visitNode2(cbNode, node.nameType) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.type) || visitNodes(cbNode, cbNodes, node.members); }, - [198 /* LiteralType */ ]: function forEachChildInLiteralType(node, cbNode, _cbNodes) { + [201 /* LiteralType */ ]: function forEachChildInLiteralType(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.literal); }, - [199 /* NamedTupleMember */ ]: function forEachChildInNamedTupleMember(node, cbNode, _cbNodes) { + [202 /* NamedTupleMember */ ]: function forEachChildInNamedTupleMember(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.dotDotDotToken) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.type); }, - [203 /* ObjectBindingPattern */ ]: forEachChildInObjectOrArrayBindingPattern, - [204 /* ArrayBindingPattern */ ]: forEachChildInObjectOrArrayBindingPattern, - [206 /* ArrayLiteralExpression */ ]: function forEachChildInArrayLiteralExpression(node, cbNode, cbNodes) { + [206 /* ObjectBindingPattern */ ]: forEachChildInObjectOrArrayBindingPattern, + [207 /* ArrayBindingPattern */ ]: forEachChildInObjectOrArrayBindingPattern, + [209 /* ArrayLiteralExpression */ ]: function forEachChildInArrayLiteralExpression(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.elements); }, - [207 /* ObjectLiteralExpression */ ]: function forEachChildInObjectLiteralExpression(node, cbNode, cbNodes) { + [210 /* ObjectLiteralExpression */ ]: function forEachChildInObjectLiteralExpression(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.properties); }, - [208 /* PropertyAccessExpression */ ]: function forEachChildInPropertyAccessExpression(node, cbNode, _cbNodes) { + [211 /* PropertyAccessExpression */ ]: function forEachChildInPropertyAccessExpression(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.questionDotToken) || visitNode2(cbNode, node.name); }, - [209 /* ElementAccessExpression */ ]: function forEachChildInElementAccessExpression(node, cbNode, _cbNodes) { + [212 /* ElementAccessExpression */ ]: function forEachChildInElementAccessExpression(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.questionDotToken) || visitNode2(cbNode, node.argumentExpression); }, - [210 /* CallExpression */ ]: forEachChildInCallOrNewExpression, - [211 /* NewExpression */ ]: forEachChildInCallOrNewExpression, - [212 /* TaggedTemplateExpression */ ]: function forEachChildInTaggedTemplateExpression(node, cbNode, cbNodes) { + [213 /* CallExpression */ ]: forEachChildInCallOrNewExpression, + [214 /* NewExpression */ ]: forEachChildInCallOrNewExpression, + [215 /* TaggedTemplateExpression */ ]: function forEachChildInTaggedTemplateExpression(node, cbNode, cbNodes) { return visitNode2(cbNode, node.tag) || visitNode2(cbNode, node.questionDotToken) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode2(cbNode, node.template); }, - [213 /* TypeAssertionExpression */ ]: function forEachChildInTypeAssertionExpression(node, cbNode, _cbNodes) { + [216 /* TypeAssertionExpression */ ]: function forEachChildInTypeAssertionExpression(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.type) || visitNode2(cbNode, node.expression); }, - [214 /* ParenthesizedExpression */ ]: function forEachChildInParenthesizedExpression(node, cbNode, _cbNodes) { + [217 /* ParenthesizedExpression */ ]: function forEachChildInParenthesizedExpression(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression); }, - [217 /* DeleteExpression */ ]: function forEachChildInDeleteExpression(node, cbNode, _cbNodes) { + [220 /* DeleteExpression */ ]: function forEachChildInDeleteExpression(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression); }, - [218 /* TypeOfExpression */ ]: function forEachChildInTypeOfExpression(node, cbNode, _cbNodes) { + [221 /* TypeOfExpression */ ]: function forEachChildInTypeOfExpression(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression); }, - [219 /* VoidExpression */ ]: function forEachChildInVoidExpression(node, cbNode, _cbNodes) { + [222 /* VoidExpression */ ]: function forEachChildInVoidExpression(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression); }, - [221 /* PrefixUnaryExpression */ ]: function forEachChildInPrefixUnaryExpression(node, cbNode, _cbNodes) { + [224 /* PrefixUnaryExpression */ ]: function forEachChildInPrefixUnaryExpression(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.operand); }, - [226 /* YieldExpression */ ]: function forEachChildInYieldExpression(node, cbNode, _cbNodes) { + [229 /* YieldExpression */ ]: function forEachChildInYieldExpression(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.asteriskToken) || visitNode2(cbNode, node.expression); }, - [220 /* AwaitExpression */ ]: function forEachChildInAwaitExpression(node, cbNode, _cbNodes) { + [223 /* AwaitExpression */ ]: function forEachChildInAwaitExpression(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression); }, - [222 /* PostfixUnaryExpression */ ]: function forEachChildInPostfixUnaryExpression(node, cbNode, _cbNodes) { + [225 /* PostfixUnaryExpression */ ]: function forEachChildInPostfixUnaryExpression(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.operand); }, - [223 /* BinaryExpression */ ]: function forEachChildInBinaryExpression(node, cbNode, _cbNodes) { + [226 /* BinaryExpression */ ]: function forEachChildInBinaryExpression(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.left) || visitNode2(cbNode, node.operatorToken) || visitNode2(cbNode, node.right); }, - [231 /* AsExpression */ ]: function forEachChildInAsExpression(node, cbNode, _cbNodes) { + [234 /* AsExpression */ ]: function forEachChildInAsExpression(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.type); }, - [232 /* NonNullExpression */ ]: function forEachChildInNonNullExpression(node, cbNode, _cbNodes) { + [235 /* NonNullExpression */ ]: function forEachChildInNonNullExpression(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression); }, - [235 /* SatisfiesExpression */ ]: function forEachChildInSatisfiesExpression(node, cbNode, _cbNodes) { + [238 /* SatisfiesExpression */ ]: function forEachChildInSatisfiesExpression(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.type); }, - [233 /* MetaProperty */ ]: function forEachChildInMetaProperty(node, cbNode, _cbNodes) { + [236 /* MetaProperty */ ]: function forEachChildInMetaProperty(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.name); }, - [224 /* ConditionalExpression */ ]: function forEachChildInConditionalExpression(node, cbNode, _cbNodes) { + [227 /* ConditionalExpression */ ]: function forEachChildInConditionalExpression(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.condition) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.whenTrue) || visitNode2(cbNode, node.colonToken) || visitNode2(cbNode, node.whenFalse); }, - [227 /* SpreadElement */ ]: function forEachChildInSpreadElement(node, cbNode, _cbNodes) { + [230 /* SpreadElement */ ]: function forEachChildInSpreadElement(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression); }, - [238 /* Block */ ]: forEachChildInBlock, - [265 /* ModuleBlock */ ]: forEachChildInBlock, - [308 /* SourceFile */ ]: function forEachChildInSourceFile(node, cbNode, cbNodes) { + [241 /* Block */ ]: forEachChildInBlock, + [268 /* ModuleBlock */ ]: forEachChildInBlock, + [312 /* SourceFile */ ]: function forEachChildInSourceFile(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.statements) || visitNode2(cbNode, node.endOfFileToken); }, - [240 /* VariableStatement */ ]: function forEachChildInVariableStatement(node, cbNode, cbNodes) { + [243 /* VariableStatement */ ]: function forEachChildInVariableStatement(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.declarationList); }, - [258 /* VariableDeclarationList */ ]: function forEachChildInVariableDeclarationList(node, cbNode, cbNodes) { + [261 /* VariableDeclarationList */ ]: function forEachChildInVariableDeclarationList(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.declarations); }, - [241 /* ExpressionStatement */ ]: function forEachChildInExpressionStatement(node, cbNode, _cbNodes) { + [244 /* ExpressionStatement */ ]: function forEachChildInExpressionStatement(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression); }, - [242 /* IfStatement */ ]: function forEachChildInIfStatement(node, cbNode, _cbNodes) { + [245 /* IfStatement */ ]: function forEachChildInIfStatement(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.thenStatement) || visitNode2(cbNode, node.elseStatement); }, - [243 /* DoStatement */ ]: function forEachChildInDoStatement(node, cbNode, _cbNodes) { + [246 /* DoStatement */ ]: function forEachChildInDoStatement(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.statement) || visitNode2(cbNode, node.expression); }, - [244 /* WhileStatement */ ]: function forEachChildInWhileStatement(node, cbNode, _cbNodes) { + [247 /* WhileStatement */ ]: function forEachChildInWhileStatement(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.statement); }, - [245 /* ForStatement */ ]: function forEachChildInForStatement(node, cbNode, _cbNodes) { + [248 /* ForStatement */ ]: function forEachChildInForStatement(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.initializer) || visitNode2(cbNode, node.condition) || visitNode2(cbNode, node.incrementor) || visitNode2(cbNode, node.statement); }, - [246 /* ForInStatement */ ]: function forEachChildInForInStatement(node, cbNode, _cbNodes) { + [249 /* ForInStatement */ ]: function forEachChildInForInStatement(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.initializer) || visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.statement); }, - [247 /* ForOfStatement */ ]: function forEachChildInForOfStatement(node, cbNode, _cbNodes) { + [250 /* ForOfStatement */ ]: function forEachChildInForOfStatement(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.awaitModifier) || visitNode2(cbNode, node.initializer) || visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.statement); }, - [248 /* ContinueStatement */ ]: forEachChildInContinueOrBreakStatement, - [249 /* BreakStatement */ ]: forEachChildInContinueOrBreakStatement, - [250 /* ReturnStatement */ ]: function forEachChildInReturnStatement(node, cbNode, _cbNodes) { + [251 /* ContinueStatement */ ]: forEachChildInContinueOrBreakStatement, + [252 /* BreakStatement */ ]: forEachChildInContinueOrBreakStatement, + [253 /* ReturnStatement */ ]: function forEachChildInReturnStatement(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression); }, - [251 /* WithStatement */ ]: function forEachChildInWithStatement(node, cbNode, _cbNodes) { + [254 /* WithStatement */ ]: function forEachChildInWithStatement(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.statement); }, - [252 /* SwitchStatement */ ]: function forEachChildInSwitchStatement(node, cbNode, _cbNodes) { + [255 /* SwitchStatement */ ]: function forEachChildInSwitchStatement(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.caseBlock); }, - [266 /* CaseBlock */ ]: function forEachChildInCaseBlock(node, cbNode, cbNodes) { + [269 /* CaseBlock */ ]: function forEachChildInCaseBlock(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.clauses); }, - [292 /* CaseClause */ ]: function forEachChildInCaseClause(node, cbNode, cbNodes) { + [296 /* CaseClause */ ]: function forEachChildInCaseClause(node, cbNode, cbNodes) { return visitNode2(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements); }, - [293 /* DefaultClause */ ]: function forEachChildInDefaultClause(node, cbNode, cbNodes) { + [297 /* DefaultClause */ ]: function forEachChildInDefaultClause(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.statements); }, - [253 /* LabeledStatement */ ]: function forEachChildInLabeledStatement(node, cbNode, _cbNodes) { + [256 /* LabeledStatement */ ]: function forEachChildInLabeledStatement(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.label) || visitNode2(cbNode, node.statement); }, - [254 /* ThrowStatement */ ]: function forEachChildInThrowStatement(node, cbNode, _cbNodes) { + [257 /* ThrowStatement */ ]: function forEachChildInThrowStatement(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression); }, - [255 /* TryStatement */ ]: function forEachChildInTryStatement(node, cbNode, _cbNodes) { + [258 /* TryStatement */ ]: function forEachChildInTryStatement(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.tryBlock) || visitNode2(cbNode, node.catchClause) || visitNode2(cbNode, node.finallyBlock); }, - [295 /* CatchClause */ ]: function forEachChildInCatchClause(node, cbNode, _cbNodes) { + [299 /* CatchClause */ ]: function forEachChildInCatchClause(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.variableDeclaration) || visitNode2(cbNode, node.block); }, - [167 /* Decorator */ ]: function forEachChildInDecorator(node, cbNode, _cbNodes) { + [170 /* Decorator */ ]: function forEachChildInDecorator(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression); }, - [260 /* ClassDeclaration */ ]: forEachChildInClassDeclarationOrExpression, - [228 /* ClassExpression */ ]: forEachChildInClassDeclarationOrExpression, - [261 /* InterfaceDeclaration */ ]: function forEachChildInInterfaceDeclaration(node, cbNode, cbNodes) { + [263 /* ClassDeclaration */ ]: forEachChildInClassDeclarationOrExpression, + [231 /* ClassExpression */ ]: forEachChildInClassDeclarationOrExpression, + [264 /* InterfaceDeclaration */ ]: function forEachChildInInterfaceDeclaration(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); }, - [262 /* TypeAliasDeclaration */ ]: function forEachChildInTypeAliasDeclaration(node, cbNode, cbNodes) { + [265 /* TypeAliasDeclaration */ ]: function forEachChildInTypeAliasDeclaration(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode2(cbNode, node.type); }, - [263 /* EnumDeclaration */ ]: function forEachChildInEnumDeclaration(node, cbNode, cbNodes) { + [266 /* EnumDeclaration */ ]: function forEachChildInEnumDeclaration(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); }, - [302 /* EnumMember */ ]: function forEachChildInEnumMember(node, cbNode, _cbNodes) { + [306 /* EnumMember */ ]: function forEachChildInEnumMember(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.name) || visitNode2(cbNode, node.initializer); }, - [264 /* ModuleDeclaration */ ]: function forEachChildInModuleDeclaration(node, cbNode, cbNodes) { + [267 /* ModuleDeclaration */ ]: function forEachChildInModuleDeclaration(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.body); }, - [268 /* ImportEqualsDeclaration */ ]: function forEachChildInImportEqualsDeclaration(node, cbNode, cbNodes) { + [271 /* ImportEqualsDeclaration */ ]: function forEachChildInImportEqualsDeclaration(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.moduleReference); }, - [269 /* ImportDeclaration */ ]: function forEachChildInImportDeclaration(node, cbNode, cbNodes) { + [272 /* ImportDeclaration */ ]: function forEachChildInImportDeclaration(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.importClause) || visitNode2(cbNode, node.moduleSpecifier) || visitNode2(cbNode, node.assertClause); }, - [270 /* ImportClause */ ]: function forEachChildInImportClause(node, cbNode, _cbNodes) { + [273 /* ImportClause */ ]: function forEachChildInImportClause(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.name) || visitNode2(cbNode, node.namedBindings); }, - [296 /* AssertClause */ ]: function forEachChildInAssertClause(node, cbNode, cbNodes) { + [300 /* AssertClause */ ]: function forEachChildInAssertClause(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.elements); }, - [297 /* AssertEntry */ ]: function forEachChildInAssertEntry(node, cbNode, _cbNodes) { + [301 /* AssertEntry */ ]: function forEachChildInAssertEntry(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.name) || visitNode2(cbNode, node.value); }, - [267 /* NamespaceExportDeclaration */ ]: function forEachChildInNamespaceExportDeclaration(node, cbNode, cbNodes) { + [270 /* NamespaceExportDeclaration */ ]: function forEachChildInNamespaceExportDeclaration(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name); }, - [271 /* NamespaceImport */ ]: function forEachChildInNamespaceImport(node, cbNode, _cbNodes) { + [274 /* NamespaceImport */ ]: function forEachChildInNamespaceImport(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.name); }, - [277 /* NamespaceExport */ ]: function forEachChildInNamespaceExport(node, cbNode, _cbNodes) { + [280 /* NamespaceExport */ ]: function forEachChildInNamespaceExport(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.name); }, - [272 /* NamedImports */ ]: forEachChildInNamedImportsOrExports, - [276 /* NamedExports */ ]: forEachChildInNamedImportsOrExports, - [275 /* ExportDeclaration */ ]: function forEachChildInExportDeclaration(node, cbNode, cbNodes) { + [275 /* NamedImports */ ]: forEachChildInNamedImportsOrExports, + [279 /* NamedExports */ ]: forEachChildInNamedImportsOrExports, + [278 /* ExportDeclaration */ ]: function forEachChildInExportDeclaration(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.exportClause) || visitNode2(cbNode, node.moduleSpecifier) || visitNode2(cbNode, node.assertClause); }, - [273 /* ImportSpecifier */ ]: forEachChildInImportOrExportSpecifier, - [278 /* ExportSpecifier */ ]: forEachChildInImportOrExportSpecifier, - [274 /* ExportAssignment */ ]: function forEachChildInExportAssignment(node, cbNode, cbNodes) { + [276 /* ImportSpecifier */ ]: forEachChildInImportOrExportSpecifier, + [281 /* ExportSpecifier */ ]: forEachChildInImportOrExportSpecifier, + [277 /* ExportAssignment */ ]: function forEachChildInExportAssignment(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.expression); }, - [225 /* TemplateExpression */ ]: function forEachChildInTemplateExpression(node, cbNode, cbNodes) { + [228 /* TemplateExpression */ ]: function forEachChildInTemplateExpression(node, cbNode, cbNodes) { return visitNode2(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); }, - [236 /* TemplateSpan */ ]: function forEachChildInTemplateSpan(node, cbNode, _cbNodes) { + [239 /* TemplateSpan */ ]: function forEachChildInTemplateSpan(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.literal); }, - [200 /* TemplateLiteralType */ ]: function forEachChildInTemplateLiteralType(node, cbNode, cbNodes) { + [203 /* TemplateLiteralType */ ]: function forEachChildInTemplateLiteralType(node, cbNode, cbNodes) { return visitNode2(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); }, - [201 /* TemplateLiteralTypeSpan */ ]: function forEachChildInTemplateLiteralTypeSpan(node, cbNode, _cbNodes) { + [204 /* TemplateLiteralTypeSpan */ ]: function forEachChildInTemplateLiteralTypeSpan(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.type) || visitNode2(cbNode, node.literal); }, - [164 /* ComputedPropertyName */ ]: function forEachChildInComputedPropertyName(node, cbNode, _cbNodes) { + [167 /* ComputedPropertyName */ ]: function forEachChildInComputedPropertyName(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression); }, - [294 /* HeritageClause */ ]: function forEachChildInHeritageClause(node, cbNode, cbNodes) { + [298 /* HeritageClause */ ]: function forEachChildInHeritageClause(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.types); }, - [230 /* ExpressionWithTypeArguments */ ]: function forEachChildInExpressionWithTypeArguments(node, cbNode, cbNodes) { + [233 /* ExpressionWithTypeArguments */ ]: function forEachChildInExpressionWithTypeArguments(node, cbNode, cbNodes) { return visitNode2(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); }, - [280 /* ExternalModuleReference */ ]: function forEachChildInExternalModuleReference(node, cbNode, _cbNodes) { + [283 /* ExternalModuleReference */ ]: function forEachChildInExternalModuleReference(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression); }, - [279 /* MissingDeclaration */ ]: function forEachChildInMissingDeclaration(node, cbNode, cbNodes) { + [282 /* MissingDeclaration */ ]: function forEachChildInMissingDeclaration(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers); }, - [357 /* CommaListExpression */ ]: function forEachChildInCommaListExpression(node, cbNode, cbNodes) { + [361 /* CommaListExpression */ ]: function forEachChildInCommaListExpression(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.elements); }, - [281 /* JsxElement */ ]: function forEachChildInJsxElement(node, cbNode, cbNodes) { + [284 /* JsxElement */ ]: function forEachChildInJsxElement(node, cbNode, cbNodes) { return visitNode2(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode2(cbNode, node.closingElement); }, - [285 /* JsxFragment */ ]: function forEachChildInJsxFragment(node, cbNode, cbNodes) { + [288 /* JsxFragment */ ]: function forEachChildInJsxFragment(node, cbNode, cbNodes) { return visitNode2(cbNode, node.openingFragment) || visitNodes(cbNode, cbNodes, node.children) || visitNode2(cbNode, node.closingFragment); }, - [282 /* JsxSelfClosingElement */ ]: forEachChildInJsxOpeningOrSelfClosingElement, - [283 /* JsxOpeningElement */ ]: forEachChildInJsxOpeningOrSelfClosingElement, - [289 /* JsxAttributes */ ]: function forEachChildInJsxAttributes(node, cbNode, cbNodes) { + [285 /* JsxSelfClosingElement */ ]: forEachChildInJsxOpeningOrSelfClosingElement, + [286 /* JsxOpeningElement */ ]: forEachChildInJsxOpeningOrSelfClosingElement, + [292 /* JsxAttributes */ ]: function forEachChildInJsxAttributes(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.properties); }, - [288 /* JsxAttribute */ ]: function forEachChildInJsxAttribute(node, cbNode, _cbNodes) { + [291 /* JsxAttribute */ ]: function forEachChildInJsxAttribute(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.name) || visitNode2(cbNode, node.initializer); }, - [290 /* JsxSpreadAttribute */ ]: function forEachChildInJsxSpreadAttribute(node, cbNode, _cbNodes) { + [293 /* JsxSpreadAttribute */ ]: function forEachChildInJsxSpreadAttribute(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.expression); }, - [291 /* JsxExpression */ ]: function forEachChildInJsxExpression(node, cbNode, _cbNodes) { + [294 /* JsxExpression */ ]: function forEachChildInJsxExpression(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.dotDotDotToken) || visitNode2(cbNode, node.expression); }, - [284 /* JsxClosingElement */ ]: function forEachChildInJsxClosingElement(node, cbNode, _cbNodes) { + [287 /* JsxClosingElement */ ]: function forEachChildInJsxClosingElement(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.tagName); }, - [187 /* OptionalType */ ]: forEachChildInOptionalRestOrJSDocParameterModifier, - [188 /* RestType */ ]: forEachChildInOptionalRestOrJSDocParameterModifier, - [312 /* JSDocTypeExpression */ ]: forEachChildInOptionalRestOrJSDocParameterModifier, - [318 /* JSDocNonNullableType */ ]: forEachChildInOptionalRestOrJSDocParameterModifier, - [317 /* JSDocNullableType */ ]: forEachChildInOptionalRestOrJSDocParameterModifier, - [319 /* JSDocOptionalType */ ]: forEachChildInOptionalRestOrJSDocParameterModifier, - [321 /* JSDocVariadicType */ ]: forEachChildInOptionalRestOrJSDocParameterModifier, - [320 /* JSDocFunctionType */ ]: function forEachChildInJSDocFunctionType(node, cbNode, cbNodes) { + [295 /* JsxNamespacedName */ ]: function forEachChildInJsxNamespacedName(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.namespace) || visitNode2(cbNode, node.name); + }, + [190 /* OptionalType */ ]: forEachChildInOptionalRestOrJSDocParameterModifier, + [191 /* RestType */ ]: forEachChildInOptionalRestOrJSDocParameterModifier, + [316 /* JSDocTypeExpression */ ]: forEachChildInOptionalRestOrJSDocParameterModifier, + [322 /* JSDocNonNullableType */ ]: forEachChildInOptionalRestOrJSDocParameterModifier, + [321 /* JSDocNullableType */ ]: forEachChildInOptionalRestOrJSDocParameterModifier, + [323 /* JSDocOptionalType */ ]: forEachChildInOptionalRestOrJSDocParameterModifier, + [325 /* JSDocVariadicType */ ]: forEachChildInOptionalRestOrJSDocParameterModifier, + [324 /* JSDocFunctionType */ ]: function forEachChildInJSDocFunctionType(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type); }, - [323 /* JSDoc */ ]: function forEachChildInJSDoc(node, cbNode, cbNodes) { + [327 /* JSDoc */ ]: function forEachChildInJSDoc(node, cbNode, cbNodes) { return (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)) || visitNodes(cbNode, cbNodes, node.tags); }, - [350 /* JSDocSeeTag */ ]: function forEachChildInJSDocSeeTag(node, cbNode, cbNodes) { + [354 /* JSDocSeeTag */ ]: function forEachChildInJSDocSeeTag(node, cbNode, cbNodes) { return visitNode2(cbNode, node.tagName) || visitNode2(cbNode, node.name) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)); }, - [313 /* JSDocNameReference */ ]: function forEachChildInJSDocNameReference(node, cbNode, _cbNodes) { + [317 /* JSDocNameReference */ ]: function forEachChildInJSDocNameReference(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.name); }, - [314 /* JSDocMemberName */ ]: function forEachChildInJSDocMemberName(node, cbNode, _cbNodes) { + [318 /* JSDocMemberName */ ]: function forEachChildInJSDocMemberName(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.left) || visitNode2(cbNode, node.right); }, - [344 /* JSDocParameterTag */ ]: forEachChildInJSDocParameterOrPropertyTag, - [351 /* JSDocPropertyTag */ ]: forEachChildInJSDocParameterOrPropertyTag, - [333 /* JSDocAuthorTag */ ]: function forEachChildInJSDocAuthorTag(node, cbNode, cbNodes) { + [348 /* JSDocParameterTag */ ]: forEachChildInJSDocParameterOrPropertyTag, + [355 /* JSDocPropertyTag */ ]: forEachChildInJSDocParameterOrPropertyTag, + [337 /* JSDocAuthorTag */ ]: function forEachChildInJSDocAuthorTag(node, cbNode, cbNodes) { return visitNode2(cbNode, node.tagName) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)); }, - [332 /* JSDocImplementsTag */ ]: function forEachChildInJSDocImplementsTag(node, cbNode, cbNodes) { + [336 /* JSDocImplementsTag */ ]: function forEachChildInJSDocImplementsTag(node, cbNode, cbNodes) { return visitNode2(cbNode, node.tagName) || visitNode2(cbNode, node.class) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)); }, - [331 /* JSDocAugmentsTag */ ]: function forEachChildInJSDocAugmentsTag(node, cbNode, cbNodes) { + [335 /* JSDocAugmentsTag */ ]: function forEachChildInJSDocAugmentsTag(node, cbNode, cbNodes) { return visitNode2(cbNode, node.tagName) || visitNode2(cbNode, node.class) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)); }, - [348 /* JSDocTemplateTag */ ]: function forEachChildInJSDocTemplateTag(node, cbNode, cbNodes) { + [352 /* JSDocTemplateTag */ ]: function forEachChildInJSDocTemplateTag(node, cbNode, cbNodes) { return visitNode2(cbNode, node.tagName) || visitNode2(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)); }, - [349 /* JSDocTypedefTag */ ]: function forEachChildInJSDocTypedefTag(node, cbNode, cbNodes) { - return visitNode2(cbNode, node.tagName) || (node.typeExpression && node.typeExpression.kind === 312 /* JSDocTypeExpression */ ? visitNode2(cbNode, node.typeExpression) || visitNode2(cbNode, node.fullName) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)) : visitNode2(cbNode, node.fullName) || visitNode2(cbNode, node.typeExpression) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment))); + [353 /* JSDocTypedefTag */ ]: function forEachChildInJSDocTypedefTag(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.tagName) || (node.typeExpression && node.typeExpression.kind === 316 /* JSDocTypeExpression */ ? visitNode2(cbNode, node.typeExpression) || visitNode2(cbNode, node.fullName) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)) : visitNode2(cbNode, node.fullName) || visitNode2(cbNode, node.typeExpression) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment))); }, - [341 /* JSDocCallbackTag */ ]: function forEachChildInJSDocCallbackTag(node, cbNode, cbNodes) { + [345 /* JSDocCallbackTag */ ]: function forEachChildInJSDocCallbackTag(node, cbNode, cbNodes) { return visitNode2(cbNode, node.tagName) || visitNode2(cbNode, node.fullName) || visitNode2(cbNode, node.typeExpression) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)); }, - [345 /* JSDocReturnTag */ ]: forEachChildInJSDocTypeLikeTag, - [347 /* JSDocTypeTag */ ]: forEachChildInJSDocTypeLikeTag, - [346 /* JSDocThisTag */ ]: forEachChildInJSDocTypeLikeTag, - [343 /* JSDocEnumTag */ ]: forEachChildInJSDocTypeLikeTag, - [353 /* JSDocSatisfiesTag */ ]: forEachChildInJSDocTypeLikeTag, - [352 /* JSDocThrowsTag */ ]: forEachChildInJSDocTypeLikeTag, - [342 /* JSDocOverloadTag */ ]: forEachChildInJSDocTypeLikeTag, - [326 /* JSDocSignature */ ]: function forEachChildInJSDocSignature(node, cbNode, _cbNodes) { + [349 /* JSDocReturnTag */ ]: forEachChildInJSDocTypeLikeTag, + [351 /* JSDocTypeTag */ ]: forEachChildInJSDocTypeLikeTag, + [350 /* JSDocThisTag */ ]: forEachChildInJSDocTypeLikeTag, + [347 /* JSDocEnumTag */ ]: forEachChildInJSDocTypeLikeTag, + [357 /* JSDocSatisfiesTag */ ]: forEachChildInJSDocTypeLikeTag, + [356 /* JSDocThrowsTag */ ]: forEachChildInJSDocTypeLikeTag, + [346 /* JSDocOverloadTag */ ]: forEachChildInJSDocTypeLikeTag, + [330 /* JSDocSignature */ ]: function forEachChildInJSDocSignature(node, cbNode, _cbNodes) { return forEach(node.typeParameters, cbNode) || forEach(node.parameters, cbNode) || visitNode2(cbNode, node.type); }, - [327 /* JSDocLink */ ]: forEachChildInJSDocLinkCodeOrPlain, - [328 /* JSDocLinkCode */ ]: forEachChildInJSDocLinkCodeOrPlain, - [329 /* JSDocLinkPlain */ ]: forEachChildInJSDocLinkCodeOrPlain, - [325 /* JSDocTypeLiteral */ ]: function forEachChildInJSDocTypeLiteral(node, cbNode, _cbNodes) { + [331 /* JSDocLink */ ]: forEachChildInJSDocLinkCodeOrPlain, + [332 /* JSDocLinkCode */ ]: forEachChildInJSDocLinkCodeOrPlain, + [333 /* JSDocLinkPlain */ ]: forEachChildInJSDocLinkCodeOrPlain, + [329 /* JSDocTypeLiteral */ ]: function forEachChildInJSDocTypeLiteral(node, cbNode, _cbNodes) { return forEach(node.jsDocPropertyTags, cbNode); }, - [330 /* JSDocTag */ ]: forEachChildInJSDocTag, - [335 /* JSDocClassTag */ ]: forEachChildInJSDocTag, - [336 /* JSDocPublicTag */ ]: forEachChildInJSDocTag, - [337 /* JSDocPrivateTag */ ]: forEachChildInJSDocTag, - [338 /* JSDocProtectedTag */ ]: forEachChildInJSDocTag, - [339 /* JSDocReadonlyTag */ ]: forEachChildInJSDocTag, - [334 /* JSDocDeprecatedTag */ ]: forEachChildInJSDocTag, - [340 /* JSDocOverrideTag */ ]: forEachChildInJSDocTag, - [356 /* PartiallyEmittedExpression */ ]: forEachChildInPartiallyEmittedExpression + [334 /* JSDocTag */ ]: forEachChildInJSDocTag, + [339 /* JSDocClassTag */ ]: forEachChildInJSDocTag, + [340 /* JSDocPublicTag */ ]: forEachChildInJSDocTag, + [341 /* JSDocPrivateTag */ ]: forEachChildInJSDocTag, + [342 /* JSDocProtectedTag */ ]: forEachChildInJSDocTag, + [343 /* JSDocReadonlyTag */ ]: forEachChildInJSDocTag, + [338 /* JSDocDeprecatedTag */ ]: forEachChildInJSDocTag, + [344 /* JSDocOverrideTag */ ]: forEachChildInJSDocTag, + [360 /* PartiallyEmittedExpression */ ]: forEachChildInPartiallyEmittedExpression }; ((Parser2)=>{ var scanner2 = createScanner(99 /* Latest */ , /*skipTrivia*/ true); - var disallowInAndDecoratorContext = 20480 /* DecoratorContext */ ; + var disallowInAndDecoratorContext = 40960 /* DecoratorContext */ ; var NodeConstructor2; var TokenConstructor2; var IdentifierConstructor2; @@ -30540,7 +30796,7 @@ ${lanes.join("\n")} createBaseNode: (kind)=>countNode(new NodeConstructor2(kind, /*pos*/ 0, /*end*/ 0)) }; var factory2 = createNodeFactory(11 /* NoOriginalNode */ , baseNodeFactory); - var { createNodeArray: factoryCreateNodeArray , createNumericLiteral: factoryCreateNumericLiteral , createStringLiteral: factoryCreateStringLiteral , createLiteralLikeNode: factoryCreateLiteralLikeNode , createIdentifier: factoryCreateIdentifier , createPrivateIdentifier: factoryCreatePrivateIdentifier , createToken: factoryCreateToken , createArrayLiteralExpression: factoryCreateArrayLiteralExpression , createObjectLiteralExpression: factoryCreateObjectLiteralExpression , createPropertyAccessExpression: factoryCreatePropertyAccessExpression , createPropertyAccessChain: factoryCreatePropertyAccessChain , createElementAccessExpression: factoryCreateElementAccessExpression , createElementAccessChain: factoryCreateElementAccessChain , createCallExpression: factoryCreateCallExpression , createCallChain: factoryCreateCallChain , createNewExpression: factoryCreateNewExpression , createParenthesizedExpression: factoryCreateParenthesizedExpression , createBlock: factoryCreateBlock , createVariableStatement: factoryCreateVariableStatement , createExpressionStatement: factoryCreateExpressionStatement , createIfStatement: factoryCreateIfStatement , createWhileStatement: factoryCreateWhileStatement , createForStatement: factoryCreateForStatement , createForOfStatement: factoryCreateForOfStatement , createVariableDeclaration: factoryCreateVariableDeclaration , createVariableDeclarationList: factoryCreateVariableDeclarationList } = factory2; + var { createNodeArray: factoryCreateNodeArray, createNumericLiteral: factoryCreateNumericLiteral, createStringLiteral: factoryCreateStringLiteral, createLiteralLikeNode: factoryCreateLiteralLikeNode, createIdentifier: factoryCreateIdentifier, createPrivateIdentifier: factoryCreatePrivateIdentifier, createToken: factoryCreateToken, createArrayLiteralExpression: factoryCreateArrayLiteralExpression, createObjectLiteralExpression: factoryCreateObjectLiteralExpression, createPropertyAccessExpression: factoryCreatePropertyAccessExpression, createPropertyAccessChain: factoryCreatePropertyAccessChain, createElementAccessExpression: factoryCreateElementAccessExpression, createElementAccessChain: factoryCreateElementAccessChain, createCallExpression: factoryCreateCallExpression, createCallChain: factoryCreateCallChain, createNewExpression: factoryCreateNewExpression, createParenthesizedExpression: factoryCreateParenthesizedExpression, createBlock: factoryCreateBlock, createVariableStatement: factoryCreateVariableStatement, createExpressionStatement: factoryCreateExpressionStatement, createIfStatement: factoryCreateIfStatement, createWhileStatement: factoryCreateWhileStatement, createForStatement: factoryCreateForStatement, createForOfStatement: factoryCreateForOfStatement, createVariableDeclaration: factoryCreateVariableDeclaration, createVariableDeclarationList: factoryCreateVariableDeclarationList } = factory2; var fileName; var sourceFlags; var sourceText; @@ -30560,11 +30816,11 @@ ${lanes.join("\n")} var topLevel = true; var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName2, sourceText2, languageVersion2, syntaxCursor2, setParentNodes = false, scriptKind2, setExternalModuleIndicatorOverride) { - var _a2; + var _a; scriptKind2 = ensureScriptKind(fileName2, scriptKind2); if (scriptKind2 === 6 /* JSON */ ) { const result2 = parseJsonText2(fileName2, sourceText2, languageVersion2, syntaxCursor2, setParentNodes); - convertToObjectWorker(result2, (_a2 = result2.statements[0]) == null ? void 0 : _a2.expression, result2.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ void 0, /*jsonConversionNotifier*/ void 0); + convertToJson(result2, (_a = result2.statements[0]) == null ? void 0 : _a.expression, result2.parseDiagnostics, /*returnValue*/ false, /*jsonConversionNotifier*/ void 0); result2.referencedFiles = emptyArray; result2.typeReferenceDirectives = emptyArray; result2.libReferenceDirectives = emptyArray; @@ -30602,21 +30858,21 @@ ${lanes.join("\n")} while(token() !== 1 /* EndOfFileToken */ ){ let expression2; switch(token()){ - case 22 /* OpenBracketToken */ : + case 23 /* OpenBracketToken */ : expression2 = parseArrayLiteralExpression(); break; - case 110 /* TrueKeyword */ : - case 95 /* FalseKeyword */ : - case 104 /* NullKeyword */ : + case 112 /* TrueKeyword */ : + case 97 /* FalseKeyword */ : + case 106 /* NullKeyword */ : expression2 = parseTokenNode(); break; - case 40 /* MinusToken */ : - if (lookAhead(()=>nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */ )) expression2 = parsePrefixUnaryExpression(); + case 41 /* MinusToken */ : + if (lookAhead(()=>nextToken() === 9 /* NumericLiteral */ && nextToken() !== 59 /* ColonToken */ )) expression2 = parsePrefixUnaryExpression(); else expression2 = parseObjectLiteralExpression(); break; - case 8 /* NumericLiteral */ : - case 10 /* StringLiteral */ : - if (lookAhead(()=>nextToken() !== 58 /* ColonToken */ )) { + case 9 /* NumericLiteral */ : + case 11 /* StringLiteral */ : + if (lookAhead(()=>nextToken() !== 59 /* ColonToken */ )) { expression2 = parseLiteralNode(); break; } @@ -30642,7 +30898,7 @@ ${lanes.join("\n")} ], pos); endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */ , Diagnostics.Unexpected_token); } - const sourceFile = createSourceFile2(fileName2, 2 /* ES2015 */ , 6 /* JSON */ , /*isDeclaration*/ false, statements, endOfFileToken, sourceFlags, noop); + const sourceFile = createSourceFile2(fileName2, 2 /* ES2015 */ , 6 /* JSON */ , /*isDeclarationFile*/ false, statements, endOfFileToken, sourceFlags, noop); if (setParentNodes) fixupParentReferences(sourceFile); sourceFile.nodeCount = nodeCount; sourceFile.identifierCount = identifierCount; @@ -30676,10 +30932,10 @@ ${lanes.join("\n")} switch(scriptKind){ case 1 /* JS */ : case 2 /* JSX */ : - contextFlags = 262144 /* JavaScriptFile */ ; + contextFlags = 524288 /* JavaScriptFile */ ; break; case 6 /* JSON */ : - contextFlags = 67371008 /* JsonFile */ ; + contextFlags = 134742016 /* JsonFile */ ; break; default: contextFlags = 0 /* None */ ; @@ -30710,12 +30966,13 @@ ${lanes.join("\n")} } function parseSourceFileWorker(languageVersion2, setParentNodes, scriptKind2, setExternalModuleIndicator2) { const isDeclarationFile = isDeclarationFileName(fileName); - if (isDeclarationFile) contextFlags |= 16777216 /* Ambient */ ; + if (isDeclarationFile) contextFlags |= 33554432 /* Ambient */ ; sourceFlags = contextFlags; nextToken(); const statements = parseList(0 /* SourceElements */ , parseStatement); Debug.assert(token() === 1 /* EndOfFileToken */ ); - const endOfFileToken = addJSDocComment(parseTokenNode()); + const endHasJSDoc = hasPrecedingJSDocComment(); + const endOfFileToken = withJSDoc(parseTokenNode(), endHasJSDoc); const sourceFile = createSourceFile2(fileName, languageVersion2, scriptKind2, isDeclarationFile, statements, endOfFileToken, sourceFlags, setExternalModuleIndicator2); processCommentPragmas(sourceFile, sourceText); processPragmasIntoFields(sourceFile, reportPragmaDiagnostic); @@ -30731,17 +30988,15 @@ ${lanes.join("\n")} parseDiagnostics.push(createDetachedDiagnostic(fileName, pos, end, diagnostic)); } } - function withJSDoc(node, hasJSDoc) { - return hasJSDoc ? addJSDocComment(node) : node; - } let hasDeprecatedTag = false; - function addJSDocComment(node) { + function withJSDoc(node, hasJSDoc) { + if (!hasJSDoc) return node; Debug.assert(!node.jsDoc); const jsDoc = mapDefined(getJSDocCommentRanges(node, sourceText), (comment)=>JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); if (jsDoc.length) node.jsDoc = jsDoc; if (hasDeprecatedTag) { hasDeprecatedTag = false; - node.flags |= 268435456 /* Deprecated */ ; + node.flags |= 536870912 /* Deprecated */ ; } return node; } @@ -30766,14 +31021,14 @@ ${lanes.join("\n")} if (diagnosticStart >= 0) addRange(parseDiagnostics, savedParseDiagnostics, diagnosticStart, diagnosticEnd >= 0 ? diagnosticEnd : void 0); speculationHelper(()=>{ const savedContextFlags = contextFlags; - contextFlags |= 32768 /* AwaitContext */ ; - scanner2.setTextPos(nextStatement.pos); + contextFlags |= 65536 /* AwaitContext */ ; + scanner2.resetTokenState(nextStatement.pos); nextToken(); while(token() !== 1 /* EndOfFileToken */ ){ - const startPos = scanner2.getStartPos(); + const startPos = scanner2.getTokenFullStart(); const statement = parseListElement(0 /* SourceElements */ , parseStatement); statements.push(statement); - if (startPos === scanner2.getStartPos()) nextToken(); + if (startPos === scanner2.getTokenFullStart()) nextToken(); if (pos >= 0) { const nonAwaitStatement = sourceFile.statements[pos]; if (statement.end === nonAwaitStatement.pos) break; @@ -30793,7 +31048,7 @@ ${lanes.join("\n")} syntaxCursor = savedSyntaxCursor; return factory2.updateSourceFile(sourceFile, setTextRange(factoryCreateNodeArray(statements), sourceFile.statements)); function containsPossibleTopLevelAwait(node) { - return !(node.flags & 32768 /* AwaitContext */ ) && !!(node.transformFlags & 67108864 /* ContainsPossibleTopLevelAwait */ ); + return !(node.flags & 65536 /* AwaitContext */ ) && !!(node.transformFlags & 67108864 /* ContainsPossibleTopLevelAwait */ ); } function findNextStatementWithAwait(statements2, start2) { for(let i = start2; i < statements2.length; i++){ @@ -30844,16 +31099,16 @@ ${lanes.join("\n")} else contextFlags &= ~flag; } function setDisallowInContext(val) { - setContextFlag(val, 4096 /* DisallowInContext */ ); + setContextFlag(val, 8192 /* DisallowInContext */ ); } function setYieldContext(val) { - setContextFlag(val, 8192 /* YieldContext */ ); + setContextFlag(val, 16384 /* YieldContext */ ); } function setDecoratorContext(val) { - setContextFlag(val, 16384 /* DecoratorContext */ ); + setContextFlag(val, 32768 /* DecoratorContext */ ); } function setAwaitContext(val) { - setContextFlag(val, 32768 /* AwaitContext */ ); + setContextFlag(val, 65536 /* AwaitContext */ ); } function doOutsideOfContext(context, func) { const contextFlagsToClear = context & contextFlags; @@ -30876,77 +31131,77 @@ ${lanes.join("\n")} return func(); } function allowInAnd(func) { - return doOutsideOfContext(4096 /* DisallowInContext */ , func); + return doOutsideOfContext(8192 /* DisallowInContext */ , func); } function disallowInAnd(func) { - return doInsideOfContext(4096 /* DisallowInContext */ , func); + return doInsideOfContext(8192 /* DisallowInContext */ , func); } function allowConditionalTypesAnd(func) { - return doOutsideOfContext(65536 /* DisallowConditionalTypesContext */ , func); + return doOutsideOfContext(131072 /* DisallowConditionalTypesContext */ , func); } function disallowConditionalTypesAnd(func) { - return doInsideOfContext(65536 /* DisallowConditionalTypesContext */ , func); + return doInsideOfContext(131072 /* DisallowConditionalTypesContext */ , func); } function doInYieldContext(func) { - return doInsideOfContext(8192 /* YieldContext */ , func); + return doInsideOfContext(16384 /* YieldContext */ , func); } function doInDecoratorContext(func) { - return doInsideOfContext(16384 /* DecoratorContext */ , func); + return doInsideOfContext(32768 /* DecoratorContext */ , func); } function doInAwaitContext(func) { - return doInsideOfContext(32768 /* AwaitContext */ , func); + return doInsideOfContext(65536 /* AwaitContext */ , func); } function doOutsideOfAwaitContext(func) { - return doOutsideOfContext(32768 /* AwaitContext */ , func); + return doOutsideOfContext(65536 /* AwaitContext */ , func); } function doInYieldAndAwaitContext(func) { - return doInsideOfContext(40960 /* AwaitContext */ , func); + return doInsideOfContext(81920 /* AwaitContext */ , func); } function doOutsideOfYieldAndAwaitContext(func) { - return doOutsideOfContext(40960 /* AwaitContext */ , func); + return doOutsideOfContext(81920 /* AwaitContext */ , func); } function inContext(flags) { return (contextFlags & flags) !== 0; } function inYieldContext() { - return inContext(8192 /* YieldContext */ ); + return inContext(16384 /* YieldContext */ ); } function inDisallowInContext() { - return inContext(4096 /* DisallowInContext */ ); + return inContext(8192 /* DisallowInContext */ ); } function inDisallowConditionalTypesContext() { - return inContext(65536 /* DisallowConditionalTypesContext */ ); + return inContext(131072 /* DisallowConditionalTypesContext */ ); } function inDecoratorContext() { - return inContext(16384 /* DecoratorContext */ ); + return inContext(32768 /* DecoratorContext */ ); } function inAwaitContext() { - return inContext(32768 /* AwaitContext */ ); + return inContext(65536 /* AwaitContext */ ); } - function parseErrorAtCurrentToken(message, arg0) { - return parseErrorAt(scanner2.getTokenPos(), scanner2.getTextPos(), message, arg0); + function parseErrorAtCurrentToken(message, ...args) { + return parseErrorAt(scanner2.getTokenStart(), scanner2.getTokenEnd(), message, ...args); } - function parseErrorAtPosition(start, length2, message, arg0) { + function parseErrorAtPosition(start, length2, message, ...args) { const lastError = lastOrUndefined(parseDiagnostics); let result; if (!lastError || start !== lastError.start) { - result = createDetachedDiagnostic(fileName, start, length2, message, arg0); + result = createDetachedDiagnostic(fileName, start, length2, message, ...args); parseDiagnostics.push(result); } parseErrorBeforeNextFinishedNode = true; return result; } - function parseErrorAt(start, end, message, arg0) { - return parseErrorAtPosition(start, end - start, message, arg0); + function parseErrorAt(start, end, message, ...args) { + return parseErrorAtPosition(start, end - start, message, ...args); } - function parseErrorAtRange(range, message, arg0) { - parseErrorAt(range.pos, range.end, message, arg0); + function parseErrorAtRange(range, message, ...args) { + parseErrorAt(range.pos, range.end, message, ...args); } - function scanError(message, length2) { - parseErrorAtPosition(scanner2.getTextPos(), length2, message); + function scanError(message, length2, arg0) { + parseErrorAtPosition(scanner2.getTokenEnd(), length2, message, arg0); } function getNodePos() { - return scanner2.getStartPos(); + return scanner2.getTokenFullStart(); } function hasPrecedingJSDocComment() { return scanner2.hasPrecedingJSDocComment(); @@ -30962,12 +31217,15 @@ ${lanes.join("\n")} return func(); } function nextToken() { - if (isKeyword(currentToken) && (scanner2.hasUnicodeEscape() || scanner2.hasExtendedUnicodeEscape())) parseErrorAt(scanner2.getTokenPos(), scanner2.getTextPos(), Diagnostics.Keywords_cannot_contain_escape_characters); + if (isKeyword(currentToken) && (scanner2.hasUnicodeEscape() || scanner2.hasExtendedUnicodeEscape())) parseErrorAt(scanner2.getTokenStart(), scanner2.getTokenEnd(), Diagnostics.Keywords_cannot_contain_escape_characters); return nextTokenWithoutCheck(); } function nextTokenJSDoc() { return currentToken = scanner2.scanJsDocToken(); } + function nextJSDocCommentTextToken(inBackticks) { + return currentToken = scanner2.scanJSDocCommentTextToken(inBackticks); + } function reScanGreaterToken() { return currentToken = scanner2.reScanGreaterToken(); } @@ -30977,9 +31235,6 @@ ${lanes.join("\n")} function reScanTemplateToken(isTaggedTemplate) { return currentToken = scanner2.reScanTemplateToken(isTaggedTemplate); } - function reScanTemplateHeadOrNoSubstitutionTemplate() { - return currentToken = scanner2.reScanTemplateHeadOrNoSubstitutionTemplate(); - } function reScanLessThanToken() { return currentToken = scanner2.reScanLessThanToken(); } @@ -31016,14 +31271,14 @@ ${lanes.join("\n")} return speculationHelper(callback, 0 /* TryParse */ ); } function isBindingIdentifier() { - if (token() === 79 /* Identifier */ ) return true; - return token() > 116 /* LastReservedWord */ ; + if (token() === 80 /* Identifier */ ) return true; + return token() > 118 /* LastReservedWord */ ; } function isIdentifier2() { - if (token() === 79 /* Identifier */ ) return true; - if (token() === 125 /* YieldKeyword */ && inYieldContext()) return false; - if (token() === 133 /* AwaitKeyword */ && inAwaitContext()) return false; - return token() > 116 /* LastReservedWord */ ; + if (token() === 80 /* Identifier */ ) return true; + if (token() === 127 /* YieldKeyword */ && inYieldContext()) return false; + if (token() === 135 /* AwaitKeyword */ && inAwaitContext()) return false; + return token() > 118 /* LastReservedWord */ ; } function parseExpected(kind, diagnosticMessage, shouldAdvance = true) { if (token() === kind) { @@ -31036,14 +31291,13 @@ ${lanes.join("\n")} } const viableKeywordSuggestions = Object.keys(textToKeywordObj).filter((keyword)=>keyword.length > 2); function parseErrorForMissingSemicolonAfter(node) { - var _a2; if (isTaggedTemplateExpression(node)) { parseErrorAt(skipTrivia(sourceText, node.template.pos), node.template.end, Diagnostics.Module_declaration_names_may_only_use_or_quoted_strings); return; } const expressionText = isIdentifier(node) ? idText(node) : void 0; if (!expressionText || !isIdentifierText(expressionText, languageVersion)) { - parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(26 /* SemicolonToken */ )); + parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(27 /* SemicolonToken */ )); return; } const pos = skipTrivia(sourceText, node.pos); @@ -31056,20 +31310,20 @@ ${lanes.join("\n")} case "declare": return; case "interface": - parseErrorForInvalidName(Diagnostics.Interface_name_cannot_be_0, Diagnostics.Interface_must_be_given_a_name, 18 /* OpenBraceToken */ ); + parseErrorForInvalidName(Diagnostics.Interface_name_cannot_be_0, Diagnostics.Interface_must_be_given_a_name, 19 /* OpenBraceToken */ ); return; case "is": - parseErrorAt(pos, scanner2.getTextPos(), Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + parseErrorAt(pos, scanner2.getTokenStart(), Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); return; case "module": case "namespace": - parseErrorForInvalidName(Diagnostics.Namespace_name_cannot_be_0, Diagnostics.Namespace_must_be_given_a_name, 18 /* OpenBraceToken */ ); + parseErrorForInvalidName(Diagnostics.Namespace_name_cannot_be_0, Diagnostics.Namespace_must_be_given_a_name, 19 /* OpenBraceToken */ ); return; case "type": - parseErrorForInvalidName(Diagnostics.Type_alias_name_cannot_be_0, Diagnostics.Type_alias_must_be_given_a_name, 63 /* EqualsToken */ ); + parseErrorForInvalidName(Diagnostics.Type_alias_name_cannot_be_0, Diagnostics.Type_alias_must_be_given_a_name, 64 /* EqualsToken */ ); return; } - const suggestion = (_a2 = getSpellingSuggestion(expressionText, viableKeywordSuggestions, (n)=>n)) != null ? _a2 : getSpaceSuggestion(expressionText); + const suggestion = getSpellingSuggestion(expressionText, viableKeywordSuggestions, (n)=>n) ?? getSpaceSuggestion(expressionText); if (suggestion) { parseErrorAt(pos, node.end, Diagnostics.Unknown_keyword_or_identifier_Did_you_mean_0, suggestion); return; @@ -31088,23 +31342,23 @@ ${lanes.join("\n")} return void 0; } function parseSemicolonAfterPropertyName(name, type, initializer) { - if (token() === 59 /* AtToken */ && !scanner2.hasPrecedingLineBreak()) { + if (token() === 60 /* AtToken */ && !scanner2.hasPrecedingLineBreak()) { parseErrorAtCurrentToken(Diagnostics.Decorators_must_precede_the_name_and_all_keywords_of_property_declarations); return; } - if (token() === 20 /* OpenParenToken */ ) { + if (token() === 21 /* OpenParenToken */ ) { parseErrorAtCurrentToken(Diagnostics.Cannot_start_a_function_call_in_a_type_annotation); nextToken(); return; } if (type && !canParseSemicolon()) { - if (initializer) parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(26 /* SemicolonToken */ )); + if (initializer) parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(27 /* SemicolonToken */ )); else parseErrorAtCurrentToken(Diagnostics.Expected_for_property_initializer); return; } if (tryParseSemicolon()) return; if (initializer) { - parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(26 /* SemicolonToken */ )); + parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(27 /* SemicolonToken */ )); return; } parseErrorForMissingSemicolonAfter(name); @@ -31114,6 +31368,7 @@ ${lanes.join("\n")} nextTokenJSDoc(); return true; } + Debug.assert(isKeywordOrPunctuation(kind)); parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(kind)); return false; } @@ -31145,7 +31400,10 @@ ${lanes.join("\n")} return parseOptionalToken(t) || createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || Diagnostics._0_expected, arg0 || tokenToString(t)); } function parseExpectedTokenJSDoc(t) { - return parseOptionalTokenJSDoc(t) || createMissingNode(t, /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, tokenToString(t)); + const optional = parseOptionalTokenJSDoc(t); + if (optional) return optional; + Debug.assert(isKeywordOrPunctuation(t)); + return createMissingNode(t, /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, tokenToString(t)); } function parseTokenNode() { const pos = getNodePos(); @@ -31160,36 +31418,36 @@ ${lanes.join("\n")} return finishNode(factoryCreateToken(kind), pos); } function canParseSemicolon() { - if (token() === 26 /* SemicolonToken */ ) return true; - return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner2.hasPrecedingLineBreak(); + if (token() === 27 /* SemicolonToken */ ) return true; + return token() === 20 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner2.hasPrecedingLineBreak(); } function tryParseSemicolon() { if (!canParseSemicolon()) return false; - if (token() === 26 /* SemicolonToken */ ) nextToken(); + if (token() === 27 /* SemicolonToken */ ) nextToken(); return true; } function parseSemicolon() { - return tryParseSemicolon() || parseExpected(26 /* SemicolonToken */ ); + return tryParseSemicolon() || parseExpected(27 /* SemicolonToken */ ); } function createNodeArray(elements, pos, end, hasTrailingComma) { const array = factoryCreateNodeArray(elements, hasTrailingComma); - setTextRangePosEnd(array, pos, end != null ? end : scanner2.getStartPos()); + setTextRangePosEnd(array, pos, end ?? scanner2.getTokenFullStart()); return array; } function finishNode(node, pos, end) { - setTextRangePosEnd(node, pos, end != null ? end : scanner2.getStartPos()); + setTextRangePosEnd(node, pos, end ?? scanner2.getTokenFullStart()); if (contextFlags) node.flags |= contextFlags; if (parseErrorBeforeNextFinishedNode) { parseErrorBeforeNextFinishedNode = false; - node.flags |= 131072 /* ThisNodeHasError */ ; + node.flags |= 262144 /* ThisNodeHasError */ ; } return node; } - function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) { - if (reportAtCurrentPosition) parseErrorAtPosition(scanner2.getStartPos(), 0, diagnosticMessage, arg0); - else if (diagnosticMessage) parseErrorAtCurrentToken(diagnosticMessage, arg0); + function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, ...args) { + if (reportAtCurrentPosition) parseErrorAtPosition(scanner2.getTokenFullStart(), 0, diagnosticMessage, ...args); + else if (diagnosticMessage) parseErrorAtCurrentToken(diagnosticMessage, ...args); const pos = getNodePos(); - const result = kind === 79 /* Identifier */ ? factoryCreateIdentifier("", /*originalKeywordKind*/ void 0) : isTemplateLiteralKind(kind) ? factory2.createTemplateLiteralLikeNode(kind, "", "", /*templateFlags*/ void 0) : kind === 8 /* NumericLiteral */ ? factoryCreateNumericLiteral("", /*numericLiteralFlags*/ void 0) : kind === 10 /* StringLiteral */ ? factoryCreateStringLiteral("", /*isSingleQuote*/ void 0) : kind === 279 /* MissingDeclaration */ ? factory2.createMissingDeclaration() : factoryCreateToken(kind); + const result = kind === 80 /* Identifier */ ? factoryCreateIdentifier("", /*originalKeywordKind*/ void 0) : isTemplateLiteralKind(kind) ? factory2.createTemplateLiteralLikeNode(kind, "", "", /*templateFlags*/ void 0) : kind === 9 /* NumericLiteral */ ? factoryCreateNumericLiteral("", /*numericLiteralFlags*/ void 0) : kind === 11 /* StringLiteral */ ? factoryCreateStringLiteral("", /*isSingleQuote*/ void 0) : kind === 282 /* MissingDeclaration */ ? factory2.createMissingDeclaration() : factoryCreateToken(kind); return finishNode(result, pos); } function internIdentifier(text) { @@ -31207,17 +31465,17 @@ ${lanes.join("\n")} nextTokenWithoutCheck(); return finishNode(factoryCreateIdentifier(text, originalKeywordKind, hasExtendedUnicodeEscape), pos); } - if (token() === 80 /* PrivateIdentifier */ ) { + if (token() === 81 /* PrivateIdentifier */ ) { parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); return createIdentifier(/*isIdentifier*/ true); } - if (token() === 0 /* Unknown */ && scanner2.tryScan(()=>scanner2.reScanInvalidIdentifier() === 79 /* Identifier */ )) return createIdentifier(/*isIdentifier*/ true); + if (token() === 0 /* Unknown */ && scanner2.tryScan(()=>scanner2.reScanInvalidIdentifier() === 80 /* Identifier */ )) return createIdentifier(/*isIdentifier*/ true); identifierCount++; const reportAtCurrentPosition = token() === 1 /* EndOfFileToken */ ; const isReservedWord = scanner2.isReservedWord(); const msgArg = scanner2.getTokenText(); const defaultMessage = isReservedWord ? Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here : Diagnostics.Identifier_expected; - return createMissingNode(79 /* Identifier */ , reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg); + return createMissingNode(80 /* Identifier */ , reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg); } function parseBindingIdentifier(privateIdentifierDiagnosticMessage) { return createIdentifier(isBindingIdentifier(), /*diagnosticMessage*/ void 0, privateIdentifierDiagnosticMessage); @@ -31229,19 +31487,19 @@ ${lanes.join("\n")} return createIdentifier(tokenIsIdentifierOrKeyword(token()), diagnosticMessage); } function isLiteralPropertyName() { - return tokenIsIdentifierOrKeyword(token()) || token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */ ; + return tokenIsIdentifierOrKeyword(token()) || token() === 11 /* StringLiteral */ || token() === 9 /* NumericLiteral */ ; } function isAssertionKey2() { - return tokenIsIdentifierOrKeyword(token()) || token() === 10 /* StringLiteral */ ; + return tokenIsIdentifierOrKeyword(token()) || token() === 11 /* StringLiteral */ ; } function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */ ) { + if (token() === 11 /* StringLiteral */ || token() === 9 /* NumericLiteral */ ) { const node = parseLiteralNode(); node.text = internIdentifier(node.text); return node; } - if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */ ) return parseComputedPropertyName(); - if (token() === 80 /* PrivateIdentifier */ ) return parsePrivateIdentifier(); + if (allowComputedPropertyNames && token() === 23 /* OpenBracketToken */ ) return parseComputedPropertyName(); + if (token() === 81 /* PrivateIdentifier */ ) return parsePrivateIdentifier(); return parseIdentifierName(); } function parsePropertyName() { @@ -31249,9 +31507,9 @@ ${lanes.join("\n")} } function parseComputedPropertyName() { const pos = getNodePos(); - parseExpected(22 /* OpenBracketToken */ ); + parseExpected(23 /* OpenBracketToken */ ); const expression = allowInAnd(parseExpression); - parseExpected(23 /* CloseBracketToken */ ); + parseExpected(24 /* CloseBracketToken */ ); return finishNode(factory2.createComputedPropertyName(expression), pos); } function parsePrivateIdentifier() { @@ -31270,18 +31528,18 @@ ${lanes.join("\n")} } function nextTokenCanFollowModifier() { switch(token()){ - case 85 /* ConstKeyword */ : - return nextToken() === 92 /* EnumKeyword */ ; - case 93 /* ExportKeyword */ : + case 87 /* ConstKeyword */ : + return nextToken() === 94 /* EnumKeyword */ ; + case 95 /* ExportKeyword */ : nextToken(); - if (token() === 88 /* DefaultKeyword */ ) return lookAhead(nextTokenCanFollowDefaultKeyword); - if (token() === 154 /* TypeKeyword */ ) return lookAhead(nextTokenCanFollowExportModifier); + if (token() === 90 /* DefaultKeyword */ ) return lookAhead(nextTokenCanFollowDefaultKeyword); + if (token() === 156 /* TypeKeyword */ ) return lookAhead(nextTokenCanFollowExportModifier); return canFollowExportModifier(); - case 88 /* DefaultKeyword */ : + case 90 /* DefaultKeyword */ : return nextTokenCanFollowDefaultKeyword(); - case 124 /* StaticKeyword */ : - case 137 /* GetKeyword */ : - case 151 /* SetKeyword */ : + case 126 /* StaticKeyword */ : + case 139 /* GetKeyword */ : + case 153 /* SetKeyword */ : nextToken(); return canFollowModifier(); default: @@ -31289,7 +31547,7 @@ ${lanes.join("\n")} } } function canFollowExportModifier() { - return token() === 59 /* AtToken */ || token() !== 41 /* AsteriskToken */ && token() !== 128 /* AsKeyword */ && token() !== 18 /* OpenBraceToken */ && canFollowModifier(); + return token() === 60 /* AtToken */ || token() !== 42 /* AsteriskToken */ && token() !== 130 /* AsKeyword */ && token() !== 19 /* OpenBraceToken */ && canFollowModifier(); } function nextTokenCanFollowExportModifier() { nextToken(); @@ -31299,11 +31557,11 @@ ${lanes.join("\n")} return isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */ || token() === 41 /* AsteriskToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName(); + return token() === 23 /* OpenBracketToken */ || token() === 19 /* OpenBraceToken */ || token() === 42 /* AsteriskToken */ || token() === 26 /* DotDotDotToken */ || isLiteralPropertyName(); } function nextTokenCanFollowDefaultKeyword() { nextToken(); - return token() === 84 /* ClassKeyword */ || token() === 98 /* FunctionKeyword */ || token() === 118 /* InterfaceKeyword */ || token() === 59 /* AtToken */ || token() === 126 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine) || token() === 132 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine); + return token() === 86 /* ClassKeyword */ || token() === 100 /* FunctionKeyword */ || token() === 120 /* InterfaceKeyword */ || token() === 60 /* AtToken */ || token() === 128 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine) || token() === 134 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine); } function isListElement2(parsingContext2, inErrorRecovery) { const node = currentNode(parsingContext2); @@ -31312,21 +31570,21 @@ ${lanes.join("\n")} case 0 /* SourceElements */ : case 1 /* BlockStatements */ : case 3 /* SwitchClauseStatements */ : - return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + return !(token() === 27 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); case 2 /* SwitchClauses */ : - return token() === 82 /* CaseKeyword */ || token() === 88 /* DefaultKeyword */ ; + return token() === 84 /* CaseKeyword */ || token() === 90 /* DefaultKeyword */ ; case 4 /* TypeMembers */ : return lookAhead(isTypeMemberStart); case 5 /* ClassMembers */ : - return lookAhead(isClassMemberStart) || token() === 26 /* SemicolonToken */ && !inErrorRecovery; + return lookAhead(isClassMemberStart) || token() === 27 /* SemicolonToken */ && !inErrorRecovery; case 6 /* EnumMembers */ : - return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName(); + return token() === 23 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */ : switch(token()){ - case 22 /* OpenBracketToken */ : - case 41 /* AsteriskToken */ : - case 25 /* DotDotDotToken */ : - case 24 /* DotToken */ : + case 23 /* OpenBracketToken */ : + case 42 /* AsteriskToken */ : + case 26 /* DotDotDotToken */ : + case 25 /* DotToken */ : return true; default: return isLiteralPropertyName(); @@ -31334,50 +31592,56 @@ ${lanes.join("\n")} case 18 /* RestProperties */ : return isLiteralPropertyName(); case 9 /* ObjectBindingElements */ : - return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName(); + return token() === 23 /* OpenBracketToken */ || token() === 26 /* DotDotDotToken */ || isLiteralPropertyName(); case 24 /* AssertEntries */ : return isAssertionKey2(); case 7 /* HeritageClauseElement */ : - if (token() === 18 /* OpenBraceToken */ ) return lookAhead(isValidHeritageClauseObjectLiteral); + if (token() === 19 /* OpenBraceToken */ ) return lookAhead(isValidHeritageClauseObjectLiteral); if (!inErrorRecovery) return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); else return isIdentifier2() && !isHeritageClauseExtendsOrImplementsKeyword(); case 8 /* VariableDeclarations */ : return isBindingIdentifierOrPrivateIdentifierOrPattern(); case 10 /* ArrayBindingElements */ : - return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isBindingIdentifierOrPrivateIdentifierOrPattern(); + return token() === 28 /* CommaToken */ || token() === 26 /* DotDotDotToken */ || isBindingIdentifierOrPrivateIdentifierOrPattern(); case 19 /* TypeParameters */ : - return token() === 101 /* InKeyword */ || token() === 85 /* ConstKeyword */ || isIdentifier2(); + return token() === 103 /* InKeyword */ || token() === 87 /* ConstKeyword */ || isIdentifier2(); case 15 /* ArrayLiteralMembers */ : switch(token()){ - case 27 /* CommaToken */ : - case 24 /* DotToken */ : + case 28 /* CommaToken */ : + case 25 /* DotToken */ : return true; } case 11 /* ArgumentExpressions */ : - return token() === 25 /* DotDotDotToken */ || isStartOfExpression(); + return token() === 26 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */ : return isStartOfParameter(/*isJSDocParameter*/ false); case 17 /* JSDocParameters */ : return isStartOfParameter(/*isJSDocParameter*/ true); case 20 /* TypeArguments */ : case 21 /* TupleElementTypes */ : - return token() === 27 /* CommaToken */ || isStartOfType(); + return token() === 28 /* CommaToken */ || isStartOfType(); case 22 /* HeritageClauses */ : return isHeritageClause2(); case 23 /* ImportOrExportSpecifiers */ : + if (token() === 161 /* FromKeyword */ && lookAhead(nextTokenIsStringLiteral)) return false; return tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */ : - return tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */ ; + return tokenIsIdentifierOrKeyword(token()) || token() === 19 /* OpenBraceToken */ ; case 14 /* JsxChildren */ : return true; + case 25 /* JSDocComment */ : + return true; + case 26 /* Count */ : + return Debug.fail("ParsingContext.Count used as a context"); + default: + Debug.assertNever(parsingContext2, "Non-exhaustive case in 'isListElement'."); } - return Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - Debug.assert(token() === 18 /* OpenBraceToken */ ); - if (nextToken() === 19 /* CloseBraceToken */ ) { + Debug.assert(token() === 19 /* OpenBraceToken */ ); + if (nextToken() === 20 /* CloseBraceToken */ ) { const next = nextToken(); - return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 94 /* ExtendsKeyword */ || next === 117 /* ImplementsKeyword */ ; + return next === 28 /* CommaToken */ || next === 19 /* OpenBraceToken */ || next === 96 /* ExtendsKeyword */ || next === 119 /* ImplementsKeyword */ ; } return true; } @@ -31394,7 +31658,7 @@ ${lanes.join("\n")} return tokenIsIdentifierOrKeywordOrGreaterThan(token()); } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 117 /* ImplementsKeyword */ || token() === 94 /* ExtendsKeyword */ ) return lookAhead(nextTokenIsStartOfExpression); + if (token() === 119 /* ImplementsKeyword */ || token() === 96 /* ExtendsKeyword */ ) return lookAhead(nextTokenIsStartOfExpression); return false; } function nextTokenIsStartOfExpression() { @@ -31417,33 +31681,33 @@ ${lanes.join("\n")} case 9 /* ObjectBindingElements */ : case 23 /* ImportOrExportSpecifiers */ : case 24 /* AssertEntries */ : - return token() === 19 /* CloseBraceToken */ ; + return token() === 20 /* CloseBraceToken */ ; case 3 /* SwitchClauseStatements */ : - return token() === 19 /* CloseBraceToken */ || token() === 82 /* CaseKeyword */ || token() === 88 /* DefaultKeyword */ ; + return token() === 20 /* CloseBraceToken */ || token() === 84 /* CaseKeyword */ || token() === 90 /* DefaultKeyword */ ; case 7 /* HeritageClauseElement */ : - return token() === 18 /* OpenBraceToken */ || token() === 94 /* ExtendsKeyword */ || token() === 117 /* ImplementsKeyword */ ; + return token() === 19 /* OpenBraceToken */ || token() === 96 /* ExtendsKeyword */ || token() === 119 /* ImplementsKeyword */ ; case 8 /* VariableDeclarations */ : return isVariableDeclaratorListTerminator(); case 19 /* TypeParameters */ : - return token() === 31 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 94 /* ExtendsKeyword */ || token() === 117 /* ImplementsKeyword */ ; + return token() === 32 /* GreaterThanToken */ || token() === 21 /* OpenParenToken */ || token() === 19 /* OpenBraceToken */ || token() === 96 /* ExtendsKeyword */ || token() === 119 /* ImplementsKeyword */ ; case 11 /* ArgumentExpressions */ : - return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */ ; + return token() === 22 /* CloseParenToken */ || token() === 27 /* SemicolonToken */ ; case 15 /* ArrayLiteralMembers */ : case 21 /* TupleElementTypes */ : case 10 /* ArrayBindingElements */ : - return token() === 23 /* CloseBracketToken */ ; + return token() === 24 /* CloseBracketToken */ ; case 17 /* JSDocParameters */ : case 16 /* Parameters */ : case 18 /* RestProperties */ : - return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ ; + return token() === 22 /* CloseParenToken */ || token() === 24 /* CloseBracketToken */ ; case 20 /* TypeArguments */ : - return token() !== 27 /* CommaToken */ ; + return token() !== 28 /* CommaToken */ ; case 22 /* HeritageClauses */ : - return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */ ; + return token() === 19 /* OpenBraceToken */ || token() === 20 /* CloseBraceToken */ ; case 13 /* JsxAttributes */ : - return token() === 31 /* GreaterThanToken */ || token() === 43 /* SlashToken */ ; + return token() === 32 /* GreaterThanToken */ || token() === 44 /* SlashToken */ ; case 14 /* JsxChildren */ : - return token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + return token() === 30 /* LessThanToken */ && lookAhead(nextTokenIsSlash); default: return false; } @@ -31451,11 +31715,12 @@ ${lanes.join("\n")} function isVariableDeclaratorListTerminator() { if (canParseSemicolon()) return true; if (isInOrOfKeyword(token())) return true; - if (token() === 38 /* EqualsGreaterThanToken */ ) return true; + if (token() === 39 /* EqualsGreaterThanToken */ ) return true; return false; } function isInSomeParsingContext() { - for(let kind = 0; kind < 25 /* Count */ ; kind++)if (parsingContext & 1 << kind) { + Debug.assert(parsingContext, "Missing parsing context"); + for(let kind = 0; kind < 26 /* Count */ ; kind++)if (parsingContext & 1 << kind) { if (isListElement2(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) return true; } return false; @@ -31481,18 +31746,18 @@ ${lanes.join("\n")} return parseElement(); } function currentNode(parsingContext2, pos) { - var _a2; + var _a; if (!syntaxCursor || !isReusableParsingContext(parsingContext2) || parseErrorBeforeNextFinishedNode) return void 0; - const node = syntaxCursor.currentNode(pos != null ? pos : scanner2.getStartPos()); + const node = syntaxCursor.currentNode(pos ?? scanner2.getTokenFullStart()); if (nodeIsMissing(node) || node.intersectsChange || containsParseError(node)) return void 0; - const nodeContextFlags = node.flags & 50720768 /* ContextFlags */ ; + const nodeContextFlags = node.flags & 101441536 /* ContextFlags */ ; if (nodeContextFlags !== contextFlags) return void 0; if (!canReuseNode(node, parsingContext2)) return void 0; - if (canHaveJSDoc(node) && ((_a2 = node.jsDoc) == null ? void 0 : _a2.jsDocCache)) node.jsDoc.jsDocCache = void 0; + if (canHaveJSDoc(node) && ((_a = node.jsDoc) == null ? void 0 : _a.jsDocCache)) node.jsDoc.jsDocCache = void 0; return node; } function consumeNode(node) { - scanner2.setTextPos(node.end); + scanner2.resetTokenState(node.end); nextToken(); return node; } @@ -31536,84 +31801,84 @@ ${lanes.join("\n")} } function isReusableClassMember(node) { if (node) switch(node.kind){ - case 173 /* Constructor */ : - case 178 /* IndexSignature */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 169 /* PropertyDeclaration */ : - case 237 /* SemicolonClassElement */ : + case 176 /* Constructor */ : + case 181 /* IndexSignature */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 172 /* PropertyDeclaration */ : + case 240 /* SemicolonClassElement */ : return true; - case 171 /* MethodDeclaration */ : + case 174 /* MethodDeclaration */ : const methodDeclaration = node; - const nameIsConstructor = methodDeclaration.name.kind === 79 /* Identifier */ && methodDeclaration.name.escapedText === "constructor"; + const nameIsConstructor = methodDeclaration.name.kind === 80 /* Identifier */ && methodDeclaration.name.escapedText === "constructor"; return !nameIsConstructor; } return false; } function isReusableSwitchClause(node) { if (node) switch(node.kind){ - case 292 /* CaseClause */ : - case 293 /* DefaultClause */ : + case 296 /* CaseClause */ : + case 297 /* DefaultClause */ : return true; } return false; } function isReusableStatement(node) { if (node) switch(node.kind){ - case 259 /* FunctionDeclaration */ : - case 240 /* VariableStatement */ : - case 238 /* Block */ : - case 242 /* IfStatement */ : - case 241 /* ExpressionStatement */ : - case 254 /* ThrowStatement */ : - case 250 /* ReturnStatement */ : - case 252 /* SwitchStatement */ : - case 249 /* BreakStatement */ : - case 248 /* ContinueStatement */ : - case 246 /* ForInStatement */ : - case 247 /* ForOfStatement */ : - case 245 /* ForStatement */ : - case 244 /* WhileStatement */ : - case 251 /* WithStatement */ : - case 239 /* EmptyStatement */ : - case 255 /* TryStatement */ : - case 253 /* LabeledStatement */ : - case 243 /* DoStatement */ : - case 256 /* DebuggerStatement */ : - case 269 /* ImportDeclaration */ : - case 268 /* ImportEqualsDeclaration */ : - case 275 /* ExportDeclaration */ : - case 274 /* ExportAssignment */ : - case 264 /* ModuleDeclaration */ : - case 260 /* ClassDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 263 /* EnumDeclaration */ : - case 262 /* TypeAliasDeclaration */ : + case 262 /* FunctionDeclaration */ : + case 243 /* VariableStatement */ : + case 241 /* Block */ : + case 245 /* IfStatement */ : + case 244 /* ExpressionStatement */ : + case 257 /* ThrowStatement */ : + case 253 /* ReturnStatement */ : + case 255 /* SwitchStatement */ : + case 252 /* BreakStatement */ : + case 251 /* ContinueStatement */ : + case 249 /* ForInStatement */ : + case 250 /* ForOfStatement */ : + case 248 /* ForStatement */ : + case 247 /* WhileStatement */ : + case 254 /* WithStatement */ : + case 242 /* EmptyStatement */ : + case 258 /* TryStatement */ : + case 256 /* LabeledStatement */ : + case 246 /* DoStatement */ : + case 259 /* DebuggerStatement */ : + case 272 /* ImportDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : + case 278 /* ExportDeclaration */ : + case 277 /* ExportAssignment */ : + case 267 /* ModuleDeclaration */ : + case 263 /* ClassDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 266 /* EnumDeclaration */ : + case 265 /* TypeAliasDeclaration */ : return true; } return false; } function isReusableEnumMember(node) { - return node.kind === 302 /* EnumMember */ ; + return node.kind === 306 /* EnumMember */ ; } function isReusableTypeMember(node) { if (node) switch(node.kind){ - case 177 /* ConstructSignature */ : - case 170 /* MethodSignature */ : - case 178 /* IndexSignature */ : - case 168 /* PropertySignature */ : - case 176 /* CallSignature */ : + case 180 /* ConstructSignature */ : + case 173 /* MethodSignature */ : + case 181 /* IndexSignature */ : + case 171 /* PropertySignature */ : + case 179 /* CallSignature */ : return true; } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 257 /* VariableDeclaration */ ) return false; + if (node.kind !== 260 /* VariableDeclaration */ ) return false; const variableDeclarator = node; return variableDeclarator.initializer === void 0; } function isReusableParameter(node) { - if (node.kind !== 166 /* Parameter */ ) return false; + if (node.kind !== 169 /* Parameter */ ) return false; const parameter = node; return parameter.initializer === void 0; } @@ -31626,7 +31891,7 @@ ${lanes.join("\n")} function parsingContextErrors(context) { switch(context){ case 0 /* SourceElements */ : - return token() === 88 /* DefaultKeyword */ ? parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(93 /* ExportKeyword */ )) : parseErrorAtCurrentToken(Diagnostics.Declaration_or_statement_expected); + return token() === 90 /* DefaultKeyword */ ? parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(95 /* ExportKeyword */ )) : parseErrorAtCurrentToken(Diagnostics.Declaration_or_statement_expected); case 1 /* BlockStatements */ : return parseErrorAtCurrentToken(Diagnostics.Declaration_or_statement_expected); case 2 /* SwitchClauses */ : @@ -31667,6 +31932,7 @@ ${lanes.join("\n")} case 22 /* HeritageClauses */ : return parseErrorAtCurrentToken(Diagnostics.Unexpected_token_expected); case 23 /* ImportOrExportSpecifiers */ : + if (token() === 161 /* FromKeyword */ ) return parseErrorAtCurrentToken(Diagnostics._0_expected, "}"); return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); case 13 /* JsxAttributes */ : return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); @@ -31674,7 +31940,9 @@ ${lanes.join("\n")} return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); case 24 /* AssertEntries */ : return parseErrorAtCurrentToken(Diagnostics.Identifier_or_string_literal_expected); - case 25 /* Count */ : + case 25 /* JSDocComment */ : + return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); + case 26 /* Count */ : return Debug.fail("ParsingContext.Count used as a context"); default: Debug.assertNever(context); @@ -31688,20 +31956,20 @@ ${lanes.join("\n")} let commaStart = -1; while(true){ if (isListElement2(kind, /*inErrorRecovery*/ false)) { - const startPos = scanner2.getStartPos(); + const startPos = scanner2.getTokenFullStart(); const result = parseListElement(kind, parseElement); if (!result) { parsingContext = saveParsingContext; return void 0; } list.push(result); - commaStart = scanner2.getTokenPos(); - if (parseOptional(27 /* CommaToken */ )) continue; + commaStart = scanner2.getTokenStart(); + if (parseOptional(28 /* CommaToken */ )) continue; commaStart = -1; if (isListTerminator(kind)) break; - parseExpected(27 /* CommaToken */ , getExpectedCommaDiagnostic(kind)); - if (considerSemicolonAsDelimiter && token() === 26 /* SemicolonToken */ && !scanner2.hasPrecedingLineBreak()) nextToken(); - if (startPos === scanner2.getStartPos()) nextToken(); + parseExpected(28 /* CommaToken */ , getExpectedCommaDiagnostic(kind)); + if (considerSemicolonAsDelimiter && token() === 27 /* SemicolonToken */ && !scanner2.hasPrecedingLineBreak()) nextToken(); + if (startPos === scanner2.getTokenFullStart()) nextToken(); continue; } if (isListTerminator(kind)) break; @@ -31732,9 +32000,9 @@ ${lanes.join("\n")} function parseEntityName(allowReservedWords, diagnosticMessage) { const pos = getNodePos(); let entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage); - while(parseOptional(24 /* DotToken */ )){ - if (token() === 29 /* LessThanToken */ ) break; - entity = finishNode(factory2.createQualifiedName(entity, parseRightSideOfDot(allowReservedWords, /* allowPrivateIdentifiers */ false)), pos); + while(parseOptional(25 /* DotToken */ )){ + if (token() === 30 /* LessThanToken */ ) break; + entity = finishNode(factory2.createQualifiedName(entity, parseRightSideOfDot(allowReservedWords, /*allowPrivateIdentifiers*/ false)), pos); } return entity; } @@ -31744,11 +32012,11 @@ ${lanes.join("\n")} function parseRightSideOfDot(allowIdentifierNames, allowPrivateIdentifiers) { if (scanner2.hasPrecedingLineBreak() && tokenIsIdentifierOrKeyword(token())) { const matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); - if (matchesPattern) return createMissingNode(79 /* Identifier */ , /*reportAtCurrentPosition*/ true, Diagnostics.Identifier_expected); + if (matchesPattern) return createMissingNode(80 /* Identifier */ , /*reportAtCurrentPosition*/ true, Diagnostics.Identifier_expected); } - if (token() === 80 /* PrivateIdentifier */ ) { + if (token() === 81 /* PrivateIdentifier */ ) { const node = parsePrivateIdentifier(); - return allowPrivateIdentifiers ? node : createMissingNode(79 /* Identifier */ , /*reportAtCurrentPosition*/ true, Diagnostics.Identifier_expected); + return allowPrivateIdentifiers ? node : createMissingNode(80 /* Identifier */ , /*reportAtCurrentPosition*/ true, Diagnostics.Identifier_expected); } return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } @@ -31759,7 +32027,7 @@ ${lanes.join("\n")} do { node = parseTemplateSpan(isTaggedTemplate); list.push(node); - }while (node.literal.kind === 16 /* TemplateMiddle */ ); + }while (node.literal.kind === 17 /* TemplateMiddle */ ); return createNodeArray(list, pos); } function parseTemplateExpression(isTaggedTemplate) { @@ -31777,7 +32045,7 @@ ${lanes.join("\n")} do { node = parseTemplateTypeSpan(); list.push(node); - }while (node.literal.kind === 16 /* TemplateMiddle */ ); + }while (node.literal.kind === 17 /* TemplateMiddle */ ); return createNodeArray(list, pos); } function parseTemplateTypeSpan() { @@ -31785,10 +32053,10 @@ ${lanes.join("\n")} return finishNode(factory2.createTemplateLiteralTypeSpan(parseType(), parseLiteralOfTemplateSpan(/*isTaggedTemplate*/ false)), pos); } function parseLiteralOfTemplateSpan(isTaggedTemplate) { - if (token() === 19 /* CloseBraceToken */ ) { + if (token() === 20 /* CloseBraceToken */ ) { reScanTemplateToken(isTaggedTemplate); return parseTemplateMiddleOrTemplateTail(); - } else return parseExpectedToken(17 /* TemplateTail */ , Diagnostics._0_expected, tokenToString(19 /* CloseBraceToken */ )); + } else return parseExpectedToken(18 /* TemplateTail */ , Diagnostics._0_expected, tokenToString(20 /* CloseBraceToken */ )); } function parseTemplateSpan(isTaggedTemplate) { const pos = getNodePos(); @@ -31798,30 +32066,29 @@ ${lanes.join("\n")} return parseLiteralLikeNode(token()); } function parseTemplateHead(isTaggedTemplate) { - if (isTaggedTemplate) reScanTemplateHeadOrNoSubstitutionTemplate(); + if (!isTaggedTemplate && scanner2.getTokenFlags() & 26656 /* IsInvalid */ ) reScanTemplateToken(/*isTaggedTemplate*/ false); const fragment = parseLiteralLikeNode(token()); - Debug.assert(fragment.kind === 15 /* TemplateHead */ , "Template head has wrong token kind"); + Debug.assert(fragment.kind === 16 /* TemplateHead */ , "Template head has wrong token kind"); return fragment; } function parseTemplateMiddleOrTemplateTail() { const fragment = parseLiteralLikeNode(token()); - Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */ , "Template fragment has wrong token kind"); + Debug.assert(fragment.kind === 17 /* TemplateMiddle */ || fragment.kind === 18 /* TemplateTail */ , "Template fragment has wrong token kind"); return fragment; } function getTemplateLiteralRawText(kind) { - const isLast = kind === 14 /* NoSubstitutionTemplateLiteral */ || kind === 17 /* TemplateTail */ ; + const isLast = kind === 15 /* NoSubstitutionTemplateLiteral */ || kind === 18 /* TemplateTail */ ; const tokenText = scanner2.getTokenText(); return tokenText.substring(1, tokenText.length - (scanner2.isUnterminated() ? 0 : isLast ? 1 : 2)); } function parseLiteralLikeNode(kind) { const pos = getNodePos(); - const node = isTemplateLiteralKind(kind) ? factory2.createTemplateLiteralLikeNode(kind, scanner2.getTokenValue(), getTemplateLiteralRawText(kind), scanner2.getTokenFlags() & 2048 /* TemplateLiteralLikeFlags */ ) : // Octal literals are not allowed in strict mode or ES5 - // Note that theoretically the following condition would hold true literals like 009, + const node = isTemplateLiteralKind(kind) ? factory2.createTemplateLiteralLikeNode(kind, scanner2.getTokenValue(), getTemplateLiteralRawText(kind), scanner2.getTokenFlags() & 7176 /* TemplateLiteralLikeFlags */ ) : // Note that theoretically the following condition would hold true literals like 009, // which is not octal. But because of how the scanner separates the tokens, we would // never get a token like this. Instead, we would get 00 and 9 as two separate tokens. // We also do not need to check for negatives because any prefix operator would be part of a // parent unary expression. - kind === 8 /* NumericLiteral */ ? factoryCreateNumericLiteral(scanner2.getTokenValue(), scanner2.getNumericLiteralFlags()) : kind === 10 /* StringLiteral */ ? factoryCreateStringLiteral(scanner2.getTokenValue(), /*isSingleQuote*/ void 0, scanner2.hasExtendedUnicodeEscape()) : isLiteralKind(kind) ? factoryCreateLiteralLikeNode(kind, scanner2.getTokenValue()) : Debug.fail(); + kind === 9 /* NumericLiteral */ ? factoryCreateNumericLiteral(scanner2.getTokenValue(), scanner2.getNumericLiteralFlags()) : kind === 11 /* StringLiteral */ ? factoryCreateStringLiteral(scanner2.getTokenValue(), /*isSingleQuote*/ void 0, scanner2.hasExtendedUnicodeEscape()) : isLiteralKind(kind) ? factoryCreateLiteralLikeNode(kind, scanner2.getTokenValue()) : Debug.fail(); if (scanner2.hasExtendedUnicodeEscape()) node.hasExtendedUnicodeEscape = true; if (scanner2.isUnterminated()) node.isUnterminated = true; nextToken(); @@ -31831,7 +32098,7 @@ ${lanes.join("\n")} return parseEntityName(/*allowReservedWords*/ true, Diagnostics.Type_expected); } function parseTypeArgumentsOfTypeReference() { - if (!scanner2.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */ ) return parseBracketedList(20 /* TypeArguments */ , parseType, 29 /* LessThanToken */ , 31 /* GreaterThanToken */ ); + if (!scanner2.hasPrecedingLineBreak() && reScanLessThanToken() === 30 /* LessThanToken */ ) return parseBracketedList(20 /* TypeArguments */ , parseType, 30 /* LessThanToken */ , 32 /* GreaterThanToken */ ); } function parseTypeReference() { const pos = getNodePos(); @@ -31839,15 +32106,15 @@ ${lanes.join("\n")} } function typeHasArrowFunctionBlockingParseError(node) { switch(node.kind){ - case 180 /* TypeReference */ : + case 183 /* TypeReference */ : return nodeIsMissing(node.typeName); - case 181 /* FunctionType */ : - case 182 /* ConstructorType */ : + case 184 /* FunctionType */ : + case 185 /* ConstructorType */ : { - const { parameters: parameters , type: type } = node; + const { parameters: parameters, type: type } = node; return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); } - case 193 /* ParenthesizedType */ : + case 196 /* ParenthesizedType */ : return typeHasArrowFunctionBlockingParseError(node.type); default: return false; @@ -31875,7 +32142,7 @@ ${lanes.join("\n")} function parseJSDocUnknownOrNullableType() { const pos = getNodePos(); nextToken(); - if (token() === 27 /* CommaToken */ || token() === 19 /* CloseBraceToken */ || token() === 21 /* CloseParenToken */ || token() === 31 /* GreaterThanToken */ || token() === 63 /* EqualsToken */ || token() === 51 /* BarToken */ ) return finishNode(factory2.createJSDocUnknownType(), pos); + if (token() === 28 /* CommaToken */ || token() === 20 /* CloseBraceToken */ || token() === 22 /* CloseParenToken */ || token() === 32 /* GreaterThanToken */ || token() === 64 /* EqualsToken */ || token() === 52 /* BarToken */ ) return finishNode(factory2.createJSDocUnknownType(), pos); else return finishNode(factory2.createJSDocNullableType(parseType(), /*postfix*/ false), pos); } function parseJSDocFunctionType() { @@ -31884,7 +32151,7 @@ ${lanes.join("\n")} if (lookAhead(nextTokenIsOpenParen)) { nextToken(); const parameters = parseParameters(36 /* JSDoc */ ); - const type = parseReturnType(58 /* ColonToken */ , /*isType*/ false); + const type = parseReturnType(59 /* ColonToken */ , /*isType*/ false); return withJSDoc(finishNode(factory2.createJSDocFunctionType(parameters, type), pos), hasJSDoc); } return finishNode(factory2.createTypeReferenceNode(parseIdentifierName(), /*typeArguments*/ void 0), pos); @@ -31892,9 +32159,9 @@ ${lanes.join("\n")} function parseJSDocParameter() { const pos = getNodePos(); let name; - if (token() === 108 /* ThisKeyword */ || token() === 103 /* NewKeyword */ ) { + if (token() === 110 /* ThisKeyword */ || token() === 105 /* NewKeyword */ ) { name = parseIdentifierName(); - parseExpected(58 /* ColonToken */ ); + parseExpected(59 /* ColonToken */ ); } return finishNode(factory2.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, // TODO(rbuckton): JSDoc parameters don't have names (except `this`/`new`), should we manufacture an empty identifier? name, /*questionToken*/ void 0, parseJSDocType(), /*initializer*/ void 0), pos); @@ -31902,12 +32169,12 @@ ${lanes.join("\n")} function parseJSDocType() { scanner2.setInJSDocType(true); const pos = getNodePos(); - if (parseOptional(142 /* ModuleKeyword */ )) { + if (parseOptional(144 /* ModuleKeyword */ )) { const moduleTag = factory2.createJSDocNamepathType(/*type*/ void 0); terminate: while(true)switch(token()){ - case 19 /* CloseBraceToken */ : + case 20 /* CloseBraceToken */ : case 1 /* EndOfFileToken */ : - case 27 /* CommaToken */ : + case 28 /* CommaToken */ : case 5 /* WhitespaceTrivia */ : break terminate; default: @@ -31916,11 +32183,11 @@ ${lanes.join("\n")} scanner2.setInJSDocType(false); return finishNode(moduleTag, pos); } - const hasDotDotDot = parseOptional(25 /* DotDotDotToken */ ); + const hasDotDotDot = parseOptional(26 /* DotDotDotToken */ ); let type = parseTypeOrTypePredicate(); scanner2.setInJSDocType(false); if (hasDotDotDot) type = finishNode(factory2.createJSDocVariadicType(type), pos); - if (token() === 63 /* EqualsToken */ ) { + if (token() === 64 /* EqualsToken */ ) { nextToken(); return finishNode(factory2.createJSDocOptionalType(type), pos); } @@ -31928,7 +32195,7 @@ ${lanes.join("\n")} } function parseTypeQuery() { const pos = getNodePos(); - parseExpected(112 /* TypeOfKeyword */ ); + parseExpected(114 /* TypeOfKeyword */ ); const entityName = parseEntityName(/*allowReservedWords*/ true); const typeArguments = !scanner2.hasPrecedingLineBreak() ? tryParseTypeArguments() : void 0; return finishNode(factory2.createTypeQueryNode(entityName, typeArguments), pos); @@ -31939,20 +32206,20 @@ ${lanes.join("\n")} const name = parseIdentifier(); let constraint; let expression; - if (parseOptional(94 /* ExtendsKeyword */ )) { + if (parseOptional(96 /* ExtendsKeyword */ )) { if (isStartOfType() || !isStartOfExpression()) constraint = parseType(); else expression = parseUnaryExpressionOrHigher(); } - const defaultType = parseOptional(63 /* EqualsToken */ ) ? parseType() : void 0; + const defaultType = parseOptional(64 /* EqualsToken */ ) ? parseType() : void 0; const node = factory2.createTypeParameterDeclaration(modifiers, name, constraint, defaultType); node.expression = expression; return finishNode(node, pos); } function parseTypeParameters() { - if (token() === 29 /* LessThanToken */ ) return parseBracketedList(19 /* TypeParameters */ , parseTypeParameter, 29 /* LessThanToken */ , 31 /* GreaterThanToken */ ); + if (token() === 30 /* LessThanToken */ ) return parseBracketedList(19 /* TypeParameters */ , parseTypeParameter, 30 /* LessThanToken */ , 32 /* GreaterThanToken */ ); } function isStartOfParameter(isJSDocParameter) { - return token() === 25 /* DotDotDotToken */ || isBindingIdentifierOrPrivateIdentifierOrPattern() || isModifierKind(token()) || token() === 59 /* AtToken */ || isStartOfType(/*inStartOfParameter*/ !isJSDocParameter); + return token() === 26 /* DotDotDotToken */ || isBindingIdentifierOrPrivateIdentifierOrPattern() || isModifierKind(token()) || token() === 60 /* AtToken */ || isStartOfType(/*inStartOfParameter*/ !isJSDocParameter); } function parseNameOfParameter(modifiers) { const name = parseIdentifierOrPattern(Diagnostics.Private_identifiers_cannot_be_used_as_parameters); @@ -31960,7 +32227,7 @@ ${lanes.join("\n")} return name; } function isParameterNameStart() { - return isBindingIdentifier() || token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */ ; + return isBindingIdentifier() || token() === 23 /* OpenBracketToken */ || token() === 19 /* OpenBraceToken */ ; } function parseParameter(inOuterAwaitContext) { return parseParameterWorker(inOuterAwaitContext); @@ -31972,7 +32239,7 @@ ${lanes.join("\n")} const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); const modifiers = inOuterAwaitContext ? doInAwaitContext(()=>parseModifiers(/*allowDecorators*/ true)) : doOutsideOfAwaitContext(()=>parseModifiers(/*allowDecorators*/ true)); - if (token() === 108 /* ThisKeyword */ ) { + if (token() === 110 /* ThisKeyword */ ) { const node2 = factory2.createParameterDeclaration(modifiers, /*dotDotDotToken*/ void 0, createIdentifier(/*isIdentifier*/ true), /*questionToken*/ void 0, parseTypeAnnotation(), /*initializer*/ void 0); const modifier = firstOrUndefined(modifiers); if (modifier) parseErrorAtRange(modifier, Diagnostics.Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters); @@ -31980,9 +32247,9 @@ ${lanes.join("\n")} } const savedTopLevel = topLevel; topLevel = false; - const dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */ ); + const dotDotDotToken = parseOptionalToken(26 /* DotDotDotToken */ ); if (!allowAmbiguity && !isParameterNameStart()) return void 0; - const node = withJSDoc(finishNode(factory2.createParameterDeclaration(modifiers, dotDotDotToken, parseNameOfParameter(modifiers), parseOptionalToken(57 /* QuestionToken */ ), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc); + const node = withJSDoc(finishNode(factory2.createParameterDeclaration(modifiers, dotDotDotToken, parseNameOfParameter(modifiers), parseOptionalToken(58 /* QuestionToken */ ), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc); topLevel = savedTopLevel; return node; } @@ -31990,12 +32257,12 @@ ${lanes.join("\n")} if (shouldParseReturnType(returnToken, isType)) return allowConditionalTypesAnd(parseTypeOrTypePredicate); } function shouldParseReturnType(returnToken, isType) { - if (returnToken === 38 /* EqualsGreaterThanToken */ ) { + if (returnToken === 39 /* EqualsGreaterThanToken */ ) { parseExpected(returnToken); return true; - } else if (parseOptional(58 /* ColonToken */ )) return true; - else if (isType && token() === 38 /* EqualsGreaterThanToken */ ) { - parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(58 /* ColonToken */ )); + } else if (parseOptional(59 /* ColonToken */ )) return true; + else if (isType && token() === 39 /* EqualsGreaterThanToken */ ) { + parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(59 /* ColonToken */ )); nextToken(); return true; } @@ -32012,44 +32279,44 @@ ${lanes.join("\n")} return parameters; } function parseParameters(flags) { - if (!parseExpected(20 /* OpenParenToken */ )) return createMissingList(); + if (!parseExpected(21 /* OpenParenToken */ )) return createMissingList(); const parameters = parseParametersWorker(flags, /*allowAmbiguity*/ true); - parseExpected(21 /* CloseParenToken */ ); + parseExpected(22 /* CloseParenToken */ ); return parameters; } function parseTypeMemberSemicolon() { - if (parseOptional(27 /* CommaToken */ )) return; + if (parseOptional(28 /* CommaToken */ )) return; parseSemicolon(); } function parseSignatureMember(kind) { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - if (kind === 177 /* ConstructSignature */ ) parseExpected(103 /* NewKeyword */ ); + if (kind === 180 /* ConstructSignature */ ) parseExpected(105 /* NewKeyword */ ); const typeParameters = parseTypeParameters(); const parameters = parseParameters(4 /* Type */ ); - const type = parseReturnType(58 /* ColonToken */ , /*isType*/ true); + const type = parseReturnType(59 /* ColonToken */ , /*isType*/ true); parseTypeMemberSemicolon(); - const node = kind === 176 /* CallSignature */ ? factory2.createCallSignature(typeParameters, parameters, type) : factory2.createConstructSignature(typeParameters, parameters, type); + const node = kind === 179 /* CallSignature */ ? factory2.createCallSignature(typeParameters, parameters, type) : factory2.createConstructSignature(typeParameters, parameters, type); return withJSDoc(finishNode(node, pos), hasJSDoc); } function isIndexSignature() { - return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature); + return token() === 23 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature); } function isUnambiguouslyIndexSignature() { nextToken(); - if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */ ) return true; + if (token() === 26 /* DotDotDotToken */ || token() === 24 /* CloseBracketToken */ ) return true; if (isModifierKind(token())) { nextToken(); if (isIdentifier2()) return true; } else if (!isIdentifier2()) return false; else nextToken(); - if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ ) return true; - if (token() !== 57 /* QuestionToken */ ) return false; + if (token() === 59 /* ColonToken */ || token() === 28 /* CommaToken */ ) return true; + if (token() !== 58 /* QuestionToken */ ) return false; nextToken(); - return token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */ ; + return token() === 59 /* ColonToken */ || token() === 28 /* CommaToken */ || token() === 24 /* CloseBracketToken */ ; } function parseIndexSignatureDeclaration(pos, hasJSDoc, modifiers) { - const parameters = parseBracketedList(16 /* Parameters */ , ()=>parseParameter(/*inOuterAwaitContext*/ false), 22 /* OpenBracketToken */ , 23 /* CloseBracketToken */ ); + const parameters = parseBracketedList(16 /* Parameters */ , ()=>parseParameter(/*inOuterAwaitContext*/ false), 23 /* OpenBracketToken */ , 24 /* CloseBracketToken */ ); const type = parseTypeAnnotation(); parseTypeMemberSemicolon(); const node = factory2.createIndexSignature(modifiers, parameters, type); @@ -32057,59 +32324,59 @@ ${lanes.join("\n")} } function parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers) { const name = parsePropertyName(); - const questionToken = parseOptionalToken(57 /* QuestionToken */ ); + const questionToken = parseOptionalToken(58 /* QuestionToken */ ); let node; - if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */ ) { + if (token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */ ) { const typeParameters = parseTypeParameters(); const parameters = parseParameters(4 /* Type */ ); - const type = parseReturnType(58 /* ColonToken */ , /*isType*/ true); + const type = parseReturnType(59 /* ColonToken */ , /*isType*/ true); node = factory2.createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type); } else { const type = parseTypeAnnotation(); node = factory2.createPropertySignature(modifiers, name, questionToken, type); - if (token() === 63 /* EqualsToken */ ) node.initializer = parseInitializer(); + if (token() === 64 /* EqualsToken */ ) node.initializer = parseInitializer(); } parseTypeMemberSemicolon(); return withJSDoc(finishNode(node, pos), hasJSDoc); } function isTypeMemberStart() { - if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */ || token() === 137 /* GetKeyword */ || token() === 151 /* SetKeyword */ ) return true; + if (token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */ || token() === 139 /* GetKeyword */ || token() === 153 /* SetKeyword */ ) return true; let idToken = false; while(isModifierKind(token())){ idToken = true; nextToken(); } - if (token() === 22 /* OpenBracketToken */ ) return true; + if (token() === 23 /* OpenBracketToken */ ) return true; if (isLiteralPropertyName()) { idToken = true; nextToken(); } - if (idToken) return token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */ || token() === 57 /* QuestionToken */ || token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || canParseSemicolon(); + if (idToken) return token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */ || token() === 58 /* QuestionToken */ || token() === 59 /* ColonToken */ || token() === 28 /* CommaToken */ || canParseSemicolon(); return false; } function parseTypeMember() { - if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */ ) return parseSignatureMember(176 /* CallSignature */ ); - if (token() === 103 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) return parseSignatureMember(177 /* ConstructSignature */ ); + if (token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */ ) return parseSignatureMember(179 /* CallSignature */ ); + if (token() === 105 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) return parseSignatureMember(180 /* ConstructSignature */ ); const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); const modifiers = parseModifiers(/*allowDecorators*/ false); - if (parseContextualModifier(137 /* GetKeyword */ )) return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 174 /* GetAccessor */ , 4 /* Type */ ); - if (parseContextualModifier(151 /* SetKeyword */ )) return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 175 /* SetAccessor */ , 4 /* Type */ ); + if (parseContextualModifier(139 /* GetKeyword */ )) return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 177 /* GetAccessor */ , 4 /* Type */ ); + if (parseContextualModifier(153 /* SetKeyword */ )) return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 178 /* SetAccessor */ , 4 /* Type */ ); if (isIndexSignature()) return parseIndexSignatureDeclaration(pos, hasJSDoc, modifiers); return parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers); } function nextTokenIsOpenParenOrLessThan() { nextToken(); - return token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */ ; + return token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */ ; } function nextTokenIsDot() { - return nextToken() === 24 /* DotToken */ ; + return nextToken() === 25 /* DotToken */ ; } function nextTokenIsOpenParenOrLessThanOrDot() { switch(nextToken()){ - case 20 /* OpenParenToken */ : - case 29 /* LessThanToken */ : - case 24 /* DotToken */ : + case 21 /* OpenParenToken */ : + case 30 /* LessThanToken */ : + case 25 /* DotToken */ : return true; } return false; @@ -32120,51 +32387,51 @@ ${lanes.join("\n")} } function parseObjectTypeMembers() { let members; - if (parseExpected(18 /* OpenBraceToken */ )) { + if (parseExpected(19 /* OpenBraceToken */ )) { members = parseList(4 /* TypeMembers */ , parseTypeMember); - parseExpected(19 /* CloseBraceToken */ ); + parseExpected(20 /* CloseBraceToken */ ); } else members = createMissingList(); return members; } function isStartOfMappedType() { nextToken(); - if (token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */ ) return nextToken() === 146 /* ReadonlyKeyword */ ; - if (token() === 146 /* ReadonlyKeyword */ ) nextToken(); - return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 101 /* InKeyword */ ; + if (token() === 40 /* PlusToken */ || token() === 41 /* MinusToken */ ) return nextToken() === 148 /* ReadonlyKeyword */ ; + if (token() === 148 /* ReadonlyKeyword */ ) nextToken(); + return token() === 23 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 103 /* InKeyword */ ; } function parseMappedTypeParameter() { const pos = getNodePos(); const name = parseIdentifierName(); - parseExpected(101 /* InKeyword */ ); + parseExpected(103 /* InKeyword */ ); const type = parseType(); return finishNode(factory2.createTypeParameterDeclaration(/*modifiers*/ void 0, name, type, /*defaultType*/ void 0), pos); } function parseMappedType() { const pos = getNodePos(); - parseExpected(18 /* OpenBraceToken */ ); + parseExpected(19 /* OpenBraceToken */ ); let readonlyToken; - if (token() === 146 /* ReadonlyKeyword */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */ ) { + if (token() === 148 /* ReadonlyKeyword */ || token() === 40 /* PlusToken */ || token() === 41 /* MinusToken */ ) { readonlyToken = parseTokenNode(); - if (readonlyToken.kind !== 146 /* ReadonlyKeyword */ ) parseExpected(146 /* ReadonlyKeyword */ ); + if (readonlyToken.kind !== 148 /* ReadonlyKeyword */ ) parseExpected(148 /* ReadonlyKeyword */ ); } - parseExpected(22 /* OpenBracketToken */ ); + parseExpected(23 /* OpenBracketToken */ ); const typeParameter = parseMappedTypeParameter(); - const nameType = parseOptional(128 /* AsKeyword */ ) ? parseType() : void 0; - parseExpected(23 /* CloseBracketToken */ ); + const nameType = parseOptional(130 /* AsKeyword */ ) ? parseType() : void 0; + parseExpected(24 /* CloseBracketToken */ ); let questionToken; - if (token() === 57 /* QuestionToken */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */ ) { + if (token() === 58 /* QuestionToken */ || token() === 40 /* PlusToken */ || token() === 41 /* MinusToken */ ) { questionToken = parseTokenNode(); - if (questionToken.kind !== 57 /* QuestionToken */ ) parseExpected(57 /* QuestionToken */ ); + if (questionToken.kind !== 58 /* QuestionToken */ ) parseExpected(58 /* QuestionToken */ ); } const type = parseTypeAnnotation(); parseSemicolon(); const members = parseList(4 /* TypeMembers */ , parseTypeMember); - parseExpected(19 /* CloseBraceToken */ ); + parseExpected(20 /* CloseBraceToken */ ); return finishNode(factory2.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), pos); } function parseTupleElementType() { const pos = getNodePos(); - if (parseOptional(25 /* DotDotDotToken */ )) return finishNode(factory2.createRestTypeNode(parseType()), pos); + if (parseOptional(26 /* DotDotDotToken */ )) return finishNode(factory2.createRestTypeNode(parseType()), pos); const type = parseType(); if (isJSDocNullableType(type) && type.pos === type.type.pos) { const node = factory2.createOptionalTypeNode(type.type); @@ -32175,20 +32442,20 @@ ${lanes.join("\n")} return type; } function isNextTokenColonOrQuestionColon() { - return nextToken() === 58 /* ColonToken */ || token() === 57 /* QuestionToken */ && nextToken() === 58 /* ColonToken */ ; + return nextToken() === 59 /* ColonToken */ || token() === 58 /* QuestionToken */ && nextToken() === 59 /* ColonToken */ ; } function isTupleElementName() { - if (token() === 25 /* DotDotDotToken */ ) return tokenIsIdentifierOrKeyword(nextToken()) && isNextTokenColonOrQuestionColon(); + if (token() === 26 /* DotDotDotToken */ ) return tokenIsIdentifierOrKeyword(nextToken()) && isNextTokenColonOrQuestionColon(); return tokenIsIdentifierOrKeyword(token()) && isNextTokenColonOrQuestionColon(); } function parseTupleElementNameOrTupleElementType() { if (lookAhead(isTupleElementName)) { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - const dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */ ); + const dotDotDotToken = parseOptionalToken(26 /* DotDotDotToken */ ); const name = parseIdentifierName(); - const questionToken = parseOptionalToken(57 /* QuestionToken */ ); - parseExpected(58 /* ColonToken */ ); + const questionToken = parseOptionalToken(58 /* QuestionToken */ ); + parseExpected(59 /* ColonToken */ ); const type = parseTupleElementType(); const node = factory2.createNamedTupleMember(dotDotDotToken, name, questionToken, type); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -32197,21 +32464,21 @@ ${lanes.join("\n")} } function parseTupleType() { const pos = getNodePos(); - return finishNode(factory2.createTupleTypeNode(parseBracketedList(21 /* TupleElementTypes */ , parseTupleElementNameOrTupleElementType, 22 /* OpenBracketToken */ , 23 /* CloseBracketToken */ )), pos); + return finishNode(factory2.createTupleTypeNode(parseBracketedList(21 /* TupleElementTypes */ , parseTupleElementNameOrTupleElementType, 23 /* OpenBracketToken */ , 24 /* CloseBracketToken */ )), pos); } function parseParenthesizedType() { const pos = getNodePos(); - parseExpected(20 /* OpenParenToken */ ); + parseExpected(21 /* OpenParenToken */ ); const type = parseType(); - parseExpected(21 /* CloseParenToken */ ); + parseExpected(22 /* CloseParenToken */ ); return finishNode(factory2.createParenthesizedType(type), pos); } function parseModifiersForConstructorType() { let modifiers; - if (token() === 126 /* AbstractKeyword */ ) { + if (token() === 128 /* AbstractKeyword */ ) { const pos = getNodePos(); nextToken(); - const modifier = finishNode(factoryCreateToken(126 /* AbstractKeyword */ ), pos); + const modifier = finishNode(factoryCreateToken(128 /* AbstractKeyword */ ), pos); modifiers = createNodeArray([ modifier ], pos); @@ -32222,117 +32489,117 @@ ${lanes.join("\n")} const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); const modifiers = parseModifiersForConstructorType(); - const isConstructorType = parseOptional(103 /* NewKeyword */ ); + const isConstructorType = parseOptional(105 /* NewKeyword */ ); Debug.assert(!modifiers || isConstructorType, "Per isStartOfFunctionOrConstructorType, a function type cannot have modifiers."); const typeParameters = parseTypeParameters(); const parameters = parseParameters(4 /* Type */ ); - const type = parseReturnType(38 /* EqualsGreaterThanToken */ , /*isType*/ false); + const type = parseReturnType(39 /* EqualsGreaterThanToken */ , /*isType*/ false); const node = isConstructorType ? factory2.createConstructorTypeNode(modifiers, typeParameters, parameters, type) : factory2.createFunctionTypeNode(typeParameters, parameters, type); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseKeywordAndNoDot() { const node = parseTokenNode(); - return token() === 24 /* DotToken */ ? void 0 : node; + return token() === 25 /* DotToken */ ? void 0 : node; } function parseLiteralTypeNode(negative) { const pos = getNodePos(); if (negative) nextToken(); - let expression = token() === 110 /* TrueKeyword */ || token() === 95 /* FalseKeyword */ || token() === 104 /* NullKeyword */ ? parseTokenNode() : parseLiteralLikeNode(token()); - if (negative) expression = finishNode(factory2.createPrefixUnaryExpression(40 /* MinusToken */ , expression), pos); + let expression = token() === 112 /* TrueKeyword */ || token() === 97 /* FalseKeyword */ || token() === 106 /* NullKeyword */ ? parseTokenNode() : parseLiteralLikeNode(token()); + if (negative) expression = finishNode(factory2.createPrefixUnaryExpression(41 /* MinusToken */ , expression), pos); return finishNode(factory2.createLiteralTypeNode(expression), pos); } function isStartOfTypeOfImportType() { nextToken(); - return token() === 100 /* ImportKeyword */ ; + return token() === 102 /* ImportKeyword */ ; } function parseImportTypeAssertions() { const pos = getNodePos(); - const openBracePosition = scanner2.getTokenPos(); - parseExpected(18 /* OpenBraceToken */ ); + const openBracePosition = scanner2.getTokenStart(); + parseExpected(19 /* OpenBraceToken */ ); const multiLine = scanner2.hasPrecedingLineBreak(); - parseExpected(130 /* AssertKeyword */ ); - parseExpected(58 /* ColonToken */ ); + parseExpected(132 /* AssertKeyword */ ); + parseExpected(59 /* ColonToken */ ); const clause = parseAssertClause(/*skipAssertKeyword*/ true); - if (!parseExpected(19 /* CloseBraceToken */ )) { + if (!parseExpected(20 /* 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_1_to_match_the_0_token_here, "{", "}")); } return finishNode(factory2.createImportTypeAssertionContainer(clause, multiLine), pos); } function parseImportType() { - sourceFlags |= 2097152 /* PossiblyContainsDynamicImport */ ; + sourceFlags |= 4194304 /* PossiblyContainsDynamicImport */ ; const pos = getNodePos(); - const isTypeOf = parseOptional(112 /* TypeOfKeyword */ ); - parseExpected(100 /* ImportKeyword */ ); - parseExpected(20 /* OpenParenToken */ ); + const isTypeOf = parseOptional(114 /* TypeOfKeyword */ ); + parseExpected(102 /* ImportKeyword */ ); + parseExpected(21 /* OpenParenToken */ ); const type = parseType(); let assertions; - if (parseOptional(27 /* CommaToken */ )) assertions = parseImportTypeAssertions(); - parseExpected(21 /* CloseParenToken */ ); - const qualifier = parseOptional(24 /* DotToken */ ) ? parseEntityNameOfTypeReference() : void 0; + if (parseOptional(28 /* CommaToken */ )) assertions = parseImportTypeAssertions(); + parseExpected(22 /* CloseParenToken */ ); + const qualifier = parseOptional(25 /* DotToken */ ) ? parseEntityNameOfTypeReference() : void 0; const typeArguments = parseTypeArgumentsOfTypeReference(); return finishNode(factory2.createImportTypeNode(type, assertions, qualifier, typeArguments, isTypeOf), pos); } function nextTokenIsNumericOrBigIntLiteral() { nextToken(); - return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ ; + return token() === 9 /* NumericLiteral */ || token() === 10 /* BigIntLiteral */ ; } function parseNonArrayType() { switch(token()){ - case 131 /* AnyKeyword */ : - case 157 /* UnknownKeyword */ : - case 152 /* StringKeyword */ : - case 148 /* NumberKeyword */ : - case 160 /* BigIntKeyword */ : - case 153 /* SymbolKeyword */ : - case 134 /* BooleanKeyword */ : - case 155 /* UndefinedKeyword */ : - case 144 /* NeverKeyword */ : - case 149 /* ObjectKeyword */ : + case 133 /* AnyKeyword */ : + case 159 /* UnknownKeyword */ : + case 154 /* StringKeyword */ : + case 150 /* NumberKeyword */ : + case 163 /* BigIntKeyword */ : + case 155 /* SymbolKeyword */ : + case 136 /* BooleanKeyword */ : + case 157 /* UndefinedKeyword */ : + case 146 /* NeverKeyword */ : + case 151 /* ObjectKeyword */ : return tryParse(parseKeywordAndNoDot) || parseTypeReference(); - case 66 /* AsteriskEqualsToken */ : + case 67 /* AsteriskEqualsToken */ : scanner2.reScanAsteriskEqualsToken(); - case 41 /* AsteriskToken */ : + case 42 /* AsteriskToken */ : return parseJSDocAllType(); - case 60 /* QuestionQuestionToken */ : + case 61 /* QuestionQuestionToken */ : scanner2.reScanQuestionToken(); - case 57 /* QuestionToken */ : + case 58 /* QuestionToken */ : return parseJSDocUnknownOrNullableType(); - case 98 /* FunctionKeyword */ : + case 100 /* FunctionKeyword */ : return parseJSDocFunctionType(); - case 53 /* ExclamationToken */ : + case 54 /* ExclamationToken */ : return parseJSDocNonNullableType(); - case 14 /* NoSubstitutionTemplateLiteral */ : - case 10 /* StringLiteral */ : - case 8 /* NumericLiteral */ : - case 9 /* BigIntLiteral */ : - case 110 /* TrueKeyword */ : - case 95 /* FalseKeyword */ : - case 104 /* NullKeyword */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + case 11 /* StringLiteral */ : + case 9 /* NumericLiteral */ : + case 10 /* BigIntLiteral */ : + case 112 /* TrueKeyword */ : + case 97 /* FalseKeyword */ : + case 106 /* NullKeyword */ : return parseLiteralTypeNode(); - case 40 /* MinusToken */ : + case 41 /* MinusToken */ : return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); - case 114 /* VoidKeyword */ : + case 116 /* VoidKeyword */ : return parseTokenNode(); - case 108 /* ThisKeyword */ : + case 110 /* ThisKeyword */ : { const thisKeyword = parseThisTypeNode(); - if (token() === 140 /* IsKeyword */ && !scanner2.hasPrecedingLineBreak()) return parseThisTypePredicate(thisKeyword); + if (token() === 142 /* IsKeyword */ && !scanner2.hasPrecedingLineBreak()) return parseThisTypePredicate(thisKeyword); else return thisKeyword; } - case 112 /* TypeOfKeyword */ : + case 114 /* TypeOfKeyword */ : return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery(); - case 18 /* OpenBraceToken */ : + case 19 /* OpenBraceToken */ : return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); - case 22 /* OpenBracketToken */ : + case 23 /* OpenBracketToken */ : return parseTupleType(); - case 20 /* OpenParenToken */ : + case 21 /* OpenParenToken */ : return parseParenthesizedType(); - case 100 /* ImportKeyword */ : + case 102 /* ImportKeyword */ : return parseImportType(); - case 129 /* AssertsKeyword */ : + case 131 /* AssertsKeyword */ : return lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine) ? parseAssertsTypePredicate() : parseTypeReference(); - case 15 /* TemplateHead */ : + case 16 /* TemplateHead */ : return parseTemplateType(); default: return parseTypeReference(); @@ -32340,48 +32607,48 @@ ${lanes.join("\n")} } function isStartOfType(inStartOfParameter) { switch(token()){ - case 131 /* AnyKeyword */ : - case 157 /* UnknownKeyword */ : - case 152 /* StringKeyword */ : - case 148 /* NumberKeyword */ : - case 160 /* BigIntKeyword */ : - case 134 /* BooleanKeyword */ : - case 146 /* ReadonlyKeyword */ : - case 153 /* SymbolKeyword */ : - case 156 /* UniqueKeyword */ : - case 114 /* VoidKeyword */ : - case 155 /* UndefinedKeyword */ : - case 104 /* NullKeyword */ : - case 108 /* ThisKeyword */ : - case 112 /* TypeOfKeyword */ : - case 144 /* NeverKeyword */ : - case 18 /* OpenBraceToken */ : - case 22 /* OpenBracketToken */ : - case 29 /* LessThanToken */ : - case 51 /* BarToken */ : - case 50 /* AmpersandToken */ : - case 103 /* NewKeyword */ : - case 10 /* StringLiteral */ : - case 8 /* NumericLiteral */ : - case 9 /* BigIntLiteral */ : - case 110 /* TrueKeyword */ : - case 95 /* FalseKeyword */ : - case 149 /* ObjectKeyword */ : - case 41 /* AsteriskToken */ : - case 57 /* QuestionToken */ : - case 53 /* ExclamationToken */ : - case 25 /* DotDotDotToken */ : - case 138 /* InferKeyword */ : - case 100 /* ImportKeyword */ : - case 129 /* AssertsKeyword */ : - case 14 /* NoSubstitutionTemplateLiteral */ : - case 15 /* TemplateHead */ : + case 133 /* AnyKeyword */ : + case 159 /* UnknownKeyword */ : + case 154 /* StringKeyword */ : + case 150 /* NumberKeyword */ : + case 163 /* BigIntKeyword */ : + case 136 /* BooleanKeyword */ : + case 148 /* ReadonlyKeyword */ : + case 155 /* SymbolKeyword */ : + case 158 /* UniqueKeyword */ : + case 116 /* VoidKeyword */ : + case 157 /* UndefinedKeyword */ : + case 106 /* NullKeyword */ : + case 110 /* ThisKeyword */ : + case 114 /* TypeOfKeyword */ : + case 146 /* NeverKeyword */ : + case 19 /* OpenBraceToken */ : + case 23 /* OpenBracketToken */ : + case 30 /* LessThanToken */ : + case 52 /* BarToken */ : + case 51 /* AmpersandToken */ : + case 105 /* NewKeyword */ : + case 11 /* StringLiteral */ : + case 9 /* NumericLiteral */ : + case 10 /* BigIntLiteral */ : + case 112 /* TrueKeyword */ : + case 97 /* FalseKeyword */ : + case 151 /* ObjectKeyword */ : + case 42 /* AsteriskToken */ : + case 58 /* QuestionToken */ : + case 54 /* ExclamationToken */ : + case 26 /* DotDotDotToken */ : + case 140 /* InferKeyword */ : + case 102 /* ImportKeyword */ : + case 131 /* AssertsKeyword */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + case 16 /* TemplateHead */ : return true; - case 98 /* FunctionKeyword */ : + case 100 /* FunctionKeyword */ : return !inStartOfParameter; - case 40 /* MinusToken */ : + case 41 /* MinusToken */ : return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral); - case 20 /* OpenParenToken */ : + case 21 /* OpenParenToken */ : return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType); default: return isIdentifier2(); @@ -32389,29 +32656,29 @@ ${lanes.join("\n")} } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); + return token() === 22 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); } function parsePostfixTypeOrHigher() { const pos = getNodePos(); let type = parseNonArrayType(); while(!scanner2.hasPrecedingLineBreak())switch(token()){ - case 53 /* ExclamationToken */ : + case 54 /* ExclamationToken */ : nextToken(); type = finishNode(factory2.createJSDocNonNullableType(type, /*postfix*/ true), pos); break; - case 57 /* QuestionToken */ : + case 58 /* QuestionToken */ : if (lookAhead(nextTokenIsStartOfType)) return type; nextToken(); type = finishNode(factory2.createJSDocNullableType(type, /*postfix*/ true), pos); break; - case 22 /* OpenBracketToken */ : - parseExpected(22 /* OpenBracketToken */ ); + case 23 /* OpenBracketToken */ : + parseExpected(23 /* OpenBracketToken */ ); if (isStartOfType()) { const indexType = parseType(); - parseExpected(23 /* CloseBracketToken */ ); + parseExpected(24 /* CloseBracketToken */ ); type = finishNode(factory2.createIndexedAccessTypeNode(type, indexType), pos); } else { - parseExpected(23 /* CloseBracketToken */ ); + parseExpected(24 /* CloseBracketToken */ ); type = finishNode(factory2.createArrayTypeNode(type), pos); } break; @@ -32426,9 +32693,9 @@ ${lanes.join("\n")} return finishNode(factory2.createTypeOperatorNode(operator, parseTypeOperatorOrHigher()), pos); } function tryParseConstraintOfInferType() { - if (parseOptional(94 /* ExtendsKeyword */ )) { + if (parseOptional(96 /* ExtendsKeyword */ )) { const constraint = disallowConditionalTypesAnd(parseType); - if (inDisallowConditionalTypesContext() || token() !== 57 /* QuestionToken */ ) return constraint; + if (inDisallowConditionalTypesContext() || token() !== 58 /* QuestionToken */ ) return constraint; } } function parseTypeParameterOfInferType() { @@ -32440,17 +32707,17 @@ ${lanes.join("\n")} } function parseInferType() { const pos = getNodePos(); - parseExpected(138 /* InferKeyword */ ); + parseExpected(140 /* InferKeyword */ ); return finishNode(factory2.createInferTypeNode(parseTypeParameterOfInferType()), pos); } function parseTypeOperatorOrHigher() { const operator = token(); switch(operator){ - case 141 /* KeyOfKeyword */ : - case 156 /* UniqueKeyword */ : - case 146 /* ReadonlyKeyword */ : + case 143 /* KeyOfKeyword */ : + case 158 /* UniqueKeyword */ : + case 148 /* ReadonlyKeyword */ : return parseTypeOperator(operator); - case 138 /* InferKeyword */ : + case 140 /* InferKeyword */ : return parseInferType(); } return allowConditionalTypesAnd(parsePostfixTypeOrHigher); @@ -32468,7 +32735,7 @@ ${lanes.join("\n")} } function parseUnionOrIntersectionType(operator, parseConstituentType, createTypeNode) { const pos = getNodePos(); - const isUnionType = operator === 51 /* BarToken */ ; + const isUnionType = operator === 52 /* BarToken */ ; const hasLeadingOperator = parseOptional(operator); let type = hasLeadingOperator && parseFunctionOrConstructorTypeToError(isUnionType) || parseConstituentType(); if (token() === operator || hasLeadingOperator) { @@ -32481,27 +32748,27 @@ ${lanes.join("\n")} return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(50 /* AmpersandToken */ , parseTypeOperatorOrHigher, factory2.createIntersectionTypeNode); + return parseUnionOrIntersectionType(51 /* AmpersandToken */ , parseTypeOperatorOrHigher, factory2.createIntersectionTypeNode); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(51 /* BarToken */ , parseIntersectionTypeOrHigher, factory2.createUnionTypeNode); + return parseUnionOrIntersectionType(52 /* BarToken */ , parseIntersectionTypeOrHigher, factory2.createUnionTypeNode); } function nextTokenIsNewKeyword() { nextToken(); - return token() === 103 /* NewKeyword */ ; + return token() === 105 /* NewKeyword */ ; } function isStartOfFunctionTypeOrConstructorType() { - if (token() === 29 /* LessThanToken */ ) return true; - if (token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType)) return true; - return token() === 103 /* NewKeyword */ || token() === 126 /* AbstractKeyword */ && lookAhead(nextTokenIsNewKeyword); + if (token() === 30 /* LessThanToken */ ) return true; + if (token() === 21 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType)) return true; + return token() === 105 /* NewKeyword */ || token() === 128 /* AbstractKeyword */ && lookAhead(nextTokenIsNewKeyword); } function skipParameterStart() { if (isModifierKind(token())) parseModifiers(/*allowDecorators*/ false); - if (isIdentifier2() || token() === 108 /* ThisKeyword */ ) { + if (isIdentifier2() || token() === 110 /* ThisKeyword */ ) { nextToken(); return true; } - if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */ ) { + if (token() === 23 /* OpenBracketToken */ || token() === 19 /* OpenBraceToken */ ) { const previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); return previousErrorCount === parseDiagnostics.length; @@ -32510,12 +32777,12 @@ ${lanes.join("\n")} } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */ ) return true; + if (token() === 22 /* CloseParenToken */ || token() === 26 /* DotDotDotToken */ ) return true; if (skipParameterStart()) { - if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 57 /* QuestionToken */ || token() === 63 /* EqualsToken */ ) return true; - if (token() === 21 /* CloseParenToken */ ) { + if (token() === 59 /* ColonToken */ || token() === 28 /* CommaToken */ || token() === 58 /* QuestionToken */ || token() === 64 /* EqualsToken */ ) return true; + if (token() === 22 /* CloseParenToken */ ) { nextToken(); - if (token() === 38 /* EqualsGreaterThanToken */ ) return true; + if (token() === 39 /* EqualsGreaterThanToken */ ) return true; } } return false; @@ -32529,59 +32796,59 @@ ${lanes.join("\n")} } function parseTypePredicatePrefix() { const id = parseIdentifier(); - if (token() === 140 /* IsKeyword */ && !scanner2.hasPrecedingLineBreak()) { + if (token() === 142 /* IsKeyword */ && !scanner2.hasPrecedingLineBreak()) { nextToken(); return id; } } function parseAssertsTypePredicate() { const pos = getNodePos(); - const assertsModifier = parseExpectedToken(129 /* AssertsKeyword */ ); - const parameterName = token() === 108 /* ThisKeyword */ ? parseThisTypeNode() : parseIdentifier(); - const type = parseOptional(140 /* IsKeyword */ ) ? parseType() : void 0; + const assertsModifier = parseExpectedToken(131 /* AssertsKeyword */ ); + const parameterName = token() === 110 /* ThisKeyword */ ? parseThisTypeNode() : parseIdentifier(); + const type = parseOptional(142 /* IsKeyword */ ) ? parseType() : void 0; return finishNode(factory2.createTypePredicateNode(assertsModifier, parameterName, type), pos); } function parseType() { - if (contextFlags & 40960 /* TypeExcludesFlags */ ) return doOutsideOfContext(40960 /* TypeExcludesFlags */ , parseType); + if (contextFlags & 81920 /* TypeExcludesFlags */ ) return doOutsideOfContext(81920 /* TypeExcludesFlags */ , parseType); if (isStartOfFunctionTypeOrConstructorType()) return parseFunctionOrConstructorType(); const pos = getNodePos(); const type = parseUnionTypeOrHigher(); - if (!inDisallowConditionalTypesContext() && !scanner2.hasPrecedingLineBreak() && parseOptional(94 /* ExtendsKeyword */ )) { + if (!inDisallowConditionalTypesContext() && !scanner2.hasPrecedingLineBreak() && parseOptional(96 /* ExtendsKeyword */ )) { const extendsType = disallowConditionalTypesAnd(parseType); - parseExpected(57 /* QuestionToken */ ); + parseExpected(58 /* QuestionToken */ ); const trueType = allowConditionalTypesAnd(parseType); - parseExpected(58 /* ColonToken */ ); + parseExpected(59 /* ColonToken */ ); const falseType = allowConditionalTypesAnd(parseType); return finishNode(factory2.createConditionalTypeNode(type, extendsType, trueType, falseType), pos); } return type; } function parseTypeAnnotation() { - return parseOptional(58 /* ColonToken */ ) ? parseType() : void 0; + return parseOptional(59 /* ColonToken */ ) ? parseType() : void 0; } function isStartOfLeftHandSideExpression() { switch(token()){ - case 108 /* ThisKeyword */ : - case 106 /* SuperKeyword */ : - case 104 /* NullKeyword */ : - case 110 /* TrueKeyword */ : - case 95 /* FalseKeyword */ : - case 8 /* NumericLiteral */ : - case 9 /* BigIntLiteral */ : - case 10 /* StringLiteral */ : - case 14 /* NoSubstitutionTemplateLiteral */ : - case 15 /* TemplateHead */ : - case 20 /* OpenParenToken */ : - case 22 /* OpenBracketToken */ : - case 18 /* OpenBraceToken */ : - case 98 /* FunctionKeyword */ : - case 84 /* ClassKeyword */ : - case 103 /* NewKeyword */ : - case 43 /* SlashToken */ : - case 68 /* SlashEqualsToken */ : - case 79 /* Identifier */ : + case 110 /* ThisKeyword */ : + case 108 /* SuperKeyword */ : + case 106 /* NullKeyword */ : + case 112 /* TrueKeyword */ : + case 97 /* FalseKeyword */ : + case 9 /* NumericLiteral */ : + case 10 /* BigIntLiteral */ : + case 11 /* StringLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + case 16 /* TemplateHead */ : + case 21 /* OpenParenToken */ : + case 23 /* OpenBracketToken */ : + case 19 /* OpenBraceToken */ : + case 100 /* FunctionKeyword */ : + case 86 /* ClassKeyword */ : + case 105 /* NewKeyword */ : + case 44 /* SlashToken */ : + case 69 /* SlashEqualsToken */ : + case 80 /* Identifier */ : return true; - case 100 /* ImportKeyword */ : + case 102 /* ImportKeyword */ : return lookAhead(nextTokenIsOpenParenOrLessThanOrDot); default: return isIdentifier2(); @@ -32590,20 +32857,20 @@ ${lanes.join("\n")} function isStartOfExpression() { if (isStartOfLeftHandSideExpression()) return true; switch(token()){ - case 39 /* PlusToken */ : - case 40 /* MinusToken */ : - case 54 /* TildeToken */ : - case 53 /* ExclamationToken */ : - case 89 /* DeleteKeyword */ : - case 112 /* TypeOfKeyword */ : - case 114 /* VoidKeyword */ : - case 45 /* PlusPlusToken */ : - case 46 /* MinusMinusToken */ : - case 29 /* LessThanToken */ : - case 133 /* AwaitKeyword */ : - case 125 /* YieldKeyword */ : - case 80 /* PrivateIdentifier */ : - case 59 /* AtToken */ : + case 40 /* PlusToken */ : + case 41 /* MinusToken */ : + case 55 /* TildeToken */ : + case 54 /* ExclamationToken */ : + case 91 /* DeleteKeyword */ : + case 114 /* TypeOfKeyword */ : + case 116 /* VoidKeyword */ : + case 46 /* PlusPlusToken */ : + case 47 /* MinusMinusToken */ : + case 30 /* LessThanToken */ : + case 135 /* AwaitKeyword */ : + case 127 /* YieldKeyword */ : + case 81 /* PrivateIdentifier */ : + case 60 /* AtToken */ : return true; default: if (isBinaryOperator2()) return true; @@ -32611,7 +32878,7 @@ ${lanes.join("\n")} } } function isStartOfExpressionStatement() { - return token() !== 18 /* OpenBraceToken */ && token() !== 98 /* FunctionKeyword */ && token() !== 84 /* ClassKeyword */ && token() !== 59 /* AtToken */ && isStartOfExpression(); + return token() !== 19 /* OpenBraceToken */ && token() !== 100 /* FunctionKeyword */ && token() !== 86 /* ClassKeyword */ && token() !== 60 /* AtToken */ && isStartOfExpression(); } function parseExpression() { const saveDecoratorContext = inDecoratorContext(); @@ -32619,25 +32886,26 @@ ${lanes.join("\n")} const pos = getNodePos(); let expr = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); let operatorToken; - while(operatorToken = parseOptionalToken(27 /* CommaToken */ ))expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true), pos); + while(operatorToken = parseOptionalToken(28 /* CommaToken */ ))expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true), pos); if (saveDecoratorContext) setDecoratorContext(/*val*/ true); return expr; } function parseInitializer() { - return parseOptional(63 /* EqualsToken */ ) ? parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true) : void 0; + return parseOptional(64 /* EqualsToken */ ) ? parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true) : void 0; } function parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) { if (isYieldExpression2()) return parseYieldExpression(); const arrowExpression = tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) || tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction); if (arrowExpression) return arrowExpression; const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); const expr = parseBinaryExpressionOrHigher(0 /* Lowest */ ); - if (expr.kind === 79 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */ ) return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, /*asyncModifier*/ void 0); + if (expr.kind === 80 /* Identifier */ && token() === 39 /* EqualsGreaterThanToken */ ) return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, hasJSDoc, /*asyncModifier*/ void 0); if (isLeftHandSideExpression(expr) && isAssignmentOperator(reScanGreaterToken())) return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction), pos); return parseConditionalExpressionRest(expr, pos, allowReturnTypeInArrowFunction); } function isYieldExpression2() { - if (token() === 125 /* YieldKeyword */ ) { + if (token() === 127 /* YieldKeyword */ ) { if (inYieldContext()) return true; return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); } @@ -32650,20 +32918,20 @@ ${lanes.join("\n")} function parseYieldExpression() { const pos = getNodePos(); nextToken(); - if (!scanner2.hasPrecedingLineBreak() && (token() === 41 /* AsteriskToken */ || isStartOfExpression())) return finishNode(factory2.createYieldExpression(parseOptionalToken(41 /* AsteriskToken */ ), parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true)), pos); + if (!scanner2.hasPrecedingLineBreak() && (token() === 42 /* AsteriskToken */ || isStartOfExpression())) return finishNode(factory2.createYieldExpression(parseOptionalToken(42 /* AsteriskToken */ ), parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true)), pos); else return finishNode(factory2.createYieldExpression(/*asteriskToken*/ void 0, /*expression*/ void 0), pos); } - function parseSimpleArrowFunctionExpression(pos, identifier, allowReturnTypeInArrowFunction, asyncModifier) { - Debug.assert(token() === 38 /* EqualsGreaterThanToken */ , "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + function parseSimpleArrowFunctionExpression(pos, identifier, allowReturnTypeInArrowFunction, hasJSDoc, asyncModifier) { + Debug.assert(token() === 39 /* EqualsGreaterThanToken */ , "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); const parameter = factory2.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, identifier, /*questionToken*/ void 0, /*type*/ void 0, /*initializer*/ void 0); finishNode(parameter, identifier.pos); const parameters = createNodeArray([ parameter ], parameter.pos, parameter.end); - const equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */ ); + const equalsGreaterThanToken = parseExpectedToken(39 /* EqualsGreaterThanToken */ ); const body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier, allowReturnTypeInArrowFunction); const node = factory2.createArrowFunction(asyncModifier, /*typeParameters*/ void 0, parameters, /*type*/ void 0, equalsGreaterThanToken, body); - return addJSDocComment(finishNode(node, pos)); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { const triState = isParenthesizedArrowFunctionExpression(); @@ -32671,68 +32939,68 @@ ${lanes.join("\n")} return triState === 1 /* True */ ? parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ true, /*allowReturnTypeInArrowFunction*/ true) : tryParse(()=>parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction)); } function isParenthesizedArrowFunctionExpression() { - if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */ || token() === 132 /* AsyncKeyword */ ) return lookAhead(isParenthesizedArrowFunctionExpressionWorker); - if (token() === 38 /* EqualsGreaterThanToken */ ) return 1 /* True */ ; + if (token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */ || token() === 134 /* AsyncKeyword */ ) return lookAhead(isParenthesizedArrowFunctionExpressionWorker); + if (token() === 39 /* EqualsGreaterThanToken */ ) return 1 /* True */ ; return 0 /* False */ ; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 132 /* AsyncKeyword */ ) { + if (token() === 134 /* AsyncKeyword */ ) { nextToken(); if (scanner2.hasPrecedingLineBreak()) return 0 /* False */ ; - if (token() !== 20 /* OpenParenToken */ && token() !== 29 /* LessThanToken */ ) return 0 /* False */ ; + if (token() !== 21 /* OpenParenToken */ && token() !== 30 /* LessThanToken */ ) return 0 /* False */ ; } const first2 = token(); const second = nextToken(); - if (first2 === 20 /* OpenParenToken */ ) { - if (second === 21 /* CloseParenToken */ ) { + if (first2 === 21 /* OpenParenToken */ ) { + if (second === 22 /* CloseParenToken */ ) { const third = nextToken(); switch(third){ - case 38 /* EqualsGreaterThanToken */ : - case 58 /* ColonToken */ : - case 18 /* OpenBraceToken */ : + case 39 /* EqualsGreaterThanToken */ : + case 59 /* ColonToken */ : + case 19 /* OpenBraceToken */ : return 1 /* True */ ; default: return 0 /* False */ ; } } - if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */ ) return 2 /* Unknown */ ; - if (second === 25 /* DotDotDotToken */ ) return 1 /* True */ ; - if (isModifierKind(second) && second !== 132 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { - if (nextToken() === 128 /* AsKeyword */ ) return 0 /* False */ ; + if (second === 23 /* OpenBracketToken */ || second === 19 /* OpenBraceToken */ ) return 2 /* Unknown */ ; + if (second === 26 /* DotDotDotToken */ ) return 1 /* True */ ; + if (isModifierKind(second) && second !== 134 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { + if (nextToken() === 130 /* AsKeyword */ ) return 0 /* False */ ; return 1 /* True */ ; } - if (!isIdentifier2() && second !== 108 /* ThisKeyword */ ) return 0 /* False */ ; + if (!isIdentifier2() && second !== 110 /* ThisKeyword */ ) return 0 /* False */ ; switch(nextToken()){ - case 58 /* ColonToken */ : + case 59 /* ColonToken */ : return 1 /* True */ ; - case 57 /* QuestionToken */ : + case 58 /* QuestionToken */ : nextToken(); - if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 63 /* EqualsToken */ || token() === 21 /* CloseParenToken */ ) return 1 /* True */ ; + if (token() === 59 /* ColonToken */ || token() === 28 /* CommaToken */ || token() === 64 /* EqualsToken */ || token() === 22 /* CloseParenToken */ ) return 1 /* True */ ; return 0 /* False */ ; - case 27 /* CommaToken */ : - case 63 /* EqualsToken */ : - case 21 /* CloseParenToken */ : + case 28 /* CommaToken */ : + case 64 /* EqualsToken */ : + case 22 /* CloseParenToken */ : return 2 /* Unknown */ ; } return 0 /* False */ ; } else { - Debug.assert(first2 === 29 /* LessThanToken */ ); - if (!isIdentifier2() && token() !== 85 /* ConstKeyword */ ) return 0 /* False */ ; + Debug.assert(first2 === 30 /* LessThanToken */ ); + if (!isIdentifier2() && token() !== 87 /* ConstKeyword */ ) return 0 /* False */ ; if (languageVariant === 1 /* JSX */ ) { const isArrowFunctionInJsx = lookAhead(()=>{ - parseOptional(85 /* ConstKeyword */ ); + parseOptional(87 /* ConstKeyword */ ); const third = nextToken(); - if (third === 94 /* ExtendsKeyword */ ) { + if (third === 96 /* ExtendsKeyword */ ) { const fourth = nextToken(); switch(fourth){ - case 63 /* EqualsToken */ : - case 31 /* GreaterThanToken */ : - case 43 /* SlashToken */ : + case 64 /* EqualsToken */ : + case 32 /* GreaterThanToken */ : + case 44 /* SlashToken */ : return false; default: return true; } - } else if (third === 27 /* CommaToken */ || third === 63 /* EqualsToken */ ) return true; + } else if (third === 28 /* CommaToken */ || third === 64 /* EqualsToken */ ) return true; return false; }); if (isArrowFunctionInJsx) return 1 /* True */ ; @@ -32742,29 +33010,30 @@ ${lanes.join("\n")} } } function parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { - const tokenPos = scanner2.getTokenPos(); + const tokenPos = scanner2.getTokenStart(); if (notParenthesizedArrow == null ? void 0 : notParenthesizedArrow.has(tokenPos)) return void 0; const result = parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ false, allowReturnTypeInArrowFunction); if (!result) (notParenthesizedArrow || (notParenthesizedArrow = /* @__PURE__ */ new Set())).add(tokenPos); return result; } function tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction) { - if (token() === 132 /* AsyncKeyword */ ) { + if (token() === 134 /* AsyncKeyword */ ) { if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */ ) { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); const asyncModifier = parseModifiersForArrowFunction(); const expr = parseBinaryExpressionOrHigher(0 /* Lowest */ ); - return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, asyncModifier); + return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, hasJSDoc, asyncModifier); } } return void 0; } function isUnParenthesizedAsyncArrowFunctionWorker() { - if (token() === 132 /* AsyncKeyword */ ) { + if (token() === 134 /* AsyncKeyword */ ) { nextToken(); - if (scanner2.hasPrecedingLineBreak() || token() === 38 /* EqualsGreaterThanToken */ ) return 0 /* False */ ; + if (scanner2.hasPrecedingLineBreak() || token() === 39 /* EqualsGreaterThanToken */ ) return 0 /* False */ ; const expr = parseBinaryExpressionOrHigher(0 /* Lowest */ ); - if (!scanner2.hasPrecedingLineBreak() && expr.kind === 79 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */ ) return 1 /* True */ ; + if (!scanner2.hasPrecedingLineBreak() && expr.kind === 80 /* Identifier */ && token() === 39 /* EqualsGreaterThanToken */ ) return 1 /* True */ ; } return 0 /* False */ ; } @@ -32775,7 +33044,7 @@ ${lanes.join("\n")} const isAsync = some(modifiers, isAsyncModifier) ? 2 /* Await */ : 0 /* None */ ; const typeParameters = parseTypeParameters(); let parameters; - if (!parseExpected(20 /* OpenParenToken */ )) { + if (!parseExpected(21 /* OpenParenToken */ )) { if (!allowAmbiguity) return void 0; parameters = createMissingList(); } else { @@ -32784,27 +33053,27 @@ ${lanes.join("\n")} if (!maybeParameters) return void 0; parameters = maybeParameters; } else parameters = parseParametersWorker(isAsync, allowAmbiguity); - if (!parseExpected(21 /* CloseParenToken */ ) && !allowAmbiguity) return void 0; + if (!parseExpected(22 /* CloseParenToken */ ) && !allowAmbiguity) return void 0; } - const hasReturnColon = token() === 58 /* ColonToken */ ; - const type = parseReturnType(58 /* ColonToken */ , /*isType*/ false); + const hasReturnColon = token() === 59 /* ColonToken */ ; + const type = parseReturnType(59 /* ColonToken */ , /*isType*/ false); if (type && !allowAmbiguity && typeHasArrowFunctionBlockingParseError(type)) return void 0; let unwrappedType = type; - while((unwrappedType == null ? void 0 : unwrappedType.kind) === 193 /* ParenthesizedType */ )unwrappedType = unwrappedType.type; + while((unwrappedType == null ? void 0 : unwrappedType.kind) === 196 /* ParenthesizedType */ )unwrappedType = unwrappedType.type; const hasJSDocFunctionType = unwrappedType && isJSDocFunctionType(unwrappedType); - if (!allowAmbiguity && token() !== 38 /* EqualsGreaterThanToken */ && (hasJSDocFunctionType || token() !== 18 /* OpenBraceToken */ )) return void 0; + if (!allowAmbiguity && token() !== 39 /* EqualsGreaterThanToken */ && (hasJSDocFunctionType || token() !== 19 /* OpenBraceToken */ )) return void 0; const lastToken = token(); - const equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */ ); - const body = lastToken === 38 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */ ? parseArrowFunctionExpressionBody(some(modifiers, isAsyncModifier), allowReturnTypeInArrowFunction) : parseIdentifier(); + const equalsGreaterThanToken = parseExpectedToken(39 /* EqualsGreaterThanToken */ ); + const body = lastToken === 39 /* EqualsGreaterThanToken */ || lastToken === 19 /* OpenBraceToken */ ? parseArrowFunctionExpressionBody(some(modifiers, isAsyncModifier), allowReturnTypeInArrowFunction) : parseIdentifier(); if (!allowReturnTypeInArrowFunction && hasReturnColon) { - if (token() !== 58 /* ColonToken */ ) return void 0; + if (token() !== 59 /* ColonToken */ ) return void 0; } const node = factory2.createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseArrowFunctionExpressionBody(isAsync, allowReturnTypeInArrowFunction) { - if (token() === 18 /* OpenBraceToken */ ) return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */ ); - if (token() !== 26 /* SemicolonToken */ && token() !== 98 /* FunctionKeyword */ && token() !== 84 /* ClassKeyword */ && isStartOfStatement() && !isStartOfExpressionStatement()) return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */ )); + if (token() === 19 /* OpenBraceToken */ ) return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */ ); + if (token() !== 27 /* SemicolonToken */ && token() !== 100 /* FunctionKeyword */ && token() !== 86 /* ClassKeyword */ && isStartOfStatement() && !isStartOfExpressionStatement()) return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */ )); const savedTopLevel = topLevel; topLevel = false; const node = isAsync ? doInAwaitContext(()=>parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction)) : doOutsideOfAwaitContext(()=>parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction)); @@ -32812,10 +33081,10 @@ ${lanes.join("\n")} return node; } function parseConditionalExpressionRest(leftOperand, pos, allowReturnTypeInArrowFunction) { - const questionToken = parseOptionalToken(57 /* QuestionToken */ ); + const questionToken = parseOptionalToken(58 /* QuestionToken */ ); if (!questionToken) return leftOperand; let colonToken; - return finishNode(factory2.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, ()=>parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ false)), colonToken = parseExpectedToken(58 /* ColonToken */ ), nodeIsPresent(colonToken) ? parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) : createMissingNode(79 /* Identifier */ , /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, tokenToString(58 /* ColonToken */ ))), pos); + return finishNode(factory2.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, ()=>parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ false)), colonToken = parseExpectedToken(59 /* ColonToken */ ), nodeIsPresent(colonToken) ? parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) : createMissingNode(80 /* Identifier */ , /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, tokenToString(59 /* ColonToken */ ))), pos); } function parseBinaryExpressionOrHigher(precedence) { const pos = getNodePos(); @@ -32823,28 +33092,28 @@ ${lanes.join("\n")} return parseBinaryExpressionRest(precedence, leftOperand, pos); } function isInOrOfKeyword(t) { - return t === 101 /* InKeyword */ || t === 162 /* OfKeyword */ ; + return t === 103 /* InKeyword */ || t === 165 /* OfKeyword */ ; } function parseBinaryExpressionRest(precedence, leftOperand, pos) { while(true){ reScanGreaterToken(); const newPrecedence = getBinaryOperatorPrecedence(token()); - const consumeCurrentOperator = token() === 42 /* AsteriskAsteriskToken */ ? newPrecedence >= precedence : newPrecedence > precedence; + const consumeCurrentOperator = token() === 43 /* AsteriskAsteriskToken */ ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) break; - if (token() === 101 /* InKeyword */ && inDisallowInContext()) break; - if (token() === 128 /* AsKeyword */ || token() === 150 /* SatisfiesKeyword */ ) { + if (token() === 103 /* InKeyword */ && inDisallowInContext()) break; + if (token() === 130 /* AsKeyword */ || token() === 152 /* SatisfiesKeyword */ ) { if (scanner2.hasPrecedingLineBreak()) break; else { const keywordKind = token(); nextToken(); - leftOperand = keywordKind === 150 /* SatisfiesKeyword */ ? makeSatisfiesExpression(leftOperand, parseType()) : makeAsExpression(leftOperand, parseType()); + leftOperand = keywordKind === 152 /* SatisfiesKeyword */ ? makeSatisfiesExpression(leftOperand, parseType()) : makeAsExpression(leftOperand, parseType()); } } else leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence), pos); } return leftOperand; } function isBinaryOperator2() { - if (inDisallowInContext() && token() === 101 /* InKeyword */ ) return false; + if (inDisallowInContext() && token() === 103 /* InKeyword */ ) return false; return getBinaryOperatorPrecedence(token()) > 0; } function makeSatisfiesExpression(left, right) { @@ -32873,7 +33142,7 @@ ${lanes.join("\n")} return finishNode(factory2.createVoidExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos); } function isAwaitExpression2() { - if (token() === 133 /* AwaitKeyword */ ) { + if (token() === 135 /* AwaitKeyword */ ) { if (inAwaitContext()) return true; return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); } @@ -32887,35 +33156,38 @@ ${lanes.join("\n")} if (isUpdateExpression()) { const pos = getNodePos(); const updateExpression = parseUpdateExpression(); - return token() === 42 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(token()), updateExpression, pos) : updateExpression; + return token() === 43 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(token()), updateExpression, pos) : updateExpression; } const unaryOperator = token(); const simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 42 /* AsteriskAsteriskToken */ ) { + if (token() === 43 /* AsteriskAsteriskToken */ ) { const pos = skipTrivia(sourceText, simpleUnaryExpression.pos); - const { end: end } = simpleUnaryExpression; - if (simpleUnaryExpression.kind === 213 /* TypeAssertionExpression */ ) parseErrorAt(pos, end, Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); - else parseErrorAt(pos, end, Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, tokenToString(unaryOperator)); + const { end: end } = simpleUnaryExpression; + if (simpleUnaryExpression.kind === 216 /* TypeAssertionExpression */ ) parseErrorAt(pos, end, Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); + else { + Debug.assert(isKeywordOrPunctuation(unaryOperator)); + parseErrorAt(pos, end, Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, tokenToString(unaryOperator)); + } } return simpleUnaryExpression; } function parseSimpleUnaryExpression() { switch(token()){ - case 39 /* PlusToken */ : - case 40 /* MinusToken */ : - case 54 /* TildeToken */ : - case 53 /* ExclamationToken */ : + case 40 /* PlusToken */ : + case 41 /* MinusToken */ : + case 55 /* TildeToken */ : + case 54 /* ExclamationToken */ : return parsePrefixUnaryExpression(); - case 89 /* DeleteKeyword */ : + case 91 /* DeleteKeyword */ : return parseDeleteExpression(); - case 112 /* TypeOfKeyword */ : + case 114 /* TypeOfKeyword */ : return parseTypeOfExpression(); - case 114 /* VoidKeyword */ : + case 116 /* VoidKeyword */ : return parseVoidExpression(); - case 29 /* LessThanToken */ : + case 30 /* LessThanToken */ : if (languageVariant === 1 /* JSX */ ) return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true, /*topInvalidNodePosition*/ void 0, /*openingTag*/ void 0, /*mustBeUnary*/ true); return parseTypeAssertion(); - case 133 /* AwaitKeyword */ : + case 135 /* AwaitKeyword */ : if (isAwaitExpression2()) return parseAwaitExpression(); default: return parseUpdateExpression(); @@ -32923,29 +33195,29 @@ ${lanes.join("\n")} } function isUpdateExpression() { switch(token()){ - case 39 /* PlusToken */ : - case 40 /* MinusToken */ : - case 54 /* TildeToken */ : - case 53 /* ExclamationToken */ : - case 89 /* DeleteKeyword */ : - case 112 /* TypeOfKeyword */ : - case 114 /* VoidKeyword */ : - case 133 /* AwaitKeyword */ : + case 40 /* PlusToken */ : + case 41 /* MinusToken */ : + case 55 /* TildeToken */ : + case 54 /* ExclamationToken */ : + case 91 /* DeleteKeyword */ : + case 114 /* TypeOfKeyword */ : + case 116 /* VoidKeyword */ : + case 135 /* AwaitKeyword */ : return false; - case 29 /* LessThanToken */ : + case 30 /* LessThanToken */ : if (languageVariant !== 1 /* JSX */ ) return false; default: return true; } } function parseUpdateExpression() { - if (token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */ ) { + if (token() === 46 /* PlusPlusToken */ || token() === 47 /* MinusMinusToken */ ) { const pos = getNodePos(); return finishNode(factory2.createPrefixUnaryExpression(token(), nextTokenAnd(parseLeftHandSideExpressionOrHigher)), pos); - } else if (languageVariant === 1 /* JSX */ && token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); + } else if (languageVariant === 1 /* JSX */ && token() === 30 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); const expression = parseLeftHandSideExpressionOrHigher(); Debug.assert(isLeftHandSideExpression(expression)); - if ((token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */ ) && !scanner2.hasPrecedingLineBreak()) { + if ((token() === 46 /* PlusPlusToken */ || token() === 47 /* MinusMinusToken */ ) && !scanner2.hasPrecedingLineBreak()) { const operator = token(); nextToken(); return finishNode(factory2.createPostfixUnaryExpression(expression, operator), expression.pos); @@ -32955,17 +33227,17 @@ ${lanes.join("\n")} function parseLeftHandSideExpressionOrHigher() { const pos = getNodePos(); let expression; - if (token() === 100 /* ImportKeyword */ ) { + if (token() === 102 /* ImportKeyword */ ) { if (lookAhead(nextTokenIsOpenParenOrLessThan)) { - sourceFlags |= 2097152 /* PossiblyContainsDynamicImport */ ; + sourceFlags |= 4194304 /* PossiblyContainsDynamicImport */ ; expression = parseTokenNode(); } else if (lookAhead(nextTokenIsDot)) { nextToken(); nextToken(); - expression = finishNode(factory2.createMetaProperty(100 /* ImportKeyword */ , parseIdentifierName()), pos); - sourceFlags |= 4194304 /* PossiblyContainsImportMeta */ ; + expression = finishNode(factory2.createMetaProperty(102 /* ImportKeyword */ , parseIdentifierName()), pos); + sourceFlags |= 8388608 /* PossiblyContainsImportMeta */ ; } else expression = parseMemberExpressionOrHigher(); - } else expression = token() === 106 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); + } else expression = token() === 108 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); return parseCallExpressionRest(pos, expression); } function parseMemberExpressionOrHigher() { @@ -32976,7 +33248,7 @@ ${lanes.join("\n")} function parseSuperExpression() { const pos = getNodePos(); let expression = parseTokenNode(); - if (token() === 29 /* LessThanToken */ ) { + if (token() === 30 /* LessThanToken */ ) { const startPos = getNodePos(); const typeArguments = tryParse(parseTypeArgumentsInExpression); if (typeArguments !== void 0) { @@ -32984,19 +33256,19 @@ ${lanes.join("\n")} if (!isTemplateStartOfTaggedTemplate()) expression = factory2.createExpressionWithTypeArguments(expression, typeArguments); } } - if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */ ) return expression; - parseExpectedToken(24 /* DotToken */ , Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + if (token() === 21 /* OpenParenToken */ || token() === 25 /* DotToken */ || token() === 23 /* OpenBracketToken */ ) return expression; + parseExpectedToken(25 /* DotToken */ , Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); return finishNode(factoryCreatePropertyAccessExpression(expression, parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true)), pos); } function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext, topInvalidNodePosition, openingTag, mustBeUnary = false) { const pos = getNodePos(); const opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); let result; - if (opening.kind === 283 /* JsxOpeningElement */ ) { + if (opening.kind === 286 /* JsxOpeningElement */ ) { let children = parseJsxChildren(opening); let closingElement; const lastChild = children[children.length - 1]; - if ((lastChild == null ? void 0 : lastChild.kind) === 281 /* JsxElement */ && !tagNamesAreEquivalent(lastChild.openingElement.tagName, lastChild.closingElement.tagName) && tagNamesAreEquivalent(opening.tagName, lastChild.closingElement.tagName)) { + if ((lastChild == null ? void 0 : lastChild.kind) === 284 /* JsxElement */ && !tagNamesAreEquivalent(lastChild.openingElement.tagName, lastChild.closingElement.tagName) && tagNamesAreEquivalent(opening.tagName, lastChild.closingElement.tagName)) { const end = lastChild.children.end; const newLast = finishNode(factory2.createJsxElement(lastChild.openingElement, lastChild.children, finishNode(factory2.createJsxClosingElement(finishNode(factoryCreateIdentifier(""), end, end)), end, end)), lastChild.openingElement.pos, end); children = createNodeArray([ @@ -33012,16 +33284,16 @@ ${lanes.join("\n")} } } result = finishNode(factory2.createJsxElement(opening, children, closingElement), pos); - } else if (opening.kind === 286 /* JsxOpeningFragment */ ) result = finishNode(factory2.createJsxFragment(opening, parseJsxChildren(opening), parseJsxClosingFragment(inExpressionContext)), pos); + } else if (opening.kind === 289 /* JsxOpeningFragment */ ) result = finishNode(factory2.createJsxFragment(opening, parseJsxChildren(opening), parseJsxClosingFragment(inExpressionContext)), pos); else { - Debug.assert(opening.kind === 282 /* JsxSelfClosingElement */ ); + Debug.assert(opening.kind === 285 /* JsxSelfClosingElement */ ); result = opening; } - if (!mustBeUnary && inExpressionContext && token() === 29 /* LessThanToken */ ) { + if (!mustBeUnary && inExpressionContext && token() === 30 /* LessThanToken */ ) { const topBadPos = typeof topInvalidNodePosition === "undefined" ? result.pos : topInvalidNodePosition; const invalidElement = tryParse(()=>parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true, topBadPos)); if (invalidElement) { - const operatorToken = createMissingNode(27 /* CommaToken */ , /*reportAtCurrentPosition*/ false); + const operatorToken = createMissingNode(28 /* CommaToken */ , /*reportAtCurrentPosition*/ false); setTextRangePosWidth(operatorToken, invalidElement.pos, 0); parseErrorAt(skipTrivia(sourceText, topBadPos), invalidElement.end, Diagnostics.JSX_expressions_must_have_one_parent_element); return finishNode(factory2.createBinaryExpression(result, operatorToken, invalidElement), pos); @@ -33031,7 +33303,7 @@ ${lanes.join("\n")} } function parseJsxText() { const pos = getNodePos(); - const node = factory2.createJsxText(scanner2.getTokenValue(), currentToken === 12 /* JsxTextAllWhiteSpaces */ ); + const node = factory2.createJsxText(scanner2.getTokenValue(), currentToken === 13 /* JsxTextAllWhiteSpaces */ ); currentToken = scanner2.scanJsxToken(); return finishNode(node, pos); } @@ -33041,19 +33313,19 @@ ${lanes.join("\n")} if (isJsxOpeningFragment(openingTag)) parseErrorAtRange(openingTag, Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); else { const tag = openingTag.tagName; - const start = skipTrivia(sourceText, tag.pos); + const start = Math.min(skipTrivia(sourceText, tag.pos), tag.end); parseErrorAt(start, tag.end, Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); } return void 0; - case 30 /* LessThanSlashToken */ : + case 31 /* LessThanSlashToken */ : case 7 /* ConflictMarkerTrivia */ : return void 0; - case 11 /* JsxText */ : - case 12 /* JsxTextAllWhiteSpaces */ : + case 12 /* JsxText */ : + case 13 /* JsxTextAllWhiteSpaces */ : return parseJsxText(); - case 18 /* OpenBraceToken */ : + case 19 /* OpenBraceToken */ : return parseJsxExpression(/*inExpressionContext*/ false); - case 29 /* LessThanToken */ : + case 30 /* LessThanToken */ : return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false, /*topInvalidNodePosition*/ void 0, openingTag); default: return Debug.assertNever(token2); @@ -33068,7 +33340,7 @@ ${lanes.join("\n")} const child = parseJsxChild(openingTag, currentToken = scanner2.reScanJsxToken()); if (!child) break; list.push(child); - if (isJsxOpeningElement(openingTag) && (child == null ? void 0 : child.kind) === 281 /* JsxElement */ && !tagNamesAreEquivalent(child.openingElement.tagName, child.closingElement.tagName) && tagNamesAreEquivalent(openingTag.tagName, child.closingElement.tagName)) break; + if (isJsxOpeningElement(openingTag) && (child == null ? void 0 : child.kind) === 284 /* JsxElement */ && !tagNamesAreEquivalent(child.openingElement.tagName, child.closingElement.tagName) && tagNamesAreEquivalent(openingTag.tagName, child.closingElement.tagName)) break; } parsingContext = saveParsingContext; return createNodeArray(list, listPos); @@ -33079,21 +33351,21 @@ ${lanes.join("\n")} } function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) { const pos = getNodePos(); - parseExpected(29 /* LessThanToken */ ); - if (token() === 31 /* GreaterThanToken */ ) { + parseExpected(30 /* LessThanToken */ ); + if (token() === 32 /* GreaterThanToken */ ) { scanJsxText(); return finishNode(factory2.createJsxOpeningFragment(), pos); } const tagName = parseJsxElementName(); - const typeArguments = (contextFlags & 262144 /* JavaScriptFile */ ) === 0 ? tryParseTypeArguments() : void 0; + const typeArguments = (contextFlags & 524288 /* JavaScriptFile */ ) === 0 ? tryParseTypeArguments() : void 0; const attributes = parseJsxAttributes(); let node; - if (token() === 31 /* GreaterThanToken */ ) { + if (token() === 32 /* GreaterThanToken */ ) { scanJsxText(); node = factory2.createJsxOpeningElement(tagName, typeArguments, attributes); } else { - parseExpected(43 /* SlashToken */ ); - if (parseExpected(31 /* GreaterThanToken */ , /*diagnostic*/ void 0, /*shouldAdvance*/ false)) { + parseExpected(44 /* SlashToken */ ); + if (parseExpected(32 /* GreaterThanToken */ , /*diagnosticMessage*/ void 0, /*shouldAdvance*/ false)) { if (inExpressionContext) nextToken(); else scanJsxText(); } @@ -33103,52 +33375,73 @@ ${lanes.join("\n")} } function parseJsxElementName() { const pos = getNodePos(); - scanJsxIdentifier(); - let expression = token() === 108 /* ThisKeyword */ ? parseTokenNode() : parseIdentifierName(); - while(parseOptional(24 /* DotToken */ ))expression = finishNode(factoryCreatePropertyAccessExpression(expression, parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ false)), pos); + const initialExpression = parseJsxTagName(); + if (isJsxNamespacedName(initialExpression)) return initialExpression; + let expression = initialExpression; + while(parseOptional(25 /* DotToken */ ))expression = finishNode(factoryCreatePropertyAccessExpression(expression, parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ false)), pos); return expression; } + function parseJsxTagName() { + const pos = getNodePos(); + scanJsxIdentifier(); + const isThis2 = token() === 110 /* ThisKeyword */ ; + const tagName = parseIdentifierName(); + if (parseOptional(59 /* ColonToken */ )) { + scanJsxIdentifier(); + return finishNode(factory2.createJsxNamespacedName(tagName, parseIdentifierName()), pos); + } + return isThis2 ? finishNode(factory2.createToken(110 /* ThisKeyword */ ), pos) : tagName; + } function parseJsxExpression(inExpressionContext) { const pos = getNodePos(); - if (!parseExpected(18 /* OpenBraceToken */ )) return void 0; + if (!parseExpected(19 /* OpenBraceToken */ )) return void 0; let dotDotDotToken; let expression; - if (token() !== 19 /* CloseBraceToken */ ) { - dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */ ); + if (token() !== 20 /* CloseBraceToken */ ) { + dotDotDotToken = parseOptionalToken(26 /* DotDotDotToken */ ); expression = parseExpression(); } - if (inExpressionContext) parseExpected(19 /* CloseBraceToken */ ); - else if (parseExpected(19 /* CloseBraceToken */ , /*message*/ void 0, /*shouldAdvance*/ false)) scanJsxText(); + if (inExpressionContext) parseExpected(20 /* CloseBraceToken */ ); + else if (parseExpected(20 /* CloseBraceToken */ , /*diagnosticMessage*/ void 0, /*shouldAdvance*/ false)) scanJsxText(); return finishNode(factory2.createJsxExpression(dotDotDotToken, expression), pos); } function parseJsxAttribute() { - if (token() === 18 /* OpenBraceToken */ ) return parseJsxSpreadAttribute(); - scanJsxIdentifier(); + if (token() === 19 /* OpenBraceToken */ ) return parseJsxSpreadAttribute(); const pos = getNodePos(); - return finishNode(factory2.createJsxAttribute(parseIdentifierName(), parseJsxAttributeValue()), pos); + return finishNode(factory2.createJsxAttribute(parseJsxAttributeName(), parseJsxAttributeValue()), pos); } function parseJsxAttributeValue() { - if (token() === 63 /* EqualsToken */ ) { - if (scanJsxAttributeValue() === 10 /* StringLiteral */ ) return parseLiteralNode(); - if (token() === 18 /* OpenBraceToken */ ) return parseJsxExpression(/*inExpressionContext*/ true); - if (token() === 29 /* LessThanToken */ ) return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); + if (token() === 64 /* EqualsToken */ ) { + if (scanJsxAttributeValue() === 11 /* StringLiteral */ ) return parseLiteralNode(); + if (token() === 19 /* OpenBraceToken */ ) return parseJsxExpression(/*inExpressionContext*/ true); + if (token() === 30 /* LessThanToken */ ) return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); parseErrorAtCurrentToken(Diagnostics.or_JSX_element_expected); } return void 0; } + function parseJsxAttributeName() { + const pos = getNodePos(); + scanJsxIdentifier(); + const attrName = parseIdentifierName(); + if (parseOptional(59 /* ColonToken */ )) { + scanJsxIdentifier(); + return finishNode(factory2.createJsxNamespacedName(attrName, parseIdentifierName()), pos); + } + return attrName; + } function parseJsxSpreadAttribute() { const pos = getNodePos(); - parseExpected(18 /* OpenBraceToken */ ); - parseExpected(25 /* DotDotDotToken */ ); + parseExpected(19 /* OpenBraceToken */ ); + parseExpected(26 /* DotDotDotToken */ ); const expression = parseExpression(); - parseExpected(19 /* CloseBraceToken */ ); + parseExpected(20 /* CloseBraceToken */ ); return finishNode(factory2.createJsxSpreadAttribute(expression), pos); } function parseJsxClosingElement(open, inExpressionContext) { const pos = getNodePos(); - parseExpected(30 /* LessThanSlashToken */ ); + parseExpected(31 /* LessThanSlashToken */ ); const tagName = parseJsxElementName(); - if (parseExpected(31 /* GreaterThanToken */ , /*diagnostic*/ void 0, /*shouldAdvance*/ false)) { + if (parseExpected(32 /* GreaterThanToken */ , /*diagnosticMessage*/ void 0, /*shouldAdvance*/ false)) { if (inExpressionContext || !tagNamesAreEquivalent(open.tagName, tagName)) nextToken(); else scanJsxText(); } @@ -33156,8 +33449,8 @@ ${lanes.join("\n")} } function parseJsxClosingFragment(inExpressionContext) { const pos = getNodePos(); - parseExpected(30 /* LessThanSlashToken */ ); - if (parseExpected(31 /* GreaterThanToken */ , Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment, /*shouldAdvance*/ false)) { + parseExpected(31 /* LessThanSlashToken */ ); + if (parseExpected(32 /* GreaterThanToken */ , Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment, /*shouldAdvance*/ false)) { if (inExpressionContext) nextToken(); else scanJsxText(); } @@ -33166,27 +33459,27 @@ ${lanes.join("\n")} function parseTypeAssertion() { Debug.assert(languageVariant !== 1 /* JSX */ , "Type assertions should never be parsed in JSX; they should be parsed as comparisons or JSX elements/fragments."); const pos = getNodePos(); - parseExpected(29 /* LessThanToken */ ); + parseExpected(30 /* LessThanToken */ ); const type = parseType(); - parseExpected(31 /* GreaterThanToken */ ); + parseExpected(32 /* GreaterThanToken */ ); const expression = parseSimpleUnaryExpression(); return finishNode(factory2.createTypeAssertion(type, expression), pos); } function nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate() { nextToken(); - return tokenIsIdentifierOrKeyword(token()) || token() === 22 /* OpenBracketToken */ || isTemplateStartOfTaggedTemplate(); + return tokenIsIdentifierOrKeyword(token()) || token() === 23 /* OpenBracketToken */ || isTemplateStartOfTaggedTemplate(); } function isStartOfOptionalPropertyOrElementAccessChain() { - return token() === 28 /* QuestionDotToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate); + return token() === 29 /* QuestionDotToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate); } function tryReparseOptionalChain(node) { - if (node.flags & 32 /* OptionalChain */ ) return true; + if (node.flags & 64 /* OptionalChain */ ) return true; if (isNonNullExpression(node)) { let expr = node.expression; - while(isNonNullExpression(expr) && !(expr.flags & 32 /* OptionalChain */ ))expr = expr.expression; - if (expr.flags & 32 /* OptionalChain */ ) { + while(isNonNullExpression(expr) && !(expr.flags & 64 /* OptionalChain */ ))expr = expr.expression; + if (expr.flags & 64 /* OptionalChain */ ) { while(isNonNullExpression(node)){ - node.flags |= 32 /* OptionalChain */ ; + node.flags |= 64 /* OptionalChain */ ; node = node.expression; } return true; @@ -33208,13 +33501,13 @@ ${lanes.join("\n")} } function parseElementAccessExpressionRest(pos, expression, questionDotToken) { let argumentExpression; - if (token() === 23 /* CloseBracketToken */ ) argumentExpression = createMissingNode(79 /* Identifier */ , /*reportAtCurrentPosition*/ true, Diagnostics.An_element_access_expression_should_take_an_argument); + if (token() === 24 /* CloseBracketToken */ ) argumentExpression = createMissingNode(80 /* Identifier */ , /*reportAtCurrentPosition*/ true, Diagnostics.An_element_access_expression_should_take_an_argument); else { const argument = allowInAnd(parseExpression); if (isStringOrNumericLiteralLike(argument)) argument.text = internIdentifier(argument.text); argumentExpression = argument; } - parseExpected(23 /* CloseBracketToken */ ); + parseExpected(24 /* CloseBracketToken */ ); const indexedAccess = questionDotToken || tryReparseOptionalChain(expression) ? factoryCreateElementAccessChain(expression, questionDotToken, argumentExpression) : factoryCreateElementAccessExpression(expression, argumentExpression); return finishNode(indexedAccess, pos); } @@ -33223,23 +33516,23 @@ ${lanes.join("\n")} let questionDotToken; let isPropertyAccess = false; if (allowOptionalChain && isStartOfOptionalPropertyOrElementAccessChain()) { - questionDotToken = parseExpectedToken(28 /* QuestionDotToken */ ); + questionDotToken = parseExpectedToken(29 /* QuestionDotToken */ ); isPropertyAccess = tokenIsIdentifierOrKeyword(token()); - } else isPropertyAccess = parseOptional(24 /* DotToken */ ); + } else isPropertyAccess = parseOptional(25 /* DotToken */ ); if (isPropertyAccess) { expression = parsePropertyAccessExpressionRest(pos, expression, questionDotToken); continue; } - if ((questionDotToken || !inDecoratorContext()) && parseOptional(22 /* OpenBracketToken */ )) { + if ((questionDotToken || !inDecoratorContext()) && parseOptional(23 /* OpenBracketToken */ )) { expression = parseElementAccessExpressionRest(pos, expression, questionDotToken); continue; } if (isTemplateStartOfTaggedTemplate()) { - expression = !questionDotToken && expression.kind === 230 /* ExpressionWithTypeArguments */ ? parseTaggedTemplateRest(pos, expression.expression, questionDotToken, expression.typeArguments) : parseTaggedTemplateRest(pos, expression, questionDotToken, /*typeArguments*/ void 0); + expression = !questionDotToken && expression.kind === 233 /* ExpressionWithTypeArguments */ ? parseTaggedTemplateRest(pos, expression.expression, questionDotToken, expression.typeArguments) : parseTaggedTemplateRest(pos, expression, questionDotToken, /*typeArguments*/ void 0); continue; } if (!questionDotToken) { - if (token() === 53 /* ExclamationToken */ && !scanner2.hasPrecedingLineBreak()) { + if (token() === 54 /* ExclamationToken */ && !scanner2.hasPrecedingLineBreak()) { nextToken(); expression = finishNode(factory2.createNonNullExpression(expression), pos); continue; @@ -33254,11 +33547,11 @@ ${lanes.join("\n")} } } function isTemplateStartOfTaggedTemplate() { - return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */ ; + return token() === 15 /* NoSubstitutionTemplateLiteral */ || token() === 16 /* TemplateHead */ ; } function parseTaggedTemplateRest(pos, tag, questionDotToken, typeArguments) { - const tagExpression = factory2.createTaggedTemplateExpression(tag, typeArguments, token() === 14 /* NoSubstitutionTemplateLiteral */ ? (reScanTemplateHeadOrNoSubstitutionTemplate(), parseLiteralNode()) : parseTemplateExpression(/*isTaggedTemplate*/ true)); - if (questionDotToken || tag.flags & 32 /* OptionalChain */ ) tagExpression.flags |= 32 /* OptionalChain */ ; + const tagExpression = factory2.createTaggedTemplateExpression(tag, typeArguments, token() === 15 /* NoSubstitutionTemplateLiteral */ ? (reScanTemplateToken(/*isTaggedTemplate*/ true), parseLiteralNode()) : parseTemplateExpression(/*isTaggedTemplate*/ true)); + if (questionDotToken || tag.flags & 64 /* OptionalChain */ ) tagExpression.flags |= 64 /* OptionalChain */ ; tagExpression.questionDotToken = questionDotToken; return finishNode(tagExpression, pos); } @@ -33266,7 +33559,7 @@ ${lanes.join("\n")} while(true){ expression = parseMemberExpressionRest(pos, expression, /*allowOptionalChain*/ true); let typeArguments; - const questionDotToken = parseOptionalToken(28 /* QuestionDotToken */ ); + const questionDotToken = parseOptionalToken(29 /* QuestionDotToken */ ); if (questionDotToken) { typeArguments = tryParse(parseTypeArgumentsInExpression); if (isTemplateStartOfTaggedTemplate()) { @@ -33274,8 +33567,8 @@ ${lanes.join("\n")} continue; } } - if (typeArguments || token() === 20 /* OpenParenToken */ ) { - if (!questionDotToken && expression.kind === 230 /* ExpressionWithTypeArguments */ ) { + if (typeArguments || token() === 21 /* OpenParenToken */ ) { + if (!questionDotToken && expression.kind === 233 /* ExpressionWithTypeArguments */ ) { typeArguments = expression.typeArguments; expression = expression.expression; } @@ -33285,7 +33578,7 @@ ${lanes.join("\n")} continue; } if (questionDotToken) { - const name = createMissingNode(79 /* Identifier */ , /*reportAtCurrentPosition*/ false, Diagnostics.Identifier_expected); + const name = createMissingNode(80 /* Identifier */ , /*reportAtCurrentPosition*/ false, Diagnostics.Identifier_expected); expression = finishNode(factoryCreatePropertyAccessChain(expression, questionDotToken, name), pos); } break; @@ -33293,71 +33586,72 @@ ${lanes.join("\n")} return expression; } function parseArgumentList() { - parseExpected(20 /* OpenParenToken */ ); + parseExpected(21 /* OpenParenToken */ ); const result = parseDelimitedList(11 /* ArgumentExpressions */ , parseArgumentExpression); - parseExpected(21 /* CloseParenToken */ ); + parseExpected(22 /* CloseParenToken */ ); return result; } function parseTypeArgumentsInExpression() { - if ((contextFlags & 262144 /* JavaScriptFile */ ) !== 0) return void 0; - if (reScanLessThanToken() !== 29 /* LessThanToken */ ) return void 0; + if ((contextFlags & 524288 /* JavaScriptFile */ ) !== 0) return void 0; + if (reScanLessThanToken() !== 30 /* LessThanToken */ ) return void 0; nextToken(); const typeArguments = parseDelimitedList(20 /* TypeArguments */ , parseType); - if (reScanGreaterToken() !== 31 /* GreaterThanToken */ ) return void 0; + if (reScanGreaterToken() !== 32 /* GreaterThanToken */ ) return void 0; nextToken(); return typeArguments && canFollowTypeArgumentsInExpression() ? typeArguments : void 0; } function canFollowTypeArgumentsInExpression() { switch(token()){ - case 20 /* OpenParenToken */ : - case 14 /* NoSubstitutionTemplateLiteral */ : - case 15 /* TemplateHead */ : + case 21 /* OpenParenToken */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + case 16 /* TemplateHead */ : return true; - case 29 /* LessThanToken */ : - case 31 /* GreaterThanToken */ : - case 39 /* PlusToken */ : - case 40 /* MinusToken */ : + case 30 /* LessThanToken */ : + case 32 /* GreaterThanToken */ : + case 40 /* PlusToken */ : + case 41 /* MinusToken */ : return false; } return scanner2.hasPrecedingLineBreak() || isBinaryOperator2() || !isStartOfExpression(); } function parsePrimaryExpression() { switch(token()){ - case 8 /* NumericLiteral */ : - case 9 /* BigIntLiteral */ : - case 10 /* StringLiteral */ : - case 14 /* NoSubstitutionTemplateLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + if (scanner2.getTokenFlags() & 26656 /* IsInvalid */ ) reScanTemplateToken(/*isTaggedTemplate*/ false); + case 9 /* NumericLiteral */ : + case 10 /* BigIntLiteral */ : + case 11 /* StringLiteral */ : return parseLiteralNode(); - case 108 /* ThisKeyword */ : - case 106 /* SuperKeyword */ : - case 104 /* NullKeyword */ : - case 110 /* TrueKeyword */ : - case 95 /* FalseKeyword */ : + case 110 /* ThisKeyword */ : + case 108 /* SuperKeyword */ : + case 106 /* NullKeyword */ : + case 112 /* TrueKeyword */ : + case 97 /* FalseKeyword */ : return parseTokenNode(); - case 20 /* OpenParenToken */ : + case 21 /* OpenParenToken */ : return parseParenthesizedExpression(); - case 22 /* OpenBracketToken */ : + case 23 /* OpenBracketToken */ : return parseArrayLiteralExpression(); - case 18 /* OpenBraceToken */ : + case 19 /* OpenBraceToken */ : return parseObjectLiteralExpression(); - case 132 /* AsyncKeyword */ : + case 134 /* AsyncKeyword */ : if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) break; return parseFunctionExpression(); - case 59 /* AtToken */ : + case 60 /* AtToken */ : return parseDecoratedExpression(); - case 84 /* ClassKeyword */ : + case 86 /* ClassKeyword */ : return parseClassExpression(); - case 98 /* FunctionKeyword */ : + case 100 /* FunctionKeyword */ : return parseFunctionExpression(); - case 103 /* NewKeyword */ : + case 105 /* NewKeyword */ : return parseNewExpressionOrNewDotTarget(); - case 43 /* SlashToken */ : - case 68 /* SlashEqualsToken */ : - if (reScanSlashToken() === 13 /* RegularExpressionLiteral */ ) return parseLiteralNode(); + case 44 /* SlashToken */ : + case 69 /* SlashEqualsToken */ : + if (reScanSlashToken() === 14 /* RegularExpressionLiteral */ ) return parseLiteralNode(); break; - case 15 /* TemplateHead */ : - return parseTemplateExpression(/* isTaggedTemplate */ false); - case 80 /* PrivateIdentifier */ : + case 16 /* TemplateHead */ : + return parseTemplateExpression(/*isTaggedTemplate*/ false); + case 81 /* PrivateIdentifier */ : return parsePrivateIdentifier(); } return parseIdentifier(Diagnostics.Expression_expected); @@ -33365,57 +33659,57 @@ ${lanes.join("\n")} function parseParenthesizedExpression() { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - parseExpected(20 /* OpenParenToken */ ); + parseExpected(21 /* OpenParenToken */ ); const expression = allowInAnd(parseExpression); - parseExpected(21 /* CloseParenToken */ ); + parseExpected(22 /* CloseParenToken */ ); return withJSDoc(finishNode(factoryCreateParenthesizedExpression(expression), pos), hasJSDoc); } function parseSpreadElement() { const pos = getNodePos(); - parseExpected(25 /* DotDotDotToken */ ); + parseExpected(26 /* DotDotDotToken */ ); const expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); return finishNode(factory2.createSpreadElement(expression), pos); } function parseArgumentOrArrayLiteralElement() { - return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() : token() === 27 /* CommaToken */ ? finishNode(factory2.createOmittedExpression(), getNodePos()) : parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); + return token() === 26 /* DotDotDotToken */ ? parseSpreadElement() : token() === 28 /* CommaToken */ ? finishNode(factory2.createOmittedExpression(), getNodePos()) : parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { const pos = getNodePos(); - const openBracketPosition = scanner2.getTokenPos(); - const openBracketParsed = parseExpected(22 /* OpenBracketToken */ ); + const openBracketPosition = scanner2.getTokenStart(); + const openBracketParsed = parseExpected(23 /* OpenBracketToken */ ); const multiLine = scanner2.hasPrecedingLineBreak(); const elements = parseDelimitedList(15 /* ArrayLiteralMembers */ , parseArgumentOrArrayLiteralElement); - parseExpectedMatchingBrackets(22 /* OpenBracketToken */ , 23 /* CloseBracketToken */ , openBracketParsed, openBracketPosition); + parseExpectedMatchingBrackets(23 /* OpenBracketToken */ , 24 /* CloseBracketToken */ , openBracketParsed, openBracketPosition); return finishNode(factoryCreateArrayLiteralExpression(elements, multiLine), pos); } function parseObjectLiteralElement() { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - if (parseOptionalToken(25 /* DotDotDotToken */ )) { + if (parseOptionalToken(26 /* DotDotDotToken */ )) { const expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); return withJSDoc(finishNode(factory2.createSpreadAssignment(expression), pos), hasJSDoc); } const modifiers = parseModifiers(/*allowDecorators*/ true); - if (parseContextualModifier(137 /* GetKeyword */ )) return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 174 /* GetAccessor */ , 0 /* None */ ); - if (parseContextualModifier(151 /* SetKeyword */ )) return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 175 /* SetAccessor */ , 0 /* None */ ); - const asteriskToken = parseOptionalToken(41 /* AsteriskToken */ ); + if (parseContextualModifier(139 /* GetKeyword */ )) return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 177 /* GetAccessor */ , 0 /* None */ ); + if (parseContextualModifier(153 /* SetKeyword */ )) return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 178 /* SetAccessor */ , 0 /* None */ ); + const asteriskToken = parseOptionalToken(42 /* AsteriskToken */ ); const tokenIsIdentifier = isIdentifier2(); const name = parsePropertyName(); - const questionToken = parseOptionalToken(57 /* QuestionToken */ ); - const exclamationToken = parseOptionalToken(53 /* ExclamationToken */ ); - if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */ ) return parseMethodDeclaration(pos, hasJSDoc, modifiers, asteriskToken, name, questionToken, exclamationToken); + const questionToken = parseOptionalToken(58 /* QuestionToken */ ); + const exclamationToken = parseOptionalToken(54 /* ExclamationToken */ ); + if (asteriskToken || token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */ ) return parseMethodDeclaration(pos, hasJSDoc, modifiers, asteriskToken, name, questionToken, exclamationToken); let node; - const isShorthandPropertyAssignment2 = tokenIsIdentifier && token() !== 58 /* ColonToken */ ; + const isShorthandPropertyAssignment2 = tokenIsIdentifier && token() !== 59 /* ColonToken */ ; if (isShorthandPropertyAssignment2) { - const equalsToken = parseOptionalToken(63 /* EqualsToken */ ); + const equalsToken = parseOptionalToken(64 /* EqualsToken */ ); const objectAssignmentInitializer = equalsToken ? allowInAnd(()=>parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true)) : void 0; node = factory2.createShorthandPropertyAssignment(name, objectAssignmentInitializer); node.equalsToken = equalsToken; } else { - parseExpected(58 /* ColonToken */ ); + parseExpected(59 /* ColonToken */ ); const initializer = allowInAnd(()=>parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true)); node = factory2.createPropertyAssignment(name, initializer); } @@ -33426,11 +33720,11 @@ ${lanes.join("\n")} } function parseObjectLiteralExpression() { const pos = getNodePos(); - const openBracePosition = scanner2.getTokenPos(); - const openBraceParsed = parseExpected(18 /* OpenBraceToken */ ); + const openBracePosition = scanner2.getTokenStart(); + const openBraceParsed = parseExpected(19 /* OpenBraceToken */ ); const multiLine = scanner2.hasPrecedingLineBreak(); const properties = parseDelimitedList(12 /* ObjectLiteralMembers */ , parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); - parseExpectedMatchingBrackets(18 /* OpenBraceToken */ , 19 /* CloseBraceToken */ , openBraceParsed, openBracePosition); + parseExpectedMatchingBrackets(19 /* OpenBraceToken */ , 20 /* CloseBraceToken */ , openBraceParsed, openBracePosition); return finishNode(factoryCreateObjectLiteralExpression(properties, multiLine), pos); } function parseFunctionExpression() { @@ -33439,14 +33733,14 @@ ${lanes.join("\n")} const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); const modifiers = parseModifiers(/*allowDecorators*/ false); - parseExpected(98 /* FunctionKeyword */ ); - const asteriskToken = parseOptionalToken(41 /* AsteriskToken */ ); + parseExpected(100 /* FunctionKeyword */ ); + const asteriskToken = parseOptionalToken(42 /* AsteriskToken */ ); const isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */ ; const isAsync = some(modifiers, isAsyncModifier) ? 2 /* Await */ : 0 /* None */ ; const name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalBindingIdentifier) : isGenerator ? doInYieldContext(parseOptionalBindingIdentifier) : isAsync ? doInAwaitContext(parseOptionalBindingIdentifier) : parseOptionalBindingIdentifier(); const typeParameters = parseTypeParameters(); const parameters = parseParameters(isGenerator | isAsync); - const type = parseReturnType(58 /* ColonToken */ , /*isType*/ false); + const type = parseReturnType(59 /* ColonToken */ , /*isType*/ false); const body = parseFunctionBlock(isGenerator | isAsync); setDecoratorContext(savedDecoratorContext); const node = factory2.createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body); @@ -33457,33 +33751,33 @@ ${lanes.join("\n")} } function parseNewExpressionOrNewDotTarget() { const pos = getNodePos(); - parseExpected(103 /* NewKeyword */ ); - if (parseOptional(24 /* DotToken */ )) { + parseExpected(105 /* NewKeyword */ ); + if (parseOptional(25 /* DotToken */ )) { const name = parseIdentifierName(); - return finishNode(factory2.createMetaProperty(103 /* NewKeyword */ , name), pos); + return finishNode(factory2.createMetaProperty(105 /* NewKeyword */ , name), pos); } const expressionPos = getNodePos(); let expression = parseMemberExpressionRest(expressionPos, parsePrimaryExpression(), /*allowOptionalChain*/ false); let typeArguments; - if (expression.kind === 230 /* ExpressionWithTypeArguments */ ) { + if (expression.kind === 233 /* ExpressionWithTypeArguments */ ) { typeArguments = expression.typeArguments; expression = expression.expression; } - if (token() === 28 /* QuestionDotToken */ ) parseErrorAtCurrentToken(Diagnostics.Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0, getTextOfNodeFromSourceText(sourceText, expression)); - const argumentList = token() === 20 /* OpenParenToken */ ? parseArgumentList() : void 0; + if (token() === 29 /* QuestionDotToken */ ) parseErrorAtCurrentToken(Diagnostics.Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0, getTextOfNodeFromSourceText(sourceText, expression)); + const argumentList = token() === 21 /* OpenParenToken */ ? parseArgumentList() : void 0; return finishNode(factoryCreateNewExpression(expression, typeArguments, argumentList), pos); } function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - const openBracePosition = scanner2.getTokenPos(); - const openBraceParsed = parseExpected(18 /* OpenBraceToken */ , diagnosticMessage); + const openBracePosition = scanner2.getTokenStart(); + const openBraceParsed = parseExpected(19 /* OpenBraceToken */ , diagnosticMessage); if (openBraceParsed || ignoreMissingOpenBrace) { const multiLine = scanner2.hasPrecedingLineBreak(); const statements = parseList(1 /* BlockStatements */ , parseStatement); - parseExpectedMatchingBrackets(18 /* OpenBraceToken */ , 19 /* CloseBraceToken */ , openBraceParsed, openBracePosition); + parseExpectedMatchingBrackets(19 /* OpenBraceToken */ , 20 /* CloseBraceToken */ , openBraceParsed, openBracePosition); const result = withJSDoc(finishNode(factoryCreateBlock(statements, multiLine), pos), hasJSDoc); - if (token() === 63 /* EqualsToken */ ) { + if (token() === 64 /* EqualsToken */ ) { parseErrorAtCurrentToken(Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_whole_assignment_in_parentheses); nextToken(); } @@ -33512,71 +33806,71 @@ ${lanes.join("\n")} function parseEmptyStatement() { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - parseExpected(26 /* SemicolonToken */ ); + parseExpected(27 /* SemicolonToken */ ); return withJSDoc(finishNode(factory2.createEmptyStatement(), pos), hasJSDoc); } function parseIfStatement() { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - parseExpected(99 /* IfKeyword */ ); - const openParenPosition = scanner2.getTokenPos(); - const openParenParsed = parseExpected(20 /* OpenParenToken */ ); + parseExpected(101 /* IfKeyword */ ); + const openParenPosition = scanner2.getTokenStart(); + const openParenParsed = parseExpected(21 /* OpenParenToken */ ); const expression = allowInAnd(parseExpression); - parseExpectedMatchingBrackets(20 /* OpenParenToken */ , 21 /* CloseParenToken */ , openParenParsed, openParenPosition); + parseExpectedMatchingBrackets(21 /* OpenParenToken */ , 22 /* CloseParenToken */ , openParenParsed, openParenPosition); const thenStatement = parseStatement(); - const elseStatement = parseOptional(91 /* ElseKeyword */ ) ? parseStatement() : void 0; + const elseStatement = parseOptional(93 /* ElseKeyword */ ) ? parseStatement() : void 0; return withJSDoc(finishNode(factoryCreateIfStatement(expression, thenStatement, elseStatement), pos), hasJSDoc); } function parseDoStatement() { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - parseExpected(90 /* DoKeyword */ ); + parseExpected(92 /* DoKeyword */ ); const statement = parseStatement(); - parseExpected(115 /* WhileKeyword */ ); - const openParenPosition = scanner2.getTokenPos(); - const openParenParsed = parseExpected(20 /* OpenParenToken */ ); + parseExpected(117 /* WhileKeyword */ ); + const openParenPosition = scanner2.getTokenStart(); + const openParenParsed = parseExpected(21 /* OpenParenToken */ ); const expression = allowInAnd(parseExpression); - parseExpectedMatchingBrackets(20 /* OpenParenToken */ , 21 /* CloseParenToken */ , openParenParsed, openParenPosition); - parseOptional(26 /* SemicolonToken */ ); + parseExpectedMatchingBrackets(21 /* OpenParenToken */ , 22 /* CloseParenToken */ , openParenParsed, openParenPosition); + parseOptional(27 /* SemicolonToken */ ); return withJSDoc(finishNode(factory2.createDoStatement(statement, expression), pos), hasJSDoc); } function parseWhileStatement() { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - parseExpected(115 /* WhileKeyword */ ); - const openParenPosition = scanner2.getTokenPos(); - const openParenParsed = parseExpected(20 /* OpenParenToken */ ); + parseExpected(117 /* WhileKeyword */ ); + const openParenPosition = scanner2.getTokenStart(); + const openParenParsed = parseExpected(21 /* OpenParenToken */ ); const expression = allowInAnd(parseExpression); - parseExpectedMatchingBrackets(20 /* OpenParenToken */ , 21 /* CloseParenToken */ , openParenParsed, openParenPosition); + parseExpectedMatchingBrackets(21 /* OpenParenToken */ , 22 /* CloseParenToken */ , openParenParsed, openParenPosition); const statement = parseStatement(); return withJSDoc(finishNode(factoryCreateWhileStatement(expression, statement), pos), hasJSDoc); } function parseForOrForInOrForOfStatement() { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - parseExpected(97 /* ForKeyword */ ); - const awaitToken = parseOptionalToken(133 /* AwaitKeyword */ ); - parseExpected(20 /* OpenParenToken */ ); + parseExpected(99 /* ForKeyword */ ); + const awaitToken = parseOptionalToken(135 /* AwaitKeyword */ ); + parseExpected(21 /* OpenParenToken */ ); let initializer; - if (token() !== 26 /* SemicolonToken */ ) { - if (token() === 113 /* VarKeyword */ || token() === 119 /* LetKeyword */ || token() === 85 /* ConstKeyword */ ) initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); + if (token() !== 27 /* SemicolonToken */ ) { + if (token() === 115 /* VarKeyword */ || token() === 121 /* LetKeyword */ || token() === 87 /* ConstKeyword */ || token() === 160 /* UsingKeyword */ && lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLineDisallowOf) || token() === 135 /* AwaitKeyword */ && lookAhead(nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLineDisallowOf)) initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); else initializer = disallowInAnd(parseExpression); } let node; - if (awaitToken ? parseExpected(162 /* OfKeyword */ ) : parseOptional(162 /* OfKeyword */ )) { + if (awaitToken ? parseExpected(165 /* OfKeyword */ ) : parseOptional(165 /* OfKeyword */ )) { const expression = allowInAnd(()=>parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true)); - parseExpected(21 /* CloseParenToken */ ); + parseExpected(22 /* CloseParenToken */ ); node = factoryCreateForOfStatement(awaitToken, initializer, expression, parseStatement()); - } else if (parseOptional(101 /* InKeyword */ )) { + } else if (parseOptional(103 /* InKeyword */ )) { const expression = allowInAnd(parseExpression); - parseExpected(21 /* CloseParenToken */ ); + parseExpected(22 /* CloseParenToken */ ); node = factory2.createForInStatement(initializer, expression, parseStatement()); } else { - parseExpected(26 /* SemicolonToken */ ); - const condition = token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */ ? allowInAnd(parseExpression) : void 0; - parseExpected(26 /* SemicolonToken */ ); - const incrementor = token() !== 21 /* CloseParenToken */ ? allowInAnd(parseExpression) : void 0; - parseExpected(21 /* CloseParenToken */ ); + parseExpected(27 /* SemicolonToken */ ); + const condition = token() !== 27 /* SemicolonToken */ && token() !== 22 /* CloseParenToken */ ? allowInAnd(parseExpression) : void 0; + parseExpected(27 /* SemicolonToken */ ); + const incrementor = token() !== 22 /* CloseParenToken */ ? allowInAnd(parseExpression) : void 0; + parseExpected(22 /* CloseParenToken */ ); node = factoryCreateForStatement(initializer, condition, incrementor, parseStatement()); } return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -33584,16 +33878,16 @@ ${lanes.join("\n")} function parseBreakOrContinueStatement(kind) { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - parseExpected(kind === 249 /* BreakStatement */ ? 81 /* BreakKeyword */ : 86 /* ContinueKeyword */ ); + parseExpected(kind === 252 /* BreakStatement */ ? 83 /* BreakKeyword */ : 88 /* ContinueKeyword */ ); const label = canParseSemicolon() ? void 0 : parseIdentifier(); parseSemicolon(); - const node = kind === 249 /* BreakStatement */ ? factory2.createBreakStatement(label) : factory2.createContinueStatement(label); + const node = kind === 252 /* BreakStatement */ ? factory2.createBreakStatement(label) : factory2.createContinueStatement(label); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseReturnStatement() { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - parseExpected(105 /* ReturnKeyword */ ); + parseExpected(107 /* ReturnKeyword */ ); const expression = canParseSemicolon() ? void 0 : allowInAnd(parseExpression); parseSemicolon(); return withJSDoc(finishNode(factory2.createReturnStatement(expression), pos), hasJSDoc); @@ -33601,54 +33895,54 @@ ${lanes.join("\n")} function parseWithStatement() { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - parseExpected(116 /* WithKeyword */ ); - const openParenPosition = scanner2.getTokenPos(); - const openParenParsed = parseExpected(20 /* OpenParenToken */ ); + parseExpected(118 /* WithKeyword */ ); + const openParenPosition = scanner2.getTokenStart(); + const openParenParsed = parseExpected(21 /* OpenParenToken */ ); const expression = allowInAnd(parseExpression); - parseExpectedMatchingBrackets(20 /* OpenParenToken */ , 21 /* CloseParenToken */ , openParenParsed, openParenPosition); - const statement = doInsideOfContext(33554432 /* InWithStatement */ , parseStatement); + parseExpectedMatchingBrackets(21 /* OpenParenToken */ , 22 /* CloseParenToken */ , openParenParsed, openParenPosition); + const statement = doInsideOfContext(67108864 /* InWithStatement */ , parseStatement); return withJSDoc(finishNode(factory2.createWithStatement(expression, statement), pos), hasJSDoc); } function parseCaseClause() { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - parseExpected(82 /* CaseKeyword */ ); + parseExpected(84 /* CaseKeyword */ ); const expression = allowInAnd(parseExpression); - parseExpected(58 /* ColonToken */ ); + parseExpected(59 /* ColonToken */ ); const statements = parseList(3 /* SwitchClauseStatements */ , parseStatement); return withJSDoc(finishNode(factory2.createCaseClause(expression, statements), pos), hasJSDoc); } function parseDefaultClause() { const pos = getNodePos(); - parseExpected(88 /* DefaultKeyword */ ); - parseExpected(58 /* ColonToken */ ); + parseExpected(90 /* DefaultKeyword */ ); + parseExpected(59 /* ColonToken */ ); const statements = parseList(3 /* SwitchClauseStatements */ , parseStatement); return finishNode(factory2.createDefaultClause(statements), pos); } function parseCaseOrDefaultClause() { - return token() === 82 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); + return token() === 84 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseCaseBlock() { const pos = getNodePos(); - parseExpected(18 /* OpenBraceToken */ ); + parseExpected(19 /* OpenBraceToken */ ); const clauses = parseList(2 /* SwitchClauses */ , parseCaseOrDefaultClause); - parseExpected(19 /* CloseBraceToken */ ); + parseExpected(20 /* CloseBraceToken */ ); return finishNode(factory2.createCaseBlock(clauses), pos); } function parseSwitchStatement() { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - parseExpected(107 /* SwitchKeyword */ ); - parseExpected(20 /* OpenParenToken */ ); + parseExpected(109 /* SwitchKeyword */ ); + parseExpected(21 /* OpenParenToken */ ); const expression = allowInAnd(parseExpression); - parseExpected(21 /* CloseParenToken */ ); + parseExpected(22 /* CloseParenToken */ ); const caseBlock = parseCaseBlock(); return withJSDoc(finishNode(factory2.createSwitchStatement(expression, caseBlock), pos), hasJSDoc); } function parseThrowStatement() { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - parseExpected(109 /* ThrowKeyword */ ); + parseExpected(111 /* ThrowKeyword */ ); let expression = scanner2.hasPrecedingLineBreak() ? void 0 : allowInAnd(parseExpression); if (expression === void 0) { identifierCount++; @@ -33660,23 +33954,23 @@ ${lanes.join("\n")} function parseTryStatement() { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - parseExpected(111 /* TryKeyword */ ); + parseExpected(113 /* TryKeyword */ ); const tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); - const catchClause = token() === 83 /* CatchKeyword */ ? parseCatchClause() : void 0; + const catchClause = token() === 85 /* CatchKeyword */ ? parseCatchClause() : void 0; let finallyBlock; - if (!catchClause || token() === 96 /* FinallyKeyword */ ) { - parseExpected(96 /* FinallyKeyword */ , Diagnostics.catch_or_finally_expected); + if (!catchClause || token() === 98 /* FinallyKeyword */ ) { + parseExpected(98 /* FinallyKeyword */ , Diagnostics.catch_or_finally_expected); finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } return withJSDoc(finishNode(factory2.createTryStatement(tryBlock, catchClause, finallyBlock), pos), hasJSDoc); } function parseCatchClause() { const pos = getNodePos(); - parseExpected(83 /* CatchKeyword */ ); + parseExpected(85 /* CatchKeyword */ ); let variableDeclaration; - if (parseOptional(20 /* OpenParenToken */ )) { + if (parseOptional(21 /* OpenParenToken */ )) { variableDeclaration = parseVariableDeclaration(); - parseExpected(21 /* CloseParenToken */ ); + parseExpected(22 /* CloseParenToken */ ); } else variableDeclaration = void 0; const block = parseBlock(/*ignoreMissingOpenBrace*/ false); return finishNode(factory2.createCatchClause(variableDeclaration, block), pos); @@ -33684,7 +33978,7 @@ ${lanes.join("\n")} function parseDebuggerStatement() { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - parseExpected(87 /* DebuggerKeyword */ ); + parseExpected(89 /* DebuggerKeyword */ ); parseSemicolon(); return withJSDoc(finishNode(factory2.createDebuggerStatement(), pos), hasJSDoc); } @@ -33692,9 +33986,9 @@ ${lanes.join("\n")} const pos = getNodePos(); let hasJSDoc = hasPrecedingJSDocComment(); let node; - const hasParen = token() === 20 /* OpenParenToken */ ; + const hasParen = token() === 21 /* OpenParenToken */ ; const expression = allowInAnd(parseExpression); - if (isIdentifier(expression) && parseOptional(58 /* ColonToken */ )) node = factory2.createLabeledStatement(expression, parseStatement()); + if (isIdentifier(expression) && parseOptional(59 /* ColonToken */ )) node = factory2.createLabeledStatement(expression, parseStatement()); else { if (!tryParseSemicolon()) parseErrorForMissingSemicolonAfter(expression); node = factoryCreateExpressionStatement(expression); @@ -33708,54 +34002,60 @@ ${lanes.join("\n")} } function nextTokenIsClassKeywordOnSameLine() { nextToken(); - return token() === 84 /* ClassKeyword */ && !scanner2.hasPrecedingLineBreak(); + return token() === 86 /* ClassKeyword */ && !scanner2.hasPrecedingLineBreak(); } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token() === 98 /* FunctionKeyword */ && !scanner2.hasPrecedingLineBreak(); + return token() === 100 /* FunctionKeyword */ && !scanner2.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { nextToken(); - return (tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */ ) && !scanner2.hasPrecedingLineBreak(); + return (tokenIsIdentifierOrKeyword(token()) || token() === 9 /* NumericLiteral */ || token() === 10 /* BigIntLiteral */ || token() === 11 /* StringLiteral */ ) && !scanner2.hasPrecedingLineBreak(); } function isDeclaration2() { while(true)switch(token()){ - case 113 /* VarKeyword */ : - case 119 /* LetKeyword */ : - case 85 /* ConstKeyword */ : - case 98 /* FunctionKeyword */ : - case 84 /* ClassKeyword */ : - case 92 /* EnumKeyword */ : + case 115 /* VarKeyword */ : + case 121 /* LetKeyword */ : + case 87 /* ConstKeyword */ : + case 100 /* FunctionKeyword */ : + case 86 /* ClassKeyword */ : + case 94 /* EnumKeyword */ : return true; - case 118 /* InterfaceKeyword */ : - case 154 /* TypeKeyword */ : + case 160 /* UsingKeyword */ : + return isUsingDeclaration(); + case 135 /* AwaitKeyword */ : + return isAwaitUsingDeclaration(); + case 120 /* InterfaceKeyword */ : + case 156 /* TypeKeyword */ : return nextTokenIsIdentifierOnSameLine(); - case 142 /* ModuleKeyword */ : - case 143 /* NamespaceKeyword */ : + case 144 /* ModuleKeyword */ : + case 145 /* NamespaceKeyword */ : return nextTokenIsIdentifierOrStringLiteralOnSameLine(); - case 126 /* AbstractKeyword */ : - case 127 /* AccessorKeyword */ : - case 132 /* AsyncKeyword */ : - case 136 /* DeclareKeyword */ : - case 121 /* PrivateKeyword */ : - case 122 /* ProtectedKeyword */ : - case 123 /* PublicKeyword */ : - case 146 /* ReadonlyKeyword */ : + case 128 /* AbstractKeyword */ : + case 129 /* AccessorKeyword */ : + case 134 /* AsyncKeyword */ : + case 138 /* DeclareKeyword */ : + case 123 /* PrivateKeyword */ : + case 124 /* ProtectedKeyword */ : + case 125 /* PublicKeyword */ : + case 148 /* ReadonlyKeyword */ : + const previousToken = token(); nextToken(); if (scanner2.hasPrecedingLineBreak()) return false; + if (previousToken === 138 /* DeclareKeyword */ && token() === 156 /* TypeKeyword */ ) return true; continue; - case 159 /* GlobalKeyword */ : + case 162 /* GlobalKeyword */ : nextToken(); - return token() === 18 /* OpenBraceToken */ || token() === 79 /* Identifier */ || token() === 93 /* ExportKeyword */ ; - case 100 /* ImportKeyword */ : + return token() === 19 /* OpenBraceToken */ || token() === 80 /* Identifier */ || token() === 95 /* ExportKeyword */ ; + case 102 /* ImportKeyword */ : nextToken(); - return token() === 10 /* StringLiteral */ || token() === 41 /* AsteriskToken */ || token() === 18 /* OpenBraceToken */ || tokenIsIdentifierOrKeyword(token()); - case 93 /* ExportKeyword */ : + return token() === 11 /* StringLiteral */ || token() === 42 /* AsteriskToken */ || token() === 19 /* OpenBraceToken */ || tokenIsIdentifierOrKeyword(token()); + case 95 /* ExportKeyword */ : let currentToken2 = nextToken(); - if (currentToken2 === 154 /* TypeKeyword */ ) currentToken2 = lookAhead(nextToken); - if (currentToken2 === 63 /* EqualsToken */ || currentToken2 === 41 /* AsteriskToken */ || currentToken2 === 18 /* OpenBraceToken */ || currentToken2 === 88 /* DefaultKeyword */ || currentToken2 === 128 /* AsKeyword */ || currentToken2 === 59 /* AtToken */ ) return true; + if (currentToken2 === 156 /* TypeKeyword */ ) currentToken2 = lookAhead(nextToken); + if (currentToken2 === 64 /* EqualsToken */ || currentToken2 === 42 /* AsteriskToken */ || currentToken2 === 19 /* OpenBraceToken */ || currentToken2 === 90 /* DefaultKeyword */ || currentToken2 === 130 /* AsKeyword */ || currentToken2 === 60 /* AtToken */ ) return true; continue; - case 124 /* StaticKeyword */ : + case 126 /* StaticKeyword */ : nextToken(); continue; default: @@ -33767,48 +34067,49 @@ ${lanes.join("\n")} } function isStartOfStatement() { switch(token()){ - case 59 /* AtToken */ : - case 26 /* SemicolonToken */ : - case 18 /* OpenBraceToken */ : - case 113 /* VarKeyword */ : - case 119 /* LetKeyword */ : - case 98 /* FunctionKeyword */ : - case 84 /* ClassKeyword */ : - case 92 /* EnumKeyword */ : - case 99 /* IfKeyword */ : - case 90 /* DoKeyword */ : - case 115 /* WhileKeyword */ : - case 97 /* ForKeyword */ : - case 86 /* ContinueKeyword */ : - case 81 /* BreakKeyword */ : - case 105 /* ReturnKeyword */ : - case 116 /* WithKeyword */ : - case 107 /* SwitchKeyword */ : - case 109 /* ThrowKeyword */ : - case 111 /* TryKeyword */ : - case 87 /* DebuggerKeyword */ : - case 83 /* CatchKeyword */ : - case 96 /* FinallyKeyword */ : + case 60 /* AtToken */ : + case 27 /* SemicolonToken */ : + case 19 /* OpenBraceToken */ : + case 115 /* VarKeyword */ : + case 121 /* LetKeyword */ : + case 160 /* UsingKeyword */ : + case 100 /* FunctionKeyword */ : + case 86 /* ClassKeyword */ : + case 94 /* EnumKeyword */ : + case 101 /* IfKeyword */ : + case 92 /* DoKeyword */ : + case 117 /* WhileKeyword */ : + case 99 /* ForKeyword */ : + case 88 /* ContinueKeyword */ : + case 83 /* BreakKeyword */ : + case 107 /* ReturnKeyword */ : + case 118 /* WithKeyword */ : + case 109 /* SwitchKeyword */ : + case 111 /* ThrowKeyword */ : + case 113 /* TryKeyword */ : + case 89 /* DebuggerKeyword */ : + case 85 /* CatchKeyword */ : + case 98 /* FinallyKeyword */ : return true; - case 100 /* ImportKeyword */ : + case 102 /* ImportKeyword */ : return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot); - case 85 /* ConstKeyword */ : - case 93 /* ExportKeyword */ : + case 87 /* ConstKeyword */ : + case 95 /* ExportKeyword */ : return isStartOfDeclaration(); - case 132 /* AsyncKeyword */ : - case 136 /* DeclareKeyword */ : - case 118 /* InterfaceKeyword */ : - case 142 /* ModuleKeyword */ : - case 143 /* NamespaceKeyword */ : - case 154 /* TypeKeyword */ : - case 159 /* GlobalKeyword */ : + case 134 /* AsyncKeyword */ : + case 138 /* DeclareKeyword */ : + case 120 /* InterfaceKeyword */ : + case 144 /* ModuleKeyword */ : + case 145 /* NamespaceKeyword */ : + case 156 /* TypeKeyword */ : + case 162 /* GlobalKeyword */ : return true; - case 127 /* AccessorKeyword */ : - case 123 /* PublicKeyword */ : - case 121 /* PrivateKeyword */ : - case 122 /* ProtectedKeyword */ : - case 124 /* StaticKeyword */ : - case 146 /* ReadonlyKeyword */ : + case 129 /* AccessorKeyword */ : + case 125 /* PublicKeyword */ : + case 123 /* PrivateKeyword */ : + case 124 /* ProtectedKeyword */ : + case 126 /* StaticKeyword */ : + case 148 /* ReadonlyKeyword */ : return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); default: return isStartOfExpression(); @@ -33816,79 +34117,106 @@ ${lanes.join("\n")} } function nextTokenIsBindingIdentifierOrStartOfDestructuring() { nextToken(); - return isBindingIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */ ; + return isBindingIdentifier() || token() === 19 /* OpenBraceToken */ || token() === 23 /* OpenBracketToken */ ; } function isLetDeclaration() { return lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuring); } + function nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLineDisallowOf() { + return nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine(/*disallowOf*/ true); + } + function nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine(disallowOf) { + nextToken(); + if (disallowOf && token() === 165 /* OfKeyword */ ) return false; + return (isBindingIdentifier() || token() === 19 /* OpenBraceToken */ ) && !scanner2.hasPrecedingLineBreak(); + } + function isUsingDeclaration() { + return lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine); + } + function nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLineDisallowOf() { + return nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine(/*disallowOf*/ true); + } + function nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine(disallowOf) { + if (nextToken() === 160 /* UsingKeyword */ ) return nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine(disallowOf); + return false; + } + function isAwaitUsingDeclaration() { + return lookAhead(nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine); + } function parseStatement() { switch(token()){ - case 26 /* SemicolonToken */ : + case 27 /* SemicolonToken */ : return parseEmptyStatement(); - case 18 /* OpenBraceToken */ : + case 19 /* OpenBraceToken */ : return parseBlock(/*ignoreMissingOpenBrace*/ false); - case 113 /* VarKeyword */ : + case 115 /* VarKeyword */ : return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ void 0); - case 119 /* LetKeyword */ : + case 121 /* LetKeyword */ : if (isLetDeclaration()) return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ void 0); break; - case 98 /* FunctionKeyword */ : + case 135 /* AwaitKeyword */ : + if (isAwaitUsingDeclaration()) return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ void 0); + break; + case 160 /* UsingKeyword */ : + if (isUsingDeclaration()) return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ void 0); + break; + case 100 /* FunctionKeyword */ : return parseFunctionDeclaration(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ void 0); - case 84 /* ClassKeyword */ : + case 86 /* ClassKeyword */ : return parseClassDeclaration(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ void 0); - case 99 /* IfKeyword */ : + case 101 /* IfKeyword */ : return parseIfStatement(); - case 90 /* DoKeyword */ : + case 92 /* DoKeyword */ : return parseDoStatement(); - case 115 /* WhileKeyword */ : + case 117 /* WhileKeyword */ : return parseWhileStatement(); - case 97 /* ForKeyword */ : + case 99 /* ForKeyword */ : return parseForOrForInOrForOfStatement(); - case 86 /* ContinueKeyword */ : - return parseBreakOrContinueStatement(248 /* ContinueStatement */ ); - case 81 /* BreakKeyword */ : - return parseBreakOrContinueStatement(249 /* BreakStatement */ ); - case 105 /* ReturnKeyword */ : + case 88 /* ContinueKeyword */ : + return parseBreakOrContinueStatement(251 /* ContinueStatement */ ); + case 83 /* BreakKeyword */ : + return parseBreakOrContinueStatement(252 /* BreakStatement */ ); + case 107 /* ReturnKeyword */ : return parseReturnStatement(); - case 116 /* WithKeyword */ : + case 118 /* WithKeyword */ : return parseWithStatement(); - case 107 /* SwitchKeyword */ : + case 109 /* SwitchKeyword */ : return parseSwitchStatement(); - case 109 /* ThrowKeyword */ : + case 111 /* ThrowKeyword */ : return parseThrowStatement(); - case 111 /* TryKeyword */ : - case 83 /* CatchKeyword */ : - case 96 /* FinallyKeyword */ : + case 113 /* TryKeyword */ : + case 85 /* CatchKeyword */ : + case 98 /* FinallyKeyword */ : return parseTryStatement(); - case 87 /* DebuggerKeyword */ : + case 89 /* DebuggerKeyword */ : return parseDebuggerStatement(); - case 59 /* AtToken */ : + case 60 /* AtToken */ : return parseDeclaration(); - case 132 /* AsyncKeyword */ : - case 118 /* InterfaceKeyword */ : - case 154 /* TypeKeyword */ : - case 142 /* ModuleKeyword */ : - case 143 /* NamespaceKeyword */ : - case 136 /* DeclareKeyword */ : - case 85 /* ConstKeyword */ : - case 92 /* EnumKeyword */ : - case 93 /* ExportKeyword */ : - case 100 /* ImportKeyword */ : - case 121 /* PrivateKeyword */ : - case 122 /* ProtectedKeyword */ : - case 123 /* PublicKeyword */ : - case 126 /* AbstractKeyword */ : - case 127 /* AccessorKeyword */ : - case 124 /* StaticKeyword */ : - case 146 /* ReadonlyKeyword */ : - case 159 /* GlobalKeyword */ : + case 134 /* AsyncKeyword */ : + case 120 /* InterfaceKeyword */ : + case 156 /* TypeKeyword */ : + case 144 /* ModuleKeyword */ : + case 145 /* NamespaceKeyword */ : + case 138 /* DeclareKeyword */ : + case 87 /* ConstKeyword */ : + case 94 /* EnumKeyword */ : + case 95 /* ExportKeyword */ : + case 102 /* ImportKeyword */ : + case 123 /* PrivateKeyword */ : + case 124 /* ProtectedKeyword */ : + case 125 /* PublicKeyword */ : + case 128 /* AbstractKeyword */ : + case 129 /* AccessorKeyword */ : + case 126 /* StaticKeyword */ : + case 148 /* ReadonlyKeyword */ : + case 162 /* GlobalKeyword */ : if (isStartOfDeclaration()) return parseDeclaration(); break; } return parseExpressionOrLabeledStatement(); } function isDeclareModifier(modifier) { - return modifier.kind === 136 /* DeclareKeyword */ ; + return modifier.kind === 138 /* DeclareKeyword */ ; } function parseDeclaration() { const pos = getNodePos(); @@ -33898,52 +34226,54 @@ ${lanes.join("\n")} if (isAmbient) { const node = tryReuseAmbientDeclaration(pos); if (node) return node; - for (const m of modifiers)m.flags |= 16777216 /* Ambient */ ; - return doInsideOfContext(16777216 /* Ambient */ , ()=>parseDeclarationWorker(pos, hasJSDoc, modifiers)); + for (const m of modifiers)m.flags |= 33554432 /* Ambient */ ; + return doInsideOfContext(33554432 /* Ambient */ , ()=>parseDeclarationWorker(pos, hasJSDoc, modifiers)); } else return parseDeclarationWorker(pos, hasJSDoc, modifiers); } function tryReuseAmbientDeclaration(pos) { - return doInsideOfContext(16777216 /* Ambient */ , ()=>{ + return doInsideOfContext(33554432 /* Ambient */ , ()=>{ const node = currentNode(parsingContext, pos); if (node) return consumeNode(node); }); } function parseDeclarationWorker(pos, hasJSDoc, modifiersIn) { switch(token()){ - case 113 /* VarKeyword */ : - case 119 /* LetKeyword */ : - case 85 /* ConstKeyword */ : + case 115 /* VarKeyword */ : + case 121 /* LetKeyword */ : + case 87 /* ConstKeyword */ : + case 160 /* UsingKeyword */ : + case 135 /* AwaitKeyword */ : return parseVariableStatement(pos, hasJSDoc, modifiersIn); - case 98 /* FunctionKeyword */ : + case 100 /* FunctionKeyword */ : return parseFunctionDeclaration(pos, hasJSDoc, modifiersIn); - case 84 /* ClassKeyword */ : + case 86 /* ClassKeyword */ : return parseClassDeclaration(pos, hasJSDoc, modifiersIn); - case 118 /* InterfaceKeyword */ : + case 120 /* InterfaceKeyword */ : return parseInterfaceDeclaration(pos, hasJSDoc, modifiersIn); - case 154 /* TypeKeyword */ : + case 156 /* TypeKeyword */ : return parseTypeAliasDeclaration(pos, hasJSDoc, modifiersIn); - case 92 /* EnumKeyword */ : + case 94 /* EnumKeyword */ : return parseEnumDeclaration(pos, hasJSDoc, modifiersIn); - case 159 /* GlobalKeyword */ : - case 142 /* ModuleKeyword */ : - case 143 /* NamespaceKeyword */ : + case 162 /* GlobalKeyword */ : + case 144 /* ModuleKeyword */ : + case 145 /* NamespaceKeyword */ : return parseModuleDeclaration(pos, hasJSDoc, modifiersIn); - case 100 /* ImportKeyword */ : + case 102 /* ImportKeyword */ : return parseImportDeclarationOrImportEqualsDeclaration(pos, hasJSDoc, modifiersIn); - case 93 /* ExportKeyword */ : + case 95 /* ExportKeyword */ : nextToken(); switch(token()){ - case 88 /* DefaultKeyword */ : - case 63 /* EqualsToken */ : + case 90 /* DefaultKeyword */ : + case 64 /* EqualsToken */ : return parseExportAssignment(pos, hasJSDoc, modifiersIn); - case 128 /* AsKeyword */ : + case 130 /* AsKeyword */ : return parseNamespaceExportDeclaration(pos, hasJSDoc, modifiersIn); default: return parseExportDeclaration(pos, hasJSDoc, modifiersIn); } default: if (modifiersIn) { - const missing = createMissingNode(279 /* MissingDeclaration */ , /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); + const missing = createMissingNode(282 /* MissingDeclaration */ , /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); setTextRangePos(missing, pos); missing.modifiers = modifiersIn; return missing; @@ -33951,12 +34281,15 @@ ${lanes.join("\n")} return void 0; } } + function nextTokenIsStringLiteral() { + return nextToken() === 11 /* StringLiteral */ ; + } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); - return !scanner2.hasPrecedingLineBreak() && (isIdentifier2() || token() === 10 /* StringLiteral */ ); + return !scanner2.hasPrecedingLineBreak() && (isIdentifier2() || token() === 11 /* StringLiteral */ ); } function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { - if (token() !== 18 /* OpenBraceToken */ ) { + if (token() !== 19 /* OpenBraceToken */ ) { if (flags & 4 /* Type */ ) { parseTypeMemberSemicolon(); return; @@ -33970,23 +34303,23 @@ ${lanes.join("\n")} } function parseArrayBindingElement() { const pos = getNodePos(); - if (token() === 27 /* CommaToken */ ) return finishNode(factory2.createOmittedExpression(), pos); - const dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */ ); + if (token() === 28 /* CommaToken */ ) return finishNode(factory2.createOmittedExpression(), pos); + const dotDotDotToken = parseOptionalToken(26 /* DotDotDotToken */ ); const name = parseIdentifierOrPattern(); const initializer = parseInitializer(); return finishNode(factory2.createBindingElement(dotDotDotToken, /*propertyName*/ void 0, name, initializer), pos); } function parseObjectBindingElement() { const pos = getNodePos(); - const dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */ ); + const dotDotDotToken = parseOptionalToken(26 /* DotDotDotToken */ ); const tokenIsIdentifier = isBindingIdentifier(); let propertyName = parsePropertyName(); let name; - if (tokenIsIdentifier && token() !== 58 /* ColonToken */ ) { + if (tokenIsIdentifier && token() !== 59 /* ColonToken */ ) { name = propertyName; propertyName = void 0; } else { - parseExpected(58 /* ColonToken */ ); + parseExpected(59 /* ColonToken */ ); name = parseIdentifierOrPattern(); } const initializer = parseInitializer(); @@ -33994,24 +34327,24 @@ ${lanes.join("\n")} } function parseObjectBindingPattern() { const pos = getNodePos(); - parseExpected(18 /* OpenBraceToken */ ); - const elements = parseDelimitedList(9 /* ObjectBindingElements */ , parseObjectBindingElement); - parseExpected(19 /* CloseBraceToken */ ); + parseExpected(19 /* OpenBraceToken */ ); + const elements = allowInAnd(()=>parseDelimitedList(9 /* ObjectBindingElements */ , parseObjectBindingElement)); + parseExpected(20 /* CloseBraceToken */ ); return finishNode(factory2.createObjectBindingPattern(elements), pos); } function parseArrayBindingPattern() { const pos = getNodePos(); - parseExpected(22 /* OpenBracketToken */ ); - const elements = parseDelimitedList(10 /* ArrayBindingElements */ , parseArrayBindingElement); - parseExpected(23 /* CloseBracketToken */ ); + parseExpected(23 /* OpenBracketToken */ ); + const elements = allowInAnd(()=>parseDelimitedList(10 /* ArrayBindingElements */ , parseArrayBindingElement)); + parseExpected(24 /* CloseBracketToken */ ); return finishNode(factory2.createArrayBindingPattern(elements), pos); } function isBindingIdentifierOrPrivateIdentifierOrPattern() { - return token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */ || token() === 80 /* PrivateIdentifier */ || isBindingIdentifier(); + return token() === 19 /* OpenBraceToken */ || token() === 23 /* OpenBracketToken */ || token() === 81 /* PrivateIdentifier */ || isBindingIdentifier(); } function parseIdentifierOrPattern(privateIdentifierDiagnosticMessage) { - if (token() === 22 /* OpenBracketToken */ ) return parseArrayBindingPattern(); - if (token() === 18 /* OpenBraceToken */ ) return parseObjectBindingPattern(); + if (token() === 23 /* OpenBracketToken */ ) return parseArrayBindingPattern(); + if (token() === 19 /* OpenBraceToken */ ) return parseObjectBindingPattern(); return parseBindingIdentifier(privateIdentifierDiagnosticMessage); } function parseVariableDeclarationAllowExclamation() { @@ -34022,7 +34355,7 @@ ${lanes.join("\n")} const hasJSDoc = hasPrecedingJSDocComment(); const name = parseIdentifierOrPattern(Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations); let exclamationToken; - if (allowExclamation && name.kind === 79 /* Identifier */ && token() === 53 /* ExclamationToken */ && !scanner2.hasPrecedingLineBreak()) exclamationToken = parseTokenNode(); + if (allowExclamation && name.kind === 80 /* Identifier */ && token() === 54 /* ExclamationToken */ && !scanner2.hasPrecedingLineBreak()) exclamationToken = parseTokenNode(); const type = parseTypeAnnotation(); const initializer = isInOrOfKeyword(token()) ? void 0 : parseInitializer(); const node = factoryCreateVariableDeclaration(name, exclamationToken, type, initializer); @@ -34032,20 +34365,28 @@ ${lanes.join("\n")} const pos = getNodePos(); let flags = 0; switch(token()){ - case 113 /* VarKeyword */ : + case 115 /* VarKeyword */ : break; - case 119 /* LetKeyword */ : + case 121 /* LetKeyword */ : flags |= 1 /* Let */ ; break; - case 85 /* ConstKeyword */ : + case 87 /* ConstKeyword */ : flags |= 2 /* Const */ ; break; + case 160 /* UsingKeyword */ : + flags |= 4 /* Using */ ; + break; + case 135 /* AwaitKeyword */ : + Debug.assert(isAwaitUsingDeclaration()); + flags |= 6 /* AwaitUsing */ ; + nextToken(); + break; default: Debug.fail(); } nextToken(); let declarations; - if (token() === 162 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) declarations = createMissingList(); + if (token() === 165 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) declarations = createMissingList(); else { const savedDisallowIn = inDisallowInContext(); setDisallowInContext(inForStatementInitializer); @@ -34055,7 +34396,7 @@ ${lanes.join("\n")} return finishNode(factoryCreateVariableDeclarationList(declarations, flags), pos); } function canFollowContextualOfKeyword() { - return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */ ; + return nextTokenIsIdentifier() && nextToken() === 22 /* CloseParenToken */ ; } function parseVariableStatement(pos, hasJSDoc, modifiers) { const declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); @@ -34066,23 +34407,23 @@ ${lanes.join("\n")} function parseFunctionDeclaration(pos, hasJSDoc, modifiers) { const savedAwaitContext = inAwaitContext(); const modifierFlags = modifiersToFlags(modifiers); - parseExpected(98 /* FunctionKeyword */ ); - const asteriskToken = parseOptionalToken(41 /* AsteriskToken */ ); + parseExpected(100 /* FunctionKeyword */ ); + const asteriskToken = parseOptionalToken(42 /* AsteriskToken */ ); const name = modifierFlags & 1024 /* Default */ ? parseOptionalBindingIdentifier() : parseBindingIdentifier(); const isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */ ; const isAsync = modifierFlags & 512 /* Async */ ? 2 /* Await */ : 0 /* None */ ; const typeParameters = parseTypeParameters(); if (modifierFlags & 1 /* Export */ ) setAwaitContext(/*value*/ true); const parameters = parseParameters(isGenerator | isAsync); - const type = parseReturnType(58 /* ColonToken */ , /*isType*/ false); + const type = parseReturnType(59 /* ColonToken */ , /*isType*/ false); const body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, Diagnostics.or_expected); setAwaitContext(savedAwaitContext); const node = factory2.createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseConstructorName() { - if (token() === 135 /* ConstructorKeyword */ ) return parseExpected(135 /* ConstructorKeyword */ ); - if (token() === 10 /* StringLiteral */ && lookAhead(nextToken) === 20 /* OpenParenToken */ ) return tryParse(()=>{ + if (token() === 137 /* ConstructorKeyword */ ) return parseExpected(137 /* ConstructorKeyword */ ); + if (token() === 11 /* StringLiteral */ && lookAhead(nextToken) === 21 /* OpenParenToken */ ) return tryParse(()=>{ const literalNode = parseLiteralNode(); return literalNode.text === "constructor" ? literalNode : void 0; }); @@ -34092,7 +34433,7 @@ ${lanes.join("\n")} if (parseConstructorName()) { const typeParameters = parseTypeParameters(); const parameters = parseParameters(0 /* None */ ); - const type = parseReturnType(58 /* ColonToken */ , /*isType*/ false); + const type = parseReturnType(59 /* ColonToken */ , /*isType*/ false); const body = parseFunctionBlockOrSemicolon(0 /* None */ , Diagnostics.or_expected); const node = factory2.createConstructorDeclaration(modifiers, parameters, body); node.typeParameters = typeParameters; @@ -34106,61 +34447,61 @@ ${lanes.join("\n")} const isAsync = some(modifiers, isAsyncModifier) ? 2 /* Await */ : 0 /* None */ ; const typeParameters = parseTypeParameters(); const parameters = parseParameters(isGenerator | isAsync); - const type = parseReturnType(58 /* ColonToken */ , /*isType*/ false); + const type = parseReturnType(59 /* ColonToken */ , /*isType*/ false); const body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); const node = factory2.createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body); node.exclamationToken = exclamationToken; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parsePropertyDeclaration(pos, hasJSDoc, modifiers, name, questionToken) { - const exclamationToken = !questionToken && !scanner2.hasPrecedingLineBreak() ? parseOptionalToken(53 /* ExclamationToken */ ) : void 0; + const exclamationToken = !questionToken && !scanner2.hasPrecedingLineBreak() ? parseOptionalToken(54 /* ExclamationToken */ ) : void 0; const type = parseTypeAnnotation(); - const initializer = doOutsideOfContext(45056 /* DisallowInContext */ , parseInitializer); + const initializer = doOutsideOfContext(90112 /* DisallowInContext */ , parseInitializer); parseSemicolonAfterPropertyName(name, type, initializer); const node = factory2.createPropertyDeclaration(modifiers, name, questionToken || exclamationToken, type, initializer); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parsePropertyOrMethodDeclaration(pos, hasJSDoc, modifiers) { - const asteriskToken = parseOptionalToken(41 /* AsteriskToken */ ); + const asteriskToken = parseOptionalToken(42 /* AsteriskToken */ ); const name = parsePropertyName(); - const questionToken = parseOptionalToken(57 /* QuestionToken */ ); - if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */ ) return parseMethodDeclaration(pos, hasJSDoc, modifiers, asteriskToken, name, questionToken, /*exclamationToken*/ void 0, Diagnostics.or_expected); + const questionToken = parseOptionalToken(58 /* QuestionToken */ ); + if (asteriskToken || token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */ ) return parseMethodDeclaration(pos, hasJSDoc, modifiers, asteriskToken, name, questionToken, /*exclamationToken*/ void 0, Diagnostics.or_expected); return parsePropertyDeclaration(pos, hasJSDoc, modifiers, name, questionToken); } function parseAccessorDeclaration(pos, hasJSDoc, modifiers, kind, flags) { const name = parsePropertyName(); const typeParameters = parseTypeParameters(); const parameters = parseParameters(0 /* None */ ); - const type = parseReturnType(58 /* ColonToken */ , /*isType*/ false); + const type = parseReturnType(59 /* ColonToken */ , /*isType*/ false); const body = parseFunctionBlockOrSemicolon(flags); - const node = kind === 174 /* GetAccessor */ ? factory2.createGetAccessorDeclaration(modifiers, name, parameters, type, body) : factory2.createSetAccessorDeclaration(modifiers, name, parameters, body); + const node = kind === 177 /* GetAccessor */ ? factory2.createGetAccessorDeclaration(modifiers, name, parameters, type, body) : factory2.createSetAccessorDeclaration(modifiers, name, parameters, body); node.typeParameters = typeParameters; if (isSetAccessorDeclaration(node)) node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); } function isClassMemberStart() { let idToken; - if (token() === 59 /* AtToken */ ) return true; + if (token() === 60 /* AtToken */ ) return true; while(isModifierKind(token())){ idToken = token(); if (isClassMemberModifier(idToken)) return true; nextToken(); } - if (token() === 41 /* AsteriskToken */ ) return true; + if (token() === 42 /* AsteriskToken */ ) return true; if (isLiteralPropertyName()) { idToken = token(); nextToken(); } - if (token() === 22 /* OpenBracketToken */ ) return true; + if (token() === 23 /* OpenBracketToken */ ) return true; if (idToken !== void 0) { - if (!isKeyword(idToken) || idToken === 151 /* SetKeyword */ || idToken === 137 /* GetKeyword */ ) return true; + if (!isKeyword(idToken) || idToken === 153 /* SetKeyword */ || idToken === 139 /* GetKeyword */ ) return true; switch(token()){ - case 20 /* OpenParenToken */ : - case 29 /* LessThanToken */ : - case 53 /* ExclamationToken */ : - case 58 /* ColonToken */ : - case 63 /* EqualsToken */ : - case 57 /* QuestionToken */ : + case 21 /* OpenParenToken */ : + case 30 /* LessThanToken */ : + case 54 /* ExclamationToken */ : + case 59 /* ColonToken */ : + case 64 /* EqualsToken */ : + case 58 /* QuestionToken */ : return true; default: return canParseSemicolon(); @@ -34169,7 +34510,7 @@ ${lanes.join("\n")} return false; } function parseClassStaticBlockDeclaration(pos, hasJSDoc, modifiers) { - parseExpectedToken(124 /* StaticKeyword */ ); + parseExpectedToken(126 /* StaticKeyword */ ); const body = parseClassStaticBlockBody(); const node = withJSDoc(finishNode(factory2.createClassStaticBlockDeclaration(body), pos), hasJSDoc); node.modifiers = modifiers; @@ -34186,7 +34527,7 @@ ${lanes.join("\n")} return body; } function parseDecoratorExpression() { - if (inAwaitContext() && token() === 133 /* AwaitKeyword */ ) { + if (inAwaitContext() && token() === 135 /* AwaitKeyword */ ) { const pos = getNodePos(); const awaitExpression = parseIdentifier(Diagnostics.Expression_expected); nextToken(); @@ -34197,17 +34538,17 @@ ${lanes.join("\n")} } function tryParseDecorator() { const pos = getNodePos(); - if (!parseOptional(59 /* AtToken */ )) return void 0; + if (!parseOptional(60 /* AtToken */ )) return void 0; const expression = doInDecoratorContext(parseDecoratorExpression); return finishNode(factory2.createDecorator(expression), pos); } function tryParseModifier(hasSeenStaticModifier, permitConstAsModifier, stopOnStartOfClassStaticBlock) { const pos = getNodePos(); const kind = token(); - if (token() === 85 /* ConstKeyword */ && permitConstAsModifier) { + if (token() === 87 /* ConstKeyword */ && permitConstAsModifier) { if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) return void 0; - } else if (stopOnStartOfClassStaticBlock && token() === 124 /* StaticKeyword */ && lookAhead(nextTokenIsOpenBrace)) return void 0; - else if (hasSeenStaticModifier && token() === 124 /* StaticKeyword */ ) return void 0; + } else if (stopOnStartOfClassStaticBlock && token() === 126 /* StaticKeyword */ && lookAhead(nextTokenIsOpenBrace)) return void 0; + else if (hasSeenStaticModifier && token() === 126 /* StaticKeyword */ ) return void 0; else { if (!parseAnyContextualModifier()) return void 0; } @@ -34217,28 +34558,28 @@ ${lanes.join("\n")} const pos = getNodePos(); let list; let decorator, modifier, hasSeenStaticModifier = false, hasLeadingModifier = false, hasTrailingDecorator = false; - if (allowDecorators && token() === 59 /* AtToken */ ) while(decorator = tryParseDecorator())list = append(list, decorator); + if (allowDecorators && token() === 60 /* AtToken */ ) while(decorator = tryParseDecorator())list = append(list, decorator); while(modifier = tryParseModifier(hasSeenStaticModifier, permitConstAsModifier, stopOnStartOfClassStaticBlock)){ - if (modifier.kind === 124 /* StaticKeyword */ ) hasSeenStaticModifier = true; + if (modifier.kind === 126 /* StaticKeyword */ ) hasSeenStaticModifier = true; list = append(list, modifier); hasLeadingModifier = true; } - if (hasLeadingModifier && allowDecorators && token() === 59 /* AtToken */ ) while(decorator = tryParseDecorator()){ + if (hasLeadingModifier && allowDecorators && token() === 60 /* AtToken */ ) while(decorator = tryParseDecorator()){ list = append(list, decorator); hasTrailingDecorator = true; } if (hasTrailingDecorator) while(modifier = tryParseModifier(hasSeenStaticModifier, permitConstAsModifier, stopOnStartOfClassStaticBlock)){ - if (modifier.kind === 124 /* StaticKeyword */ ) hasSeenStaticModifier = true; + if (modifier.kind === 126 /* StaticKeyword */ ) hasSeenStaticModifier = true; list = append(list, modifier); } return list && createNodeArray(list, pos); } function parseModifiersForArrowFunction() { let modifiers; - if (token() === 132 /* AsyncKeyword */ ) { + if (token() === 134 /* AsyncKeyword */ ) { const pos = getNodePos(); nextToken(); - const modifier = finishNode(factoryCreateToken(132 /* AsyncKeyword */ ), pos); + const modifier = finishNode(factoryCreateToken(134 /* AsyncKeyword */ ), pos); modifiers = createNodeArray([ modifier ], pos); @@ -34247,29 +34588,29 @@ ${lanes.join("\n")} } function parseClassElement() { const pos = getNodePos(); - if (token() === 26 /* SemicolonToken */ ) { + const hasJSDoc = hasPrecedingJSDocComment(); + if (token() === 27 /* SemicolonToken */ ) { nextToken(); - return finishNode(factory2.createSemicolonClassElement(), pos); + return withJSDoc(finishNode(factory2.createSemicolonClassElement(), pos), hasJSDoc); } - const hasJSDoc = hasPrecedingJSDocComment(); const modifiers = parseModifiers(/*allowDecorators*/ true, /*permitConstAsModifier*/ true, /*stopOnStartOfClassStaticBlock*/ true); - if (token() === 124 /* StaticKeyword */ && lookAhead(nextTokenIsOpenBrace)) return parseClassStaticBlockDeclaration(pos, hasJSDoc, modifiers); - if (parseContextualModifier(137 /* GetKeyword */ )) return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 174 /* GetAccessor */ , 0 /* None */ ); - if (parseContextualModifier(151 /* SetKeyword */ )) return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 175 /* SetAccessor */ , 0 /* None */ ); - if (token() === 135 /* ConstructorKeyword */ || token() === 10 /* StringLiteral */ ) { + if (token() === 126 /* StaticKeyword */ && lookAhead(nextTokenIsOpenBrace)) return parseClassStaticBlockDeclaration(pos, hasJSDoc, modifiers); + if (parseContextualModifier(139 /* GetKeyword */ )) return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 177 /* GetAccessor */ , 0 /* None */ ); + if (parseContextualModifier(153 /* SetKeyword */ )) return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 178 /* SetAccessor */ , 0 /* None */ ); + if (token() === 137 /* ConstructorKeyword */ || token() === 11 /* StringLiteral */ ) { const constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, modifiers); if (constructorDeclaration) return constructorDeclaration; } if (isIndexSignature()) return parseIndexSignatureDeclaration(pos, hasJSDoc, modifiers); - if (tokenIsIdentifierOrKeyword(token()) || token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */ || token() === 41 /* AsteriskToken */ || token() === 22 /* OpenBracketToken */ ) { + if (tokenIsIdentifierOrKeyword(token()) || token() === 11 /* StringLiteral */ || token() === 9 /* NumericLiteral */ || token() === 42 /* AsteriskToken */ || token() === 23 /* OpenBracketToken */ ) { const isAmbient = some(modifiers, isDeclareModifier); if (isAmbient) { - for (const m of modifiers)m.flags |= 16777216 /* Ambient */ ; - return doInsideOfContext(16777216 /* Ambient */ , ()=>parsePropertyOrMethodDeclaration(pos, hasJSDoc, modifiers)); + for (const m of modifiers)m.flags |= 33554432 /* Ambient */ ; + return doInsideOfContext(33554432 /* Ambient */ , ()=>parsePropertyOrMethodDeclaration(pos, hasJSDoc, modifiers)); } else return parsePropertyOrMethodDeclaration(pos, hasJSDoc, modifiers); } if (modifiers) { - const name = createMissingNode(79 /* Identifier */ , /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); + const name = createMissingNode(80 /* Identifier */ , /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); return parsePropertyDeclaration(pos, hasJSDoc, modifiers, name, /*questionToken*/ void 0); } return Debug.fail("Should not have attempted to parse class member declaration."); @@ -34278,39 +34619,39 @@ ${lanes.join("\n")} const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); const modifiers = parseModifiers(/*allowDecorators*/ true); - if (token() === 84 /* ClassKeyword */ ) return parseClassDeclarationOrExpression(pos, hasJSDoc, modifiers, 228 /* ClassExpression */ ); - const missing = createMissingNode(279 /* MissingDeclaration */ , /*reportAtCurrentPosition*/ true, Diagnostics.Expression_expected); + if (token() === 86 /* ClassKeyword */ ) return parseClassDeclarationOrExpression(pos, hasJSDoc, modifiers, 231 /* ClassExpression */ ); + const missing = createMissingNode(282 /* MissingDeclaration */ , /*reportAtCurrentPosition*/ true, Diagnostics.Expression_expected); setTextRangePos(missing, pos); missing.modifiers = modifiers; return missing; } function parseClassExpression() { - return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ void 0, 228 /* ClassExpression */ ); + return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ void 0, 231 /* ClassExpression */ ); } function parseClassDeclaration(pos, hasJSDoc, modifiers) { - return parseClassDeclarationOrExpression(pos, hasJSDoc, modifiers, 260 /* ClassDeclaration */ ); + return parseClassDeclarationOrExpression(pos, hasJSDoc, modifiers, 263 /* ClassDeclaration */ ); } function parseClassDeclarationOrExpression(pos, hasJSDoc, modifiers, kind) { const savedAwaitContext = inAwaitContext(); - parseExpected(84 /* ClassKeyword */ ); + parseExpected(86 /* ClassKeyword */ ); const name = parseNameOfClassDeclarationOrExpression(); const typeParameters = parseTypeParameters(); if (some(modifiers, isExportModifier)) setAwaitContext(/*value*/ true); const heritageClauses = parseHeritageClauses(); let members; - if (parseExpected(18 /* OpenBraceToken */ )) { + if (parseExpected(19 /* OpenBraceToken */ )) { members = parseClassMembers(); - parseExpected(19 /* CloseBraceToken */ ); + parseExpected(20 /* CloseBraceToken */ ); } else members = createMissingList(); setAwaitContext(savedAwaitContext); - const node = kind === 260 /* ClassDeclaration */ ? factory2.createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members) : factory2.createClassExpression(modifiers, name, typeParameters, heritageClauses, members); + const node = kind === 263 /* ClassDeclaration */ ? factory2.createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members) : factory2.createClassExpression(modifiers, name, typeParameters, heritageClauses, members); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseNameOfClassDeclarationOrExpression() { return isBindingIdentifier() && !isImplementsClause() ? createIdentifier(isBindingIdentifier()) : void 0; } function isImplementsClause() { - return token() === 117 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); + return token() === 119 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); } function parseHeritageClauses() { if (isHeritageClause2()) return parseList(22 /* HeritageClauses */ , parseHeritageClause); @@ -34319,7 +34660,7 @@ ${lanes.join("\n")} function parseHeritageClause() { const pos = getNodePos(); const tok = token(); - Debug.assert(tok === 94 /* ExtendsKeyword */ || tok === 117 /* ImplementsKeyword */ ); + Debug.assert(tok === 96 /* ExtendsKeyword */ || tok === 119 /* ImplementsKeyword */ ); nextToken(); const types = parseDelimitedList(7 /* HeritageClauseElement */ , parseExpressionWithTypeArguments); return finishNode(factory2.createHeritageClause(tok, types), pos); @@ -34327,21 +34668,21 @@ ${lanes.join("\n")} function parseExpressionWithTypeArguments() { const pos = getNodePos(); const expression = parseLeftHandSideExpressionOrHigher(); - if (expression.kind === 230 /* ExpressionWithTypeArguments */ ) return expression; + if (expression.kind === 233 /* ExpressionWithTypeArguments */ ) return expression; const typeArguments = tryParseTypeArguments(); return finishNode(factory2.createExpressionWithTypeArguments(expression, typeArguments), pos); } function tryParseTypeArguments() { - return token() === 29 /* LessThanToken */ ? parseBracketedList(20 /* TypeArguments */ , parseType, 29 /* LessThanToken */ , 31 /* GreaterThanToken */ ) : void 0; + return token() === 30 /* LessThanToken */ ? parseBracketedList(20 /* TypeArguments */ , parseType, 30 /* LessThanToken */ , 32 /* GreaterThanToken */ ) : void 0; } function isHeritageClause2() { - return token() === 94 /* ExtendsKeyword */ || token() === 117 /* ImplementsKeyword */ ; + return token() === 96 /* ExtendsKeyword */ || token() === 119 /* ImplementsKeyword */ ; } function parseClassMembers() { return parseList(5 /* ClassMembers */ , parseClassElement); } function parseInterfaceDeclaration(pos, hasJSDoc, modifiers) { - parseExpected(118 /* InterfaceKeyword */ ); + parseExpected(120 /* InterfaceKeyword */ ); const name = parseIdentifier(); const typeParameters = parseTypeParameters(); const heritageClauses = parseHeritageClauses(); @@ -34350,11 +34691,12 @@ ${lanes.join("\n")} return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseTypeAliasDeclaration(pos, hasJSDoc, modifiers) { - parseExpected(154 /* TypeKeyword */ ); + parseExpected(156 /* TypeKeyword */ ); + if (scanner2.hasPrecedingLineBreak()) parseErrorAtCurrentToken(Diagnostics.Line_break_not_permitted_here); const name = parseIdentifier(); const typeParameters = parseTypeParameters(); - parseExpected(63 /* EqualsToken */ ); - const type = token() === 139 /* IntrinsicKeyword */ && tryParse(parseKeywordAndNoDot) || parseType(); + parseExpected(64 /* EqualsToken */ ); + const type = token() === 141 /* IntrinsicKeyword */ && tryParse(parseKeywordAndNoDot) || parseType(); parseSemicolon(); const node = factory2.createTypeAliasDeclaration(modifiers, name, typeParameters, type); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -34367,12 +34709,12 @@ ${lanes.join("\n")} return withJSDoc(finishNode(factory2.createEnumMember(name, initializer), pos), hasJSDoc); } function parseEnumDeclaration(pos, hasJSDoc, modifiers) { - parseExpected(92 /* EnumKeyword */ ); + parseExpected(94 /* EnumKeyword */ ); const name = parseIdentifier(); let members; - if (parseExpected(18 /* OpenBraceToken */ )) { + if (parseExpected(19 /* OpenBraceToken */ )) { members = doOutsideOfYieldAndAwaitContext(()=>parseDelimitedList(6 /* EnumMembers */ , parseEnumMember)); - parseExpected(19 /* CloseBraceToken */ ); + parseExpected(20 /* CloseBraceToken */ ); } else members = createMissingList(); const node = factory2.createEnumDeclaration(modifiers, name, members); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -34380,60 +34722,60 @@ ${lanes.join("\n")} function parseModuleBlock() { const pos = getNodePos(); let statements; - if (parseExpected(18 /* OpenBraceToken */ )) { + if (parseExpected(19 /* OpenBraceToken */ )) { statements = parseList(1 /* BlockStatements */ , parseStatement); - parseExpected(19 /* CloseBraceToken */ ); + parseExpected(20 /* CloseBraceToken */ ); } else statements = createMissingList(); return finishNode(factory2.createModuleBlock(statements), pos); } function parseModuleOrNamespaceDeclaration(pos, hasJSDoc, modifiers, flags) { - const namespaceFlag = flags & 16 /* Namespace */ ; + const namespaceFlag = flags & 32 /* Namespace */ ; const name = parseIdentifier(); - const body = parseOptional(24 /* DotToken */ ) ? parseModuleOrNamespaceDeclaration(getNodePos(), /*hasJSDoc*/ false, /*modifiers*/ void 0, 4 /* NestedNamespace */ | namespaceFlag) : parseModuleBlock(); + const body = parseOptional(25 /* DotToken */ ) ? parseModuleOrNamespaceDeclaration(getNodePos(), /*hasJSDoc*/ false, /*modifiers*/ void 0, 8 /* NestedNamespace */ | namespaceFlag) : parseModuleBlock(); const node = factory2.createModuleDeclaration(modifiers, name, body, flags); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseAmbientExternalModuleDeclaration(pos, hasJSDoc, modifiersIn) { let flags = 0; let name; - if (token() === 159 /* GlobalKeyword */ ) { + if (token() === 162 /* GlobalKeyword */ ) { name = parseIdentifier(); - flags |= 1024 /* GlobalAugmentation */ ; + flags |= 2048 /* GlobalAugmentation */ ; } else { name = parseLiteralNode(); name.text = internIdentifier(name.text); } let body; - if (token() === 18 /* OpenBraceToken */ ) body = parseModuleBlock(); + if (token() === 19 /* OpenBraceToken */ ) body = parseModuleBlock(); else parseSemicolon(); const node = factory2.createModuleDeclaration(modifiersIn, name, body, flags); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseModuleDeclaration(pos, hasJSDoc, modifiersIn) { let flags = 0; - if (token() === 159 /* GlobalKeyword */ ) return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, modifiersIn); - else if (parseOptional(143 /* NamespaceKeyword */ )) flags |= 16 /* Namespace */ ; + if (token() === 162 /* GlobalKeyword */ ) return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, modifiersIn); + else if (parseOptional(145 /* NamespaceKeyword */ )) flags |= 32 /* Namespace */ ; else { - parseExpected(142 /* ModuleKeyword */ ); - if (token() === 10 /* StringLiteral */ ) return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, modifiersIn); + parseExpected(144 /* ModuleKeyword */ ); + if (token() === 11 /* StringLiteral */ ) return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, modifiersIn); } return parseModuleOrNamespaceDeclaration(pos, hasJSDoc, modifiersIn, flags); } function isExternalModuleReference2() { - return token() === 147 /* RequireKeyword */ && lookAhead(nextTokenIsOpenParen); + return token() === 149 /* RequireKeyword */ && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { - return nextToken() === 20 /* OpenParenToken */ ; + return nextToken() === 21 /* OpenParenToken */ ; } function nextTokenIsOpenBrace() { - return nextToken() === 18 /* OpenBraceToken */ ; + return nextToken() === 19 /* OpenBraceToken */ ; } function nextTokenIsSlash() { - return nextToken() === 43 /* SlashToken */ ; + return nextToken() === 44 /* SlashToken */ ; } function parseNamespaceExportDeclaration(pos, hasJSDoc, modifiers) { - parseExpected(128 /* AsKeyword */ ); - parseExpected(143 /* NamespaceKeyword */ ); + parseExpected(130 /* AsKeyword */ ); + parseExpected(145 /* NamespaceKeyword */ ); const name = parseIdentifier(); parseSemicolon(); const node = factory2.createNamespaceExportDeclaration(name); @@ -34441,45 +34783,45 @@ ${lanes.join("\n")} return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseImportDeclarationOrImportEqualsDeclaration(pos, hasJSDoc, modifiers) { - parseExpected(100 /* ImportKeyword */ ); - const afterImportPos = scanner2.getStartPos(); + parseExpected(102 /* ImportKeyword */ ); + const afterImportPos = scanner2.getTokenFullStart(); let identifier; if (isIdentifier2()) identifier = parseIdentifier(); let isTypeOnly = false; - if (token() !== 158 /* FromKeyword */ && (identifier == null ? void 0 : identifier.escapedText) === "type" && (isIdentifier2() || tokenAfterImportDefinitelyProducesImportDeclaration())) { + if (token() !== 161 /* FromKeyword */ && (identifier == null ? void 0 : identifier.escapedText) === "type" && (isIdentifier2() || tokenAfterImportDefinitelyProducesImportDeclaration())) { isTypeOnly = true; identifier = isIdentifier2() ? parseIdentifier() : void 0; } if (identifier && !tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration()) return parseImportEqualsDeclaration(pos, hasJSDoc, modifiers, identifier, isTypeOnly); let importClause; if (identifier || // import id - token() === 41 /* AsteriskToken */ || // import * - token() === 18 /* OpenBraceToken */ ) { + token() === 42 /* AsteriskToken */ || // import * + token() === 19 /* OpenBraceToken */ ) { importClause = parseImportClause(identifier, afterImportPos, isTypeOnly); - parseExpected(158 /* FromKeyword */ ); + parseExpected(161 /* FromKeyword */ ); } const moduleSpecifier = parseModuleSpecifier(); let assertClause; - if (token() === 130 /* AssertKeyword */ && !scanner2.hasPrecedingLineBreak()) assertClause = parseAssertClause(); + if (token() === 132 /* AssertKeyword */ && !scanner2.hasPrecedingLineBreak()) assertClause = parseAssertClause(); parseSemicolon(); const node = factory2.createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseAssertEntry() { const pos = getNodePos(); - const name = tokenIsIdentifierOrKeyword(token()) ? parseIdentifierName() : parseLiteralLikeNode(10 /* StringLiteral */ ); - parseExpected(58 /* ColonToken */ ); + const name = tokenIsIdentifierOrKeyword(token()) ? parseIdentifierName() : parseLiteralLikeNode(11 /* StringLiteral */ ); + parseExpected(59 /* ColonToken */ ); const value1 = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); return finishNode(factory2.createAssertEntry(name, value1), pos); } function parseAssertClause(skipAssertKeyword) { const pos = getNodePos(); - if (!skipAssertKeyword) parseExpected(130 /* AssertKeyword */ ); - const openBracePosition = scanner2.getTokenPos(); - if (parseExpected(18 /* OpenBraceToken */ )) { + if (!skipAssertKeyword) parseExpected(132 /* AssertKeyword */ ); + const openBracePosition = scanner2.getTokenStart(); + if (parseExpected(19 /* OpenBraceToken */ )) { const multiLine = scanner2.hasPrecedingLineBreak(); const elements = parseDelimitedList(24 /* AssertEntries */ , parseAssertEntry, /*considerSemicolonAsDelimiter*/ true); - if (!parseExpected(19 /* CloseBraceToken */ )) { + if (!parseExpected(20 /* 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_1_to_match_the_0_token_here, "{", "}")); } @@ -34490,13 +34832,13 @@ ${lanes.join("\n")} } } function tokenAfterImportDefinitelyProducesImportDeclaration() { - return token() === 41 /* AsteriskToken */ || token() === 18 /* OpenBraceToken */ ; + return token() === 42 /* AsteriskToken */ || token() === 19 /* OpenBraceToken */ ; } function tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() { - return token() === 27 /* CommaToken */ || token() === 158 /* FromKeyword */ ; + return token() === 28 /* CommaToken */ || token() === 161 /* FromKeyword */ ; } function parseImportEqualsDeclaration(pos, hasJSDoc, modifiers, identifier, isTypeOnly) { - parseExpected(63 /* EqualsToken */ ); + parseExpected(64 /* EqualsToken */ ); const moduleReference = parseModuleReference(); parseSemicolon(); const node = factory2.createImportEqualsDeclaration(modifiers, isTypeOnly, identifier, moduleReference); @@ -34505,7 +34847,7 @@ ${lanes.join("\n")} } function parseImportClause(identifier, pos, isTypeOnly) { let namedBindings; - if (!identifier || parseOptional(27 /* CommaToken */ )) namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(272 /* NamedImports */ ); + if (!identifier || parseOptional(28 /* CommaToken */ )) namedBindings = token() === 42 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(275 /* NamedImports */ ); return finishNode(factory2.createImportClause(isTypeOnly, identifier, namedBindings), pos); } function parseModuleReference() { @@ -34513,14 +34855,14 @@ ${lanes.join("\n")} } function parseExternalModuleReference() { const pos = getNodePos(); - parseExpected(147 /* RequireKeyword */ ); - parseExpected(20 /* OpenParenToken */ ); + parseExpected(149 /* RequireKeyword */ ); + parseExpected(21 /* OpenParenToken */ ); const expression = parseModuleSpecifier(); - parseExpected(21 /* CloseParenToken */ ); + parseExpected(22 /* CloseParenToken */ ); return finishNode(factory2.createExternalModuleReference(expression), pos); } function parseModuleSpecifier() { - if (token() === 10 /* StringLiteral */ ) { + if (token() === 11 /* StringLiteral */ ) { const result = parseLiteralNode(); result.text = internIdentifier(result.text); return result; @@ -34528,36 +34870,36 @@ ${lanes.join("\n")} } function parseNamespaceImport() { const pos = getNodePos(); - parseExpected(41 /* AsteriskToken */ ); - parseExpected(128 /* AsKeyword */ ); + parseExpected(42 /* AsteriskToken */ ); + parseExpected(130 /* AsKeyword */ ); const name = parseIdentifier(); return finishNode(factory2.createNamespaceImport(name), pos); } function parseNamedImportsOrExports(kind) { const pos = getNodePos(); - const node = kind === 272 /* NamedImports */ ? factory2.createNamedImports(parseBracketedList(23 /* ImportOrExportSpecifiers */ , parseImportSpecifier, 18 /* OpenBraceToken */ , 19 /* CloseBraceToken */ )) : factory2.createNamedExports(parseBracketedList(23 /* ImportOrExportSpecifiers */ , parseExportSpecifier, 18 /* OpenBraceToken */ , 19 /* CloseBraceToken */ )); + const node = kind === 275 /* NamedImports */ ? factory2.createNamedImports(parseBracketedList(23 /* ImportOrExportSpecifiers */ , parseImportSpecifier, 19 /* OpenBraceToken */ , 20 /* CloseBraceToken */ )) : factory2.createNamedExports(parseBracketedList(23 /* ImportOrExportSpecifiers */ , parseExportSpecifier, 19 /* OpenBraceToken */ , 20 /* CloseBraceToken */ )); return finishNode(node, pos); } function parseExportSpecifier() { const hasJSDoc = hasPrecedingJSDocComment(); - return withJSDoc(parseImportOrExportSpecifier(278 /* ExportSpecifier */ ), hasJSDoc); + return withJSDoc(parseImportOrExportSpecifier(281 /* ExportSpecifier */ ), hasJSDoc); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(273 /* ImportSpecifier */ ); + return parseImportOrExportSpecifier(276 /* ImportSpecifier */ ); } function parseImportOrExportSpecifier(kind) { const pos = getNodePos(); let checkIdentifierIsKeyword = isKeyword(token()) && !isIdentifier2(); - let checkIdentifierStart = scanner2.getTokenPos(); - let checkIdentifierEnd = scanner2.getTextPos(); + let checkIdentifierStart = scanner2.getTokenStart(); + let checkIdentifierEnd = scanner2.getTokenEnd(); let isTypeOnly = false; let propertyName; let canParseAsKeyword = true; let name = parseIdentifierName(); if (name.escapedText === "type") { - if (token() === 128 /* AsKeyword */ ) { + if (token() === 130 /* AsKeyword */ ) { const firstAs = parseIdentifierName(); - if (token() === 128 /* AsKeyword */ ) { + if (token() === 130 /* AsKeyword */ ) { const secondAs = parseIdentifierName(); if (tokenIsIdentifierOrKeyword(token())) { isTypeOnly = true; @@ -34582,18 +34924,18 @@ ${lanes.join("\n")} name = parseNameWithKeywordCheck(); } } - if (canParseAsKeyword && token() === 128 /* AsKeyword */ ) { + if (canParseAsKeyword && token() === 130 /* AsKeyword */ ) { propertyName = name; - parseExpected(128 /* AsKeyword */ ); + parseExpected(130 /* AsKeyword */ ); name = parseNameWithKeywordCheck(); } - if (kind === 273 /* ImportSpecifier */ && checkIdentifierIsKeyword) parseErrorAt(checkIdentifierStart, checkIdentifierEnd, Diagnostics.Identifier_expected); - const node = kind === 273 /* ImportSpecifier */ ? factory2.createImportSpecifier(isTypeOnly, propertyName, name) : factory2.createExportSpecifier(isTypeOnly, propertyName, name); + if (kind === 276 /* ImportSpecifier */ && checkIdentifierIsKeyword) parseErrorAt(checkIdentifierStart, checkIdentifierEnd, Diagnostics.Identifier_expected); + const node = kind === 276 /* ImportSpecifier */ ? factory2.createImportSpecifier(isTypeOnly, propertyName, name) : factory2.createExportSpecifier(isTypeOnly, propertyName, name); return finishNode(node, pos); function parseNameWithKeywordCheck() { checkIdentifierIsKeyword = isKeyword(token()) && !isIdentifier2(); - checkIdentifierStart = scanner2.getTokenPos(); - checkIdentifierEnd = scanner2.getTextPos(); + checkIdentifierStart = scanner2.getTokenStart(); + checkIdentifierEnd = scanner2.getTokenEnd(); return parseIdentifierName(); } } @@ -34606,20 +34948,20 @@ ${lanes.join("\n")} let exportClause; let moduleSpecifier; let assertClause; - const isTypeOnly = parseOptional(154 /* TypeKeyword */ ); + const isTypeOnly = parseOptional(156 /* TypeKeyword */ ); const namespaceExportPos = getNodePos(); - if (parseOptional(41 /* AsteriskToken */ )) { - if (parseOptional(128 /* AsKeyword */ )) exportClause = parseNamespaceExport(namespaceExportPos); - parseExpected(158 /* FromKeyword */ ); + if (parseOptional(42 /* AsteriskToken */ )) { + if (parseOptional(130 /* AsKeyword */ )) exportClause = parseNamespaceExport(namespaceExportPos); + parseExpected(161 /* FromKeyword */ ); moduleSpecifier = parseModuleSpecifier(); } else { - exportClause = parseNamedImportsOrExports(276 /* NamedExports */ ); - if (token() === 158 /* FromKeyword */ || token() === 10 /* StringLiteral */ && !scanner2.hasPrecedingLineBreak()) { - parseExpected(158 /* FromKeyword */ ); + exportClause = parseNamedImportsOrExports(279 /* NamedExports */ ); + if (token() === 161 /* FromKeyword */ || token() === 11 /* StringLiteral */ && !scanner2.hasPrecedingLineBreak()) { + parseExpected(161 /* FromKeyword */ ); moduleSpecifier = parseModuleSpecifier(); } } - if (moduleSpecifier && token() === 130 /* AssertKeyword */ && !scanner2.hasPrecedingLineBreak()) assertClause = parseAssertClause(); + if (moduleSpecifier && token() === 132 /* AssertKeyword */ && !scanner2.hasPrecedingLineBreak()) assertClause = parseAssertClause(); parseSemicolon(); setAwaitContext(savedAwaitContext); const node = factory2.createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); @@ -34629,8 +34971,8 @@ ${lanes.join("\n")} const savedAwaitContext = inAwaitContext(); setAwaitContext(/*value*/ true); let isExportEquals; - if (parseOptional(63 /* EqualsToken */ )) isExportEquals = true; - else parseExpected(88 /* DefaultKeyword */ ); + if (parseOptional(64 /* EqualsToken */ )) isExportEquals = true; + else parseExpected(90 /* DefaultKeyword */ ); const expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); parseSemicolon(); setAwaitContext(savedAwaitContext); @@ -34664,7 +35006,8 @@ ${lanes.join("\n")} ParsingContext2[ParsingContext2["HeritageClauses"] = 22] = "HeritageClauses"; ParsingContext2[ParsingContext2["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers"; ParsingContext2[ParsingContext2["AssertEntries"] = 24] = "AssertEntries"; - ParsingContext2[ParsingContext2["Count"] = 25] = "Count"; + ParsingContext2[ParsingContext2["JSDocComment"] = 25] = "JSDocComment"; + ParsingContext2[ParsingContext2["Count"] = 26] = "Count"; })(ParsingContext || (ParsingContext = {})); let Tristate; ((Tristate2)=>{ @@ -34675,7 +35018,7 @@ ${lanes.join("\n")} let JSDocParser; ((JSDocParser2)=>{ function parseJSDocTypeExpressionForTests2(content, start, length2) { - initializeState("file.js", content, 99 /* Latest */ , /*_syntaxCursor:*/ void 0, 1 /* JS */ ); + initializeState("file.js", content, 99 /* Latest */ , /*syntaxCursor*/ void 0, 1 /* JS */ ); scanner2.setText(content, start, length2); currentToken = scanner2.scan(); const jsDocTypeExpression = parseJSDocTypeExpression(); @@ -34691,9 +35034,9 @@ ${lanes.join("\n")} JSDocParser2.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests2; function parseJSDocTypeExpression(mayOmitBraces) { const pos = getNodePos(); - const hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */ ); - const type = doInsideOfContext(8388608 /* JSDoc */ , parseJSDocType); - if (!mayOmitBraces || hasBrace) parseExpectedJSDoc(19 /* CloseBraceToken */ ); + const hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(19 /* OpenBraceToken */ ); + const type = doInsideOfContext(16777216 /* JSDoc */ , parseJSDocType); + if (!mayOmitBraces || hasBrace) parseExpectedJSDoc(20 /* CloseBraceToken */ ); const result = factory2.createJSDocTypeExpression(type); fixupParentReferences(result); return finishNode(result, pos); @@ -34701,23 +35044,23 @@ ${lanes.join("\n")} JSDocParser2.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseJSDocNameReference() { const pos = getNodePos(); - const hasBrace = parseOptional(18 /* OpenBraceToken */ ); + const hasBrace = parseOptional(19 /* OpenBraceToken */ ); const p2 = getNodePos(); - let entityName = parseEntityName(/* allowReservedWords*/ false); - while(token() === 80 /* PrivateIdentifier */ ){ + let entityName = parseEntityName(/*allowReservedWords*/ false); + while(token() === 81 /* PrivateIdentifier */ ){ reScanHashToken(); nextTokenJSDoc(); entityName = finishNode(factory2.createJSDocMemberName(entityName, parseIdentifier()), p2); } - if (hasBrace) parseExpectedJSDoc(19 /* CloseBraceToken */ ); + if (hasBrace) parseExpectedJSDoc(20 /* CloseBraceToken */ ); const result = factory2.createJSDocNameReference(entityName); fixupParentReferences(result); return finishNode(result, pos); } JSDocParser2.parseJSDocNameReference = parseJSDocNameReference; function parseIsolatedJSDocComment2(content, start, length2) { - initializeState("", content, 99 /* Latest */ , /*_syntaxCursor:*/ void 0, 1 /* JS */ ); - const jsDoc = doInsideOfContext(8388608 /* JSDoc */ , ()=>parseJSDocCommentWorker(start, length2)); + initializeState("", content, 99 /* Latest */ , /*syntaxCursor*/ void 0, 1 /* JS */ ); + const jsDoc = doInsideOfContext(16777216 /* JSDoc */ , ()=>parseJSDocCommentWorker(start, length2)); const sourceFile = { languageVariant: 0 /* Standard */ , text: content @@ -34734,9 +35077,9 @@ ${lanes.join("\n")} const saveToken = currentToken; const saveParseDiagnosticsLength = parseDiagnostics.length; const saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; - const comment = doInsideOfContext(8388608 /* JSDoc */ , ()=>parseJSDocCommentWorker(start, length2)); + const comment = doInsideOfContext(16777216 /* JSDoc */ , ()=>parseJSDocCommentWorker(start, length2)); setParent(comment, parent2); - if (contextFlags & 262144 /* JavaScriptFile */ ) { + if (contextFlags & 524288 /* JavaScriptFile */ ) { if (!jsDocDiagnostics) jsDocDiagnostics = []; jsDocDiagnostics.push(...parseDiagnostics); } @@ -34760,6 +35103,8 @@ ${lanes.join("\n")} PropertyLikeParse2[PropertyLikeParse2["CallbackParameter"] = 4] = "CallbackParameter"; })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start = 0, length2) { + const saveParsingContext = parsingContext; + parsingContext |= 33554432 /* JSDocComment */ ; const content = sourceText; const end = length2 === void 0 ? content.length : start + length2; length2 = end - start; @@ -34774,7 +35119,10 @@ ${lanes.join("\n")} let commentsPos; let comments = []; const parts = []; - return scanner2.scanRange(start + 3, length2 - 5, ()=>{ + const result = scanner2.scanRange(start + 3, length2 - 5, doJSDocScan); + parsingContext = saveParsingContext; + return result; + function doJSDocScan() { let state = 1 /* SawAsterisk */ ; let margin; let indent2 = start - (content.lastIndexOf("\n", start) + 1) + 4; @@ -34791,49 +35139,52 @@ ${lanes.join("\n")} } loop: while(true){ switch(token()){ - case 59 /* AtToken */ : - if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */ ) { - removeTrailingWhitespace(comments); - if (!commentsPos) commentsPos = getNodePos(); - addTag(parseTag(indent2)); - state = 0 /* BeginningOfLine */ ; - margin = void 0; - } else pushComment(scanner2.getTokenText()); + case 60 /* AtToken */ : + removeTrailingWhitespace(comments); + if (!commentsPos) commentsPos = getNodePos(); + addTag(parseTag(indent2)); + state = 0 /* BeginningOfLine */ ; + margin = void 0; break; case 4 /* NewLineTrivia */ : comments.push(scanner2.getTokenText()); state = 0 /* BeginningOfLine */ ; indent2 = 0; break; - case 41 /* AsteriskToken */ : + case 42 /* AsteriskToken */ : const asterisk = scanner2.getTokenText(); - if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */ ) { + if (state === 1 /* SawAsterisk */ ) { state = 2 /* SavingComments */ ; pushComment(asterisk); } else { + Debug.assert(state === 0 /* BeginningOfLine */ ); state = 1 /* SawAsterisk */ ; indent2 += asterisk.length; } break; case 5 /* WhitespaceTrivia */ : + Debug.assert(state !== 2 /* SavingComments */ , "whitespace shouldn't come from the scanner while saving top-level comment text"); const whitespace = scanner2.getTokenText(); - if (state === 2 /* SavingComments */ ) comments.push(whitespace); - else if (margin !== void 0 && indent2 + whitespace.length > margin) comments.push(whitespace.slice(margin - indent2)); + if (margin !== void 0 && indent2 + whitespace.length > margin) comments.push(whitespace.slice(margin - indent2)); indent2 += whitespace.length; break; case 1 /* EndOfFileToken */ : break loop; - case 18 /* OpenBraceToken */ : + case 82 /* JSDocCommentTextToken */ : + state = 2 /* SavingComments */ ; + pushComment(scanner2.getTokenValue()); + break; + case 19 /* OpenBraceToken */ : state = 2 /* SavingComments */ ; - const commentEnd = scanner2.getStartPos(); - const linkStart = scanner2.getTextPos() - 1; + const commentEnd = scanner2.getTokenFullStart(); + const linkStart = scanner2.getTokenEnd() - 1; const link = parseJSDocLink(linkStart); if (link) { if (!linkEnd) removeLeadingNewlines(comments); - parts.push(finishNode(factory2.createJSDocText(comments.join("")), linkEnd != null ? linkEnd : start, commentEnd)); + parts.push(finishNode(factory2.createJSDocText(comments.join("")), linkEnd ?? start, commentEnd)); parts.push(link); comments = []; - linkEnd = scanner2.getTextPos(); + linkEnd = scanner2.getTokenEnd(); break; } default: @@ -34841,19 +35192,27 @@ ${lanes.join("\n")} pushComment(scanner2.getTokenText()); break; } - nextTokenJSDoc(); + if (state === 2 /* SavingComments */ ) nextJSDocCommentTextToken(/*inBackticks*/ false); + else nextTokenJSDoc(); } - removeTrailingWhitespace(comments); - if (parts.length && comments.length) parts.push(finishNode(factory2.createJSDocText(comments.join("")), linkEnd != null ? linkEnd : start, commentsPos)); + const trimmedComments = trimStringEnd(comments.join("")); + if (parts.length && trimmedComments.length) parts.push(finishNode(factory2.createJSDocText(trimmedComments), linkEnd ?? start, commentsPos)); if (parts.length && tags) Debug.assertIsDefined(commentsPos, "having parsed tags implies that the end of the comment span should be set"); const tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); - return finishNode(factory2.createJSDocComment(parts.length ? createNodeArray(parts, start, commentsPos) : comments.length ? comments.join("") : void 0, tagsArray), start, end); - }); + return finishNode(factory2.createJSDocComment(parts.length ? createNodeArray(parts, start, commentsPos) : trimmedComments.length ? trimmedComments : void 0, tagsArray), start, end); + } function removeLeadingNewlines(comments2) { while(comments2.length && (comments2[0] === "\n" || comments2[0] === "\r"))comments2.shift(); } function removeTrailingWhitespace(comments2) { - while(comments2.length && comments2[comments2.length - 1].trim() === "")comments2.pop(); + while(comments2.length){ + const trimmed = trimStringEnd(comments2[comments2.length - 1]); + if (trimmed === "") comments2.pop(); + else if (trimmed.length < comments2[comments2.length - 1].length) { + comments2[comments2.length - 1] = trimmed; + break; + } else break; + } } function isNextNonwhitespaceTokenEndOfFile() { while(true){ @@ -34875,20 +35234,20 @@ ${lanes.join("\n")} let precedingLineBreak = scanner2.hasPrecedingLineBreak(); let seenLineBreak = false; let indentText = ""; - while(precedingLineBreak && token() === 41 /* AsteriskToken */ || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */ ){ + while(precedingLineBreak && token() === 42 /* AsteriskToken */ || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */ ){ indentText += scanner2.getTokenText(); if (token() === 4 /* NewLineTrivia */ ) { precedingLineBreak = true; seenLineBreak = true; indentText = ""; - } else if (token() === 41 /* AsteriskToken */ ) precedingLineBreak = false; + } else if (token() === 42 /* AsteriskToken */ ) precedingLineBreak = false; nextTokenJSDoc(); } return seenLineBreak ? indentText : ""; } function parseTag(margin) { - Debug.assert(token() === 59 /* AtToken */ ); - const start2 = scanner2.getTokenPos(); + Debug.assert(token() === 60 /* AtToken */ ); + const start2 = scanner2.getTokenStart(); nextTokenJSDoc(); const tagName = parseJSDocIdentifierName(/*message*/ void 0); const indentText = skipWhitespaceOrAsterisk(); @@ -34982,7 +35341,6 @@ ${lanes.join("\n")} const parts2 = []; let linkEnd2; let state = 0 /* BeginningOfLine */ ; - let previousWhitespace = true; let margin; function pushComment(text) { if (!margin) margin = indent2; @@ -35001,40 +35359,42 @@ ${lanes.join("\n")} comments2.push(scanner2.getTokenText()); indent2 = 0; break; - case 59 /* AtToken */ : - if (state === 3 /* SavingBackticks */ || state === 2 /* SavingComments */ && (!previousWhitespace || lookAhead(isNextJSDocTokenWhitespace))) { - comments2.push(scanner2.getTokenText()); - break; - } - scanner2.setTextPos(scanner2.getTextPos() - 1); + case 60 /* AtToken */ : + scanner2.resetTokenState(scanner2.getTokenEnd() - 1); + break loop; case 1 /* EndOfFileToken */ : break loop; case 5 /* WhitespaceTrivia */ : - if (state === 2 /* SavingComments */ || state === 3 /* SavingBackticks */ ) pushComment(scanner2.getTokenText()); - else { - const whitespace = scanner2.getTokenText(); - if (margin !== void 0 && indent2 + whitespace.length > margin) comments2.push(whitespace.slice(margin - indent2)); - indent2 += whitespace.length; + Debug.assert(state !== 2 /* SavingComments */ && state !== 3 /* SavingBackticks */ , "whitespace shouldn't come from the scanner while saving comment text"); + const whitespace = scanner2.getTokenText(); + if (margin !== void 0 && indent2 + whitespace.length > margin) { + comments2.push(whitespace.slice(margin - indent2)); + state = 2 /* SavingComments */ ; } + indent2 += whitespace.length; break; - case 18 /* OpenBraceToken */ : + case 19 /* OpenBraceToken */ : state = 2 /* SavingComments */ ; - const commentEnd = scanner2.getStartPos(); - const linkStart = scanner2.getTextPos() - 1; + const commentEnd = scanner2.getTokenFullStart(); + const linkStart = scanner2.getTokenEnd() - 1; const link = parseJSDocLink(linkStart); if (link) { - parts2.push(finishNode(factory2.createJSDocText(comments2.join("")), linkEnd2 != null ? linkEnd2 : commentsPos2, commentEnd)); + parts2.push(finishNode(factory2.createJSDocText(comments2.join("")), linkEnd2 ?? commentsPos2, commentEnd)); parts2.push(link); comments2 = []; - linkEnd2 = scanner2.getTextPos(); + linkEnd2 = scanner2.getTokenEnd(); } else pushComment(scanner2.getTokenText()); break; - case 61 /* BacktickToken */ : + case 62 /* BacktickToken */ : if (state === 3 /* SavingBackticks */ ) state = 2 /* SavingComments */ ; else state = 3 /* SavingBackticks */ ; pushComment(scanner2.getTokenText()); break; - case 41 /* AsteriskToken */ : + case 82 /* JSDocCommentTextToken */ : + if (state !== 3 /* SavingBackticks */ ) state = 2 /* SavingComments */ ; + pushComment(scanner2.getTokenValue()); + break; + case 42 /* AsteriskToken */ : if (state === 0 /* BeginningOfLine */ ) { state = 1 /* SawAsterisk */ ; indent2 += 1; @@ -35045,19 +35405,15 @@ ${lanes.join("\n")} pushComment(scanner2.getTokenText()); break; } - previousWhitespace = token() === 5 /* WhitespaceTrivia */ ; - tok = nextTokenJSDoc(); + if (state === 2 /* SavingComments */ || state === 3 /* SavingBackticks */ ) tok = nextJSDocCommentTextToken(state === 3 /* SavingBackticks */ ); + else tok = nextTokenJSDoc(); } removeLeadingNewlines(comments2); - removeTrailingWhitespace(comments2); + const trimmedComments = trimStringEnd(comments2.join("")); if (parts2.length) { - if (comments2.length) parts2.push(finishNode(factory2.createJSDocText(comments2.join("")), linkEnd2 != null ? linkEnd2 : commentsPos2)); - return createNodeArray(parts2, commentsPos2, scanner2.getTextPos()); - } else if (comments2.length) return comments2.join(""); - } - function isNextJSDocTokenWhitespace() { - const next = nextTokenJSDoc(); - return next === 5 /* WhitespaceTrivia */ || next === 4 /* NewLineTrivia */ ; + if (trimmedComments.length) parts2.push(finishNode(factory2.createJSDocText(trimmedComments), linkEnd2 ?? commentsPos2)); + return createNodeArray(parts2, commentsPos2, scanner2.getTokenEnd()); + } else if (trimmedComments.length) return trimmedComments; } function parseJSDocLink(start2) { const linkType = tryParse(parseJSDocLinkPrefix); @@ -35066,22 +35422,22 @@ ${lanes.join("\n")} skipWhitespace(); const p2 = getNodePos(); let name = tokenIsIdentifierOrKeyword(token()) ? parseEntityName(/*allowReservedWords*/ true) : void 0; - if (name) while(token() === 80 /* PrivateIdentifier */ ){ + if (name) while(token() === 81 /* PrivateIdentifier */ ){ reScanHashToken(); nextTokenJSDoc(); name = finishNode(factory2.createJSDocMemberName(name, parseIdentifier()), p2); } const text = []; - while(token() !== 19 /* CloseBraceToken */ && token() !== 4 /* NewLineTrivia */ && token() !== 1 /* EndOfFileToken */ ){ + while(token() !== 20 /* CloseBraceToken */ && token() !== 4 /* NewLineTrivia */ && token() !== 1 /* EndOfFileToken */ ){ text.push(scanner2.getTokenText()); nextTokenJSDoc(); } const create = linkType === "link" ? factory2.createJSDocLink : linkType === "linkcode" ? factory2.createJSDocLinkCode : factory2.createJSDocLinkPlain; - return finishNode(create(name, text.join("")), start2, scanner2.getTextPos()); + return finishNode(create(name, text.join("")), start2, scanner2.getTokenEnd()); } function parseJSDocLinkPrefix() { skipWhitespaceOrAsterisk(); - if (token() === 18 /* OpenBraceToken */ && nextTokenJSDoc() === 59 /* AtToken */ && tokenIsIdentifierOrKeyword(nextTokenJSDoc())) { + if (token() === 19 /* OpenBraceToken */ && nextTokenJSDoc() === 60 /* AtToken */ && tokenIsIdentifierOrKeyword(nextTokenJSDoc())) { const kind = scanner2.getTokenValue(); if (isJSDocLinkTag(kind)) return kind; } @@ -35104,18 +35460,18 @@ ${lanes.join("\n")} } function tryParseTypeExpression() { skipWhitespaceOrAsterisk(); - return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : void 0; + return token() === 19 /* OpenBraceToken */ ? parseJSDocTypeExpression() : void 0; } function parseBracketNameInPropertyAndParamTag() { - const isBracketed = parseOptionalJsdoc(22 /* OpenBracketToken */ ); + const isBracketed = parseOptionalJsdoc(23 /* OpenBracketToken */ ); if (isBracketed) skipWhitespace(); - const isBackquoted = parseOptionalJsdoc(61 /* BacktickToken */ ); + const isBackquoted = parseOptionalJsdoc(62 /* BacktickToken */ ); const name = parseJSDocEntityName(); - if (isBackquoted) parseExpectedTokenJSDoc(61 /* BacktickToken */ ); + if (isBackquoted) parseExpectedTokenJSDoc(62 /* BacktickToken */ ); if (isBracketed) { skipWhitespace(); - if (parseOptionalToken(63 /* EqualsToken */ )) parseExpression(); - parseExpected(23 /* CloseBracketToken */ ); + if (parseOptionalToken(64 /* EqualsToken */ )) parseExpression(); + parseExpected(24 /* CloseBracketToken */ ); } return { name: name, @@ -35124,9 +35480,9 @@ ${lanes.join("\n")} } function isObjectOrObjectArrayTypeReference(node) { switch(node.kind){ - case 149 /* ObjectKeyword */ : + case 151 /* ObjectKeyword */ : return true; - case 185 /* ArrayType */ : + case 188 /* ArrayType */ : return isObjectOrObjectArrayTypeReference(node.elementType); default: return isTypeReferenceNode(node) && isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments; @@ -35136,43 +35492,46 @@ ${lanes.join("\n")} let typeExpression = tryParseTypeExpression(); let isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); - const { name: name , isBracketed: isBracketed } = parseBracketNameInPropertyAndParamTag(); + const { name: name, isBracketed: isBracketed } = parseBracketNameInPropertyAndParamTag(); const indentText = skipWhitespaceOrAsterisk(); if (isNameFirst && !lookAhead(parseJSDocLinkPrefix)) typeExpression = tryParseTypeExpression(); const comment = parseTrailingTagComments(start2, getNodePos(), indent2, indentText); - const nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent2); + const nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name, target, indent2); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; } - const result = target === 1 /* Property */ ? factory2.createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) : factory2.createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment); - return finishNode(result, start2); + const result2 = target === 1 /* Property */ ? factory2.createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) : factory2.createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment); + return finishNode(result2, start2); } function parseNestedTypeLiteral(typeExpression, name, target, indent2) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { const pos = getNodePos(); let child; let children; - while(child = tryParse(()=>parseChildParameterOrPropertyTag(target, indent2, name)))if (child.kind === 344 /* JSDocParameterTag */ || child.kind === 351 /* JSDocPropertyTag */ ) children = append(children, child); + while(child = tryParse(()=>parseChildParameterOrPropertyTag(target, indent2, name))){ + if (child.kind === 348 /* JSDocParameterTag */ || child.kind === 355 /* JSDocPropertyTag */ ) children = append(children, child); + else if (child.kind === 352 /* JSDocTemplateTag */ ) parseErrorAtRange(child.tagName, Diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag); + } if (children) { - const literal = finishNode(factory2.createJSDocTypeLiteral(children, typeExpression.type.kind === 185 /* ArrayType */ ), pos); + const literal = finishNode(factory2.createJSDocTypeLiteral(children, typeExpression.type.kind === 188 /* ArrayType */ ), pos); return finishNode(factory2.createJSDocTypeExpression(literal), pos); } } } function parseReturnTag(start2, tagName, indent2, indentText) { - if (some(tags, isJSDocReturnTag)) parseErrorAt(tagName.pos, scanner2.getTokenPos(), Diagnostics._0_tag_already_specified, tagName.escapedText); + if (some(tags, isJSDocReturnTag)) parseErrorAt(tagName.pos, scanner2.getTokenStart(), Diagnostics._0_tag_already_specified, unescapeLeadingUnderscores(tagName.escapedText)); const typeExpression = tryParseTypeExpression(); return finishNode(factory2.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start2, getNodePos(), indent2, indentText)), start2); } function parseTypeTag(start2, tagName, indent2, indentText) { - if (some(tags, isJSDocTypeTag)) parseErrorAt(tagName.pos, scanner2.getTokenPos(), Diagnostics._0_tag_already_specified, tagName.escapedText); + if (some(tags, isJSDocTypeTag)) parseErrorAt(tagName.pos, scanner2.getTokenStart(), Diagnostics._0_tag_already_specified, unescapeLeadingUnderscores(tagName.escapedText)); const typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); const comments2 = indent2 !== void 0 && indentText !== void 0 ? parseTrailingTagComments(start2, getNodePos(), indent2, indentText) : void 0; return finishNode(factory2.createJSDocTypeTag(tagName, typeExpression, comments2), start2); } function parseSeeTag(start2, tagName, indent2, indentText) { - const isMarkdownOrJSDocLink = token() === 22 /* OpenBracketToken */ || lookAhead(()=>nextTokenJSDoc() === 59 /* AtToken */ && tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && isJSDocLinkTag(scanner2.getTokenValue())); + const isMarkdownOrJSDocLink = token() === 23 /* OpenBracketToken */ || lookAhead(()=>nextTokenJSDoc() === 60 /* AtToken */ && tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && isJSDocLinkTag(scanner2.getTokenValue())); const nameExpression = isMarkdownOrJSDocLink ? void 0 : parseJSDocNameReference(); const comments2 = indent2 !== void 0 && indentText !== void 0 ? parseTrailingTagComments(start2, getNodePos(), indent2, indentText) : void 0; return finishNode(factory2.createJSDocSeeTag(tagName, nameExpression, comments2), start2); @@ -35185,9 +35544,9 @@ ${lanes.join("\n")} function parseAuthorTag(start2, tagName, indent2, indentText) { const commentStart = getNodePos(); const textOnly = parseAuthorNameAndEmail(); - let commentEnd = scanner2.getStartPos(); + let commentEnd = scanner2.getTokenFullStart(); const comments2 = parseTrailingTagComments(start2, commentEnd, indent2, indentText); - if (!comments2) commentEnd = scanner2.getStartPos(); + if (!comments2) commentEnd = scanner2.getTokenFullStart(); const allParts = typeof comments2 !== "string" ? createNodeArray(concatenate([ finishNode(textOnly, commentStart, commentEnd) ], comments2), commentStart) : textOnly.text + comments2; @@ -35198,11 +35557,11 @@ ${lanes.join("\n")} let inEmail = false; let token2 = scanner2.getToken(); while(token2 !== 1 /* EndOfFileToken */ && token2 !== 4 /* NewLineTrivia */ ){ - if (token2 === 29 /* LessThanToken */ ) inEmail = true; - else if (token2 === 59 /* AtToken */ && !inEmail) break; - else if (token2 === 31 /* GreaterThanToken */ && inEmail) { + if (token2 === 30 /* LessThanToken */ ) inEmail = true; + else if (token2 === 60 /* AtToken */ && !inEmail) break; + else if (token2 === 32 /* GreaterThanToken */ && inEmail) { comments2.push(scanner2.getTokenText()); - scanner2.setTextPos(scanner2.getTokenPos() + 1); + scanner2.resetTokenState(scanner2.getTokenEnd()); break; } comments2.push(scanner2.getTokenText()); @@ -35224,19 +35583,21 @@ ${lanes.join("\n")} return finishNode(factory2.createJSDocSatisfiesTag(tagName, typeExpression, comments2), start2); } function parseExpressionWithTypeArgumentsForAugments() { - const usedBrace = parseOptional(18 /* OpenBraceToken */ ); + const usedBrace = parseOptional(19 /* OpenBraceToken */ ); const pos = getNodePos(); const expression = parsePropertyAccessEntityNameExpression(); + scanner2.setInJSDocType(true); const typeArguments = tryParseTypeArguments(); + scanner2.setInJSDocType(false); const node = factory2.createExpressionWithTypeArguments(expression, typeArguments); const res = finishNode(node, pos); - if (usedBrace) parseExpected(19 /* CloseBraceToken */ ); + if (usedBrace) parseExpected(20 /* CloseBraceToken */ ); return res; } function parsePropertyAccessEntityNameExpression() { const pos = getNodePos(); let node = parseJSDocIdentifierName(); - while(parseOptional(24 /* DotToken */ )){ + while(parseOptional(25 /* DotToken */ )){ const name = parseJSDocIdentifierName(); node = finishNode(factoryCreatePropertyAccessExpression(node, name), pos); } @@ -35256,7 +35617,6 @@ ${lanes.join("\n")} return finishNode(factory2.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start2, getNodePos(), margin, indentText)), start2); } function parseTypedefTag(start2, tagName, indent2, indentText) { - var _a2; let typeExpression = tryParseTypeExpression(); skipWhitespaceOrAsterisk(); const fullName = parseJSDocTypeNameWithNamespace(); @@ -35269,8 +35629,9 @@ ${lanes.join("\n")} let jsDocPropertyTags; let hasChildren = false; while(child = tryParse(()=>parseChildPropertyTag(indent2))){ + if (child.kind === 352 /* JSDocTemplateTag */ ) break; hasChildren = true; - if (child.kind === 347 /* JSDocTypeTag */ ) { + if (child.kind === 351 /* JSDocTypeTag */ ) { if (childTypeTag) { const lastError = parseErrorAtCurrentToken(Diagnostics.A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags); if (lastError) addRelatedInfo(lastError, createDetachedDiagnostic(fileName, 0, 0, Diagnostics.The_tag_was_first_specified_here)); @@ -35279,42 +35640,48 @@ ${lanes.join("\n")} } else jsDocPropertyTags = append(jsDocPropertyTags, child); } if (hasChildren) { - const isArrayType = typeExpression && typeExpression.type.kind === 185 /* ArrayType */ ; + const isArrayType = typeExpression && typeExpression.type.kind === 188 /* ArrayType */ ; const jsdocTypeLiteral = factory2.createJSDocTypeLiteral(jsDocPropertyTags, isArrayType); typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral, start2); end2 = typeExpression.end; } } - end2 = end2 || comment !== void 0 ? getNodePos() : ((_a2 = fullName != null ? fullName : typeExpression) != null ? _a2 : tagName).end; + end2 = end2 || comment !== void 0 ? getNodePos() : (fullName ?? typeExpression ?? tagName).end; if (!comment) comment = parseTrailingTagComments(start2, end2, indent2, indentText); const typedefTag = factory2.createJSDocTypedefTag(tagName, typeExpression, fullName, comment); return finishNode(typedefTag, start2, end2); } function parseJSDocTypeNameWithNamespace(nested) { - const pos = scanner2.getTokenPos(); + const start2 = scanner2.getTokenStart(); if (!tokenIsIdentifierOrKeyword(token())) return void 0; const typeNameOrNamespaceName = parseJSDocIdentifierName(); - if (parseOptional(24 /* DotToken */ )) { + if (parseOptional(25 /* DotToken */ )) { const body = parseJSDocTypeNameWithNamespace(/*nested*/ true); - const jsDocNamespaceNode = factory2.createModuleDeclaration(/*modifiers*/ void 0, typeNameOrNamespaceName, body, nested ? 4 /* NestedNamespace */ : void 0); - return finishNode(jsDocNamespaceNode, pos); + const jsDocNamespaceNode = factory2.createModuleDeclaration(/*modifiers*/ void 0, typeNameOrNamespaceName, body, nested ? 8 /* NestedNamespace */ : void 0); + return finishNode(jsDocNamespaceNode, start2); } - if (nested) typeNameOrNamespaceName.flags |= 2048 /* IdentifierIsInJSDocNamespace */ ; + if (nested) typeNameOrNamespaceName.flags |= 4096 /* IdentifierIsInJSDocNamespace */ ; return typeNameOrNamespaceName; } function parseCallbackTagParameters(indent2) { const pos = getNodePos(); let child; let parameters; - while(child = tryParse(()=>parseChildParameterOrPropertyTag(4 /* CallbackParameter */ , indent2)))parameters = append(parameters, child); + while(child = tryParse(()=>parseChildParameterOrPropertyTag(4 /* CallbackParameter */ , indent2))){ + if (child.kind === 352 /* JSDocTemplateTag */ ) { + parseErrorAtRange(child.tagName, Diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag); + break; + } + parameters = append(parameters, child); + } return createNodeArray(parameters || [], pos); } function parseJSDocSignature(start2, indent2) { const parameters = parseCallbackTagParameters(indent2); const returnTag = tryParse(()=>{ - if (parseOptionalJsdoc(59 /* AtToken */ )) { + if (parseOptionalJsdoc(60 /* AtToken */ )) { const tag = parseTag(indent2); - if (tag && tag.kind === 345 /* JSDocReturnTag */ ) return tag; + if (tag && tag.kind === 349 /* JSDocReturnTag */ ) return tag; } }); return finishNode(factory2.createJSDocSignature(/*typeParameters*/ void 0, parameters, returnTag), start2); @@ -35352,10 +35719,10 @@ ${lanes.join("\n")} let canParseTag = true; let seenAsterisk = false; while(true)switch(nextTokenJSDoc()){ - case 59 /* AtToken */ : + case 60 /* AtToken */ : if (canParseTag) { const child = tryParseChildTag(target, indent2); - if (child && (child.kind === 344 /* JSDocParameterTag */ || child.kind === 351 /* JSDocPropertyTag */ ) && target !== 4 /* CallbackParameter */ && name && (isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) return false; + if (child && (child.kind === 348 /* JSDocParameterTag */ || child.kind === 355 /* JSDocPropertyTag */ ) && name && (isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) return false; return child; } seenAsterisk = false; @@ -35364,11 +35731,11 @@ ${lanes.join("\n")} canParseTag = true; seenAsterisk = false; break; - case 41 /* AsteriskToken */ : + case 42 /* AsteriskToken */ : if (seenAsterisk) canParseTag = false; seenAsterisk = true; break; - case 79 /* Identifier */ : + case 80 /* Identifier */ : canParseTag = false; break; case 1 /* EndOfFileToken */ : @@ -35376,11 +35743,11 @@ ${lanes.join("\n")} } } function tryParseChildTag(target, indent2) { - Debug.assert(token() === 59 /* AtToken */ ); - const start2 = scanner2.getStartPos(); + Debug.assert(token() === 60 /* AtToken */ ); + const start2 = scanner2.getTokenFullStart(); nextTokenJSDoc(); const tagName = parseJSDocIdentifierName(); - skipWhitespace(); + const indentText = skipWhitespaceOrAsterisk(); let t; switch(tagName.escapedText){ case "type": @@ -35394,6 +35761,8 @@ ${lanes.join("\n")} case "param": t = 6 /* CallbackParameter */ ; break; + case "template": + return parseTemplateTag(start2, tagName, indent2, indentText); default: return false; } @@ -35402,15 +35771,15 @@ ${lanes.join("\n")} } function parseTemplateTagTypeParameter() { const typeParameterPos = getNodePos(); - const isBracketed = parseOptionalJsdoc(22 /* OpenBracketToken */ ); + const isBracketed = parseOptionalJsdoc(23 /* OpenBracketToken */ ); if (isBracketed) skipWhitespace(); const name = parseJSDocIdentifierName(Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); let defaultType; if (isBracketed) { skipWhitespace(); - parseExpected(63 /* EqualsToken */ ); - defaultType = doInsideOfContext(8388608 /* JSDoc */ , parseJSDocType); - parseExpected(23 /* CloseBracketToken */ ); + parseExpected(64 /* EqualsToken */ ); + defaultType = doInsideOfContext(16777216 /* JSDoc */ , parseJSDocType); + parseExpected(24 /* CloseBracketToken */ ); } if (nodeIsMissing(name)) return void 0; return finishNode(factory2.createTypeParameterDeclaration(/*modifiers*/ void 0, name, /*constraint*/ void 0, defaultType), typeParameterPos); @@ -35423,11 +35792,11 @@ ${lanes.join("\n")} const node = parseTemplateTagTypeParameter(); if (node !== void 0) typeParameters.push(node); skipWhitespaceOrAsterisk(); - }while (parseOptionalJsdoc(27 /* CommaToken */ )); + }while (parseOptionalJsdoc(28 /* CommaToken */ )); return createNodeArray(typeParameters, pos); } function parseTemplateTag(start2, tagName, indent2, indentText) { - const constraint = token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : void 0; + const constraint = token() === 19 /* OpenBraceToken */ ? parseJSDocTypeExpression() : void 0; const typeParameters = parseTemplateTagTypeParameters(); return finishNode(factory2.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start2, getNodePos(), indent2, indentText)), start2); } @@ -35440,24 +35809,24 @@ ${lanes.join("\n")} } function parseJSDocEntityName() { let entity = parseJSDocIdentifierName(); - if (parseOptional(22 /* OpenBracketToken */ )) parseExpected(23 /* CloseBracketToken */ ); - while(parseOptional(24 /* DotToken */ )){ + if (parseOptional(23 /* OpenBracketToken */ )) parseExpected(24 /* CloseBracketToken */ ); + while(parseOptional(25 /* DotToken */ )){ const name = parseJSDocIdentifierName(); - if (parseOptional(22 /* OpenBracketToken */ )) parseExpected(23 /* CloseBracketToken */ ); + if (parseOptional(23 /* OpenBracketToken */ )) parseExpected(24 /* CloseBracketToken */ ); entity = createQualifiedName(entity, name); } return entity; } function parseJSDocIdentifierName(message) { - if (!tokenIsIdentifierOrKeyword(token())) return createMissingNode(79 /* Identifier */ , /*reportAtCurrentPosition*/ !message, message || Diagnostics.Identifier_expected); + if (!tokenIsIdentifierOrKeyword(token())) return createMissingNode(80 /* Identifier */ , /*reportAtCurrentPosition*/ !message, message || Diagnostics.Identifier_expected); identifierCount++; - const pos = scanner2.getTokenPos(); - const end2 = scanner2.getTextPos(); + const start2 = scanner2.getTokenStart(); + const end2 = scanner2.getTokenEnd(); const originalKeywordKind = token(); const text = internIdentifier(scanner2.getTokenValue()); - const result = finishNode(factoryCreateIdentifier(text, originalKeywordKind), pos, end2); + const result2 = finishNode(factoryCreateIdentifier(text, originalKeywordKind), start2, end2); nextTokenJSDoc(); - return result; + return result2; } } })(JSDocParser = Parser2.JSDocParser || (Parser2.JSDocParser = {})); @@ -35492,7 +35861,7 @@ ${lanes.join("\n")} let commentDirectives; let addedNewlyScannedDirectives = false; for (const directive of oldDirectives){ - const { range: range , type: type } = directive; + const { range: range, type: type } = directive; if (range.end < changeStart) commentDirectives = append(commentDirectives, directive); else if (range.pos > changeRangeOldEnd) { addNewlyScannedDirectives(); @@ -35538,9 +35907,9 @@ ${lanes.join("\n")} } function shouldCheckNode(node) { switch(node.kind){ - case 10 /* StringLiteral */ : - case 8 /* NumericLiteral */ : - case 79 /* Identifier */ : + case 11 /* StringLiteral */ : + case 9 /* NumericLiteral */ : + case 80 /* Identifier */ : return true; } return false; @@ -35731,7 +36100,7 @@ ${lanes.join("\n")} })(IncrementalParser || (IncrementalParser = {})); namedArgRegExCache = /* @__PURE__ */ new Map(); tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; - singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im; + singleLinePragmaRegEx = /^\/\/\/?\s*@([^\s:]+)(.*)\s*$/im; } }); // src/compiler/commandLineParser.ts @@ -35782,11 +36151,11 @@ ${lanes.join("\n")} function getOptionName(option) { return option.name; } - function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) { - var _a2; - if ((_a2 = diagnostics.alternateMode) == null ? void 0 : _a2.getOptionsNameMap().optionsNameMap.has(unknownOption.toLowerCase())) return createDiagnostics(diagnostics.alternateMode.diagnostic, unknownOption); + function createUnknownOptionError(unknownOption, diagnostics, unknownOptionErrorText, node, sourceFile) { + var _a; + if ((_a = diagnostics.alternateMode) == null ? void 0 : _a.getOptionsNameMap().optionsNameMap.has(unknownOption.toLowerCase())) return createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, node, diagnostics.alternateMode.diagnostic, unknownOption); const possibleOption = getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName); - return possibleOption ? createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : createDiagnostics(diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption); + return possibleOption ? createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, node, diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, node, diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption); } function parseCommandLineWorker(diagnostics, commandLine, readFile) { const options = {}; @@ -35813,7 +36182,7 @@ ${lanes.join("\n")} else { const watchOpt = getOptionDeclarationFromName(watchOptionsDidYouMeanDiagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true); if (watchOpt) i = parseOptionValue(args, i, watchOptionsDidYouMeanDiagnostics, watchOpt, watchOptions || (watchOptions = {}), errors); - else errors.push(createUnknownOptionError(inputOptionName, diagnostics, createCompilerDiagnostic, s)); + else errors.push(createUnknownOptionError(inputOptionName, diagnostics, s)); } } else fileNames.push(s); } @@ -35907,7 +36276,7 @@ ${lanes.join("\n")} } function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort = false) { optionName = optionName.toLowerCase(); - const { optionsNameMap: optionsNameMap , shortOptionNames: shortOptionNames } = getOptionNameMap(); + const { optionsNameMap: optionsNameMap, shortOptionNames: shortOptionNames } = getOptionNameMap(); if (allowShort) { const short = shortOptionNames.get(optionName); if (short !== void 0) optionName = short; @@ -35918,7 +36287,7 @@ ${lanes.join("\n")} return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(buildOpts)); } function parseBuildCommand(args) { - const { options: options , watchOptions: watchOptions , fileNames: projects , errors: errors } = parseCommandLineWorker(buildOptionsDidYouMeanDiagnostics, args); + const { options: options, watchOptions: watchOptions, fileNames: projects, errors: errors } = parseCommandLineWorker(buildOptionsDidYouMeanDiagnostics, args); const buildOptions = options; if (projects.length === 0) projects.push("."); if (buildOptions.clean && buildOptions.force) errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); @@ -35959,7 +36328,7 @@ ${lanes.join("\n")} function parseConfigFileTextToJson(fileName, jsonText) { const jsonSourceFile = parseJsonText(fileName, jsonText); return { - config: convertConfigFileToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics, /*reportOptionsErrors*/ false, /*optionsIterator*/ void 0), + config: convertConfigFileToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics, /*jsonConversionNotifier*/ void 0), error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : void 0 }; } @@ -36002,24 +36371,9 @@ ${lanes.join("\n")} // should never be needed since this is root type: "object", elementOptions: commandLineOptionsToMap([ - { - name: "compilerOptions", - type: "object", - elementOptions: getCommandLineCompilerOptionsMap(), - extraKeyDiagnostics: compilerOptionsDidYouMeanDiagnostics - }, - { - name: "watchOptions", - type: "object", - elementOptions: getCommandLineWatchOptionsMap(), - extraKeyDiagnostics: watchOptionsDidYouMeanDiagnostics - }, - { - name: "typeAcquisition", - type: "object", - elementOptions: getCommandLineTypeAcquisitionMap(), - extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics - }, + compilerOptionsDeclaration, + watchOptionsDeclaration, + typeAcquisitionDeclaration, extendsOptionDeclaration, { name: "references", @@ -36064,34 +36418,31 @@ ${lanes.join("\n")} }; return _tsconfigRootOptions; } - function convertConfigFileToObject(sourceFile, errors, reportOptionsErrors, optionsIterator) { - var _a2; - const rootExpression = (_a2 = sourceFile.statements[0]) == null ? void 0 : _a2.expression; - const knownRootOptions = reportOptionsErrors ? getTsconfigRootOptionsMap() : void 0; - if (rootExpression && rootExpression.kind !== 207 /* ObjectLiteralExpression */ ) { + function convertConfigFileToObject(sourceFile, errors, jsonConversionNotifier) { + var _a; + const rootExpression = (_a = sourceFile.statements[0]) == null ? void 0 : _a.expression; + if (rootExpression && rootExpression.kind !== 210 /* ObjectLiteralExpression */ ) { errors.push(createDiagnosticForNodeInSourceFile(sourceFile, rootExpression, Diagnostics.The_root_value_of_a_0_file_must_be_an_object, getBaseFileName(sourceFile.fileName) === "jsconfig.json" ? "jsconfig.json" : "tsconfig.json")); if (isArrayLiteralExpression(rootExpression)) { const firstObject = find(rootExpression.elements, isObjectLiteralExpression); - if (firstObject) return convertToObjectWorker(sourceFile, firstObject, errors, /*returnValue*/ true, knownRootOptions, optionsIterator); + if (firstObject) return convertToJson(sourceFile, firstObject, errors, /*returnValue*/ true, jsonConversionNotifier); } return {}; } - return convertToObjectWorker(sourceFile, rootExpression, errors, /*returnValue*/ true, knownRootOptions, optionsIterator); + return convertToJson(sourceFile, rootExpression, errors, /*returnValue*/ true, jsonConversionNotifier); } function convertToObject(sourceFile, errors) { - var _a2; - return convertToObjectWorker(sourceFile, (_a2 = sourceFile.statements[0]) == null ? void 0 : _a2.expression, errors, /*returnValue*/ true, /*knownRootOptions*/ void 0, /*jsonConversionNotifier*/ void 0); + var _a; + return convertToJson(sourceFile, (_a = sourceFile.statements[0]) == null ? void 0 : _a.expression, errors, /*returnValue*/ true, /*jsonConversionNotifier*/ void 0); } - function convertToObjectWorker(sourceFile, rootExpression, errors, returnValue, knownRootOptions, jsonConversionNotifier) { + function convertToJson(sourceFile, rootExpression, errors, returnValue, jsonConversionNotifier) { if (!rootExpression) return returnValue ? {} : void 0; - return convertPropertyValueToJson(rootExpression, knownRootOptions); - function isRootOptionMap(knownOptions) { - return knownRootOptions && knownRootOptions.elementOptions === knownOptions; - } - function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) { + return convertPropertyValueToJson(rootExpression, jsonConversionNotifier == null ? void 0 : jsonConversionNotifier.rootOptions); + function convertObjectLiteralExpressionToJson(node, objectOption) { + var _a; const result = returnValue ? {} : void 0; for (const element of node.properties){ - if (element.kind !== 299 /* PropertyAssignment */ ) { + if (element.kind !== 303 /* PropertyAssignment */ ) { errors.push(createDiagnosticForNodeInSourceFile(sourceFile, element, Diagnostics.Property_assignment_expected)); continue; } @@ -36099,24 +36450,11 @@ ${lanes.join("\n")} if (!isDoubleQuotedString(element.name)) errors.push(createDiagnosticForNodeInSourceFile(sourceFile, element.name, Diagnostics.String_literal_with_double_quotes_expected)); const textOfKey = isComputedNonLiteralName(element.name) ? void 0 : getTextOfPropertyName(element.name); const keyText = textOfKey && unescapeLeadingUnderscores(textOfKey); - const option = keyText && knownOptions ? knownOptions.get(keyText) : void 0; - if (keyText && extraKeyDiagnostics && !option) { - if (knownOptions) errors.push(createUnknownOptionError(keyText, extraKeyDiagnostics, (message, arg0, arg1)=>createDiagnosticForNodeInSourceFile(sourceFile, element.name, message, arg0, arg1))); - else errors.push(createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText)); - } + const option = keyText ? (_a = objectOption == null ? void 0 : objectOption.elementOptions) == null ? void 0 : _a.get(keyText) : void 0; const value1 = convertPropertyValueToJson(element.initializer, option); if (typeof keyText !== "undefined") { if (returnValue) result[keyText] = value1; - if (jsonConversionNotifier && // Current callbacks are only on known parent option or if we are setting values in the root - (parentOption || isRootOptionMap(knownOptions))) { - const isValidOptionValue = isCompilerOptionsValue(option, value1); - if (parentOption) { - if (isValidOptionValue) jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value1); - } else if (isRootOptionMap(knownOptions)) { - if (isValidOptionValue) jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value1, element.initializer); - else if (!option) jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value1, element.initializer); - } - } + jsonConversionNotifier == null || jsonConversionNotifier.onPropertySet(keyText, value1, element, objectOption, option); } } return result; @@ -36129,68 +36467,30 @@ ${lanes.join("\n")} return filter(elements.map((element)=>convertPropertyValueToJson(element, elementOption)), (v)=>v !== void 0); } function convertPropertyValueToJson(valueExpression, option) { - let invalidReported; switch(valueExpression.kind){ - case 110 /* TrueKeyword */ : - reportInvalidOptionValue(option && option.type !== "boolean" && (option.type !== "listOrElement" || option.element.type !== "boolean")); - return validateValue(/*value*/ true); - case 95 /* FalseKeyword */ : - reportInvalidOptionValue(option && option.type !== "boolean" && (option.type !== "listOrElement" || option.element.type !== "boolean")); - return validateValue(/*value*/ false); - case 104 /* NullKeyword */ : - reportInvalidOptionValue(option && option.name === "extends"); - return validateValue(/*value*/ null); - case 10 /* StringLiteral */ : + case 112 /* TrueKeyword */ : + return true; + case 97 /* FalseKeyword */ : + return false; + case 106 /* NullKeyword */ : + return null; + case 11 /* StringLiteral */ : if (!isDoubleQuotedString(valueExpression)) errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, Diagnostics.String_literal_with_double_quotes_expected)); - reportInvalidOptionValue(option && isString(option.type) && option.type !== "string" && (option.type !== "listOrElement" || isString(option.element.type) && option.element.type !== "string")); - const text = valueExpression.text; - if (option) Debug.assert(option.type !== "listOrElement" || option.element.type === "string", "Only string or array of string is handled for now"); - if (option && !isString(option.type)) { - const customOption = option; - if (!customOption.type.has(text.toLowerCase())) { - errors.push(createDiagnosticForInvalidCustomType(customOption, (message, arg0, arg1)=>createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1))); - invalidReported = true; - } - } - return validateValue(text); - case 8 /* NumericLiteral */ : - reportInvalidOptionValue(option && option.type !== "number" && (option.type !== "listOrElement" || option.element.type !== "number")); - return validateValue(Number(valueExpression.text)); - case 221 /* PrefixUnaryExpression */ : - if (valueExpression.operator !== 40 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */ ) break; - reportInvalidOptionValue(option && option.type !== "number" && (option.type !== "listOrElement" || option.element.type !== "number")); - return validateValue(-Number(valueExpression.operand.text)); - case 207 /* ObjectLiteralExpression */ : - reportInvalidOptionValue(option && option.type !== "object" && (option.type !== "listOrElement" || option.element.type !== "object")); + return valueExpression.text; + case 9 /* NumericLiteral */ : + return Number(valueExpression.text); + case 224 /* PrefixUnaryExpression */ : + if (valueExpression.operator !== 41 /* MinusToken */ || valueExpression.operand.kind !== 9 /* NumericLiteral */ ) break; + return -Number(valueExpression.operand.text); + case 210 /* ObjectLiteralExpression */ : const objectLiteralExpression = valueExpression; - if (option) { - const { elementOptions: elementOptions , extraKeyDiagnostics: extraKeyDiagnostics , name: optionName } = option; - return validateValue(convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName)); - } else return validateValue(convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ void 0, /*extraKeyDiagnosticMessage */ void 0, /*parentOption*/ void 0)); - case 206 /* ArrayLiteralExpression */ : - reportInvalidOptionValue(option && option.type !== "list" && option.type !== "listOrElement"); - return validateValue(convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element)); - } - if (option) reportInvalidOptionValue(/*isError*/ true); + return convertObjectLiteralExpressionToJson(objectLiteralExpression, option); + case 209 /* ArrayLiteralExpression */ : + return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); + } + if (option) errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option))); else errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal)); return void 0; - function validateValue(value1) { - var _a2; - if (!invalidReported) { - const diagnostic = (_a2 = option == null ? void 0 : option.extraValidation) == null ? void 0 : _a2.call(option, value1); - if (diagnostic) { - errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ...diagnostic)); - return void 0; - } - } - return value1; - } - function reportInvalidOptionValue(isError) { - if (isError) { - errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option))); - invalidReported = true; - } - } } function isDoubleQuotedString(node) { return isStringLiteral(node) && isStringDoubleQuoted(node, sourceFile); @@ -36201,7 +36501,7 @@ ${lanes.join("\n")} } function isCompilerOptionsValue(option, value1) { if (option) { - if (isNullOrUndefined(value1)) return true; + if (isNullOrUndefined(value1)) return !option.disallowNullOrUndefined; if (option.type === "list") return isArray(value1); if (option.type === "listOrElement") return isArray(value1) || isCompilerOptionsValue(option.element, value1); const expectedType = isString(option.type) ? option.type : "string"; @@ -36210,9 +36510,9 @@ ${lanes.join("\n")} return false; } function convertToTSConfig(configParseResult, configFileName, host) { - var _a2, _b, _c; + var _a, _b, _c; const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); - const files = map(filter(configParseResult.fileNames, !((_b = (_a2 = configParseResult.options.configFile) == null ? void 0 : _a2.configFileSpecs) == null ? void 0 : _b.validatedIncludeSpecs) ? returnTrue : matchesSpecs(configFileName, configParseResult.options.configFile.configFileSpecs.validatedIncludeSpecs, configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs, host)), (f)=>getRelativePathFromFile(getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName)); + const files = map(filter(configParseResult.fileNames, !((_b = (_a = configParseResult.options.configFile) == null ? void 0 : _a.configFileSpecs) == null ? void 0 : _b.validatedIncludeSpecs) ? returnTrue : matchesSpecs(configFileName, configParseResult.options.configFile.configFileSpecs.validatedIncludeSpecs, configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs, host)), (f)=>getRelativePathFromFile(getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName)); const optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames @@ -36298,7 +36598,7 @@ ${lanes.join("\n")} function serializeWatchOptions(options) { return serializeOptionBaseObject(options, getWatchOptionsNameMap()); } - function serializeOptionBaseObject(options, { optionsNameMap: optionsNameMap }, pathOptions) { + function serializeOptionBaseObject(options, { optionsNameMap: optionsNameMap }, pathOptions) { const result = /* @__PURE__ */ new Map(); const getCanonicalFileName = pathOptions && createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames); for(const name in options)if (hasProperty(options, name)) { @@ -36346,7 +36646,7 @@ ${lanes.join("\n")} function makePadding(paddingLength) { return Array(paddingLength + 1).join(" "); } - function isAllowedOptionForOutput({ category: category , name: name , isCommandLineOnly: isCommandLineOnly }) { + function isAllowedOptionForOutput({ category: category, name: name, isCommandLineOnly: isCommandLineOnly }) { const categoriesToSkip = [ Diagnostics.Command_line_Options, Diagnostics.Editor_Support, @@ -36400,8 +36700,8 @@ ${lanes.join("\n")} result.push(`${tab}${tab}/* ${getLocaleSpecificMessage(Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_to_read_more_about_this_file)} */`); result.push(""); for (const entry of entries){ - const { value: value1 , description: description2 = "" } = entry; - result.push(value1 && `${tab}${tab}${value1}${description2 && makePadding(marginLength - value1.length + 2) + description2}`); + const { value: value1, description: description3 = "" } = entry; + result.push(value1 && `${tab}${tab}${value1}${description3 && makePadding(marginLength - value1.length + 2) + description3}`); } if (fileNames.length) { result.push(`${tab}},`); @@ -36434,8 +36734,8 @@ ${lanes.join("\n")} return parseJsonConfigFileContentWorker(json, /*sourceFile*/ void 0, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache); } function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) { - var _a2, _b; - (_a2 = tracing) == null || _a2.push(tracing.Phase.Parse, "parseJsonSourceFileConfigFileContent", { + var _a, _b; + (_a = tracing) == null || _a.push(tracing.Phase.Parse, "parseJsonSourceFileConfigFileContent", { path: sourceFile.fileName }); const result = parseJsonConfigFileContentWorker(/*json*/ void 0, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache); @@ -36459,7 +36759,7 @@ ${lanes.join("\n")} Debug.assert(json === void 0 && sourceFile !== void 0 || json !== void 0 && sourceFile === void 0); const errors = []; const parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache); - const { raw: raw } = parsedConfig; + const { raw: raw } = parsedConfig; const options = extend(existingOptions, parsedConfig.options || {}); const watchOptions = existingWatchOptions && parsedConfig.watchOptions ? extend(existingWatchOptions, parsedConfig.watchOptions) : parsedConfig.watchOptions || existingWatchOptions; options.configFilePath = configFileName && normalizeSlashes(configFileName); @@ -36492,9 +36792,9 @@ ${lanes.join("\n")} if (sourceFile) { const fileName = configFileName || "tsconfig.json"; const diagnosticMessage = Diagnostics.The_files_list_in_config_file_0_is_empty; - const nodeValue = firstDefined(getTsConfigPropArray(sourceFile, "files"), (property)=>property.initializer); - const error = nodeValue ? createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) : createCompilerDiagnostic(diagnosticMessage, fileName); - errors.push(error); + const nodeValue = forEachTsConfigPropArray(sourceFile, "files", (property)=>property.initializer); + const error2 = createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, nodeValue, diagnosticMessage, fileName); + errors.push(error2); } else createCompilerDiagnosticOnlyIfJson(Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); } } @@ -36569,14 +36869,14 @@ ${lanes.join("\n")} } return "no-prop"; } - function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { - if (!sourceFile) errors.push(createCompilerDiagnostic(message, arg0, arg1)); + function createCompilerDiagnosticOnlyIfJson(message, ...args) { + if (!sourceFile) errors.push(createCompilerDiagnostic(message, ...args)); } } - function isErrorNoInputFiles(error) { - return error.code === Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; + function isErrorNoInputFiles(error2) { + return error2.code === Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } - function getErrorForNoInputFiles({ includeSpecs: includeSpecs , excludeSpecs: excludeSpecs }, configFileName) { + function getErrorForNoInputFiles({ includeSpecs: includeSpecs, excludeSpecs: excludeSpecs }, configFileName) { return createCompilerDiagnostic(Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); } function shouldReportNoInputFiles(fileNames, canJsonReportNoInutFiles, resolutionStack) { @@ -36588,14 +36888,14 @@ ${lanes.join("\n")} function updateErrorForNoInputFiles(fileNames, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { const existingErrors = configParseDiagnostics.length; if (shouldReportNoInputFiles(fileNames, canJsonReportNoInutFiles)) configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); - else filterMutate(configParseDiagnostics, (error)=>!isErrorNoInputFiles(error)); + else filterMutate(configParseDiagnostics, (error2)=>!isErrorNoInputFiles(error2)); return existingErrors !== configParseDiagnostics.length; } function isSuccessfulParsedTsconfig(value1) { return !!value1.options; } function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache) { - var _a2; + var _a; basePath = normalizeSlashes(basePath); const resolvedPath = getNormalizedAbsolutePath(configFileName || "", basePath); if (resolutionStack.indexOf(resolvedPath) >= 0) { @@ -36608,7 +36908,7 @@ ${lanes.join("\n")} }; } const ownConfig = json ? parseOwnConfigOfJson(json, host, basePath, configFileName, errors) : parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors); - if ((_a2 = ownConfig.options) == null ? void 0 : _a2.paths) ownConfig.options.pathsBasePath = basePath; + if ((_a = ownConfig.options) == null ? void 0 : _a.paths) ownConfig.options.pathsBasePath = basePath; if (ownConfig.extendedConfigPath) { resolutionStack = resolutionStack.concat([ resolvedPath @@ -36650,19 +36950,7 @@ ${lanes.join("\n")} const typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition, basePath, errors, configFileName); const watchOptions = convertWatchOptionsFromJsonWorker(json.watchOptions, basePath, errors); json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); - let extendedConfigPath; - if (json.extends || json.extends === "") { - if (!isCompilerOptionsValue(extendsOptionDeclaration, json.extends)) errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", getCompilerOptionValueTypeString(extendsOptionDeclaration))); - else { - const newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; - if (isString(json.extends)) extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, createCompilerDiagnostic); - else { - extendedConfigPath = []; - for (const fileName of json.extends)if (isString(fileName)) extendedConfigPath = append(extendedConfigPath, getExtendsConfigPath(fileName, host, newBase, errors, createCompilerDiagnostic)); - else errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", getCompilerOptionValueTypeString(extendsOptionDeclaration.element))); - } - } - } + const extendedConfigPath = json.extends || json.extends === "" ? getExtendsConfigPathOrArray(json.extends, host, basePath, configFileName, errors) : void 0; return { raw: json, options: options, @@ -36671,51 +36959,31 @@ ${lanes.join("\n")} extendedConfigPath: extendedConfigPath }; } + function getExtendsConfigPathOrArray(value1, host, basePath, configFileName, errors, propertyAssignment, valueExpression, sourceFile) { + let extendedConfigPath; + const newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + if (isString(value1)) extendedConfigPath = getExtendsConfigPath(value1, host, newBase, errors, valueExpression, sourceFile); + else if (isArray(value1)) { + extendedConfigPath = []; + for(let index = 0; index < value1.length; index++){ + const fileName = value1[index]; + if (isString(fileName)) extendedConfigPath = append(extendedConfigPath, getExtendsConfigPath(fileName, host, newBase, errors, valueExpression == null ? void 0 : valueExpression.elements[index], sourceFile)); + else convertJsonOption(extendsOptionDeclaration.element, value1, basePath, errors, propertyAssignment, valueExpression == null ? void 0 : valueExpression.elements[index], sourceFile); + } + } else convertJsonOption(extendsOptionDeclaration, value1, basePath, errors, propertyAssignment, valueExpression, sourceFile); + return extendedConfigPath; + } function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) { const options = getDefaultCompilerOptions(configFileName); let typeAcquisition; let watchOptions; let extendedConfigPath; let rootCompilerOptions; - const optionsIterator = { - onSetValidOptionKeyValueInParent (parentOption, option, value1) { - let currentOption; - switch(parentOption){ - case "compilerOptions": - currentOption = options; - break; - case "watchOptions": - currentOption = watchOptions || (watchOptions = {}); - break; - case "typeAcquisition": - currentOption = typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName)); - break; - default: - Debug.fail("Unknown option"); - } - currentOption[option.name] = normalizeOptionValue(option, basePath, value1); - }, - onSetValidOptionKeyValueInRoot (key, _keyNode, value1, valueNode) { - switch(key){ - case "extends": - const newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; - if (isString(value1)) extendedConfigPath = getExtendsConfigPath(value1, host, newBase, errors, (message, arg0)=>createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0)); - else { - extendedConfigPath = []; - for(let index = 0; index < value1.length; index++){ - const fileName = value1[index]; - if (isString(fileName)) extendedConfigPath = append(extendedConfigPath, getExtendsConfigPath(fileName, host, newBase, errors, (message, arg0)=>createDiagnosticForNodeInSourceFile(sourceFile, valueNode.elements[index], message, arg0))); - } - } - return; - } - }, - onSetUnknownOptionKeyValueInRoot (key, keyNode, _value, _valueNode) { - if (key === "excludes") errors.push(createDiagnosticForNodeInSourceFile(sourceFile, keyNode, Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - if (find(commandOptionsWithoutBuild, (opt)=>opt.name === key)) rootCompilerOptions = append(rootCompilerOptions, keyNode); - } - }; - const json = convertConfigFileToObject(sourceFile, errors, /*reportOptionsErrors*/ true, optionsIterator); + const rootOptions = getTsconfigRootOptionsMap(); + const json = convertConfigFileToObject(sourceFile, errors, { + rootOptions: rootOptions, + onPropertySet: onPropertySet + }); if (!typeAcquisition) typeAcquisition = getDefaultTypeAcquisition(configFileName); if (rootCompilerOptions && json && json.compilerOptions === void 0) errors.push(createDiagnosticForNodeInSourceFile(sourceFile, rootCompilerOptions[0], Diagnostics._0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file, getTextOfPropertyName(rootCompilerOptions[0]))); return { @@ -36725,15 +36993,37 @@ ${lanes.join("\n")} typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; - } - function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { + function onPropertySet(keyText, value1, propertyAssignment, parentOption, option) { + if (option && option !== extendsOptionDeclaration) value1 = convertJsonOption(option, value1, basePath, errors, propertyAssignment, propertyAssignment.initializer, sourceFile); + if (parentOption == null ? void 0 : parentOption.name) { + if (option) { + let currentOption; + if (parentOption === compilerOptionsDeclaration) currentOption = options; + else if (parentOption === watchOptionsDeclaration) currentOption = watchOptions ?? (watchOptions = {}); + else if (parentOption === typeAcquisitionDeclaration) currentOption = typeAcquisition ?? (typeAcquisition = getDefaultTypeAcquisition(configFileName)); + else Debug.fail("Unknown option"); + currentOption[option.name] = value1; + } else if (keyText && (parentOption == null ? void 0 : parentOption.extraKeyDiagnostics)) { + if (parentOption.elementOptions) errors.push(createUnknownOptionError(keyText, parentOption.extraKeyDiagnostics, /*unknownOptionErrorText*/ void 0, propertyAssignment.name, sourceFile)); + else errors.push(createDiagnosticForNodeInSourceFile(sourceFile, propertyAssignment.name, parentOption.extraKeyDiagnostics.unknownOptionDiagnostic, keyText)); + } + } else if (parentOption === rootOptions) { + if (option === extendsOptionDeclaration) extendedConfigPath = getExtendsConfigPathOrArray(value1, host, basePath, configFileName, errors, propertyAssignment, propertyAssignment.initializer, sourceFile); + else if (!option) { + if (keyText === "excludes") errors.push(createDiagnosticForNodeInSourceFile(sourceFile, propertyAssignment.name, Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + if (find(commandOptionsWithoutBuild, (opt)=>opt.name === keyText)) rootCompilerOptions = append(rootCompilerOptions, propertyAssignment.name); + } + } + } + } + function getExtendsConfigPath(extendedConfig, host, basePath, errors, valueExpression, sourceFile) { extendedConfig = normalizeSlashes(extendedConfig); if (isRootedDiskPath(extendedConfig) || startsWith(extendedConfig, "./") || startsWith(extendedConfig, "../")) { let extendedConfigPath = getNormalizedAbsolutePath(extendedConfig, basePath); if (!host.fileExists(extendedConfigPath) && !endsWith(extendedConfigPath, ".json" /* Json */ )) { extendedConfigPath = `${extendedConfigPath}.json`; if (!host.fileExists(extendedConfigPath)) { - errors.push(createDiagnostic(Diagnostics.File_0_not_found, extendedConfig)); + errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, Diagnostics.File_0_not_found, extendedConfig)); return void 0; } } @@ -36741,17 +37031,16 @@ ${lanes.join("\n")} } const resolved = nodeNextJsonConfigResolver(extendedConfig, combinePaths(basePath, "tsconfig.json"), host); if (resolved.resolvedModule) return resolved.resolvedModule.resolvedFileName; - if (extendedConfig === "") errors.push(createDiagnostic(Diagnostics.Compiler_option_0_cannot_be_given_an_empty_string, "extends")); - else errors.push(createDiagnostic(Diagnostics.File_0_not_found, extendedConfig)); + if (extendedConfig === "") errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, Diagnostics.Compiler_option_0_cannot_be_given_an_empty_string, "extends")); + else errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, Diagnostics.File_0_not_found, extendedConfig)); return void 0; } function getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache, result) { - var _a2; const path = host.useCaseSensitiveFileNames ? extendedConfigPath : toFileNameLowerCase(extendedConfigPath); let value1; let extendedResult; let extendedConfig; - if (extendedConfigCache && (value1 = extendedConfigCache.get(path))) ({ extendedResult: extendedResult , extendedConfig: extendedConfig } = value1); + if (extendedConfigCache && (value1 = extendedConfigCache.get(path))) ({ extendedResult: extendedResult, extendedConfig: extendedConfig } = value1); else { extendedResult = readJsonConfigFile(extendedConfigPath, (path2)=>host.readFile(path2)); if (!extendedResult.parseDiagnostics.length) extendedConfig = parseConfig(/*json*/ void 0, extendedResult, host, getDirectoryPath(extendedConfigPath), getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); @@ -36761,7 +37050,7 @@ ${lanes.join("\n")} }); } if (sourceFile) { - ((_a2 = result.extendedSourceFiles) != null ? _a2 : result.extendedSourceFiles = /* @__PURE__ */ new Set()).add(extendedResult.fileName); + (result.extendedSourceFiles ?? (result.extendedSourceFiles = /* @__PURE__ */ new Set())).add(extendedResult.fileName); if (extendedResult.extendedSourceFiles) for (const extenedSourceFile of extendedResult.extendedSourceFiles)result.extendedSourceFiles.add(extenedSourceFile); } if (extendedResult.parseDiagnostics.length) { @@ -36827,29 +37116,26 @@ ${lanes.join("\n")} for(const id in jsonOptions){ const opt = optionsNameMap.get(id); if (opt) (defaultOptions || (defaultOptions = {}))[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); - else errors.push(createUnknownOptionError(id, diagnostics, createCompilerDiagnostic)); + else errors.push(createUnknownOptionError(id, diagnostics)); } return defaultOptions; } - function convertJsonOption(opt, value1, basePath, errors) { + function createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, node, message, ...args) { + return sourceFile && node ? createDiagnosticForNodeInSourceFile(sourceFile, node, message, ...args) : createCompilerDiagnostic(message, ...args); + } + function convertJsonOption(opt, value1, basePath, errors, propertyAssignment, valueExpression, sourceFile) { + if (opt.isCommandLineOnly) { + errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, propertyAssignment == null ? void 0 : propertyAssignment.name, Diagnostics.Option_0_can_only_be_specified_on_command_line, opt.name)); + return void 0; + } if (isCompilerOptionsValue(opt, value1)) { const optType = opt.type; - if (optType === "list" && isArray(value1)) return convertJsonOptionOfListType(opt, value1, basePath, errors); - else if (optType === "listOrElement") return isArray(value1) ? convertJsonOptionOfListType(opt, value1, basePath, errors) : convertJsonOption(opt.element, value1, basePath, errors); - else if (!isString(opt.type)) return convertJsonOptionOfCustomType(opt, value1, errors); - const validatedValue = validateJsonOptionValue(opt, value1, errors); + if (optType === "list" && isArray(value1)) return convertJsonOptionOfListType(opt, value1, basePath, errors, propertyAssignment, valueExpression, sourceFile); + else if (optType === "listOrElement") return isArray(value1) ? convertJsonOptionOfListType(opt, value1, basePath, errors, propertyAssignment, valueExpression, sourceFile) : convertJsonOption(opt.element, value1, basePath, errors, propertyAssignment, valueExpression, sourceFile); + else if (!isString(opt.type)) return convertJsonOptionOfCustomType(opt, value1, errors, valueExpression, sourceFile); + const validatedValue = validateJsonOptionValue(opt, value1, errors, valueExpression, sourceFile); return isNullOrUndefined(validatedValue) ? validatedValue : normalizeNonListOptionValue(opt, basePath, validatedValue); - } else errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt))); - } - function normalizeOptionValue(option, basePath, value1) { - if (isNullOrUndefined(value1)) return void 0; - if (option.type === "listOrElement" && !isArray(value1)) return normalizeOptionValue(option.element, basePath, value1); - else if (option.type === "list" || option.type === "listOrElement") { - const listOption = option; - if (listOption.element.isFilePath || !isString(listOption.element.type)) return filter(map(value1, (v)=>normalizeOptionValue(listOption.element, basePath, v)), (v)=>listOption.listPreserveFalsyValues ? true : !!v); - return value1; - } else if (!isString(option.type)) return option.type.get(isString(value1) ? value1.toLowerCase() : value1); - return normalizeNonListOptionValue(option, basePath, value1); + } else errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt))); } function normalizeNonListOptionValue(option, basePath, value1) { if (option.isFilePath) { @@ -36858,23 +37144,23 @@ ${lanes.join("\n")} } return value1; } - function validateJsonOptionValue(opt, value1, errors) { - var _a2; + function validateJsonOptionValue(opt, value1, errors, valueExpression, sourceFile) { + var _a; if (isNullOrUndefined(value1)) return void 0; - const d = (_a2 = opt.extraValidation) == null ? void 0 : _a2.call(opt, value1); + const d = (_a = opt.extraValidation) == null ? void 0 : _a.call(opt, value1); if (!d) return value1; - errors.push(createCompilerDiagnostic(...d)); + errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, ...d)); return void 0; } - function convertJsonOptionOfCustomType(opt, value1, errors) { + function convertJsonOptionOfCustomType(opt, value1, errors, valueExpression, sourceFile) { if (isNullOrUndefined(value1)) return void 0; const key = value1.toLowerCase(); const val = opt.type.get(key); - if (val !== void 0) return validateJsonOptionValue(opt, val, errors); - else errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); + if (val !== void 0) return validateJsonOptionValue(opt, val, errors, valueExpression, sourceFile); + else errors.push(createDiagnosticForInvalidCustomType(opt, (message, ...args)=>createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, message, ...args))); } - function convertJsonOptionOfListType(option, values, basePath, errors) { - return filter(map(values, (v)=>convertJsonOption(option.element, v, basePath, errors)), (v)=>option.listPreserveFalsyValues ? true : !!v); + function convertJsonOptionOfListType(option, values, basePath, errors, propertyAssignment, valueExpression, sourceFile) { + return filter(map(values, (v, index)=>convertJsonOption(option.element, v, basePath, errors, propertyAssignment, valueExpression == null ? void 0 : valueExpression.elements[index], sourceFile)), (v)=>option.listPreserveFalsyValues ? true : !!v); } function getFileNamesFromConfigSpecs(configFileSpecs, basePath, options, host, extraFileExtensions = emptyArray) { basePath = normalizePath(basePath); @@ -36882,7 +37168,7 @@ ${lanes.join("\n")} const literalFileMap = /* @__PURE__ */ new Map(); const wildcardFileMap = /* @__PURE__ */ new Map(); const wildCardJsonFileMap = /* @__PURE__ */ new Map(); - const { validatedFilesSpec: validatedFilesSpec , validatedIncludeSpecs: validatedIncludeSpecs , validatedExcludeSpecs: validatedExcludeSpecs } = configFileSpecs; + const { validatedFilesSpec: validatedFilesSpec, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs } = configFileSpecs; const supportedExtensions = getSupportedExtensions(options, extraFileExtensions); const supportedExtensionsWithJsonIfResolveJsonModule = getSupportedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); if (validatedFilesSpec) for (const fileName of validatedFilesSpec){ @@ -36913,15 +37199,15 @@ ${lanes.join("\n")} const wildcardFiles = arrayFrom(wildcardFileMap.values()); return literalFiles.concat(wildcardFiles, arrayFrom(wildCardJsonFileMap.values())); } - function isExcludedFile(pathToCheck, spec, basePath, useCaseSensitiveFileNames, currentDirectory) { - const { validatedFilesSpec: validatedFilesSpec , validatedIncludeSpecs: validatedIncludeSpecs , validatedExcludeSpecs: validatedExcludeSpecs } = spec; + function isExcludedFile(pathToCheck, spec, basePath, useCaseSensitiveFileNames2, currentDirectory) { + const { validatedFilesSpec: validatedFilesSpec, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs } = spec; if (!length(validatedIncludeSpecs) || !length(validatedExcludeSpecs)) return false; basePath = normalizePath(basePath); - const keyMapper = createGetCanonicalFileName(useCaseSensitiveFileNames); + const keyMapper = createGetCanonicalFileName(useCaseSensitiveFileNames2); if (validatedFilesSpec) for (const fileName of validatedFilesSpec){ if (keyMapper(getNormalizedAbsolutePath(fileName, basePath)) === pathToCheck) return false; } - return matchesExcludeWorker(pathToCheck, validatedExcludeSpecs, useCaseSensitiveFileNames, currentDirectory, basePath); + return matchesExcludeWorker(pathToCheck, validatedExcludeSpecs, useCaseSensitiveFileNames2, currentDirectory, basePath); } function invalidDotDotAfterRecursiveWildcard(s) { const wildcardIndex = startsWith(s, "**/") ? 0 : s.indexOf("/**/"); @@ -36929,12 +37215,12 @@ ${lanes.join("\n")} const lastDotIndex = endsWith(s, "/..") ? s.length : s.lastIndexOf("/../"); return lastDotIndex > wildcardIndex; } - function matchesExclude(pathToCheck, excludeSpecs, useCaseSensitiveFileNames, currentDirectory) { - return matchesExcludeWorker(pathToCheck, filter(excludeSpecs, (spec)=>!invalidDotDotAfterRecursiveWildcard(spec)), useCaseSensitiveFileNames, currentDirectory); + function matchesExclude(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, currentDirectory) { + return matchesExcludeWorker(pathToCheck, filter(excludeSpecs, (spec)=>!invalidDotDotAfterRecursiveWildcard(spec)), useCaseSensitiveFileNames2, currentDirectory); } - function matchesExcludeWorker(pathToCheck, excludeSpecs, useCaseSensitiveFileNames, currentDirectory, basePath) { + function matchesExcludeWorker(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, currentDirectory, basePath) { const excludePattern = getRegularExpressionForWildcard(excludeSpecs, combinePaths(normalizePath(currentDirectory), basePath), "exclude"); - const excludeRegex = excludePattern && getRegexFromPattern(excludePattern, useCaseSensitiveFileNames); + const excludeRegex = excludePattern && getRegexFromPattern(excludePattern, useCaseSensitiveFileNames2); if (!excludeRegex) return false; if (excludeRegex.test(pathToCheck)) return true; return !hasExtension(pathToCheck) && excludeRegex.test(ensureTrailingDirectorySeparator(pathToCheck)); @@ -36948,7 +37234,7 @@ ${lanes.join("\n")} }); function createDiagnostic(message, spec) { const element = getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec); - return element ? createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) : createCompilerDiagnostic(message, spec); + return createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(jsonSourceFile, element, message, spec); } } function specToDiagnostic(spec, disallowTrailingRecursion) { @@ -36962,18 +37248,18 @@ ${lanes.join("\n")} spec ]; } - function getWildcardDirectories({ validatedIncludeSpecs: include , validatedExcludeSpecs: exclude }, path, useCaseSensitiveFileNames) { + function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExcludeSpecs: exclude }, path, useCaseSensitiveFileNames2) { const rawExcludeRegex = getRegularExpressionForWildcard(exclude, path, "exclude"); - const excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + const excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames2 ? "" : "i"); const wildcardDirectories = {}; if (include !== void 0) { const recursiveKeys = []; for (const file of include){ const spec = normalizePath(combinePaths(path, file)); if (excludeRegex && excludeRegex.test(spec)) continue; - const match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); + const match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames2); if (match) { - const { key: key , flags: flags } = match; + const { key: key, flags: flags } = match; const existingFlags = wildcardDirectories[key]; if (existingFlags === void 0 || existingFlags < flags) { wildcardDirectories[key] = flags; @@ -36982,24 +37268,24 @@ ${lanes.join("\n")} } } for(const key in wildcardDirectories)if (hasProperty(wildcardDirectories, key)) { - for (const recursiveKey of recursiveKeys)if (key !== recursiveKey && containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) delete wildcardDirectories[key]; + for (const recursiveKey of recursiveKeys)if (key !== recursiveKey && containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames2)) delete wildcardDirectories[key]; } } return wildcardDirectories; } - function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) { + function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames2) { const match = wildcardDirectoryPattern.exec(spec); if (match) { const questionWildcardIndex = spec.indexOf("?"); const starWildcardIndex = spec.indexOf("*"); const lastDirectorySeperatorIndex = spec.lastIndexOf(directorySeparator); return { - key: useCaseSensitiveFileNames ? match[0] : toFileNameLowerCase(match[0]), + key: useCaseSensitiveFileNames2 ? match[0] : toFileNameLowerCase(match[0]), flags: questionWildcardIndex !== -1 && questionWildcardIndex < lastDirectorySeperatorIndex || starWildcardIndex !== -1 && starWildcardIndex < lastDirectorySeperatorIndex ? 1 /* Recursive */ : 0 /* None */ }; } if (isImplicitGlob(spec.substring(spec.lastIndexOf(directorySeparator) + 1))) return { - key: removeTrailingDirectorySeparator(useCaseSensitiveFileNames ? spec : toFileNameLowerCase(spec)), + key: removeTrailingDirectorySeparator(useCaseSensitiveFileNames2 ? spec : toFileNameLowerCase(spec)), flags: 1 /* Recursive */ }; return void 0; @@ -37036,6 +37322,7 @@ ${lanes.join("\n")} return out; } function getOptionValueWithEmptyStrings(value1, option) { + if (value1 === void 0) return value1; switch(option.type){ case "object": return ""; @@ -37049,7 +37336,7 @@ ${lanes.join("\n")} if (!isArray(value1)) return getOptionValueWithEmptyStrings(value1, option.element); case "list": const elementType = option.element; - return isArray(value1) ? value1.map((v)=>getOptionValueWithEmptyStrings(v, elementType)) : ""; + return isArray(value1) ? mapDefined(value1, (v)=>getOptionValueWithEmptyStrings(v, elementType)) : ""; default: return forEachEntry(option.type, (optionEnumValue, optionStringValue)=>{ if (optionEnumValue === value1) return optionStringValue; @@ -37077,7 +37364,7 @@ ${lanes.join("\n")} return Debug.fail("Expected 'option.type' to have entries."); } } - var compileOnSaveCommandLineOption, jsxOptionMap, inverseJsxOptionMap, libEntries, libs, libMap, optionsForWatch, commonOptionsWithBuild, targetOptionDeclaration, moduleOptionDeclaration, commandOptionsWithoutBuild, optionDeclarations, semanticDiagnosticsOptionDeclarations, affectsEmitOptionDeclarations, affectsDeclarationPathOptionDeclarations, moduleResolutionOptionDeclarations, sourceFileAffectingCompilerOptions, optionsAffectingProgramStructure, transpileOptionValueCompilerOptions, optionsForBuild, buildOpts, typeAcquisitionDeclarations, optionsNameMapCache, compilerOptionsAlternateMode, defaultInitCompilerOptions, compilerOptionsDidYouMeanDiagnostics, buildOptionsNameMapCache, buildOptionsAlternateMode, buildOptionsDidYouMeanDiagnostics, typeAcquisitionDidYouMeanDiagnostics, watchOptionsNameMapCache, watchOptionsDidYouMeanDiagnostics, commandLineCompilerOptionsMapCache, commandLineWatchOptionsMapCache, commandLineTypeAcquisitionMapCache, extendsOptionDeclaration, _tsconfigRootOptions, defaultIncludeSpec, invalidTrailingRecursionPattern, wildcardDirectoryPattern; + var compileOnSaveCommandLineOption, jsxOptionMap, inverseJsxOptionMap, libEntries, libs, libMap, optionsForWatch, commonOptionsWithBuild, targetOptionDeclaration, moduleOptionDeclaration, commandOptionsWithoutBuild, optionDeclarations, semanticDiagnosticsOptionDeclarations, affectsEmitOptionDeclarations, affectsDeclarationPathOptionDeclarations, moduleResolutionOptionDeclarations, sourceFileAffectingCompilerOptions, optionsAffectingProgramStructure, transpileOptionValueCompilerOptions, optionsForBuild, buildOpts, typeAcquisitionDeclarations, optionsNameMapCache, compilerOptionsAlternateMode, defaultInitCompilerOptions, compilerOptionsDidYouMeanDiagnostics, buildOptionsNameMapCache, buildOptionsAlternateMode, buildOptionsDidYouMeanDiagnostics, typeAcquisitionDidYouMeanDiagnostics, watchOptionsNameMapCache, watchOptionsDidYouMeanDiagnostics, commandLineCompilerOptionsMapCache, commandLineWatchOptionsMapCache, commandLineTypeAcquisitionMapCache, extendsOptionDeclaration, compilerOptionsDeclaration, watchOptionsDeclaration, typeAcquisitionDeclaration, _tsconfigRootOptions, defaultIncludeSpec, invalidTrailingRecursionPattern, wildcardDirectoryPattern; var init_commandLineParser = __esm({ "src/compiler/commandLineParser.ts" () { "use strict"; @@ -37218,6 +37505,10 @@ ${lanes.join("\n")} "es2016.array.include", "lib.es2016.array.include.d.ts" ], + [ + "es2017.date", + "lib.es2017.date.d.ts" + ], [ "es2017.object", "lib.es2017.object.d.ts" @@ -37358,10 +37649,18 @@ ${lanes.join("\n")} "es2023.array", "lib.es2023.array.d.ts" ], + [ + "es2023.collection", + "lib.es2023.collection.d.ts" + ], [ "esnext.array", "lib.es2023.array.d.ts" ], + [ + "esnext.collection", + "lib.es2023.collection.d.ts" + ], [ "esnext.symbol", "lib.es2019.symbol.d.ts" @@ -37374,6 +37673,10 @@ ${lanes.join("\n")} "esnext.intl", "lib.esnext.intl.d.ts" ], + [ + "esnext.disposable", + "lib.esnext.disposable.d.ts" + ], [ "esnext.bigint", "lib.es2020.bigint.d.ts" @@ -37390,6 +37693,10 @@ ${lanes.join("\n")} "esnext.weakref", "lib.es2021.weakref.d.ts" ], + [ + "esnext.decorators", + "lib.esnext.decorators.d.ts" + ], [ "decorators", "lib.decorators.d.ts" @@ -37803,6 +38110,7 @@ ${lanes.join("\n")} { name: "checkJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: Diagnostics.JavaScript_Support, description: Diagnostics.Enable_error_reporting_in_type_checked_JavaScript_files, @@ -38029,7 +38337,7 @@ ${lanes.join("\n")} strictFlag: true, category: Diagnostics.Type_Checking, description: Diagnostics.Default_catch_clause_variables_as_unknown_instead_of_any, - defaultValueDescription: false + defaultValueDescription: Diagnostics.false_unless_strict_is_set }, { name: "alwaysStrict", @@ -38251,6 +38559,7 @@ ${lanes.join("\n")} name: "allowImportingTsExtensions", type: "boolean", affectsSemanticDiagnostics: true, + affectsBuildInfo: true, category: Diagnostics.Modules, description: Diagnostics.Allow_imports_to_include_TypeScript_file_extensions_Requires_moduleResolution_bundler_and_either_noEmit_or_emitDeclarationOnly_to_be_set, defaultValueDescription: false, @@ -38811,7 +39120,26 @@ ${lanes.join("\n")} name: "extends", type: "string" }, - category: Diagnostics.File_Management + category: Diagnostics.File_Management, + disallowNullOrUndefined: true + }; + compilerOptionsDeclaration = { + name: "compilerOptions", + type: "object", + elementOptions: getCommandLineCompilerOptionsMap(), + extraKeyDiagnostics: compilerOptionsDidYouMeanDiagnostics + }; + watchOptionsDeclaration = { + name: "watchOptions", + type: "object", + elementOptions: getCommandLineWatchOptionsMap(), + extraKeyDiagnostics: watchOptionsDidYouMeanDiagnostics + }; + typeAcquisitionDeclaration = { + name: "typeAcquisition", + type: "object", + elementOptions: getCommandLineTypeAcquisitionMap(), + extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics }; defaultIncludeSpec = "**/*"; invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; @@ -38863,6 +39191,14 @@ ${lanes.join("\n")} if (extensions & 8 /* Json */ ) result.push("JSON"); return result.join(", "); } + function extensionsToExtensionsArray(extensions) { + const result = []; + if (extensions & 1 /* TypeScript */ ) result.push(...supportedTSImplementationExtensions); + if (extensions & 2 /* JavaScript */ ) result.push(...supportedJSExtensionsFlat); + if (extensions & 4 /* Declaration */ ) result.push(...supportedDeclarationExtensions); + if (extensions & 8 /* Json */ ) result.push(".json" /* Json */ ); + return result; + } function resolvedTypeScriptOnly(resolved) { if (!resolved) return void 0; Debug.assert(extensionIsTS(resolved.extension)); @@ -38873,7 +39209,7 @@ ${lanes.join("\n")} } function createResolvedModuleWithFailedLookupLocationsHandlingSymlink(moduleName, resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, state, legacyResult) { if (!state.resultFromCache && !state.compilerOptions.preserveSymlinks && resolved && isExternalLibraryImport && !resolved.originalPath && !isExternalModuleNameRelative(moduleName)) { - const { resolvedFileName: resolvedFileName , originalPath: originalPath } = getOriginalAndResolvedFileName(resolved.path, state.host, state.traceEnabled); + const { resolvedFileName: resolvedFileName, originalPath: originalPath } = getOriginalAndResolvedFileName(resolved.path, state.host, state.traceEnabled); if (originalPath) resolved = { ...resolved, path: resolvedFileName, @@ -38962,7 +39298,7 @@ ${lanes.join("\n")} if (state.traceEnabled) trace(state.host, Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, versionMajorMinor); return; } - const { version: bestVersionKey , paths: bestVersionPaths } = result; + const { version: bestVersionKey, paths: bestVersionPaths } = result; if (typeof bestVersionPaths !== "object") { if (state.traceEnabled) trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, `typesVersions['${bestVersionKey}']`, "object", typeof bestVersionPaths); return; @@ -38986,23 +39322,19 @@ ${lanes.join("\n")} let currentDirectory; if (options.configFilePath) currentDirectory = getDirectoryPath(options.configFilePath); else if (host.getCurrentDirectory) currentDirectory = host.getCurrentDirectory(); - if (currentDirectory !== void 0) return getDefaultTypeRoots(currentDirectory, host); + if (currentDirectory !== void 0) return getDefaultTypeRoots(currentDirectory); } - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) return [ - combinePaths(currentDirectory, nodeModulesAtTypes) - ]; + function getDefaultTypeRoots(currentDirectory) { let typeRoots; forEachAncestorDirectory(normalizePath(currentDirectory), (directory)=>{ const atTypes = combinePaths(directory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) (typeRoots || (typeRoots = [])).push(atTypes); - return void 0; + (typeRoots ?? (typeRoots = [])).push(atTypes); }); return typeRoots; } function arePathsEqual(path1, path2, host) { - const useCaseSensitiveFileNames = typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames; - return comparePaths(path1, path2, !useCaseSensitiveFileNames) === 0 /* EqualTo */ ; + const useCaseSensitiveFileNames2 = typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames; + return comparePaths(path1, path2, !useCaseSensitiveFileNames2) === 0 /* EqualTo */ ; } function getOriginalAndResolvedFileName(fileName, host, traceEnabled) { const resolvedFileName = realPath(fileName, host, traceEnabled); @@ -39013,6 +39345,10 @@ ${lanes.join("\n")} originalPath: pathsAreEqual ? void 0 : fileName }; } + function getCandidateFromTypeRoot(typeRoot, typeReferenceDirectiveName, moduleResolutionState) { + const nameForLookup = endsWith(typeRoot, "/node_modules/@types") || endsWith(typeRoot, "/node_modules/@types/") ? mangleScopedPackageNameWithTrace(typeReferenceDirectiveName, moduleResolutionState) : typeReferenceDirectiveName; + return combinePaths(typeRoot, nameForLookup); + } function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, cache, resolutionMode) { Debug.assert(typeof typeReferenceDirectiveName === "string", "Non-string value passed to `ts.resolveTypeReferenceDirective`, likely by a wrapping package working with an outdated `resolveTypeReferenceDirectives` signature. This is probably not a problem in TS itself."); const traceEnabled = isTraceEnabled(options, host); @@ -39066,9 +39402,9 @@ ${lanes.join("\n")} } let resolvedTypeReferenceDirective; if (resolved) { - const { fileName: fileName , packageId: packageId } = resolved; + const { fileName: fileName, packageId: packageId } = resolved; let resolvedFileName = fileName, originalPath; - if (!options.preserveSymlinks) ({ resolvedFileName: resolvedFileName , originalPath: originalPath } = getOriginalAndResolvedFileName(fileName, host, traceEnabled)); + if (!options.preserveSymlinks) ({ resolvedFileName: resolvedFileName, originalPath: originalPath } = getOriginalAndResolvedFileName(fileName, host, traceEnabled)); resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, @@ -39090,8 +39426,8 @@ ${lanes.join("\n")} if (traceEnabled) traceResult(result); return result; function traceResult(result2) { - var _a2; - if (!((_a2 = result2.resolvedTypeReferenceDirective) == null ? void 0 : _a2.resolvedFileName)) trace(host, Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + var _a; + if (!((_a = result2.resolvedTypeReferenceDirective) == null ? void 0 : _a.resolvedFileName)) trace(host, Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); else if (result2.resolvedTypeReferenceDirective.packageId) trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, result2.resolvedTypeReferenceDirective.resolvedFileName, packageIdToString(result2.resolvedTypeReferenceDirective.packageId), result2.resolvedTypeReferenceDirective.primary); else trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, result2.resolvedTypeReferenceDirective.resolvedFileName, result2.resolvedTypeReferenceDirective.primary); } @@ -39099,10 +39435,17 @@ ${lanes.join("\n")} if (typeRoots && typeRoots.length) { if (traceEnabled) trace(host, Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); return firstDefined(typeRoots, (typeRoot)=>{ - const candidate = combinePaths(typeRoot, typeReferenceDirectiveName); - const candidateDirectory = getDirectoryPath(candidate); - const directoryExists = directoryProbablyExists(candidateDirectory, host); - if (!directoryExists && traceEnabled) trace(host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); + const candidate = getCandidateFromTypeRoot(typeRoot, typeReferenceDirectiveName, moduleResolutionState); + const directoryExists = directoryProbablyExists(typeRoot, host); + if (!directoryExists && traceEnabled) trace(host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, typeRoot); + if (options.typeRoots) { + const resolvedFromFile = loadModuleFromFile(4 /* Declaration */ , candidate, !directoryExists, moduleResolutionState); + if (resolvedFromFile) { + const packageDirectory = parseNodeModuleFromPath(resolvedFromFile.path); + const packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, moduleResolutionState) : void 0; + return resolvedTypeScriptOnly(withPackageId(packageInfo, resolvedFromFile)); + } + } return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(4 /* Declaration */ , candidate, !directoryExists, moduleResolutionState)); }); } else if (traceEnabled) trace(host, Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); @@ -39110,15 +39453,17 @@ ${lanes.join("\n")} function secondaryLookup() { const initialLocationForSecondaryLookup = containingFile && getDirectoryPath(containingFile); if (initialLocationForSecondaryLookup !== void 0) { - if (traceEnabled) trace(host, Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); let result2; - if (!isExternalModuleNameRelative(typeReferenceDirectiveName)) { - const searchResult = loadModuleFromNearestNodeModulesDirectory(4 /* Declaration */ , typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ void 0, /*redirectedReference*/ void 0); - result2 = searchResult && searchResult.value; - } else { - const { path: candidate } = normalizePathForCJSResolution(initialLocationForSecondaryLookup, typeReferenceDirectiveName); - result2 = nodeLoadModuleByRelativeName(4 /* Declaration */ , candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); - } + if (!options.typeRoots || !endsWith(containingFile, inferredTypesContainingFile)) { + if (traceEnabled) trace(host, Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + if (!isExternalModuleNameRelative(typeReferenceDirectiveName)) { + const searchResult = loadModuleFromNearestNodeModulesDirectory(4 /* Declaration */ , typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ void 0, /*redirectedReference*/ void 0); + result2 = searchResult && searchResult.value; + } else { + const { path: candidate } = normalizePathForCJSResolution(initialLocationForSecondaryLookup, typeReferenceDirectiveName); + result2 = nodeLoadModuleByRelativeName(4 /* Declaration */ , candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); + } + } else if (traceEnabled) trace(host, Diagnostics.Resolving_type_reference_directive_for_program_that_specifies_custom_typeRoots_skipping_lookup_in_node_modules_folder); return resolvedTypeScriptOnly(result2); } else if (traceEnabled) trace(host, Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); } @@ -39182,15 +39527,15 @@ ${lanes.join("\n")} return result; } function compilerOptionValueToString(value1) { - var _a2; + var _a; if (value1 === null || typeof value1 !== "object") return "" + value1; - if (isArray(value1)) return `[${(_a2 = value1.map((e)=>compilerOptionValueToString(e))) == null ? void 0 : _a2.join(",")}]`; + if (isArray(value1)) return `[${(_a = value1.map((e)=>compilerOptionValueToString(e))) == null ? void 0 : _a.join(",")}]`; let str = "{"; for(const key in value1)if (hasProperty(value1, key)) str += `${key}: ${compilerOptionValueToString(value1[key])}`; return str + "}"; } function getKeyForCompilerOptions(options, affectingOptionDeclarations) { - return affectingOptionDeclarations.map((option)=>compilerOptionValueToString(getCompilerOptionValue(options, option))).join("|") + (options.pathsBasePath ? `|${options.pathsBasePath}` : void 0); + return affectingOptionDeclarations.map((option)=>compilerOptionValueToString(getCompilerOptionValue(options, option))).join("|") + `|${options.pathsBasePath}`; } function createCacheWithRedirects(ownOptions) { const redirectsMap = /* @__PURE__ */ new Map(); @@ -39228,7 +39573,7 @@ ${lanes.join("\n")} if (ownKey === key) result = ownMap; else if (!redirectsKeyToMap.has(ownKey)) redirectsKeyToMap.set(ownKey, ownMap); } - if (create) result != null ? result : result = /* @__PURE__ */ new Map(); + if (create) result ?? (result = /* @__PURE__ */ new Map()); if (result) redirectsKeyToMap.set(key, result); } if (result) redirectsMap.set(redirectOptions, result); @@ -39305,9 +39650,9 @@ ${lanes.join("\n")} return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, ()=>createModeAwareCache()); } function getFromDirectoryCache(name, mode, directoryName, redirectedReference) { - var _a2, _b; + var _a, _b; const path = toPath(directoryName, currentDirectory, getCanonicalFileName); - return (_b = (_a2 = directoryToModuleNameMap.getMapOfCacheRedirects(redirectedReference)) == null ? void 0 : _a2.get(path)) == null ? void 0 : _b.get(name, mode); + return (_b = (_a = directoryToModuleNameMap.getMapOfCacheRedirects(redirectedReference)) == null ? void 0 : _a.get(path)) == null ? void 0 : _b.get(name, mode); } } function createModeAwareCacheKey(specifier, mode) { @@ -39381,9 +39726,9 @@ ${lanes.join("\n")} moduleNameToDirectoryMap.update(options2); } function getFromNonRelativeNameCache(nonRelativeModuleName, mode, directoryName, redirectedReference) { - var _a2, _b; + var _a, _b; Debug.assert(!isExternalModuleNameRelative(nonRelativeModuleName)); - return (_b = (_a2 = moduleNameToDirectoryMap.getMapOfCacheRedirects(redirectedReference)) == null ? void 0 : _a2.get(createModeAwareCacheKey(nonRelativeModuleName, mode))) == null ? void 0 : _b.get(directoryName); + return (_b = (_a = moduleNameToDirectoryMap.getMapOfCacheRedirects(redirectedReference)) == null ? void 0 : _a.get(createModeAwareCacheKey(nonRelativeModuleName, mode))) == null ? void 0 : _b.get(directoryName); } function getOrCreateCacheForNonRelativeName(nonRelativeModuleName, mode, redirectedReference) { Debug.assert(!isExternalModuleNameRelative(nonRelativeModuleName)); @@ -39429,7 +39774,7 @@ ${lanes.join("\n")} function createModuleOrTypeReferenceResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, getResolvedFileName) { const perDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, options); const nonRelativeNameResolutionCache = createNonRelativeNameResolutionCache(currentDirectory, getCanonicalFileName, options, getResolvedFileName); - packageJsonInfoCache != null ? packageJsonInfoCache : packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName); + packageJsonInfoCache ?? (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); return { ...packageJsonInfoCache, ...perDirectoryResolutionCache, @@ -39452,19 +39797,29 @@ ${lanes.join("\n")} nonRelativeNameResolutionCache.update(options2); } } - function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) { - const result = createModuleOrTypeReferenceResolutionCache(currentDirectory, getCanonicalFileName, options, /*packageJsonInfoCache*/ void 0, getOriginalOrResolvedModuleFileName); + function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache) { + const result = createModuleOrTypeReferenceResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, getOriginalOrResolvedModuleFileName); result.getOrCreateCacheForModuleName = (nonRelativeName, mode, redirectedReference)=>result.getOrCreateCacheForNonRelativeName(nonRelativeName, mode, redirectedReference); return result; } function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache) { return createModuleOrTypeReferenceResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, getOriginalOrResolvedTypeReferenceFileName); } + function getOptionsForLibraryResolution(options) { + return { + moduleResolution: 2 /* Node10 */ , + traceResolution: options.traceResolution + }; + } + function resolveLibrary(libraryName, resolveFrom, compilerOptions, host, cache) { + return resolveModuleName(libraryName, resolveFrom, getOptionsForLibraryResolution(compilerOptions), host, cache); + } function resolveModuleNameFromCache(moduleName, containingFile, cache, mode) { const containingDirectory = getDirectoryPath(containingFile); return cache.getFromDirectoryCache(moduleName, mode, containingDirectory, /*redirectedReference*/ void 0); } function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { + var _a, _b, _c; const traceEnabled = isTraceEnabled(compilerOptions, host); if (redirectedReference) compilerOptions = redirectedReference.commandLine.options; if (traceEnabled) { @@ -39494,7 +39849,7 @@ ${lanes.join("\n")} } if (traceEnabled) trace(host, Diagnostics.Module_resolution_kind_is_not_specified_using_0, ModuleResolutionKind[moduleResolution]); } else if (traceEnabled) trace(host, Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ModuleResolutionKind[moduleResolution]); - perfLogger.logStartResolveModule(moduleName); + (_a = perfLogger) == null || _a.logStartResolveModule(moduleName); switch(moduleResolution){ case 3 /* Node16 */ : result = node16ModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode); @@ -39514,8 +39869,8 @@ ${lanes.join("\n")} default: return Debug.fail(`Unexpected moduleResolution: ${moduleResolution}`); } - if (result && result.resolvedModule) perfLogger.logInfoEvent(`Module "${moduleName}" resolved to "${result.resolvedModule.resolvedFileName}"`); - perfLogger.logStopResolveModule(result && result.resolvedModule ? "" + result.resolvedModule.resolvedFileName : "null"); + if (result && result.resolvedModule) (_b = perfLogger) == null || _b.logInfoEvent(`Module "${moduleName}" resolved to "${result.resolvedModule.resolvedFileName}"`); + (_c = perfLogger) == null || _c.logStopResolveModule(result && result.resolvedModule ? "" + result.resolvedModule.resolvedFileName : "null"); cache == null || cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference).set(moduleName, resolutionMode, result); if (!isExternalModuleNameRelative(moduleName)) cache == null || cache.getOrCreateCacheForNonRelativeName(moduleName, resolutionMode, redirectedReference).set(containingDirectory, result); } @@ -39534,15 +39889,15 @@ ${lanes.join("\n")} else return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) { - var _a2; - const { baseUrl: baseUrl , paths: paths , configFile: configFile } = state.compilerOptions; + var _a; + const { baseUrl: baseUrl, paths: paths, configFile: configFile } = state.compilerOptions; if (paths && !pathIsRelative(moduleName)) { if (state.traceEnabled) { if (baseUrl) trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); trace(state.host, Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } const baseDirectory = getPathsBasePath(state.compilerOptions, state.host); - const pathPatterns = (configFile == null ? void 0 : configFile.configFileSpecs) ? (_a2 = configFile.configFileSpecs).pathPatterns || (_a2.pathPatterns = tryParsePatterns(paths)) : void 0; + const pathPatterns = (configFile == null ? void 0 : configFile.configFileSpecs) ? (_a = configFile.configFileSpecs).pathPatterns || (_a.pathPatterns = tryParsePatterns(paths)) : void 0; return tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, pathPatterns, loader, /*onlyRecordFailures*/ false, state); } } @@ -39582,7 +39937,7 @@ ${lanes.join("\n")} return void 0; } function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { - const { baseUrl: baseUrl } = state.compilerOptions; + const { baseUrl: baseUrl } = state.compilerOptions; if (!baseUrl) return void 0; if (state.traceEnabled) trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); const candidate = normalizePath(combinePaths(baseUrl, moduleName)); @@ -39590,7 +39945,7 @@ ${lanes.join("\n")} return loader(extensions, candidate, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); } function resolveJSModule(moduleName, initialDir, host) { - const { resolvedModule: resolvedModule , failedLookupLocations: failedLookupLocations } = tryResolveJSModuleWorker(moduleName, initialDir, host); + const { resolvedModule: resolvedModule, failedLookupLocations: failedLookupLocations } = tryResolveJSModuleWorker(moduleName, initialDir, host); if (!resolvedModule) throw new Error(`Could not resolve JS module '${moduleName}' starting at '${initialDir}'. Looked in: ${failedLookupLocations == null ? void 0 : failedLookupLocations.join(", ")}`); return resolvedModule.resolvedFileName; } @@ -39611,7 +39966,7 @@ ${lanes.join("\n")} return nodeModuleNameResolverWorker(0 /* None */ , moduleName, initialDir, { moduleResolution: 2 /* Node10 */ , allowJs: true - }, host, /*cache*/ void 0, 2 /* JavaScript */ , /*isConfigLookup*/ false, /*redirectedReferences*/ void 0); + }, host, /*cache*/ void 0, 2 /* JavaScript */ , /*isConfigLookup*/ false, /*redirectedReference*/ void 0); } function bundlerModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { const containingDirectory = getDirectoryPath(containingFile); @@ -39634,7 +39989,7 @@ ${lanes.join("\n")} }, host, /*cache*/ void 0, 8 /* Json */ , /*isConfigLookup*/ true, /*redirectedReference*/ void 0); } function nodeModuleNameResolverWorker(features, moduleName, containingDirectory, compilerOptions, host, cache, extensions, isConfigLookup, redirectedReference) { - var _a2, _b, _c, _d; + var _a, _b, _c, _d; const traceEnabled = isTraceEnabled(compilerOptions, host); const failedLookupLocations = []; const affectingLocations = []; @@ -39662,13 +40017,11 @@ ${lanes.join("\n")} result = priorityExtensions && tryResolve(priorityExtensions, state) || secondaryExtensions && tryResolve(secondaryExtensions, state) || void 0; } else result = tryResolve(extensions, state); let legacyResult; - if (((_a2 = result == null ? void 0 : result.value) == null ? void 0 : _a2.isExternalLibraryImport) && !isConfigLookup && extensions & 5 /* Declaration */ && features & 8 /* Exports */ && !isExternalModuleNameRelative(moduleName) && !extensionIsOk(5 /* Declaration */ , result.value.resolved.extension) && conditions.indexOf("import") > -1) { + if (((_a = result == null ? void 0 : result.value) == null ? void 0 : _a.isExternalLibraryImport) && !isConfigLookup && extensions & 5 /* Declaration */ && features & 8 /* Exports */ && !isExternalModuleNameRelative(moduleName) && !extensionIsOk(5 /* Declaration */ , result.value.resolved.extension) && conditions.indexOf("import") > -1) { traceIfEnabled(state, Diagnostics.Resolution_of_non_relative_name_failed_trying_with_modern_Node_resolution_features_disabled_to_see_if_npm_library_needs_configuration_update); const diagnosticState = { ...state, features: state.features & -9 /* Exports */ , - failedLookupLocations: [], - affectingLocations: [], reportDiagnostic: noop }; const diagnosticResult = tryResolve(extensions & 5 /* Declaration */ , diagnosticState); @@ -39687,9 +40040,14 @@ ${lanes.join("\n")} if (features & 2 /* Imports */ && startsWith(moduleName, "#")) resolved2 = loadModuleFromImports(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference); if (!resolved2 && features & 4 /* SelfName */ ) resolved2 = loadModuleFromSelfNameReference(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference); if (!resolved2) { + if (moduleName.indexOf(":") > -1) { + if (traceEnabled) trace(host, Diagnostics.Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1, moduleName, formatExtensions(extensions2)); + return void 0; + } if (traceEnabled) trace(host, Diagnostics.Loading_module_0_from_node_modules_folder_target_file_types_Colon_1, moduleName, formatExtensions(extensions2)); resolved2 = loadModuleFromNearestNodeModulesDirectory(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference); } + if (extensions2 & 4 /* Declaration */ ) resolved2 ?? (resolved2 = resolveFromTypeRoot(moduleName, state2)); return resolved2 && { value: resolved2.value && { resolved: resolved2.value, @@ -39697,7 +40055,7 @@ ${lanes.join("\n")} } }; } else { - const { path: candidate , parts: parts } = normalizePathForCJSResolution(containingDirectory, moduleName); + const { path: candidate, parts: parts } = normalizePathForCJSResolution(containingDirectory, moduleName); const resolved2 = nodeLoadModuleByRelativeName(extensions2, candidate, /*onlyRecordFailures*/ false, state2, /*considerPackageJson*/ true); return resolved2 && toSearchResult({ resolved: resolved2, @@ -39753,18 +40111,18 @@ ${lanes.join("\n")} function pathContainsNodeModules(path) { return stringContains(path, nodeModulesPathPart); } - function parseNodeModuleFromPath(resolved) { + function parseNodeModuleFromPath(resolved, isFolder) { const path = normalizePath(resolved); const idx = path.lastIndexOf(nodeModulesPathPart); if (idx === -1) return void 0; const indexAfterNodeModules = idx + nodeModulesPathPart.length; - let indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); - if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */ ) indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + let indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules, isFolder); + if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */ ) indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName, isFolder); return path.slice(0, indexAfterPackageName); } - function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { + function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex, isFolder) { const nextSeparatorIndex = path.indexOf(directorySeparator, prevSeparatorIndex + 1); - return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + return nextSeparatorIndex === -1 ? isFolder ? path.length : prevSeparatorIndex : nextSeparatorIndex; } function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); @@ -39842,20 +40200,21 @@ ${lanes.join("\n")} } } function tryFile(fileName, onlyRecordFailures, state) { - var _a2, _b; - if (!((_a2 = state.compilerOptions.moduleSuffixes) == null ? void 0 : _a2.length)) return tryFileLookup(fileName, onlyRecordFailures, state); - const ext = (_b = tryGetExtensionFromPath2(fileName)) != null ? _b : ""; + var _a; + if (!((_a = state.compilerOptions.moduleSuffixes) == null ? void 0 : _a.length)) return tryFileLookup(fileName, onlyRecordFailures, state); + const ext = tryGetExtensionFromPath2(fileName) ?? ""; const fileNameNoExtension = ext ? removeExtension(fileName, ext) : fileName; return forEach(state.compilerOptions.moduleSuffixes, (suffix)=>tryFileLookup(fileNameNoExtension + suffix + ext, onlyRecordFailures, state)); } function tryFileLookup(fileName, onlyRecordFailures, state) { + var _a; if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) trace(state.host, Diagnostics.File_0_exists_use_it_as_a_name_resolution_result, fileName); return fileName; } else if (state.traceEnabled) trace(state.host, Diagnostics.File_0_does_not_exist, fileName); } - state.failedLookupLocations.push(fileName); + (_a = state.failedLookupLocations) == null || _a.push(fileName); return void 0; } function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson = true) { @@ -39883,7 +40242,8 @@ ${lanes.join("\n")} const loadPackageJsonExportsState = { ...loadPackageJsonMainState, failedLookupLocations: [], - conditions: conditions + conditions: conditions, + host: host }; const exportResolutions = loadEntrypointsFromExportMap(packageJsonInfo, packageJsonInfo.contents.packageJsonContent.exports, loadPackageJsonExportsState, extensions); if (exportResolutions) for (const resolution of exportResolutions)entrypoints = appendIfUnique(entrypoints, resolution.path); @@ -39898,16 +40258,29 @@ ${lanes.join("\n")} else loadEntrypointsFromTargetExports(exports); return entrypoints; function loadEntrypointsFromTargetExports(target) { - var _a2, _b; - if (typeof target === "string" && startsWith(target, "./") && target.indexOf("*") === -1) { - const partsAfterFirst = getPathComponents(target).slice(2); - if (partsAfterFirst.indexOf("..") >= 0 || partsAfterFirst.indexOf(".") >= 0 || partsAfterFirst.indexOf("node_modules") >= 0) return false; - const resolvedTarget = combinePaths(scope.packageDirectory, target); - const finalPath = getNormalizedAbsolutePath(resolvedTarget, (_b = (_a2 = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a2)); - const result = loadFileNameFromPackageJsonField(extensions, finalPath, /*recordOnlyFailures*/ false, state); - if (result) { - entrypoints = appendIfUnique(entrypoints, result, (a, b)=>a.path === b.path); - return true; + var _a, _b; + if (typeof target === "string" && startsWith(target, "./")) { + if (target.indexOf("*") >= 0 && state.host.readDirectory) { + if (target.indexOf("*") !== target.lastIndexOf("*")) return false; + state.host.readDirectory(scope.packageDirectory, extensionsToExtensionsArray(extensions), /*excludes*/ void 0, [ + changeAnyExtension(target.replace("*", "**/*"), getDeclarationEmitExtensionForPath(target)) + ]).forEach((entry)=>{ + entrypoints = appendIfUnique(entrypoints, { + path: entry, + ext: getAnyExtensionFromPath(entry), + resolvedUsingTsExtension: void 0 + }); + }); + } else { + const partsAfterFirst = getPathComponents(target).slice(2); + if (partsAfterFirst.indexOf("..") >= 0 || partsAfterFirst.indexOf(".") >= 0 || partsAfterFirst.indexOf("node_modules") >= 0) return false; + const resolvedTarget = combinePaths(scope.packageDirectory, target); + const finalPath = getNormalizedAbsolutePath(resolvedTarget, (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)); + const result = loadFileNameFromPackageJsonField(extensions, finalPath, /*onlyRecordFailures*/ false, state); + if (result) { + entrypoints = appendIfUnique(entrypoints, result, (a, b)=>a.path === b.path); + return true; + } } } else if (Array.isArray(target)) for (const t of target){ const success = loadEntrypointsFromTargetExports(t); @@ -39926,8 +40299,8 @@ ${lanes.join("\n")} host: host, compilerOptions: options, traceEnabled: isTraceEnabled(options, host), - failedLookupLocations: noopPush, - affectingLocations: noopPush, + failedLookupLocations: void 0, + affectingLocations: void 0, packageJsonInfoCache: packageJsonInfoCache, features: 0 /* None */ , conditions: emptyArray, @@ -39952,25 +40325,25 @@ ${lanes.join("\n")} return packageJsonInfo.contents.versionPaths || void 0; } function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) { - var _a2, _b, _c; - const { host: host , traceEnabled: traceEnabled } = state; + var _a, _b, _c, _d, _e, _f, _g, _h; + const { host: host, traceEnabled: traceEnabled } = state; const packageJsonPath = combinePaths(packageDirectory, "package.json"); if (onlyRecordFailures) { - state.failedLookupLocations.push(packageJsonPath); + (_a = state.failedLookupLocations) == null || _a.push(packageJsonPath); return void 0; } - const existing = (_a2 = state.packageJsonInfoCache) == null ? void 0 : _a2.getPackageJsonInfo(packageJsonPath); + const existing = (_b = state.packageJsonInfoCache) == null ? void 0 : _b.getPackageJsonInfo(packageJsonPath); if (existing !== void 0) { if (typeof existing !== "boolean") { if (traceEnabled) trace(host, Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); - state.affectingLocations.push(packageJsonPath); + (_c = state.affectingLocations) == null || _c.push(packageJsonPath); return existing.packageDirectory === packageDirectory ? existing : { packageDirectory: packageDirectory, contents: existing.contents }; } else { if (existing && traceEnabled) trace(host, Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath); - state.failedLookupLocations.push(packageJsonPath); + (_d = state.failedLookupLocations) == null || _d.push(packageJsonPath); return void 0; } } @@ -39986,13 +40359,13 @@ ${lanes.join("\n")} resolvedEntrypoints: void 0 } }; - (_b = state.packageJsonInfoCache) == null || _b.setPackageJsonInfo(packageJsonPath, result); - state.affectingLocations.push(packageJsonPath); + (_e = state.packageJsonInfoCache) == null || _e.setPackageJsonInfo(packageJsonPath, result); + (_f = state.affectingLocations) == null || _f.push(packageJsonPath); return result; } else { if (directoryExists && traceEnabled) trace(host, Diagnostics.File_0_does_not_exist, packageJsonPath); - (_c = state.packageJsonInfoCache) == null || _c.setPackageJsonInfo(packageJsonPath, directoryExists); - state.failedLookupLocations.push(packageJsonPath); + (_g = state.packageJsonInfoCache) == null || _g.setPackageJsonInfo(packageJsonPath, directoryExists); + (_h = state.failedLookupLocations) == null || _h.push(packageJsonPath); } } function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { @@ -40060,8 +40433,8 @@ ${lanes.join("\n")} return !some(getOwnKeys(obj), (k)=>startsWith(k, ".")); } function loadModuleFromSelfNameReference(extensions, moduleName, directory, state, cache, redirectedReference) { - var _a2, _b; - const directoryPath = getNormalizedAbsolutePath(combinePaths(directory, "dummy"), (_b = (_a2 = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a2)); + var _a, _b; + const directoryPath = getNormalizedAbsolutePath(combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)); const scope = getPackageScopeForPath(directoryPath, state); if (!scope || !scope.contents.packageJsonContent.exports) return void 0; if (typeof scope.contents.packageJsonContent.name !== "string") return void 0; @@ -40070,6 +40443,7 @@ ${lanes.join("\n")} if (!every(nameParts, (p, i)=>parts[i] === p)) return void 0; const trailingParts = parts.slice(nameParts.length); const subpath = !length(trailingParts) ? "." : `.${directorySeparator}${trailingParts.join(directorySeparator)}`; + if (getAllowJSCompilerOption(state.compilerOptions) && !pathContainsNodeModules(directory)) return loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference); const priorityExtensions = extensions & 5 /* Declaration */ ; const secondaryExtensions = extensions & -6; return loadModuleFromExports(scope, priorityExtensions, subpath, state, cache, redirectedReference) || loadModuleFromExports(scope, secondaryExtensions, subpath, state, cache, redirectedReference); @@ -40096,12 +40470,12 @@ ${lanes.join("\n")} return toSearchResult(/*value*/ void 0); } function loadModuleFromImports(extensions, moduleName, directory, state, cache, redirectedReference) { - var _a2, _b; + var _a, _b; if (moduleName === "#" || startsWith(moduleName, "#/")) { if (state.traceEnabled) trace(state.host, Diagnostics.Invalid_import_specifier_0_has_no_possible_resolutions, moduleName); return toSearchResult(/*value*/ void 0); } - const directoryPath = getNormalizedAbsolutePath(combinePaths(directory, "dummy"), (_b = (_a2 = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a2)); + const directoryPath = getNormalizedAbsolutePath(combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)); const scope = getPackageScopeForPath(directoryPath, state); if (!scope) { if (state.traceEnabled) trace(state.host, Diagnostics.Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve, directoryPath); @@ -40233,25 +40607,22 @@ ${lanes.join("\n")} if (state.traceEnabled) trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName); return toSearchResult(/*value*/ void 0); function toAbsolutePath(path) { - var _a2, _b; + var _a, _b; if (path === void 0) return path; - return getNormalizedAbsolutePath(path, (_b = (_a2 = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a2)); + return getNormalizedAbsolutePath(path, (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)); } function combineDirectoryPath(root, dir) { return ensureTrailingDirectorySeparator(combinePaths(root, dir)); } - function useCaseSensitiveFileNames() { - return !state.host.useCaseSensitiveFileNames ? true : typeof state.host.useCaseSensitiveFileNames === "boolean" ? state.host.useCaseSensitiveFileNames : state.host.useCaseSensitiveFileNames(); - } function tryLoadInputFileForPath(finalPath, entry, packagePath, isImports2) { - var _a2, _b, _c, _d; - if (!state.isConfigLookup && (state.compilerOptions.declarationDir || state.compilerOptions.outDir) && finalPath.indexOf("/node_modules/") === -1 && (state.compilerOptions.configFile ? containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames()) : true)) { + var _a, _b, _c, _d; + if (!state.isConfigLookup && (state.compilerOptions.declarationDir || state.compilerOptions.outDir) && finalPath.indexOf("/node_modules/") === -1 && (state.compilerOptions.configFile ? containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames(state)) : true)) { const getCanonicalFileName = hostGetCanonicalFileName({ - useCaseSensitiveFileNames: useCaseSensitiveFileNames + useCaseSensitiveFileNames: ()=>useCaseSensitiveFileNames(state) }); const commonSourceDirGuesses = []; if (state.compilerOptions.rootDir || state.compilerOptions.composite && state.compilerOptions.configFilePath) { - const commonDir = toAbsolutePath(getCommonSourceDirectory(state.compilerOptions, ()=>[], ((_b = (_a2 = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a2)) || "", getCanonicalFileName)); + const commonDir = toAbsolutePath(getCommonSourceDirectory(state.compilerOptions, ()=>[], ((_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)) || "", getCanonicalFileName)); commonSourceDirGuesses.push(commonDir); } else if (state.requestContainingDirectory) { const requestingFile = toAbsolutePath(combinePaths(state.requestContainingDirectory, "index.ts")); @@ -40273,7 +40644,7 @@ ${lanes.join("\n")} packagePath)); for (const commonSourceDirGuess of commonSourceDirGuesses){ const candidateDirectories = getOutputDirectoriesForBaseDirectory(commonSourceDirGuess); - for (const candidateDir of candidateDirectories)if (containsPath(candidateDir, finalPath, !useCaseSensitiveFileNames())) { + for (const candidateDir of candidateDirectories)if (containsPath(candidateDir, finalPath, !useCaseSensitiveFileNames(state))) { const pathFragment = finalPath.slice(candidateDir.length + 1); const possibleInputBase = combinePaths(commonSourceDirGuess, pathFragment); const jsAndDtsExtensions = [ @@ -40289,7 +40660,7 @@ ${lanes.join("\n")} const inputExts = getPossibleOriginalInputExtensionForExtension(possibleInputBase); for (const possibleExt of inputExts){ if (!extensionIsOk(extensions, possibleExt)) continue; - const possibleInputWithInputExtension = changeAnyExtension(possibleInputBase, possibleExt, ext, !useCaseSensitiveFileNames()); + const possibleInputWithInputExtension = changeAnyExtension(possibleInputBase, possibleExt, ext, !useCaseSensitiveFileNames(state)); if (state.host.fileExists(possibleInputWithInputExtension)) return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField(extensions, possibleInputWithInputExtension, /*onlyRecordFailures*/ false, state))); } } @@ -40298,8 +40669,8 @@ ${lanes.join("\n")} } return void 0; function getOutputDirectoriesForBaseDirectory(commonSourceDirGuess) { - var _a3, _b2; - const currentDir = state.compilerOptions.configFile ? ((_b2 = (_a3 = state.host).getCurrentDirectory) == null ? void 0 : _b2.call(_a3)) || "" : commonSourceDirGuess; + var _a2, _b2; + const currentDir = state.compilerOptions.configFile ? ((_b2 = (_a2 = state.host).getCurrentDirectory) == null ? void 0 : _b2.call(_a2)) || "" : commonSourceDirGuess; const candidateDirectories = []; if (state.compilerOptions.declarationDir) candidateDirectories.push(toAbsolutePath(combineDirectoryPath(currentDir, state.compilerOptions.declarationDir))); if (state.compilerOptions.outDir && state.compilerOptions.outDir !== state.compilerOptions.declarationDir) candidateDirectories.push(toAbsolutePath(combineDirectoryPath(currentDir, state.compilerOptions.outDir))); @@ -40326,10 +40697,14 @@ ${lanes.join("\n")} const priorityExtensions = extensions & 5 /* Declaration */ ; const secondaryExtensions = extensions & -6; if (priorityExtensions) { + traceIfEnabled(state, Diagnostics.Searching_all_ancestor_node_modules_directories_for_preferred_extensions_Colon_0, formatExtensions(priorityExtensions)); const result = lookup(priorityExtensions); if (result) return result; } - if (secondaryExtensions && !typesScopeOnly) return lookup(secondaryExtensions); + if (secondaryExtensions && !typesScopeOnly) { + traceIfEnabled(state, Diagnostics.Searching_all_ancestor_node_modules_directories_for_fallback_extensions_Colon_0, formatExtensions(secondaryExtensions)); + return lookup(secondaryExtensions); + } function lookup(extensions2) { return forEachAncestorDirectory(normalizeSlashes(directory), (ancestorDirectory)=>{ if (getBaseFileName(ancestorDirectory) !== "node_modules") { @@ -40359,25 +40734,25 @@ ${lanes.join("\n")} } } function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state, cache, redirectedReference) { - var _a2, _b, _c; + var _a, _b; const candidate = normalizePath(combinePaths(nodeModulesDirectory, moduleName)); - const { packageName: packageName , rest: rest } = parsePackageName(moduleName); + const { packageName: packageName, rest: rest } = parsePackageName(moduleName); const packageDirectory = combinePaths(nodeModulesDirectory, packageName); let rootPackageInfo; let packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state); - if (rest !== "" && packageInfo && (!(state.features & 8 /* Exports */ ) || !hasProperty((_b = (_a2 = rootPackageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state)) == null ? void 0 : _a2.contents.packageJsonContent) != null ? _b : emptyArray, "exports"))) { + if (rest !== "" && packageInfo && (!(state.features & 8 /* Exports */ ) || !hasProperty(((_a = rootPackageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state)) == null ? void 0 : _a.contents.packageJsonContent) ?? emptyArray, "exports"))) { const fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); if (fromFile) return noPackageId(fromFile); const fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.contents.packageJsonContent, getVersionPathsOfPackageJsonInfo(packageInfo, state)); return withPackageId(packageInfo, fromDirectory); } const loader = (extensions2, candidate2, onlyRecordFailures, state2)=>{ - let pathAndExtension = loadModuleFromFile(extensions2, candidate2, onlyRecordFailures, state2) || loadNodeModuleFromDirectoryWorker(extensions2, candidate2, onlyRecordFailures, state2, packageInfo && packageInfo.contents.packageJsonContent, packageInfo && getVersionPathsOfPackageJsonInfo(packageInfo, state2)); + let pathAndExtension = (rest || !(state2.features & 32 /* EsmMode */ )) && loadModuleFromFile(extensions2, candidate2, onlyRecordFailures, state2) || loadNodeModuleFromDirectoryWorker(extensions2, candidate2, onlyRecordFailures, state2, packageInfo && packageInfo.contents.packageJsonContent, packageInfo && getVersionPathsOfPackageJsonInfo(packageInfo, state2)); if (!pathAndExtension && packageInfo && (packageInfo.contents.packageJsonContent.exports === void 0 || packageInfo.contents.packageJsonContent.exports === null) && state2.features & 32 /* EsmMode */ ) pathAndExtension = loadModuleFromFile(extensions2, combinePaths(candidate2, "index.js"), onlyRecordFailures, state2); return withPackageId(packageInfo, pathAndExtension); }; - if (rest !== "") packageInfo = rootPackageInfo != null ? rootPackageInfo : getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state); - if (packageInfo && packageInfo.contents.packageJsonContent.exports && state.features & 8 /* Exports */ ) return (_c = loadModuleFromExports(packageInfo, extensions, combinePaths(".", rest), state, cache, redirectedReference)) == null ? void 0 : _c.value; + if (rest !== "") packageInfo = rootPackageInfo ?? getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state); + if (packageInfo && packageInfo.contents.packageJsonContent.exports && state.features & 8 /* Exports */ ) return (_b = loadModuleFromExports(packageInfo, extensions, combinePaths(".", rest), state, cache, redirectedReference)) == null ? void 0 : _b.value; const versionPaths = rest !== "" && packageInfo ? getVersionPathsOfPackageJsonInfo(packageInfo, state) : void 0; if (versionPaths) { if (state.traceEnabled) trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, version, rest); @@ -40488,13 +40863,33 @@ ${lanes.join("\n")} return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved2) return resolved2; - if (extensions & 5 /* Declaration */ ) return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); + if (extensions & 5 /* Declaration */ ) { + let resolved3 = loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); + if (extensions & 4 /* Declaration */ ) resolved3 ?? (resolved3 = resolveFromTypeRoot(moduleName, state)); + return resolved3; + } } else { const candidate = normalizePath(combinePaths(containingDirectory, moduleName)); return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } + function resolveFromTypeRoot(moduleName, state) { + if (!state.compilerOptions.typeRoots) return; + for (const typeRoot of state.compilerOptions.typeRoots){ + const candidate = getCandidateFromTypeRoot(typeRoot, moduleName, state); + const directoryExists = directoryProbablyExists(typeRoot, state.host); + if (!directoryExists && state.traceEnabled) trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, typeRoot); + const resolvedFromFile = loadModuleFromFile(4 /* Declaration */ , candidate, !directoryExists, state); + if (resolvedFromFile) { + const packageDirectory = parseNodeModuleFromPath(resolvedFromFile.path); + const packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : void 0; + return toSearchResult(withPackageId(packageInfo, resolvedFromFile)); + } + const resolved = loadNodeModuleFromDirectory(4 /* Declaration */ , candidate, !directoryExists, state); + if (resolved) return toSearchResult(resolved); + } + } function shouldAllowImportingTsExtension(compilerOptions, fromFileName) { return !!compilerOptions.allowImportingTsExtensions || fromFileName && isDeclarationFileName(fromFileName); } @@ -40529,6 +40924,9 @@ ${lanes.join("\n")} function traceIfEnabled(state, diagnostic, ...args) { if (state.traceEnabled) trace(state.host, diagnostic, ...args); } + function useCaseSensitiveFileNames(state) { + return !state.host.useCaseSensitiveFileNames ? true : typeof state.host.useCaseSensitiveFileNames === "boolean" ? state.host.useCaseSensitiveFileNames : state.host.useCaseSensitiveFileNames(); + } var typeScriptVersion, nodeModulesAtTypes, NodeResolutionFeatures, nodeModulesPathPart, mangledScopedPackageSeparator; var init_moduleNameResolver = __esm({ "src/compiler/moduleNameResolver.ts" () { @@ -40570,19 +40968,19 @@ ${lanes.join("\n")} } function getModuleInstanceStateWorker(node, visited) { switch(node.kind){ - case 261 /* InterfaceDeclaration */ : - case 262 /* TypeAliasDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 265 /* TypeAliasDeclaration */ : return 0 /* NonInstantiated */ ; - case 263 /* EnumDeclaration */ : + case 266 /* EnumDeclaration */ : if (isEnumConst(node)) return 2 /* ConstEnumOnly */ ; break; - case 269 /* ImportDeclaration */ : - case 268 /* ImportEqualsDeclaration */ : + case 272 /* ImportDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : if (!hasSyntacticModifier(node, 1 /* Export */ )) return 0 /* NonInstantiated */ ; break; - case 275 /* ExportDeclaration */ : + case 278 /* ExportDeclaration */ : const exportDeclaration = node; - if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 276 /* NamedExports */ ) { + if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 279 /* NamedExports */ ) { let state = 0 /* NonInstantiated */ ; for (const specifier of exportDeclaration.exportClause.elements){ const specifierState = getModuleInstanceStateForAliasTarget(specifier, visited); @@ -40592,7 +40990,7 @@ ${lanes.join("\n")} return state; } break; - case 265 /* ModuleBlock */ : + case 268 /* ModuleBlock */ : { let state = 0 /* NonInstantiated */ ; forEachChild(node, (n)=>{ @@ -40612,10 +41010,10 @@ ${lanes.join("\n")} }); return state; } - case 264 /* ModuleDeclaration */ : + case 267 /* ModuleDeclaration */ : return getModuleInstanceState(node, visited); - case 79 /* Identifier */ : - if (node.flags & 2048 /* IdentifierIsInJSDocNamespace */ ) return 0 /* NonInstantiated */ ; + case 80 /* Identifier */ : + if (node.flags & 4096 /* IdentifierIsInJSDocNamespace */ ) return 0 /* NonInstantiated */ ; } return 1 /* Instantiated */ ; } @@ -40634,6 +41032,7 @@ ${lanes.join("\n")} const state = getModuleInstanceStateCached(statement, visited); if (found === void 0 || state > found) found = state; if (found === 1 /* Instantiated */ ) return found; + if (statement.kind === 271 /* ImportEqualsDeclaration */ ) found = 1 /* Instantiated */ ; } if (found !== void 0) return found; } @@ -40646,10 +41045,11 @@ ${lanes.join("\n")} return node; } function bindSourceFile(file, options) { + var _a, _b; mark("beforeBind"); - perfLogger.logStartBindFile("" + file.fileName); + (_a = perfLogger) == null || _a.logStartBindFile("" + file.fileName); binder(file, options); - perfLogger.logStopBindFile(); + (_b = perfLogger) == null || _b.logStopBindFile(); mark("afterBind"); measure("Bind", "beforeBind", "afterBind"); } @@ -40678,7 +41078,7 @@ ${lanes.join("\n")} var inStrictMode; var inAssignmentPattern = false; var symbolCount = 0; - var Symbol46; + var Symbol47; var classifiableNames; var unreachableFlow = { flags: 1 /* Unreachable */ @@ -40688,22 +41088,22 @@ ${lanes.join("\n")} }; var bindBinaryExpressionFlow = createBindBinaryExpressionFlow(); return bindSourceFile2; - function createDiagnosticForNode2(node, message, arg0, arg1, arg2) { - return createDiagnosticForNodeInSourceFile(getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2); + function createDiagnosticForNode2(node, message, ...args) { + return createDiagnosticForNodeInSourceFile(getSourceFileOfNode(node) || file, node, message, ...args); } function bindSourceFile2(f, opts) { - var _a2, _b; + var _a, _b; file = f; options = opts; languageVersion = getEmitScriptTarget(options); inStrictMode = bindInStrictMode(file, opts); classifiableNames = /* @__PURE__ */ new Set(); symbolCount = 0; - Symbol46 = objectAllocator.getSymbolConstructor(); + Symbol47 = objectAllocator.getSymbolConstructor(); Debug.attachFlowNodeDebugInfo(unreachableFlow); Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow); if (!file.locals) { - (_a2 = tracing) == null || _a2.push(tracing.Phase.Bind, "bindSourceFile", { + (_a = tracing) == null || _a.push(tracing.Phase.Bind, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); bind(file); @@ -40740,7 +41140,7 @@ ${lanes.join("\n")} } function createSymbol(flags, name) { symbolCount++; - return new Symbol46(flags, name); + return new Symbol47(flags, name); } function addDeclarationToSymbol(symbol, node, symbolFlags) { symbol.flags |= symbolFlags; @@ -40752,14 +41152,14 @@ ${lanes.join("\n")} if (symbolFlags & 111551 /* Value */ ) setValueDeclaration(symbol, node); } function getDeclarationName(node) { - if (node.kind === 274 /* ExportAssignment */ ) return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */ ; + if (node.kind === 277 /* ExportAssignment */ ) return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */ ; const name = getNameOfDeclaration(node); if (name) { if (isAmbientModule(node)) { const moduleName = getTextOfIdentifierOrLiteral(name); return isGlobalScopeAugmentation(node) ? "__global" : `"${moduleName}"`; } - if (name.kind === 164 /* ComputedPropertyName */ ) { + if (name.kind === 167 /* ComputedPropertyName */ ) { const nameExpression = name.expression; if (isStringOrNumericLiteralLike(nameExpression)) return escapeLeadingUnderscores(nameExpression.text); if (isSignedNumericLiteral(nameExpression)) return tokenToString(nameExpression.operator) + nameExpression.operand.text; @@ -40771,32 +41171,33 @@ ${lanes.join("\n")} const containingClassSymbol = containingClass.symbol; return getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText); } + if (isJsxNamespacedName(name)) return getEscapedTextOfJsxNamespacedName(name); return isPropertyNameLiteral(name) ? getEscapedTextOfIdentifierOrLiteral(name) : void 0; } switch(node.kind){ - case 173 /* Constructor */ : + case 176 /* Constructor */ : return "__constructor" /* Constructor */ ; - case 181 /* FunctionType */ : - case 176 /* CallSignature */ : - case 326 /* JSDocSignature */ : + case 184 /* FunctionType */ : + case 179 /* CallSignature */ : + case 330 /* JSDocSignature */ : return "__call" /* Call */ ; - case 182 /* ConstructorType */ : - case 177 /* ConstructSignature */ : + case 185 /* ConstructorType */ : + case 180 /* ConstructSignature */ : return "__new" /* New */ ; - case 178 /* IndexSignature */ : + case 181 /* IndexSignature */ : return "__index" /* Index */ ; - case 275 /* ExportDeclaration */ : + case 278 /* ExportDeclaration */ : return "__export" /* ExportStar */ ; - case 308 /* SourceFile */ : + case 312 /* SourceFile */ : return "export=" /* ExportEquals */ ; - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : if (getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ ) return "export=" /* ExportEquals */ ; Debug.fail("Unknown binary declaration kind"); break; - case 320 /* JSDocFunctionType */ : + case 324 /* JSDocFunctionType */ : return isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */ ; - case 166 /* Parameter */ : - Debug.assert(node.parent.kind === 320 /* JSDocFunctionType */ , "Impossible parameter parent kind", ()=>`parent is: ${Debug.formatSyntaxKind(node.parent.kind)}, expected JSDocFunctionType`); + case 169 /* Parameter */ : + Debug.assert(node.parent.kind === 324 /* JSDocFunctionType */ , "Impossible parameter parent kind", ()=>`parent is: ${Debug.formatSyntaxKind(node.parent.kind)}, expected JSDocFunctionType`); const functionType = node.parent; const index = functionType.parameters.indexOf(node); return "arg" + index; @@ -40834,7 +41235,7 @@ ${lanes.join("\n")} message = Diagnostics.A_module_cannot_have_multiple_default_exports; messageNeedsName = false; multipleDefaultExports = true; - } else if (symbol.declarations && symbol.declarations.length && node.kind === 274 /* ExportAssignment */ && !node.isExportEquals) { + } else if (symbol.declarations && symbol.declarations.length && node.kind === 277 /* ExportAssignment */ && !node.isExportEquals) { message = Diagnostics.A_module_cannot_have_multiple_default_exports; messageNeedsName = false; multipleDefaultExports = true; @@ -40845,11 +41246,11 @@ ${lanes.join("\n")} const declarationName = getNameOfDeclaration(node) || node; forEach(symbol.declarations, (declaration, index)=>{ const decl = getNameOfDeclaration(declaration) || declaration; - const diag3 = createDiagnosticForNode2(decl, message, messageNeedsName ? getDisplayName(declaration) : void 0); + const diag3 = messageNeedsName ? createDiagnosticForNode2(decl, message, getDisplayName(declaration)) : createDiagnosticForNode2(decl, message); file.bindDiagnostics.push(multipleDefaultExports ? addRelatedInfo(diag3, createDiagnosticForNode2(declarationName, index === 0 ? Diagnostics.Another_export_default_is_here : Diagnostics.and_here)) : diag3); if (multipleDefaultExports) relatedInformation.push(createDiagnosticForNode2(decl, Diagnostics.The_first_export_default_is_here)); }); - const diag2 = createDiagnosticForNode2(declarationName, message, messageNeedsName ? getDisplayName(node) : void 0); + const diag2 = messageNeedsName ? createDiagnosticForNode2(declarationName, message, getDisplayName(node)) : createDiagnosticForNode2(declarationName, message); file.bindDiagnostics.push(addRelatedInfo(diag2, ...relatedInformation)); symbol = createSymbol(0 /* None */ , name); } @@ -40863,14 +41264,14 @@ ${lanes.join("\n")} function declareModuleMember(node, symbolFlags, symbolExcludes) { const hasExportModifier = !!(getCombinedModifierFlags(node) & 1 /* Export */ ) || jsdocTreatAsExported(node); if (symbolFlags & 2097152 /* Alias */ ) { - if (node.kind === 278 /* ExportSpecifier */ || node.kind === 268 /* ImportEqualsDeclaration */ && hasExportModifier) return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + if (node.kind === 281 /* ExportSpecifier */ || node.kind === 271 /* ImportEqualsDeclaration */ && hasExportModifier) return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); else { Debug.assertNode(container, canHaveLocals); return declareSymbol(container.locals, /*parent*/ void 0, node, symbolFlags, symbolExcludes); } } else { if (isJSDocTypeAlias(node)) Debug.assert(isInJSFile(node)); - if (!isAmbientModule(node) && (hasExportModifier || container.flags & 64 /* ExportContext */ )) { + if (!isAmbientModule(node) && (hasExportModifier || container.flags & 128 /* ExportContext */ )) { if (!canHaveLocals(container) || !container.locals || hasSyntacticModifier(node, 1024 /* Default */ ) && !getDeclarationName(node)) return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); const exportKind = symbolFlags & 111551 /* Value */ ? 1048576 /* ExportValue */ : 0; const local = declareSymbol(container.locals, /*parent*/ void 0, node, exportKind, symbolExcludes); @@ -40898,7 +41299,7 @@ ${lanes.join("\n")} const saveThisParentContainer = thisParentContainer; const savedBlockScopeContainer = blockScopeContainer; if (containerFlags & 1 /* IsContainer */ ) { - if (node.kind !== 216 /* ArrowFunction */ ) thisParentContainer = container; + if (node.kind !== 219 /* ArrowFunction */ ) thisParentContainer = container; container = blockScopeContainer = node; if (containerFlags & 32 /* HasLocals */ ) { container.locals = createSymbolTable(); @@ -40916,34 +41317,34 @@ ${lanes.join("\n")} const saveExceptionTarget = currentExceptionTarget; const saveActiveLabelList = activeLabelList; const saveHasExplicitReturn = hasExplicitReturn; - const isImmediatelyInvoked = containerFlags & 16 /* IsFunctionExpression */ && !hasSyntacticModifier(node, 512 /* Async */ ) && !node.asteriskToken && !!getImmediatelyInvokedFunctionExpression(node) || node.kind === 172 /* ClassStaticBlockDeclaration */ ; + const isImmediatelyInvoked = containerFlags & 16 /* IsFunctionExpression */ && !hasSyntacticModifier(node, 512 /* Async */ ) && !node.asteriskToken && !!getImmediatelyInvokedFunctionExpression(node) || node.kind === 175 /* ClassStaticBlockDeclaration */ ; if (!isImmediatelyInvoked) { currentFlow = initFlowNode({ flags: 2 /* Start */ }); if (containerFlags & 144 /* IsObjectLiteralOrClassExpressionMethodOrAccessor */ ) currentFlow.node = node; } - currentReturnTarget = isImmediatelyInvoked || node.kind === 173 /* Constructor */ || isInJSFile(node) && (node.kind === 259 /* FunctionDeclaration */ || node.kind === 215 /* FunctionExpression */ ) ? createBranchLabel() : void 0; + currentReturnTarget = isImmediatelyInvoked || node.kind === 176 /* Constructor */ || isInJSFile(node) && (node.kind === 262 /* FunctionDeclaration */ || node.kind === 218 /* FunctionExpression */ ) ? createBranchLabel() : void 0; currentExceptionTarget = void 0; currentBreakTarget = void 0; currentContinueTarget = void 0; activeLabelList = void 0; hasExplicitReturn = false; bindChildren(node); - node.flags &= -2817 /* ReachabilityAndEmitFlags */ ; + node.flags &= -5633 /* ReachabilityAndEmitFlags */ ; if (!(currentFlow.flags & 1 /* Unreachable */ ) && containerFlags & 8 /* IsFunctionLike */ && nodeIsPresent(node.body)) { - node.flags |= 256 /* HasImplicitReturn */ ; - if (hasExplicitReturn) node.flags |= 512 /* HasExplicitReturn */ ; + node.flags |= 512 /* HasImplicitReturn */ ; + if (hasExplicitReturn) node.flags |= 1024 /* HasExplicitReturn */ ; node.endFlowNode = currentFlow; } - if (node.kind === 308 /* SourceFile */ ) { + if (node.kind === 312 /* SourceFile */ ) { node.flags |= emitFlags; node.endFlowNode = currentFlow; } if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); - if (node.kind === 173 /* Constructor */ || node.kind === 172 /* ClassStaticBlockDeclaration */ || isInJSFile(node) && (node.kind === 259 /* FunctionDeclaration */ || node.kind === 215 /* FunctionExpression */ )) node.returnFlowNode = currentFlow; + if (node.kind === 176 /* Constructor */ || node.kind === 175 /* ClassStaticBlockDeclaration */ || isInJSFile(node) && (node.kind === 262 /* FunctionDeclaration */ || node.kind === 218 /* FunctionExpression */ )) node.returnFlowNode = currentFlow; } if (!isImmediatelyInvoked) currentFlow = saveCurrentFlow; currentBreakTarget = saveBreakTarget; @@ -40956,15 +41357,15 @@ ${lanes.join("\n")} seenThisKeyword = false; bindChildren(node); Debug.assertNotNode(node, isIdentifier); - node.flags = seenThisKeyword ? node.flags | 128 /* ContainsThis */ : node.flags & -129 /* ContainsThis */ ; + node.flags = seenThisKeyword ? node.flags | 256 /* ContainsThis */ : node.flags & -257 /* ContainsThis */ ; } else bindChildren(node); container = saveContainer; thisParentContainer = saveThisParentContainer; blockScopeContainer = savedBlockScopeContainer; } function bindEachFunctionsFirst(nodes) { - bindEach(nodes, (n)=>n.kind === 259 /* FunctionDeclaration */ ? bind(n) : void 0); - bindEach(nodes, (n)=>n.kind !== 259 /* FunctionDeclaration */ ? bind(n) : void 0); + bindEach(nodes, (n)=>n.kind === 262 /* FunctionDeclaration */ ? bind(n) : void 0); + bindEach(nodes, (n)=>n.kind !== 262 /* FunctionDeclaration */ ? bind(n) : void 0); } function bindEach(nodes, bindFunction = bind) { if (nodes === void 0) return; @@ -40982,57 +41383,57 @@ ${lanes.join("\n")} inAssignmentPattern = saveInAssignmentPattern; return; } - if (node.kind >= 240 /* FirstStatement */ && node.kind <= 256 /* LastStatement */ && !options.allowUnreachableCode) node.flowNode = currentFlow; + if (node.kind >= 243 /* FirstStatement */ && node.kind <= 259 /* LastStatement */ && !options.allowUnreachableCode) node.flowNode = currentFlow; switch(node.kind){ - case 244 /* WhileStatement */ : + case 247 /* WhileStatement */ : bindWhileStatement(node); break; - case 243 /* DoStatement */ : + case 246 /* DoStatement */ : bindDoStatement(node); break; - case 245 /* ForStatement */ : + case 248 /* ForStatement */ : bindForStatement(node); break; - case 246 /* ForInStatement */ : - case 247 /* ForOfStatement */ : + case 249 /* ForInStatement */ : + case 250 /* ForOfStatement */ : bindForInOrForOfStatement(node); break; - case 242 /* IfStatement */ : + case 245 /* IfStatement */ : bindIfStatement(node); break; - case 250 /* ReturnStatement */ : - case 254 /* ThrowStatement */ : + case 253 /* ReturnStatement */ : + case 257 /* ThrowStatement */ : bindReturnOrThrow(node); break; - case 249 /* BreakStatement */ : - case 248 /* ContinueStatement */ : + case 252 /* BreakStatement */ : + case 251 /* ContinueStatement */ : bindBreakOrContinueStatement(node); break; - case 255 /* TryStatement */ : + case 258 /* TryStatement */ : bindTryStatement(node); break; - case 252 /* SwitchStatement */ : + case 255 /* SwitchStatement */ : bindSwitchStatement(node); break; - case 266 /* CaseBlock */ : + case 269 /* CaseBlock */ : bindCaseBlock(node); break; - case 292 /* CaseClause */ : + case 296 /* CaseClause */ : bindCaseClause(node); break; - case 241 /* ExpressionStatement */ : + case 244 /* ExpressionStatement */ : bindExpressionStatement(node); break; - case 253 /* LabeledStatement */ : + case 256 /* LabeledStatement */ : bindLabeledStatement(node); break; - case 221 /* PrefixUnaryExpression */ : + case 224 /* PrefixUnaryExpression */ : bindPrefixUnaryExpressionFlow(node); break; - case 222 /* PostfixUnaryExpression */ : + case 225 /* PostfixUnaryExpression */ : bindPostfixUnaryExpressionFlow(node); break; - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : if (isDestructuringAssignment(node)) { inAssignmentPattern = saveInAssignmentPattern; bindDestructuringAssignmentFlow(node); @@ -41040,48 +41441,48 @@ ${lanes.join("\n")} } bindBinaryExpressionFlow(node); break; - case 217 /* DeleteExpression */ : + case 220 /* DeleteExpression */ : bindDeleteExpressionFlow(node); break; - case 224 /* ConditionalExpression */ : + case 227 /* ConditionalExpression */ : bindConditionalExpressionFlow(node); break; - case 257 /* VariableDeclaration */ : + case 260 /* VariableDeclaration */ : bindVariableDeclarationFlow(node); break; - case 208 /* PropertyAccessExpression */ : - case 209 /* ElementAccessExpression */ : + case 211 /* PropertyAccessExpression */ : + case 212 /* ElementAccessExpression */ : bindAccessExpressionFlow(node); break; - case 210 /* CallExpression */ : + case 213 /* CallExpression */ : bindCallExpressionFlow(node); break; - case 232 /* NonNullExpression */ : + case 235 /* NonNullExpression */ : bindNonNullExpressionFlow(node); break; - case 349 /* JSDocTypedefTag */ : - case 341 /* JSDocCallbackTag */ : - case 343 /* JSDocEnumTag */ : + case 353 /* JSDocTypedefTag */ : + case 345 /* JSDocCallbackTag */ : + case 347 /* JSDocEnumTag */ : bindJSDocTypeAlias(node); break; - case 308 /* SourceFile */ : + case 312 /* SourceFile */ : bindEachFunctionsFirst(node.statements); bind(node.endOfFileToken); break; - case 238 /* Block */ : - case 265 /* ModuleBlock */ : + case 241 /* Block */ : + case 268 /* ModuleBlock */ : bindEachFunctionsFirst(node.statements); break; - case 205 /* BindingElement */ : + case 208 /* BindingElement */ : bindBindingElementFlow(node); break; - case 166 /* Parameter */ : + case 169 /* Parameter */ : bindParameterFlow(node); break; - case 207 /* ObjectLiteralExpression */ : - case 206 /* ArrayLiteralExpression */ : - case 299 /* PropertyAssignment */ : - case 227 /* SpreadElement */ : + case 210 /* ObjectLiteralExpression */ : + case 209 /* ArrayLiteralExpression */ : + case 303 /* PropertyAssignment */ : + case 230 /* SpreadElement */ : inAssignmentPattern = saveInAssignmentPattern; default: bindEachChild(node); @@ -41092,28 +41493,28 @@ ${lanes.join("\n")} } function isNarrowingExpression(expr) { switch(expr.kind){ - case 79 /* Identifier */ : - case 80 /* PrivateIdentifier */ : - case 108 /* ThisKeyword */ : - case 208 /* PropertyAccessExpression */ : - case 209 /* ElementAccessExpression */ : + case 80 /* Identifier */ : + case 81 /* PrivateIdentifier */ : + case 110 /* ThisKeyword */ : + case 211 /* PropertyAccessExpression */ : + case 212 /* ElementAccessExpression */ : return containsNarrowableReference(expr); - case 210 /* CallExpression */ : + case 213 /* CallExpression */ : return hasNarrowableArgument(expr); - case 214 /* ParenthesizedExpression */ : - case 232 /* NonNullExpression */ : + case 217 /* ParenthesizedExpression */ : + case 235 /* NonNullExpression */ : return isNarrowingExpression(expr.expression); - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : return isNarrowingBinaryExpression(expr); - case 221 /* PrefixUnaryExpression */ : - return expr.operator === 53 /* ExclamationToken */ && isNarrowingExpression(expr.operand); - case 218 /* TypeOfExpression */ : + case 224 /* PrefixUnaryExpression */ : + return expr.operator === 54 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 221 /* TypeOfExpression */ : return isNarrowingExpression(expr.expression); } return false; } function isNarrowableReference(expr) { - return isDottedName(expr) || (isPropertyAccessExpression(expr) || isNonNullExpression(expr) || isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || isBinaryExpression(expr) && expr.operatorToken.kind === 27 /* CommaToken */ && isNarrowableReference(expr.right) || isElementAccessExpression(expr) && (isStringOrNumericLiteralLike(expr.argumentExpression) || isEntityNameExpression(expr.argumentExpression)) && isNarrowableReference(expr.expression) || isAssignmentExpression(expr) && isNarrowableReference(expr.left); + return isDottedName(expr) || (isPropertyAccessExpression(expr) || isNonNullExpression(expr) || isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || isBinaryExpression(expr) && expr.operatorToken.kind === 28 /* CommaToken */ && isNarrowableReference(expr.right) || isElementAccessExpression(expr) && (isStringOrNumericLiteralLike(expr.argumentExpression) || isEntityNameExpression(expr.argumentExpression)) && isNarrowableReference(expr.expression) || isAssignmentExpression(expr) && isNarrowableReference(expr.left); } function containsNarrowableReference(expr) { return isNarrowableReference(expr) || isOptionalChain(expr) && containsNarrowableReference(expr.expression); @@ -41122,7 +41523,7 @@ ${lanes.join("\n")} if (expr.arguments) for (const argument of expr.arguments){ if (containsNarrowableReference(argument)) return true; } - if (expr.expression.kind === 208 /* PropertyAccessExpression */ && containsNarrowableReference(expr.expression.expression)) return true; + if (expr.expression.kind === 211 /* PropertyAccessExpression */ && containsNarrowableReference(expr.expression.expression)) return true; return false; } function isNarrowingTypeofOperands(expr1, expr2) { @@ -41130,34 +41531,34 @@ ${lanes.join("\n")} } function isNarrowingBinaryExpression(expr) { switch(expr.operatorToken.kind){ - case 63 /* EqualsToken */ : - case 75 /* BarBarEqualsToken */ : - case 76 /* AmpersandAmpersandEqualsToken */ : - case 77 /* QuestionQuestionEqualsToken */ : + case 64 /* EqualsToken */ : + case 76 /* BarBarEqualsToken */ : + case 77 /* AmpersandAmpersandEqualsToken */ : + case 78 /* QuestionQuestionEqualsToken */ : return containsNarrowableReference(expr.left); - case 34 /* EqualsEqualsToken */ : - case 35 /* ExclamationEqualsToken */ : - case 36 /* EqualsEqualsEqualsToken */ : - case 37 /* ExclamationEqualsEqualsToken */ : + case 35 /* EqualsEqualsToken */ : + case 36 /* ExclamationEqualsToken */ : + case 37 /* EqualsEqualsEqualsToken */ : + case 38 /* ExclamationEqualsEqualsToken */ : return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); - case 102 /* InstanceOfKeyword */ : + case 104 /* InstanceOfKeyword */ : return isNarrowableOperand(expr.left); - case 101 /* InKeyword */ : + case 103 /* InKeyword */ : return isNarrowingExpression(expr.right); - case 27 /* CommaToken */ : + case 28 /* CommaToken */ : return isNarrowingExpression(expr.right); } return false; } function isNarrowableOperand(expr) { switch(expr.kind){ - case 214 /* ParenthesizedExpression */ : + case 217 /* ParenthesizedExpression */ : return isNarrowableOperand(expr.expression); - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : switch(expr.operatorToken.kind){ - case 63 /* EqualsToken */ : + case 64 /* EqualsToken */ : return isNarrowableOperand(expr.left); - case 27 /* CommaToken */ : + case 28 /* CommaToken */ : return isNarrowableOperand(expr.right); } } @@ -41195,7 +41596,7 @@ ${lanes.join("\n")} function createFlowCondition(flags, antecedent, expression) { if (antecedent.flags & 1 /* Unreachable */ ) return antecedent; if (!expression) return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; - if ((expression.kind === 110 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || expression.kind === 95 /* FalseKeyword */ && flags & 32 /* TrueCondition */ ) && !isExpressionOfOptionalChainRoot(expression) && !isNullishCoalesce(expression.parent)) return unreachableFlow; + if ((expression.kind === 112 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || expression.kind === 97 /* FalseKeyword */ && flags & 32 /* TrueCondition */ ) && !isExpressionOfOptionalChainRoot(expression) && !isNullishCoalesce(expression.parent)) return unreachableFlow; if (!isNarrowingExpression(expression)) return antecedent; setFlowNodeReferenced(antecedent); return initFlowNode({ @@ -41241,20 +41642,20 @@ ${lanes.join("\n")} function isStatementCondition(node) { const parent3 = node.parent; switch(parent3.kind){ - case 242 /* IfStatement */ : - case 244 /* WhileStatement */ : - case 243 /* DoStatement */ : + case 245 /* IfStatement */ : + case 247 /* WhileStatement */ : + case 246 /* DoStatement */ : return parent3.expression === node; - case 245 /* ForStatement */ : - case 224 /* ConditionalExpression */ : + case 248 /* ForStatement */ : + case 227 /* ConditionalExpression */ : return parent3.condition === node; } return false; } function isLogicalExpression(node) { while(true){ - if (node.kind === 214 /* ParenthesizedExpression */ ) node = node.expression; - else if (node.kind === 221 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */ ) node = node.operand; + if (node.kind === 217 /* ParenthesizedExpression */ ) node = node.expression; + else if (node.kind === 224 /* PrefixUnaryExpression */ && node.operator === 54 /* ExclamationToken */ ) node = node.operand; else return isLogicalOrCoalescingBinaryExpression(node); } } @@ -41262,7 +41663,7 @@ ${lanes.join("\n")} return isLogicalOrCoalescingAssignmentExpression(skipParentheses(node)); } function isTopLevelLogicalExpression(node) { - while(isParenthesizedExpression(node.parent) || isPrefixUnaryExpression(node.parent) && node.parent.operator === 53 /* ExclamationToken */ )node = node.parent; + while(isParenthesizedExpression(node.parent) || isPrefixUnaryExpression(node.parent) && node.parent.operator === 54 /* ExclamationToken */ )node = node.parent; return !isStatementCondition(node) && !isLogicalExpression(node.parent) && !(isOptionalChain(node.parent) && node.parent.expression === node); } function doWithConditionalBranches(action, value1, trueTarget, falseTarget) { @@ -41292,7 +41693,7 @@ ${lanes.join("\n")} } function setContinueTarget(node, target) { let label = activeLabelList; - while(label && node.parent.kind === 253 /* LabeledStatement */ ){ + while(label && node.parent.kind === 256 /* LabeledStatement */ ){ label.continueTarget = target; label = label.next; node = node.parent; @@ -41343,10 +41744,10 @@ ${lanes.join("\n")} bind(node.expression); addAntecedent(preLoopLabel, currentFlow); currentFlow = preLoopLabel; - if (node.kind === 247 /* ForOfStatement */ ) bind(node.awaitModifier); + if (node.kind === 250 /* ForOfStatement */ ) bind(node.awaitModifier); addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 258 /* VariableDeclarationList */ ) bindAssignmentTargetFlow(node.initializer); + if (node.initializer.kind !== 261 /* VariableDeclarationList */ ) bindAssignmentTargetFlow(node.initializer); bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); addAntecedent(preLoopLabel, currentFlow); currentFlow = finishFlowLabel(postLoopLabel); @@ -41366,7 +41767,7 @@ ${lanes.join("\n")} } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 250 /* ReturnStatement */ ) { + if (node.kind === 253 /* ReturnStatement */ ) { hasExplicitReturn = true; if (currentReturnTarget) addAntecedent(currentReturnTarget, currentFlow); } @@ -41379,7 +41780,7 @@ ${lanes.join("\n")} return void 0; } function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - const flowLabel = node.kind === 249 /* BreakStatement */ ? breakTarget : continueTarget; + const flowLabel = node.kind === 252 /* BreakStatement */ ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -41438,7 +41839,7 @@ ${lanes.join("\n")} preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - const hasDefault = forEach(node.caseBlock.clauses, (c)=>c.kind === 293 /* DefaultClause */ ); + const hasDefault = forEach(node.caseBlock.clauses, (c)=>c.kind === 297 /* DefaultClause */ ); node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; if (!hasDefault) addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); currentBreakTarget = saveBreakTarget; @@ -41477,9 +41878,9 @@ ${lanes.join("\n")} maybeBindExpressionFlowIfCall(node.expression); } function maybeBindExpressionFlowIfCall(node) { - if (node.kind === 210 /* CallExpression */ ) { + if (node.kind === 213 /* CallExpression */ ) { const call = node; - if (call.expression.kind !== 106 /* SuperKeyword */ && isDottedName(call.expression)) currentFlow = createFlowCall(currentFlow, call); + if (call.expression.kind !== 108 /* SuperKeyword */ && isDottedName(call.expression)) currentFlow = createFlowCall(currentFlow, call); } } function bindLabeledStatement(node) { @@ -41499,23 +41900,23 @@ ${lanes.join("\n")} currentFlow = finishFlowLabel(postStatementLabel); } function bindDestructuringTargetFlow(node) { - if (node.kind === 223 /* BinaryExpression */ && node.operatorToken.kind === 63 /* EqualsToken */ ) bindAssignmentTargetFlow(node.left); + if (node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 64 /* EqualsToken */ ) bindAssignmentTargetFlow(node.left); else bindAssignmentTargetFlow(node); } function bindAssignmentTargetFlow(node) { if (isNarrowableReference(node)) currentFlow = createFlowMutation(16 /* Assignment */ , currentFlow, node); - else if (node.kind === 206 /* ArrayLiteralExpression */ ) { - for (const e of node.elements)if (e.kind === 227 /* SpreadElement */ ) bindAssignmentTargetFlow(e.expression); + else if (node.kind === 209 /* ArrayLiteralExpression */ ) { + for (const e of node.elements)if (e.kind === 230 /* SpreadElement */ ) bindAssignmentTargetFlow(e.expression); else bindDestructuringTargetFlow(e); - } else if (node.kind === 207 /* ObjectLiteralExpression */ ) for (const p of node.properties){ - if (p.kind === 299 /* PropertyAssignment */ ) bindDestructuringTargetFlow(p.initializer); - else if (p.kind === 300 /* ShorthandPropertyAssignment */ ) bindAssignmentTargetFlow(p.name); - else if (p.kind === 301 /* SpreadAssignment */ ) bindAssignmentTargetFlow(p.expression); + } else if (node.kind === 210 /* ObjectLiteralExpression */ ) for (const p of node.properties){ + if (p.kind === 303 /* PropertyAssignment */ ) bindDestructuringTargetFlow(p.initializer); + else if (p.kind === 304 /* ShorthandPropertyAssignment */ ) bindAssignmentTargetFlow(p.name); + else if (p.kind === 305 /* SpreadAssignment */ ) bindAssignmentTargetFlow(p.expression); } } function bindLogicalLikeExpression(node, trueTarget, falseTarget) { const preRightLabel = createBranchLabel(); - if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ || node.operatorToken.kind === 76 /* AmpersandAmpersandEqualsToken */ ) bindCondition(node.left, preRightLabel, falseTarget); + if (node.operatorToken.kind === 56 /* AmpersandAmpersandToken */ || node.operatorToken.kind === 77 /* AmpersandAmpersandEqualsToken */ ) bindCondition(node.left, preRightLabel, falseTarget); else bindCondition(node.left, trueTarget, preRightLabel); currentFlow = finishFlowLabel(preRightLabel); bind(node.operatorToken); @@ -41527,7 +41928,7 @@ ${lanes.join("\n")} } else bindCondition(node.right, trueTarget, falseTarget); } function bindPrefixUnaryExpressionFlow(node) { - if (node.operator === 53 /* ExclamationToken */ ) { + if (node.operator === 54 /* ExclamationToken */ ) { const saveTrueTarget = currentTrueTarget; currentTrueTarget = currentFalseTarget; currentFalseTarget = saveTrueTarget; @@ -41536,12 +41937,12 @@ ${lanes.join("\n")} currentTrueTarget = saveTrueTarget; } else { bindEachChild(node); - if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */ ) bindAssignmentTargetFlow(node.operand); + if (node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */ ) bindAssignmentTargetFlow(node.operand); } } function bindPostfixUnaryExpressionFlow(node) { bindEachChild(node); - if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */ ) bindAssignmentTargetFlow(node.operand); + if (node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */ ) bindAssignmentTargetFlow(node.operand); } function bindDestructuringAssignmentFlow(node) { if (inAssignmentPattern) { @@ -41596,7 +41997,7 @@ ${lanes.join("\n")} function onLeft(left, state, node) { if (!state.skip) { const maybeBound = maybeBind2(left); - if (node.operatorToken.kind === 27 /* CommaToken */ ) maybeBindExpressionFlowIfCall(left); + if (node.operatorToken.kind === 28 /* CommaToken */ ) maybeBindExpressionFlowIfCall(left); return maybeBound; } } @@ -41606,7 +42007,7 @@ ${lanes.join("\n")} function onRight(right, state, node) { if (!state.skip) { const maybeBound = maybeBind2(right); - if (node.operatorToken.kind === 27 /* CommaToken */ ) maybeBindExpressionFlowIfCall(right); + if (node.operatorToken.kind === 28 /* CommaToken */ ) maybeBindExpressionFlowIfCall(right); return maybeBound; } } @@ -41615,7 +42016,7 @@ ${lanes.join("\n")} const operator = node.operatorToken.kind; if (isAssignmentOperator(operator) && !isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); - if (operator === 63 /* EqualsToken */ && node.left.kind === 209 /* ElementAccessExpression */ ) { + if (operator === 64 /* EqualsToken */ && node.left.kind === 212 /* ElementAccessExpression */ ) { const elementAccess = node.left; if (isNarrowableOperand(elementAccess.expression)) currentFlow = createFlowMutation(256 /* ArrayMutation */ , currentFlow, node); } @@ -41635,7 +42036,7 @@ ${lanes.join("\n")} } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 208 /* PropertyAccessExpression */ ) bindAssignmentTargetFlow(node.expression); + if (node.expression.kind === 211 /* PropertyAccessExpression */ ) bindAssignmentTargetFlow(node.expression); } function bindConditionalExpressionFlow(node) { const trueLabel = createBranchLabel(); @@ -41687,7 +42088,7 @@ ${lanes.join("\n")} } function bindJSDocTypeAlias(node) { bind(node.tagName); - if (node.kind !== 343 /* JSDocEnumTag */ && node.fullName) { + if (node.kind !== 347 /* JSDocEnumTag */ && node.fullName) { setParent(node.fullName, node); setParentRecursive(node.fullName, /*incremental*/ false); } @@ -41696,7 +42097,7 @@ ${lanes.join("\n")} function bindJSDocClassTag(node) { bindEachChild(node); const host = getHostSignatureFromJSDoc(node); - if (host && host.kind !== 171 /* MethodDeclaration */ ) addDeclarationToSymbol(host.symbol, host, 32 /* Class */ ); + if (host && host.kind !== 174 /* MethodDeclaration */ ) addDeclarationToSymbol(host.symbol, host, 32 /* Class */ ); } function bindOptionalExpression(node, trueTarget, falseTarget) { doWithConditionalBranches(bind, node, trueTarget, falseTarget); @@ -41707,15 +42108,15 @@ ${lanes.join("\n")} } function bindOptionalChainRest(node) { switch(node.kind){ - case 208 /* PropertyAccessExpression */ : + case 211 /* PropertyAccessExpression */ : bind(node.questionDotToken); bind(node.name); break; - case 209 /* ElementAccessExpression */ : + case 212 /* ElementAccessExpression */ : bind(node.questionDotToken); bind(node.argumentExpression); break; - case 210 /* CallExpression */ : + case 213 /* CallExpression */ : bind(node.questionDotToken); bindEach(node.typeArguments); bindEach(node.arguments); @@ -41751,16 +42152,16 @@ ${lanes.join("\n")} if (isOptionalChain(node)) bindOptionalChainFlow(node); else { const expr = skipParentheses(node.expression); - if (expr.kind === 215 /* FunctionExpression */ || expr.kind === 216 /* ArrowFunction */ ) { + if (expr.kind === 218 /* FunctionExpression */ || expr.kind === 219 /* ArrowFunction */ ) { bindEach(node.typeArguments); bindEach(node.arguments); bind(node.expression); } else { bindEachChild(node); - if (node.expression.kind === 106 /* SuperKeyword */ ) currentFlow = createFlowCall(currentFlow, node); + if (node.expression.kind === 108 /* SuperKeyword */ ) currentFlow = createFlowCall(currentFlow, node); } } - if (node.expression.kind === 208 /* PropertyAccessExpression */ ) { + if (node.expression.kind === 211 /* PropertyAccessExpression */ ) { const propertyAccess = node.expression; if (isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && isPushOrUnshiftIdentifier(propertyAccess.name)) currentFlow = createFlowMutation(256 /* ArrayMutation */ , currentFlow, node); } @@ -41771,39 +42172,39 @@ ${lanes.join("\n")} } function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { switch(container.kind){ - case 264 /* ModuleDeclaration */ : + case 267 /* ModuleDeclaration */ : return declareModuleMember(node, symbolFlags, symbolExcludes); - case 308 /* SourceFile */ : + case 312 /* SourceFile */ : return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 228 /* ClassExpression */ : - case 260 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 263 /* ClassDeclaration */ : return declareClassMember(node, symbolFlags, symbolExcludes); - case 263 /* EnumDeclaration */ : + case 266 /* EnumDeclaration */ : return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 184 /* TypeLiteral */ : - case 325 /* JSDocTypeLiteral */ : - case 207 /* ObjectLiteralExpression */ : - case 261 /* InterfaceDeclaration */ : - case 289 /* JsxAttributes */ : + case 187 /* TypeLiteral */ : + case 329 /* JSDocTypeLiteral */ : + case 210 /* ObjectLiteralExpression */ : + case 264 /* InterfaceDeclaration */ : + case 292 /* JsxAttributes */ : return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 181 /* FunctionType */ : - case 182 /* ConstructorType */ : - case 176 /* CallSignature */ : - case 177 /* ConstructSignature */ : - case 326 /* JSDocSignature */ : - case 178 /* IndexSignature */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 173 /* Constructor */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - case 320 /* JSDocFunctionType */ : - case 172 /* ClassStaticBlockDeclaration */ : - case 262 /* TypeAliasDeclaration */ : - case 197 /* MappedType */ : + case 184 /* FunctionType */ : + case 185 /* ConstructorType */ : + case 179 /* CallSignature */ : + case 180 /* ConstructSignature */ : + case 330 /* JSDocSignature */ : + case 181 /* IndexSignature */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 176 /* Constructor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + case 324 /* JSDocFunctionType */ : + case 175 /* ClassStaticBlockDeclaration */ : + case 265 /* TypeAliasDeclaration */ : + case 200 /* MappedType */ : if (container.locals) Debug.assertNode(container, canHaveLocals); return declareSymbol(container.locals, /*parent*/ void 0, node, symbolFlags, symbolExcludes); } @@ -41819,8 +42220,8 @@ ${lanes.join("\n")} return !!body && body.statements.some((s)=>isExportDeclaration(s) || isExportAssignment(s)); } function setExportContextFlag(node) { - if (node.flags & 16777216 /* Ambient */ && !hasExportDeclarations(node)) node.flags |= 64 /* ExportContext */ ; - else node.flags &= -65 /* ExportContext */ ; + if (node.flags & 33554432 /* Ambient */ && !hasExportDeclarations(node)) node.flags |= 128 /* ExportContext */ ; + else node.flags &= -129 /* ExportContext */ ; } function bindModuleDeclaration(node) { setExportContextFlag(node); @@ -41829,8 +42230,8 @@ ${lanes.join("\n")} if (isModuleAugmentationExternal(node)) declareModuleSymbol(node); else { let pattern; - if (node.name.kind === 10 /* StringLiteral */ ) { - const { text: text } = node.name; + if (node.name.kind === 11 /* StringLiteral */ ) { + const { text: text } = node.name; pattern = tryParsePattern(text); if (pattern === void 0) errorOnFirstToken(node.name, Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } @@ -41843,7 +42244,7 @@ ${lanes.join("\n")} } else { const state = declareModuleSymbol(node); if (state !== 0 /* NonInstantiated */ ) { - const { symbol: symbol } = node; + const { symbol: symbol } = node; symbol.constEnumOnlyModule = !(symbol.flags & 304 /* RegularEnum */ ) && state === 2 /* ConstEnumOnly */ && symbol.constEnumOnlyModule !== false; } } @@ -41879,10 +42280,10 @@ ${lanes.join("\n")} } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch(blockScopeContainer.kind){ - case 264 /* ModuleDeclaration */ : + case 267 /* ModuleDeclaration */ : declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 308 /* SourceFile */ : + case 312 /* SourceFile */ : if (isExternalOrCommonJsModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -41905,7 +42306,7 @@ ${lanes.join("\n")} const saveCurrentFlow = currentFlow; for (const typeAlias of delayedTypeAliases){ const host = typeAlias.parent.parent; - container = findAncestor(host.parent, (n)=>!!(getContainerFlags(n) & 1 /* IsContainer */ )) || file; + container = getEnclosingContainer(host) || file; blockScopeContainer = getEnclosingBlockScopeContainer(host) || file; currentFlow = initFlowNode({ flags: 2 /* Start */ @@ -41939,7 +42340,7 @@ ${lanes.join("\n")} if (container) declareModuleMember(typeAlias, 524288 /* TypeAlias */ , 788968 /* TypeAliasExcludes */ ); container = oldContainer; } - } else if (isJSDocEnumTag(typeAlias) || !typeAlias.fullName || typeAlias.fullName.kind === 79 /* Identifier */ ) { + } else if (isJSDocEnumTag(typeAlias) || !typeAlias.fullName || typeAlias.fullName.kind === 80 /* Identifier */ ) { parent2 = typeAlias.parent; bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */ , 788968 /* TypeAliasExcludes */ ); } else bind(typeAlias.fullName); @@ -41951,14 +42352,14 @@ ${lanes.join("\n")} currentFlow = saveCurrentFlow; } function checkContextualIdentifier(node) { - if (!file.parseDiagnostics.length && !(node.flags & 16777216 /* Ambient */ ) && !(node.flags & 8388608 /* JSDoc */ ) && !isIdentifierName(node)) { + if (!file.parseDiagnostics.length && !(node.flags & 33554432 /* Ambient */ ) && !(node.flags & 16777216 /* JSDoc */ ) && !isIdentifierName(node)) { const originalKeywordKind = identifierToKeywordKind(node); if (originalKeywordKind === void 0) return; - if (inStrictMode && originalKeywordKind >= 117 /* FirstFutureReservedWord */ && originalKeywordKind <= 125 /* LastFutureReservedWord */ ) file.bindDiagnostics.push(createDiagnosticForNode2(node, getStrictModeIdentifierMessage(node), declarationNameToString(node))); - else if (originalKeywordKind === 133 /* AwaitKeyword */ ) { + if (inStrictMode && originalKeywordKind >= 119 /* FirstFutureReservedWord */ && originalKeywordKind <= 127 /* LastFutureReservedWord */ ) file.bindDiagnostics.push(createDiagnosticForNode2(node, getStrictModeIdentifierMessage(node), declarationNameToString(node))); + else if (originalKeywordKind === 135 /* AwaitKeyword */ ) { if (isExternalModule(file) && isInTopLevelContext(node)) file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module, declarationNameToString(node))); - else if (node.flags & 32768 /* AwaitContext */ ) file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, declarationNameToString(node))); - } else if (originalKeywordKind === 125 /* YieldKeyword */ && node.flags & 8192 /* YieldContext */ ) file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, declarationNameToString(node))); + else if (node.flags & 65536 /* AwaitContext */ ) file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, declarationNameToString(node))); + } else if (originalKeywordKind === 127 /* YieldKeyword */ && node.flags & 16384 /* YieldContext */ ) file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, declarationNameToString(node))); } } function getStrictModeIdentifierMessage(node) { @@ -41978,7 +42379,7 @@ ${lanes.join("\n")} if (inStrictMode && node.variableDeclaration) checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); } function checkStrictModeDeleteExpression(node) { - if (inStrictMode && node.expression.kind === 79 /* Identifier */ ) { + if (inStrictMode && node.expression.kind === 80 /* Identifier */ ) { const span = getErrorSpanForNode(file, node.expression); file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); } @@ -41987,7 +42388,7 @@ ${lanes.join("\n")} return isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); } function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 79 /* Identifier */ ) { + if (name && name.kind === 80 /* Identifier */ ) { const identifier = name; if (isEvalOrArgumentsIdentifier(identifier)) { const span = getErrorSpanForNode(file, name); @@ -42010,21 +42411,18 @@ ${lanes.join("\n")} } function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2 /* ES2015 */ ) { - if (blockScopeContainer.kind !== 308 /* SourceFile */ && blockScopeContainer.kind !== 264 /* ModuleDeclaration */ && !isFunctionLikeOrClassStaticBlockDeclaration(blockScopeContainer)) { + if (blockScopeContainer.kind !== 312 /* SourceFile */ && blockScopeContainer.kind !== 267 /* ModuleDeclaration */ && !isFunctionLikeOrClassStaticBlockDeclaration(blockScopeContainer)) { const errorSpan = getErrorSpanForNode(file, node); file.bindDiagnostics.push(createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); } } } - function checkStrictModeNumericLiteral(node) { - if (languageVersion < 1 /* ES5 */ && inStrictMode && node.numericLiteralFlags & 32 /* Octal */ ) file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); - } function checkStrictModePostfixUnaryExpression(node) { if (inStrictMode) checkStrictModeEvalOrArguments(node, node.operand); } function checkStrictModePrefixUnaryExpression(node) { if (inStrictMode) { - if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */ ) checkStrictModeEvalOrArguments(node, node.operand); + if (node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */ ) checkStrictModeEvalOrArguments(node, node.operand); } } function checkStrictModeWithStatement(node) { @@ -42035,9 +42433,9 @@ ${lanes.join("\n")} if (isDeclarationStatement(node.statement) || isVariableStatement(node.statement)) errorOnFirstToken(node.label, Diagnostics.A_label_is_not_allowed_here); } } - function errorOnFirstToken(node, message, arg0, arg1, arg2) { + function errorOnFirstToken(node, message, ...args) { const span = getSpanOfTokenAtPosition(file, node.pos); - file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); + file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, message, ...args)); } function errorOrSuggestionOnNode(isError, node, message) { errorOrSuggestionOnRange(isError, node, node, message); @@ -42062,7 +42460,7 @@ ${lanes.join("\n")} if (tracing) node.tracingPath = file.path; const saveInStrictMode = inStrictMode; bindWorker(node); - if (node.kind > 162 /* LastToken */ ) { + if (node.kind > 165 /* LastToken */ ) { const saveParent = parent2; parent2 = node; const containerFlags = getContainerFlags(node); @@ -42101,33 +42499,33 @@ ${lanes.join("\n")} } function bindWorker(node) { switch(node.kind){ - case 79 /* Identifier */ : - if (node.flags & 2048 /* IdentifierIsInJSDocNamespace */ ) { + case 80 /* Identifier */ : + if (node.flags & 4096 /* IdentifierIsInJSDocNamespace */ ) { let parentNode = node.parent; while(parentNode && !isJSDocTypeAlias(parentNode))parentNode = parentNode.parent; bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */ , 788968 /* TypeAliasExcludes */ ); break; } - case 108 /* ThisKeyword */ : - if (currentFlow && (isExpression(node) || parent2.kind === 300 /* ShorthandPropertyAssignment */ )) node.flowNode = currentFlow; + case 110 /* ThisKeyword */ : + if (currentFlow && (isExpression(node) || parent2.kind === 304 /* ShorthandPropertyAssignment */ )) node.flowNode = currentFlow; return checkContextualIdentifier(node); - case 163 /* QualifiedName */ : + case 166 /* QualifiedName */ : if (currentFlow && isPartOfTypeQuery(node)) node.flowNode = currentFlow; break; - case 233 /* MetaProperty */ : - case 106 /* SuperKeyword */ : + case 236 /* MetaProperty */ : + case 108 /* SuperKeyword */ : node.flowNode = currentFlow; break; - case 80 /* PrivateIdentifier */ : + case 81 /* PrivateIdentifier */ : return checkPrivateIdentifier(node); - case 208 /* PropertyAccessExpression */ : - case 209 /* ElementAccessExpression */ : + case 211 /* PropertyAccessExpression */ : + case 212 /* ElementAccessExpression */ : const expr = node; if (currentFlow && isNarrowableReference(expr)) expr.flowNode = currentFlow; if (isSpecialPropertyDeclaration(expr)) bindSpecialPropertyDeclaration(expr); if (isInJSFile(expr) && file.commonJsModuleIndicator && isModuleExportsAccessExpression(expr) && !lookupSymbolForName(blockScopeContainer, "module")) declareSymbol(file.locals, /*parent*/ void 0, expr.expression, 134217729 /* ModuleExports */ , 111550 /* FunctionScopedVariableExcludes */ ); break; - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : const specialKind = getAssignmentDeclarationKind(node); switch(specialKind){ case 1 /* ExportsProperty */ : @@ -42162,74 +42560,72 @@ ${lanes.join("\n")} Debug.fail("Unknown binary expression special property assignment kind"); } return checkStrictModeBinaryExpression(node); - case 295 /* CatchClause */ : + case 299 /* CatchClause */ : return checkStrictModeCatchClause(node); - case 217 /* DeleteExpression */ : + case 220 /* DeleteExpression */ : return checkStrictModeDeleteExpression(node); - case 8 /* NumericLiteral */ : - return checkStrictModeNumericLiteral(node); - case 222 /* PostfixUnaryExpression */ : + case 225 /* PostfixUnaryExpression */ : return checkStrictModePostfixUnaryExpression(node); - case 221 /* PrefixUnaryExpression */ : + case 224 /* PrefixUnaryExpression */ : return checkStrictModePrefixUnaryExpression(node); - case 251 /* WithStatement */ : + case 254 /* WithStatement */ : return checkStrictModeWithStatement(node); - case 253 /* LabeledStatement */ : + case 256 /* LabeledStatement */ : return checkStrictModeLabeledStatement(node); - case 194 /* ThisType */ : + case 197 /* ThisType */ : seenThisKeyword = true; return; - case 179 /* TypePredicate */ : + case 182 /* TypePredicate */ : break; - case 165 /* TypeParameter */ : + case 168 /* TypeParameter */ : return bindTypeParameter(node); - case 166 /* Parameter */ : + case 169 /* Parameter */ : return bindParameter(node); - case 257 /* VariableDeclaration */ : + case 260 /* VariableDeclaration */ : return bindVariableDeclarationOrBindingElement(node); - case 205 /* BindingElement */ : + case 208 /* BindingElement */ : node.flowNode = currentFlow; return bindVariableDeclarationOrBindingElement(node); - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : return bindPropertyWorker(node); - case 299 /* PropertyAssignment */ : - case 300 /* ShorthandPropertyAssignment */ : + case 303 /* PropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ , 0 /* PropertyExcludes */ ); - case 302 /* EnumMember */ : + case 306 /* EnumMember */ : return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */ , 900095 /* EnumMemberExcludes */ ); - case 176 /* CallSignature */ : - case 177 /* ConstructSignature */ : - case 178 /* IndexSignature */ : + case 179 /* CallSignature */ : + case 180 /* ConstructSignature */ : + case 181 /* IndexSignature */ : return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */ , 0 /* None */ ); - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */ ), isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 103359 /* MethodExcludes */ ); - case 259 /* FunctionDeclaration */ : + case 262 /* FunctionDeclaration */ : return bindFunctionDeclaration(node); - case 173 /* Constructor */ : + case 176 /* Constructor */ : return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */ , /*symbolExcludes:*/ 0 /* None */ ); - case 174 /* GetAccessor */ : + case 177 /* GetAccessor */ : return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */ , 46015 /* GetAccessorExcludes */ ); - case 175 /* SetAccessor */ : + case 178 /* SetAccessor */ : return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */ , 78783 /* SetAccessorExcludes */ ); - case 181 /* FunctionType */ : - case 320 /* JSDocFunctionType */ : - case 326 /* JSDocSignature */ : - case 182 /* ConstructorType */ : + case 184 /* FunctionType */ : + case 324 /* JSDocFunctionType */ : + case 330 /* JSDocSignature */ : + case 185 /* ConstructorType */ : return bindFunctionOrConstructorType(node); - case 184 /* TypeLiteral */ : - case 325 /* JSDocTypeLiteral */ : - case 197 /* MappedType */ : + case 187 /* TypeLiteral */ : + case 329 /* JSDocTypeLiteral */ : + case 200 /* MappedType */ : return bindAnonymousTypeWorker(node); - case 335 /* JSDocClassTag */ : + case 339 /* JSDocClassTag */ : return bindJSDocClassTag(node); - case 207 /* ObjectLiteralExpression */ : + case 210 /* ObjectLiteralExpression */ : return bindObjectLiteralExpression(node); - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : return bindFunctionExpression(node); - case 210 /* CallExpression */ : + case 213 /* CallExpression */ : const assignmentKind = getAssignmentDeclarationKind(node); switch(assignmentKind){ case 7 /* ObjectDefinePropertyValue */ : @@ -42245,54 +42641,54 @@ ${lanes.join("\n")} } if (isInJSFile(node)) bindCallExpression(node); break; - case 228 /* ClassExpression */ : - case 260 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 263 /* ClassDeclaration */ : inStrictMode = true; return bindClassLikeDeclaration(node); - case 261 /* InterfaceDeclaration */ : + case 264 /* InterfaceDeclaration */ : return bindBlockScopedDeclaration(node, 64 /* Interface */ , 788872 /* InterfaceExcludes */ ); - case 262 /* TypeAliasDeclaration */ : + case 265 /* TypeAliasDeclaration */ : return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */ , 788968 /* TypeAliasExcludes */ ); - case 263 /* EnumDeclaration */ : + case 266 /* EnumDeclaration */ : return bindEnumDeclaration(node); - case 264 /* ModuleDeclaration */ : + case 267 /* ModuleDeclaration */ : return bindModuleDeclaration(node); - case 289 /* JsxAttributes */ : + case 292 /* JsxAttributes */ : return bindJsxAttributes(node); - case 288 /* JsxAttribute */ : + case 291 /* JsxAttribute */ : return bindJsxAttribute(node, 4 /* Property */ , 0 /* PropertyExcludes */ ); - case 268 /* ImportEqualsDeclaration */ : - case 271 /* NamespaceImport */ : - case 273 /* ImportSpecifier */ : - case 278 /* ExportSpecifier */ : + case 271 /* ImportEqualsDeclaration */ : + case 274 /* NamespaceImport */ : + case 276 /* ImportSpecifier */ : + case 281 /* ExportSpecifier */ : return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */ , 2097152 /* AliasExcludes */ ); - case 267 /* NamespaceExportDeclaration */ : + case 270 /* NamespaceExportDeclaration */ : return bindNamespaceExportDeclaration(node); - case 270 /* ImportClause */ : + case 273 /* ImportClause */ : return bindImportClause(node); - case 275 /* ExportDeclaration */ : + case 278 /* ExportDeclaration */ : return bindExportDeclaration(node); - case 274 /* ExportAssignment */ : + case 277 /* ExportAssignment */ : return bindExportAssignment(node); - case 308 /* SourceFile */ : + case 312 /* SourceFile */ : updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 238 /* Block */ : + case 241 /* Block */ : if (!isFunctionLikeOrClassStaticBlockDeclaration(node.parent)) return; - case 265 /* ModuleBlock */ : + case 268 /* ModuleBlock */ : return updateStrictModeStatementList(node.statements); - case 344 /* JSDocParameterTag */ : - if (node.parent.kind === 326 /* JSDocSignature */ ) return bindParameter(node); - if (node.parent.kind !== 325 /* JSDocTypeLiteral */ ) break; - case 351 /* JSDocPropertyTag */ : + case 348 /* JSDocParameterTag */ : + if (node.parent.kind === 330 /* JSDocSignature */ ) return bindParameter(node); + if (node.parent.kind !== 329 /* JSDocTypeLiteral */ ) break; + case 355 /* JSDocPropertyTag */ : const propTag = node; - const flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 319 /* JSDocOptionalType */ ? 16777220 /* Optional */ : 4 /* Property */ ; + const flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 323 /* JSDocOptionalType */ ? 16777220 /* Optional */ : 4 /* Property */ ; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */ ); - case 349 /* JSDocTypedefTag */ : - case 341 /* JSDocCallbackTag */ : - case 343 /* JSDocEnumTag */ : + case 353 /* JSDocTypedefTag */ : + case 345 /* JSDocCallbackTag */ : + case 347 /* JSDocEnumTag */ : return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); - case 342 /* JSDocOverloadTag */ : + case 346 /* JSDocOverloadTag */ : return bind(node.typeExpression); } } @@ -42399,10 +42795,10 @@ ${lanes.join("\n")} if (hasPrivateIdentifier) return; const thisContainer = getThisContainer(node, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false); switch(thisContainer.kind){ - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : let constructorSymbol = thisContainer.symbol; - if (isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 63 /* EqualsToken */ ) { + if (isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 64 /* EqualsToken */ ) { const l = thisContainer.parent.left; if (isBindableStaticAccessExpression(l) && isPrototypeAccess(l.expression)) constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer); } @@ -42413,22 +42809,24 @@ ${lanes.join("\n")} addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */ ); } break; - case 173 /* Constructor */ : - case 169 /* PropertyDeclaration */ : - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 172 /* ClassStaticBlockDeclaration */ : + case 176 /* Constructor */ : + case 172 /* PropertyDeclaration */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 175 /* ClassStaticBlockDeclaration */ : const containingClass = thisContainer.parent; const symbolTable = isStatic(thisContainer) ? containingClass.symbol.exports : containingClass.symbol.members; if (hasDynamicName(node)) bindDynamicallyNamedThisPropertyAssignment(node, containingClass.symbol, symbolTable); else declareSymbol(symbolTable, containingClass.symbol, node, 67108868 /* Assignment */ , 0 /* None */ , /*isReplaceableByMethod*/ true); break; - case 308 /* SourceFile */ : + case 312 /* SourceFile */ : if (hasDynamicName(node)) break; else if (thisContainer.commonJsModuleIndicator) declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 1048580 /* ExportValue */ , 0 /* None */ ); else declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ , 111550 /* FunctionScopedVariableExcludes */ ); break; + case 267 /* ModuleDeclaration */ : + break; default: Debug.failBadSyntaxKind(thisContainer); } @@ -42441,8 +42839,8 @@ ${lanes.join("\n")} if (symbol) (symbol.assignmentDeclarationMembers || (symbol.assignmentDeclarationMembers = /* @__PURE__ */ new Map())).set(getNodeId(node), node); } function bindSpecialPropertyDeclaration(node) { - if (node.expression.kind === 108 /* ThisKeyword */ ) bindThisPropertyAssignment(node); - else if (isBindableStaticAccessExpression(node) && node.parent.parent.kind === 308 /* SourceFile */ ) { + if (node.expression.kind === 110 /* ThisKeyword */ ) bindThisPropertyAssignment(node); + else if (isBindableStaticAccessExpression(node) && node.parent.parent.kind === 312 /* SourceFile */ ) { if (isPrototypeAccess(node.expression)) bindPrototypePropertyAssignment(node, node.parent); else bindStaticPropertyAssignment(node); } @@ -42467,22 +42865,22 @@ ${lanes.join("\n")} } function bindObjectDefinePropertyAssignment(node) { let namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); - const isToplevel = node.parent.parent.kind === 308 /* SourceFile */ ; + const isToplevel = node.parent.parent.kind === 312 /* SourceFile */ ; namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false, /*containerIsClass*/ false); bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false); } function bindSpecialPropertyAssignment(node) { - var _a2; + var _a; const parentSymbol = lookupSymbolForPropertyAccess(node.left.expression, container) || lookupSymbolForPropertyAccess(node.left.expression, blockScopeContainer); if (!isInJSFile(node) && !isFunctionSymbol(parentSymbol)) return; const rootExpr = getLeftmostAccessExpression(node.left); - if (isIdentifier(rootExpr) && ((_a2 = lookupSymbolForName(container, rootExpr.escapedText)) == null ? void 0 : _a2.flags) & 2097152 /* Alias */ ) return; + if (isIdentifier(rootExpr) && ((_a = lookupSymbolForName(container, rootExpr.escapedText)) == null ? void 0 : _a.flags) & 2097152 /* Alias */ ) return; setParent(node.left, node); setParent(node.right, node); if (isIdentifier(node.left.expression) && container === file && isExportsOrModuleExportsOrAlias(file, node.left.expression)) bindExportsPropertyAssignment(node); else if (hasDynamicName(node)) { bindAnonymousDeclaration(node, 67108868 /* Assignment */ , "__computed" /* Computed */ ); - const sym = bindPotentiallyMissingNamespaces(parentSymbol, node.left.expression, isTopLevelNamespaceAssignment(node.left), /*isPrototype*/ false, /*containerIsClass*/ false); + const sym = bindPotentiallyMissingNamespaces(parentSymbol, node.left.expression, isTopLevelNamespaceAssignment(node.left), /*isPrototypeProperty*/ false, /*containerIsClass*/ false); addLateBoundAssignmentDeclarationToSymbol(node, sym); } else bindStaticPropertyAssignment(cast(node.left, isBindableStaticNameExpression)); } @@ -42540,7 +42938,7 @@ ${lanes.join("\n")} declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */ , excludes & -67108865 /* Assignment */ ); } function isTopLevelNamespaceAssignment(propertyAccess) { - return isBinaryExpression(propertyAccess.parent) ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 308 /* SourceFile */ : propertyAccess.parent.parent.kind === 308 /* SourceFile */ ; + return isBinaryExpression(propertyAccess.parent) ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 312 /* SourceFile */ : propertyAccess.parent.parent.kind === 312 /* SourceFile */ ; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) { let namespaceSymbol = lookupSymbolForPropertyAccess(name, container) || lookupSymbolForPropertyAccess(name, blockScopeContainer); @@ -42556,7 +42954,7 @@ ${lanes.join("\n")} init = init && getRightMostAssignedExpression(init); if (init) { const isPrototypeAssignment = isPrototypeAccess(isVariableDeclaration(node) ? node.name : isBinaryExpression(node) ? node.left : node); - return !!getExpandoInitializer(isBinaryExpression(init) && (init.operatorToken.kind === 56 /* BarBarToken */ || init.operatorToken.kind === 60 /* QuestionQuestionToken */ ) ? init.right : init, isPrototypeAssignment); + return !!getExpandoInitializer(isBinaryExpression(init) && (init.operatorToken.kind === 57 /* BarBarToken */ || init.operatorToken.kind === 61 /* QuestionQuestionToken */ ) ? init.right : init, isPrototypeAssignment); } return false; } @@ -42582,16 +42980,16 @@ ${lanes.join("\n")} } } function bindCallExpression(node) { - if (!file.commonJsModuleIndicator && isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) setCommonJsModuleIndicator(node); + if (!file.commonJsModuleIndicator && isRequireCall(node, /*requireStringLiteralLikeArgument*/ false)) setCommonJsModuleIndicator(node); } function bindClassLikeDeclaration(node) { - if (node.kind === 260 /* ClassDeclaration */ ) bindBlockScopedDeclaration(node, 32 /* Class */ , 899503 /* ClassExcludes */ ); + if (node.kind === 263 /* ClassDeclaration */ ) bindBlockScopedDeclaration(node, 32 /* Class */ , 899503 /* ClassExcludes */ ); else { const bindingName = node.name ? node.name.escapedText : "__class" /* Class */ ; bindAnonymousDeclaration(node, 32 /* Class */ , bindingName); if (node.name) classifiableNames.add(node.name.escapedText); } - const { symbol: symbol } = node; + const { symbol: symbol } = node; const prototypeSymbol = createSymbol(4194308 /* Prototype */ , "prototype"); const symbolExport = symbol.exports.get(prototypeSymbol.escapedName); if (symbolExport) { @@ -42607,7 +43005,7 @@ ${lanes.join("\n")} function bindVariableDeclarationOrBindingElement(node) { if (inStrictMode) checkStrictModeEvalOrArguments(node, node.name); if (!isBindingPattern(node.name)) { - const possibleVariableDecl = node.kind === 257 /* VariableDeclaration */ ? node : node.parent.parent; + const possibleVariableDecl = node.kind === 260 /* VariableDeclaration */ ? node : node.parent.parent; if (isInJSFile(node) && shouldResolveJsRequire(options) && isVariableDeclarationInitializedToBareOrAccessedRequire(possibleVariableDecl) && !getJSDocTypeTag(node) && !(getCombinedModifierFlags(node) & 1 /* Export */ )) declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */ , 2097152 /* AliasExcludes */ ); else if (isBlockOrCatchScoped(node)) bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ , 111551 /* BlockScopedVariableExcludes */ ); else if (isParameterDeclaration(node)) declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ , 111551 /* ParameterExcludes */ ); @@ -42615,8 +43013,8 @@ ${lanes.join("\n")} } } function bindParameter(node) { - if (node.kind === 344 /* JSDocParameterTag */ && container.kind !== 326 /* JSDocSignature */ ) return; - if (inStrictMode && !(node.flags & 16777216 /* Ambient */ )) checkStrictModeEvalOrArguments(node, node.name); + if (node.kind === 348 /* JSDocParameterTag */ && container.kind !== 330 /* JSDocSignature */ ) return; + if (inStrictMode && !(node.flags & 33554432 /* Ambient */ )) checkStrictModeEvalOrArguments(node, node.name); if (isBindingPattern(node.name)) bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */ , "__" + node.parent.parameters.indexOf(node)); else declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ , 111551 /* ParameterExcludes */ ); if (isParameterPropertyDeclaration(node, node.parent)) { @@ -42625,8 +43023,8 @@ ${lanes.join("\n")} } } function bindFunctionDeclaration(node) { - if (!file.isDeclarationFile && !(node.flags & 16777216 /* Ambient */ )) { - if (isAsyncFunction(node)) emitFlags |= 2048 /* HasAsyncFunctions */ ; + if (!file.isDeclarationFile && !(node.flags & 33554432 /* Ambient */ )) { + if (isAsyncFunction(node)) emitFlags |= 4096 /* HasAsyncFunctions */ ; } checkStrictModeFunctionName(node); if (inStrictMode) { @@ -42635,8 +43033,8 @@ ${lanes.join("\n")} } else declareSymbolAndAddToSymbolTable(node, 16 /* Function */ , 110991 /* FunctionExcludes */ ); } function bindFunctionExpression(node) { - if (!file.isDeclarationFile && !(node.flags & 16777216 /* Ambient */ )) { - if (isAsyncFunction(node)) emitFlags |= 2048 /* HasAsyncFunctions */ ; + if (!file.isDeclarationFile && !(node.flags & 33554432 /* Ambient */ )) { + if (isAsyncFunction(node)) emitFlags |= 4096 /* HasAsyncFunctions */ ; } if (currentFlow) node.flowNode = currentFlow; checkStrictModeFunctionName(node); @@ -42644,7 +43042,7 @@ ${lanes.join("\n")} return bindAnonymousDeclaration(node, 16 /* Function */ , bindingName); } function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!file.isDeclarationFile && !(node.flags & 16777216 /* Ambient */ ) && isAsyncFunction(node)) emitFlags |= 2048 /* HasAsyncFunctions */ ; + if (!file.isDeclarationFile && !(node.flags & 33554432 /* Ambient */ ) && isAsyncFunction(node)) emitFlags |= 4096 /* HasAsyncFunctions */ ; if (currentFlow && isObjectLiteralOrClassExpressionMethodOrAccessor(node)) node.flowNode = currentFlow; return hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */ ) : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } @@ -42653,19 +43051,18 @@ ${lanes.join("\n")} return extendsType && extendsType.parent; } function bindTypeParameter(node) { - var _a2, _b; if (isJSDocTemplateTag(node.parent)) { const container2 = getEffectiveContainerForJSDocTemplateTag(node.parent); if (container2) { Debug.assertNode(container2, canHaveLocals); - (_a2 = container2.locals) != null ? _a2 : container2.locals = createSymbolTable(); + container2.locals ?? (container2.locals = createSymbolTable()); declareSymbol(container2.locals, /*parent*/ void 0, node, 262144 /* TypeParameter */ , 526824 /* TypeParameterExcludes */ ); } else declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */ , 526824 /* TypeParameterExcludes */ ); - } else if (node.parent.kind === 192 /* InferType */ ) { + } else if (node.parent.kind === 195 /* InferType */ ) { const container2 = getInferTypeContainer(node.parent); if (container2) { Debug.assertNode(container2, canHaveLocals); - (_b = container2.locals) != null ? _b : container2.locals = createSymbolTable(); + container2.locals ?? (container2.locals = createSymbolTable()); declareSymbol(container2.locals, /*parent*/ void 0, node, 262144 /* TypeParameter */ , 526824 /* TypeParameterExcludes */ ); } else bindAnonymousDeclaration(node, 262144 /* TypeParameter */ , getDeclarationName(node)); } else declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */ , 526824 /* TypeParameterExcludes */ ); @@ -42678,13 +43075,13 @@ ${lanes.join("\n")} if (!(currentFlow.flags & 1 /* Unreachable */ )) return false; if (currentFlow === unreachableFlow) { const reportError = // report error on all statements except empty ones - isStatementButNotDeclaration(node) && node.kind !== 239 /* EmptyStatement */ || // report error on class declarations - node.kind === 260 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - node.kind === 264 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node); + isStatementButNotDeclaration(node) && node.kind !== 242 /* EmptyStatement */ || // report error on class declarations + node.kind === 263 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set + node.kind === 267 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { - const isError = unreachableCodeIsError(options) && !(node.flags & 16777216 /* Ambient */ ) && (!isVariableStatement(node) || !!(getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */ ) || node.declarationList.declarations.some((d)=>!!d.initializer)); + const isError = unreachableCodeIsError(options) && !(node.flags & 33554432 /* Ambient */ ) && (!isVariableStatement(node) || !!(getCombinedNodeFlags(node.declarationList) & 7 /* BlockScoped */ ) || node.declarationList.declarations.some((d)=>!!d.initializer)); eachUnreachableRange(node, (start, end)=>errorOrSuggestionOnRange(isError, start, end, Diagnostics.Unreachable_code_detected)); } } @@ -42694,23 +43091,23 @@ ${lanes.join("\n")} } function eachUnreachableRange(node, cb) { if (isStatement(node) && isExecutableStatement(node) && isBlock(node.parent)) { - const { statements: statements } = node.parent; + const { statements: statements } = node.parent; const slice = sliceAfter(statements, node); getRangesWhere(slice, isExecutableStatement, (start, afterEnd)=>cb(slice[start], slice[afterEnd - 1])); } else cb(node, node); } function isExecutableStatement(s) { return !isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !isEnumDeclaration(s) && // `var x;` may declare a variable used above - !(isVariableStatement(s) && !(getCombinedNodeFlags(s) & 3 /* Const */ ) && s.declarationList.declarations.some((d)=>!d.initializer)); + !(isVariableStatement(s) && !(getCombinedNodeFlags(s) & 7 /* BlockScoped */ ) && s.declarationList.declarations.some((d)=>!d.initializer)); } function isPurelyTypeDeclaration(s) { switch(s.kind){ - case 261 /* InterfaceDeclaration */ : - case 262 /* TypeAliasDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 265 /* TypeAliasDeclaration */ : return true; - case 264 /* ModuleDeclaration */ : + case 267 /* ModuleDeclaration */ : return getModuleInstanceState(s) !== 1 /* Instantiated */ ; - case 263 /* EnumDeclaration */ : + case 266 /* EnumDeclaration */ : return hasSyntacticModifier(s, 2048 /* Const */ ); default: return false; @@ -42740,64 +43137,64 @@ ${lanes.join("\n")} } function getContainerFlags(node) { switch(node.kind){ - case 228 /* ClassExpression */ : - case 260 /* ClassDeclaration */ : - case 263 /* EnumDeclaration */ : - case 207 /* ObjectLiteralExpression */ : - case 184 /* TypeLiteral */ : - case 325 /* JSDocTypeLiteral */ : - case 289 /* JsxAttributes */ : + case 231 /* ClassExpression */ : + case 263 /* ClassDeclaration */ : + case 266 /* EnumDeclaration */ : + case 210 /* ObjectLiteralExpression */ : + case 187 /* TypeLiteral */ : + case 329 /* JSDocTypeLiteral */ : + case 292 /* JsxAttributes */ : return 1 /* IsContainer */ ; - case 261 /* InterfaceDeclaration */ : + case 264 /* InterfaceDeclaration */ : return 65 /* IsInterface */ ; - case 264 /* ModuleDeclaration */ : - case 262 /* TypeAliasDeclaration */ : - case 197 /* MappedType */ : - case 178 /* IndexSignature */ : + case 267 /* ModuleDeclaration */ : + case 265 /* TypeAliasDeclaration */ : + case 200 /* MappedType */ : + case 181 /* IndexSignature */ : return 33 /* HasLocals */ ; - case 308 /* SourceFile */ : + case 312 /* SourceFile */ : return 37 /* HasLocals */ ; - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 171 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 174 /* MethodDeclaration */ : if (isObjectLiteralOrClassExpressionMethodOrAccessor(node)) return 173 /* IsObjectLiteralOrClassExpressionMethodOrAccessor */ ; - case 173 /* Constructor */ : - case 259 /* FunctionDeclaration */ : - case 170 /* MethodSignature */ : - case 176 /* CallSignature */ : - case 326 /* JSDocSignature */ : - case 320 /* JSDocFunctionType */ : - case 181 /* FunctionType */ : - case 177 /* ConstructSignature */ : - case 182 /* ConstructorType */ : - case 172 /* ClassStaticBlockDeclaration */ : + case 176 /* Constructor */ : + case 262 /* FunctionDeclaration */ : + case 173 /* MethodSignature */ : + case 179 /* CallSignature */ : + case 330 /* JSDocSignature */ : + case 324 /* JSDocFunctionType */ : + case 184 /* FunctionType */ : + case 180 /* ConstructSignature */ : + case 185 /* ConstructorType */ : + case 175 /* ClassStaticBlockDeclaration */ : return 45 /* IsFunctionLike */ ; - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : return 61 /* IsFunctionExpression */ ; - case 265 /* ModuleBlock */ : + case 268 /* ModuleBlock */ : return 4 /* IsControlFlowContainer */ ; - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : return node.initializer ? 4 /* IsControlFlowContainer */ : 0; - case 295 /* CatchClause */ : - case 245 /* ForStatement */ : - case 246 /* ForInStatement */ : - case 247 /* ForOfStatement */ : - case 266 /* CaseBlock */ : + case 299 /* CatchClause */ : + case 248 /* ForStatement */ : + case 249 /* ForInStatement */ : + case 250 /* ForOfStatement */ : + case 269 /* CaseBlock */ : return 34 /* HasLocals */ ; - case 238 /* Block */ : + case 241 /* Block */ : return isFunctionLike(node.parent) || isClassStaticBlockDeclaration(node.parent) ? 0 /* None */ : 34 /* HasLocals */ ; } return 0 /* None */ ; } function lookupSymbolForName(container, name) { - var _a2, _b, _c, _d, _e; - const local = (_b = (_a2 = tryCast(container, canHaveLocals)) == null ? void 0 : _a2.locals) == null ? void 0 : _b.get(name); - if (local) return (_c = local.exportSymbol) != null ? _c : local; + var _a, _b, _c, _d; + const local = (_b = (_a = tryCast(container, canHaveLocals)) == null ? void 0 : _a.locals) == null ? void 0 : _b.get(name); + if (local) return local.exportSymbol ?? local; if (isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) return container.jsGlobalAugmentations.get(name); - if (canHaveSymbol(container)) return (_e = (_d = container.symbol) == null ? void 0 : _d.exports) == null ? void 0 : _e.get(name); + if (canHaveSymbol(container)) return (_d = (_c = container.symbol) == null ? void 0 : _c.exports) == null ? void 0 : _d.get(name); } - var ModuleInstanceState, binder; + var ModuleInstanceState, ContainerFlags, binder; var init_binder = __esm({ "src/compiler/binder.ts" () { "use strict"; @@ -42809,7 +43206,19 @@ ${lanes.join("\n")} ModuleInstanceState2[ModuleInstanceState2["ConstEnumOnly"] = 2] = "ConstEnumOnly"; return ModuleInstanceState2; })(ModuleInstanceState || {}); - binder = createBinder(); + ContainerFlags = /* @__PURE__ */ ((ContainerFlags2)=>{ + ContainerFlags2[ContainerFlags2["None"] = 0] = "None"; + ContainerFlags2[ContainerFlags2["IsContainer"] = 1] = "IsContainer"; + ContainerFlags2[ContainerFlags2["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; + ContainerFlags2[ContainerFlags2["IsControlFlowContainer"] = 4] = "IsControlFlowContainer"; + ContainerFlags2[ContainerFlags2["IsFunctionLike"] = 8] = "IsFunctionLike"; + ContainerFlags2[ContainerFlags2["IsFunctionExpression"] = 16] = "IsFunctionExpression"; + ContainerFlags2[ContainerFlags2["HasLocals"] = 32] = "HasLocals"; + ContainerFlags2[ContainerFlags2["IsInterface"] = 64] = "IsInterface"; + ContainerFlags2[ContainerFlags2["IsObjectLiteralOrClassExpressionMethodOrAccessor"] = 128] = "IsObjectLiteralOrClassExpressionMethodOrAccessor"; + return ContainerFlags2; + })(ContainerFlags || {}); + binder = /* @__PURE__ */ createBinder(); } }); // src/compiler/symbolWalker.ts @@ -42921,7 +43330,7 @@ ${lanes.join("\n")} visitType(t); if (symbol.exports) symbol.exports.forEach(visitSymbol); forEach(symbol.declarations, (d)=>{ - if (d.type && d.type.kind === 183 /* TypeQuery */ ) { + if (d.type && d.type.kind === 186 /* TypeQuery */ ) { const query = d.type; const entity = getResolvedSymbol(getFirstIdentifier2(query.exprName)); visitSymbol(entity); @@ -42938,12 +43347,12 @@ ${lanes.join("\n")} } }); // src/compiler/moduleSpecifiers.ts - function getPreferences({ importModuleSpecifierPreference: importModuleSpecifierPreference , importModuleSpecifierEnding: importModuleSpecifierEnding }, compilerOptions, importingSourceFile, oldImportSpecifier) { + function getPreferences({ importModuleSpecifierPreference: importModuleSpecifierPreference, importModuleSpecifierEnding: importModuleSpecifierEnding }, compilerOptions, importingSourceFile, oldImportSpecifier) { const preferredEnding = getPreferredEnding(); return { relativePreference: oldImportSpecifier !== void 0 ? isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */ : importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : importModuleSpecifierPreference === "project-relative" ? 3 /* ExternalNonRelative */ : 2 /* Shortest */ , getAllowedEndingsInPreferredOrder: (syntaxImpliedNodeFormat)=>{ - if ((syntaxImpliedNodeFormat != null ? syntaxImpliedNodeFormat : importingSourceFile.impliedNodeFormat) === 99 /* ESNext */ ) { + if ((syntaxImpliedNodeFormat ?? importingSourceFile.impliedNodeFormat) === 99 /* ESNext */ ) { if (shouldAllowImportingTsExtension(compilerOptions, importingSourceFile.fileName)) return [ 3 /* TsExtension */ , 2 /* JsExtension */ @@ -42952,13 +43361,22 @@ ${lanes.join("\n")} 2 /* JsExtension */ ]; } - if (getEmitModuleResolutionKind(compilerOptions) === 1 /* Classic */ ) return [ + if (getEmitModuleResolutionKind(compilerOptions) === 1 /* Classic */ ) return preferredEnding === 2 /* JsExtension */ ? [ + 2 /* JsExtension */ , + 1 /* Index */ + ] : [ 1 /* Index */ , 2 /* JsExtension */ ]; + const allowImportingTsExtension = shouldAllowImportingTsExtension(compilerOptions, importingSourceFile.fileName); switch(preferredEnding){ case 2 /* JsExtension */ : - return [ + return allowImportingTsExtension ? [ + 2 /* JsExtension */ , + 3 /* TsExtension */ , + 0 /* Minimal */ , + 1 /* Index */ + ] : [ 2 /* JsExtension */ , 0 /* Minimal */ , 1 /* Index */ @@ -42971,13 +43389,23 @@ ${lanes.join("\n")} 1 /* Index */ ]; case 1 /* Index */ : - return [ + return allowImportingTsExtension ? [ + 1 /* Index */ , + 0 /* Minimal */ , + 3 /* TsExtension */ , + 2 /* JsExtension */ + ] : [ 1 /* Index */ , 0 /* Minimal */ , 2 /* JsExtension */ ]; case 0 /* Minimal */ : - return [ + return allowImportingTsExtension ? [ + 0 /* Minimal */ , + 1 /* Index */ , + 3 /* TsExtension */ , + 2 /* JsExtension */ + ] : [ 0 /* Minimal */ , 1 /* Index */ , 2 /* JsExtension */ @@ -43017,10 +43445,10 @@ ${lanes.join("\n")} return tryGetModuleSpecifiersFromCacheWorker(moduleSymbol, importingSourceFile, host, userPreferences, options)[0]; } function tryGetModuleSpecifiersFromCacheWorker(moduleSymbol, importingSourceFile, host, userPreferences, options = {}) { - var _a2; + var _a; const moduleSourceFile = getSourceFileOfModule(moduleSymbol); if (!moduleSourceFile) return emptyArray; - const cache = (_a2 = host.getModuleSpecifierCache) == null ? void 0 : _a2.call(host); + const cache = (_a = host.getModuleSpecifierCache) == null ? void 0 : _a.call(host); const cached = cache == null ? void 0 : cache.get(importingSourceFile.path, moduleSourceFile.path, userPreferences, options); return [ cached == null ? void 0 : cached.moduleSpecifiers, @@ -43102,15 +43530,15 @@ ${lanes.join("\n")} sourceDirectory: sourceDirectory }; } - function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, importMode, { getAllowedEndingsInPreferredOrder: getAllowedEndingsInPrefererredOrder , relativePreference: relativePreference }, pathsOnly) { - const { baseUrl: baseUrl , paths: paths , rootDirs: rootDirs } = compilerOptions; + function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, importMode, { getAllowedEndingsInPreferredOrder: getAllowedEndingsInPrefererredOrder, relativePreference: relativePreference }, pathsOnly) { + const { baseUrl: baseUrl, paths: paths, rootDirs: rootDirs } = compilerOptions; if (pathsOnly && !paths) return void 0; - const { sourceDirectory: sourceDirectory , getCanonicalFileName: getCanonicalFileName } = info; + const { sourceDirectory: sourceDirectory, getCanonicalFileName: getCanonicalFileName } = info; const allowedEndings = getAllowedEndingsInPrefererredOrder(importMode); const relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, allowedEndings, compilerOptions) || processEnding(ensurePathIsNonModuleName(getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), allowedEndings, compilerOptions); if (!baseUrl && !paths || relativePreference === 0 /* Relative */ ) return pathsOnly ? void 0 : relativePath; const baseDirectory = getNormalizedAbsolutePath(getPathsBasePath(compilerOptions, host) || baseUrl, host.getCurrentDirectory()); - const relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName); + const relativeToBaseUrl = getRelativePathIfInSameVolume(moduleFileName, baseDirectory, getCanonicalFileName); if (!relativeToBaseUrl) return pathsOnly ? void 0 : relativePath; const fromPaths = paths && tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, host, compilerOptions); if (pathsOnly) return fromPaths; @@ -43145,7 +43573,7 @@ ${lanes.join("\n")} }); } function forEachFileNameOfModule(importingFileName, importedFileName, host, preferSymlinks, cb) { - var _a2; + var _a; const getCanonicalFileName = hostGetCanonicalFileName(host); const cwd = host.getCurrentDirectory(); const referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : void 0; @@ -43164,7 +43592,7 @@ ${lanes.join("\n")} const result2 = forEach(targets, (p)=>!(shouldFilterIgnoredPaths && containsIgnoredPath(p)) && cb(p, referenceRedirect === p)); if (result2) return result2; } - const symlinkedDirectories = (_a2 = host.getSymlinkCache) == null ? void 0 : _a2.call(host).getSymlinkedDirectoriesByRealpath(); + const symlinkedDirectories = (_a = host.getSymlinkCache) == null ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath(); const fullImportedFileName = getNormalizedAbsolutePath(importedFileName, cwd); const result = symlinkedDirectories && forEachAncestorDirectory(getDirectoryPath(fullImportedFileName), (realPathDirectory)=>{ const symlinkDirectories = symlinkedDirectories.get(ensureTrailingDirectorySeparator(toPath(realPathDirectory, cwd, getCanonicalFileName))); @@ -43184,9 +43612,9 @@ ${lanes.join("\n")} return result || (preferSymlinks ? forEach(targets, (p)=>shouldFilterIgnoredPaths && containsIgnoredPath(p) ? void 0 : cb(p, p === referenceRedirect)) : void 0); } function getAllModulePaths(importingFilePath, importedFileName, host, preferences, options = {}) { - var _a2; + var _a; const importedFilePath = toPath(importedFileName, host.getCurrentDirectory(), hostGetCanonicalFileName(host)); - const cache = (_a2 = host.getModuleSpecifierCache) == null ? void 0 : _a2.call(host); + const cache = (_a = host.getModuleSpecifierCache) == null ? void 0 : _a.call(host); if (cache) { const cached = cache.get(importingFilePath, importedFilePath, preferences, options); if (cached == null ? void 0 : cached.modulePaths) return cached.modulePaths; @@ -43212,7 +43640,7 @@ ${lanes.join("\n")} for(let directory = getDirectoryPath(importingFileName); allFileNames.size !== 0;){ const directoryStart = ensureTrailingDirectorySeparator(directory); let pathsInDirectory; - allFileNames.forEach(({ path: path , isRedirect: isRedirect , isInNodeModules: isInNodeModules }, fileName)=>{ + allFileNames.forEach(({ path: path, isRedirect: isRedirect, isInNodeModules: isInNodeModules }, fileName)=>{ if (startsWith(path, directoryStart)) { (pathsInDirectory || (pathsInDirectory = [])).push({ path: fileName, @@ -43238,14 +43666,14 @@ ${lanes.join("\n")} return sortedPaths; } function tryGetModuleNameFromAmbientModule(moduleSymbol, checker) { - var _a2; - const decl = (_a2 = moduleSymbol.declarations) == null ? void 0 : _a2.find((d)=>isNonGlobalAmbientModule(d) && (!isExternalModuleAugmentation(d) || !isExternalModuleNameRelative(getTextOfIdentifierOrLiteral(d.name)))); + var _a; + const decl = (_a = moduleSymbol.declarations) == null ? void 0 : _a.find((d)=>isNonGlobalAmbientModule(d) && (!isExternalModuleAugmentation(d) || !isExternalModuleNameRelative(getTextOfIdentifierOrLiteral(d.name)))); if (decl) return decl.name.text; const ambientModuleDeclareCandidates = mapDefined(moduleSymbol.declarations, (d)=>{ - var _a3, _b, _c, _d; + var _a2, _b, _c, _d; if (!isModuleDeclaration(d)) return; const topNamespace = getTopNamespace(d); - if (!(((_a3 = topNamespace == null ? void 0 : topNamespace.parent) == null ? void 0 : _a3.parent) && isModuleBlock(topNamespace.parent) && isAmbientModule(topNamespace.parent.parent) && isSourceFile(topNamespace.parent.parent.parent))) return; + if (!(((_a2 = topNamespace == null ? void 0 : topNamespace.parent) == null ? void 0 : _a2.parent) && isModuleBlock(topNamespace.parent) && isAmbientModule(topNamespace.parent.parent) && isSourceFile(topNamespace.parent.parent.parent))) return; const exportAssignment = (_d = (_c = (_b = topNamespace.parent.parent.symbol.exports) == null ? void 0 : _b.get("export=")) == null ? void 0 : _c.valueDeclaration) == null ? void 0 : _d.expression; if (!exportAssignment) return; const exportSymbol = checker.getSymbolAtLocation(exportAssignment); @@ -43253,7 +43681,7 @@ ${lanes.join("\n")} const originalExportSymbol = (exportSymbol == null ? void 0 : exportSymbol.flags) & 2097152 /* Alias */ ? checker.getAliasedSymbol(exportSymbol) : exportSymbol; if (originalExportSymbol === d.symbol) return topNamespace.parent.parent; function getTopNamespace(namespaceDeclaration) { - while(namespaceDeclaration.flags & 4 /* NestedNamespace */ )namespaceDeclaration = namespaceDeclaration.parent; + while(namespaceDeclaration.flags & 8 /* NestedNamespace */ )namespaceDeclaration = namespaceDeclaration.parent; return namespaceDeclaration; } }); @@ -43277,16 +43705,16 @@ ${lanes.join("\n")} if (indexOfStar !== -1) { const prefix = pattern.substring(0, indexOfStar); const suffix = pattern.substring(indexOfStar + 1); - for (const { ending: ending , value: value1 } of candidates)if (value1.length >= prefix.length + suffix.length && startsWith(value1, prefix) && endsWith(value1, suffix) && validateEnding({ + for (const { ending: ending, value: value1 } of candidates)if (value1.length >= prefix.length + suffix.length && startsWith(value1, prefix) && endsWith(value1, suffix) && validateEnding({ ending: ending, value: value1 })) { const matchedStar = value1.substring(prefix.length, value1.length - suffix.length); - return key.replace("*", matchedStar); + if (!pathIsRelative(matchedStar)) return key.replace("*", matchedStar); } } else if (some(candidates, (c)=>c.ending !== 0 /* Minimal */ && pattern === c.value) || some(candidates, (c)=>c.ending === 0 /* Minimal */ && pattern === c.value && validateEnding(c))) return key; } - function validateEnding({ ending: ending , value: value1 }) { + function validateEnding({ ending: ending, value: value1 }) { return ending !== 0 /* Minimal */ || value1 === processEnding(relativeToBaseUrl, [ ending ], compilerOptions, host); @@ -43338,7 +43766,7 @@ ${lanes.join("\n")} else { for (const key of getOwnKeys(exports))if (key === "default" || conditions.indexOf(key) >= 0 || isApplicableVersionedTypesKey(conditions, key)) { const subTarget = exports[key]; - const result = tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, subTarget, conditions); + const result = tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, subTarget, conditions, mode); if (result) return result; } } @@ -43356,7 +43784,7 @@ ${lanes.join("\n")} if (!shortest) return void 0; return processEnding(shortest, allowedEndings, compilerOptions); } - function tryGetModuleNameAsNodeModule({ path: path , isRedirect: isRedirect }, { getCanonicalFileName: getCanonicalFileName , sourceDirectory: sourceDirectory }, importingSourceFile, host, options, userPreferences, packageNameOnly, overrideMode) { + function tryGetModuleNameAsNodeModule({ path: path, isRedirect: isRedirect }, { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }, importingSourceFile, host, options, userPreferences, packageNameOnly, overrideMode) { if (!host.fileExists || !host.readFile) return void 0; const parts = getNodeModulePathParts(path); if (!parts) return void 0; @@ -43368,7 +43796,7 @@ ${lanes.join("\n")} let packageRootIndex = parts.packageRootIndex; let moduleFileName; while(true){ - const { moduleFileToTry: moduleFileToTry , packageRootPath: packageRootPath , blockedByExports: blockedByExports , verbatimFromExports: verbatimFromExports } = tryDirectoryWithPackageJson(packageRootIndex); + const { moduleFileToTry: moduleFileToTry, packageRootPath: packageRootPath, blockedByExports: blockedByExports, verbatimFromExports: verbatimFromExports } = tryDirectoryWithPackageJson(packageRootIndex); if (getEmitModuleResolutionKind(options) !== 1 /* Classic */ ) { if (blockedByExports) return void 0; if (verbatimFromExports) return moduleFileToTry; @@ -43394,12 +43822,12 @@ ${lanes.join("\n")} const packageName = getPackageNameFromTypesPackageName(nodeModulesDirectoryName); return getEmitModuleResolutionKind(options) === 1 /* Classic */ && packageName === nodeModulesDirectoryName ? void 0 : packageName; function tryDirectoryWithPackageJson(packageRootIndex) { - var _a2, _b; + var _a, _b; const packageRootPath = path.substring(0, packageRootIndex); const packageJsonPath = combinePaths(packageRootPath, "package.json"); let moduleFileToTry = path; let maybeBlockedByTypesVersions = false; - const cachedPackageJson = (_b = (_a2 = host.getPackageJsonInfoCache) == null ? void 0 : _a2.call(host)) == null ? void 0 : _b.getPackageJsonInfo(packageJsonPath); + const cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) == null ? void 0 : _a.call(host)) == null ? void 0 : _b.getPackageJsonInfo(packageJsonPath); if (typeof cachedPackageJson === "object" || cachedPackageJson === void 0 && host.fileExists(packageJsonPath)) { const packageJsonContent = (cachedPackageJson == null ? void 0 : cachedPackageJson.contents.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath)); const importMode = overrideMode || importingSourceFile.impliedNodeFormat; @@ -43432,7 +43860,12 @@ ${lanes.join("\n")} const mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main || "index.js"; if (isString(mainFileRelative) && !(maybeBlockedByTypesVersions && matchPatternOrExact(tryParsePatterns(versionPaths.paths), mainFileRelative))) { const mainExportFile = toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (removeFileExtension(mainExportFile) === removeFileExtension(getCanonicalFileName(moduleFileToTry))) return { + const canonicalModuleFileToTry = getCanonicalFileName(moduleFileToTry); + if (removeFileExtension(mainExportFile) === removeFileExtension(canonicalModuleFileToTry)) return { + packageRootPath: packageRootPath, + moduleFileToTry: moduleFileToTry + }; + else if (packageJsonContent.type !== "module" && !fileExtensionIsOneOf(canonicalModuleFileToTry, extensionsNotSupportingExtensionlessResolution) && startsWith(canonicalModuleFileToTry, mainExportFile) && getDirectoryPath(canonicalModuleFileToTry) === removeTrailingDirectorySeparator(mainExportFile) && removeFileExtension(getBaseFileName(canonicalModuleFileToTry)) === "index") return { packageRootPath: packageRootPath, moduleFileToTry: moduleFileToTry }; @@ -43471,7 +43904,7 @@ ${lanes.join("\n")} } function getPathsRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { return mapDefined(rootDirs, (rootDir)=>{ - const relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + const relativePath = getRelativePathIfInSameVolume(path, rootDir, getCanonicalFileName); return relativePath !== void 0 && isPathRelativeToParent(relativePath) ? void 0 : relativePath; }); } @@ -43483,7 +43916,13 @@ ${lanes.join("\n")} ])) return fileName; const noExtension = removeFileExtension(fileName); if (fileName === noExtension) return fileName; + const jsPriority = allowedEndings.indexOf(2 /* JsExtension */ ); + const tsPriority = allowedEndings.indexOf(3 /* TsExtension */ ); if (fileExtensionIsOneOf(fileName, [ + ".mts" /* Mts */ , + ".cts" /* Cts */ + ]) && tsPriority !== -1 && tsPriority < jsPriority) return fileName; + else if (fileExtensionIsOneOf(fileName, [ ".d.mts" /* Dmts */ , ".mts" /* Mts */ , ".d.cts" /* Dcts */ , @@ -43506,7 +43945,6 @@ ${lanes.join("\n")} case 3 /* TsExtension */ : if (isDeclarationFileName(fileName)) { const extensionlessPriority = allowedEndings.findIndex((e)=>e === 0 /* Minimal */ || e === 1 /* Index */ ); - const jsPriority = allowedEndings.indexOf(2 /* JsExtension */ ); return extensionlessPriority !== -1 && extensionlessPriority < jsPriority ? noExtension : noExtension + getJSExtensionForFile(fileName, options); } return fileName; @@ -43524,8 +43962,7 @@ ${lanes.join("\n")} return noExtension.substring(0, noExtension.indexOf(".d.")) + ext; } function getJSExtensionForFile(fileName, options) { - var _a2; - return (_a2 = tryGetJSExtensionForFile(fileName, options)) != null ? _a2 : Debug.fail(`Extension ${extensionFromPath(fileName)} is unsupported:: FileName:: ${fileName}`); + return tryGetJSExtensionForFile(fileName, options) ?? Debug.fail(`Extension ${extensionFromPath(fileName)} is unsupported:: FileName:: ${fileName}`); } function tryGetJSExtensionForFile(fileName, options) { const ext = tryGetExtensionFromPath2(fileName); @@ -43551,7 +43988,7 @@ ${lanes.join("\n")} return void 0; } } - function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + function getRelativePathIfInSameVolume(path, directoryPath, getCanonicalFileName) { const relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); return isRootedDiskPath(relativePath) ? void 0 : relativePath; } @@ -43607,16 +44044,6 @@ ${lanes.join("\n")} return moduleState === 1 /* Instantiated */ || preserveConstEnums && moduleState === 2 /* ConstEnumOnly */ ; } function createTypeChecker(host) { - var getPackagesMap = memoize(()=>{ - var map2 = /* @__PURE__ */ new Map(); - host.getSourceFiles().forEach((sf)=>{ - if (!sf.resolvedModules) return; - sf.resolvedModules.forEach(({ resolvedModule: resolvedModule })=>{ - if (resolvedModule == null ? void 0 : resolvedModule.packageId) map2.set(resolvedModule.packageId.name, resolvedModule.extension === ".d.ts" /* Dts */ || !!map2.get(resolvedModule.packageId.name)); - }); - }); - return map2; - }); var deferredDiagnosticsCallbacks = []; var addLazyDiagnostic = (arg)=>{ deferredDiagnosticsCallbacks.push(arg); @@ -43625,7 +44052,7 @@ ${lanes.join("\n")} var requestedExternalEmitHelperNames = /* @__PURE__ */ new Set(); var requestedExternalEmitHelpers; var externalHelpersModule; - var Symbol46 = objectAllocator.getSymbolConstructor(); + var Symbol47 = objectAllocator.getSymbolConstructor(); var Type27 = objectAllocator.getTypeConstructor(); var Signature15 = objectAllocator.getSignatureConstructor(); var typeCount = 0; @@ -43646,6 +44073,7 @@ ${lanes.join("\n")} var moduleKind = getEmitModuleKind(compilerOptions); var legacyDecorators = !!compilerOptions.experimentalDecorators; var useDefineForClassFields = getUseDefineForClassFields(compilerOptions); + var emitStandardClassFields = getEmitStandardClassFields(compilerOptions); var allowSyntheticDefaultImports = getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = getStrictOptionValue(compilerOptions, "strictFunctionTypes"); @@ -43655,6 +44083,7 @@ ${lanes.join("\n")} var noImplicitThis = getStrictOptionValue(compilerOptions, "noImplicitThis"); var useUnknownInCatchVariables = getStrictOptionValue(compilerOptions, "useUnknownInCatchVariables"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; + var defaultIndexFlags = keyofStringsOnly ? 1 /* StringsOnly */ : 0 /* None */ ; var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 8192 /* FreshLiteral */ ; var exactOptionalPropertyTypes = compilerOptions.exactOptionalPropertyTypes; var checkBinaryExpression = createCheckBinaryExpression(); @@ -43670,7 +44099,12 @@ ${lanes.join("\n")} var argumentsSymbol = createSymbol(4 /* Property */ , "arguments"); var requireSymbol = createSymbol(4 /* Property */ , "require"); var isolatedModulesLikeFlagName = compilerOptions.verbatimModuleSyntax ? "verbatimModuleSyntax" : "isolatedModules"; + var canCollectSymbolAliasAccessabilityData = !compilerOptions.verbatimModuleSyntax || !!compilerOptions.importsNotUsedAsValues; var apparentArgumentCount; + var lastGetCombinedNodeFlagsNode; + var lastGetCombinedNodeFlagsResult = 0 /* None */ ; + var lastGetCombinedModifierFlagsNode; + var lastGetCombinedModifierFlagsResult = 0 /* None */ ; const checker = { getNodeCount: ()=>reduceLeft(host.getSourceFiles(), (n, s)=>n + s.nodeCount, 0), getIdentifierCount: ()=>reduceLeft(host.getSourceFiles(), (n, s)=>n + s.identifierCount, 0), @@ -43727,7 +44161,7 @@ ${lanes.join("\n")} return node ? getTypeFromTypeNode(node) : errorType; }, getParameterType: getTypeAtPosition, - getParameterIdentifierNameAtPosition: getParameterIdentifierNameAtPosition, + getParameterIdentifierInfoAtPosition: getParameterIdentifierInfoAtPosition, getPromisedTypeOfPromise: getPromisedTypeOfPromise, getAwaitedType: (type)=>getAwaitedType(type), getReturnTypeOfSignature: getReturnTypeOfSignature, @@ -43829,7 +44263,10 @@ ${lanes.join("\n")} getTypeOfPropertyOfContextualType: getTypeOfPropertyOfContextualType, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: (node, candidatesOutArray, argumentCount)=>getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */ ), - getResolvedSignatureForStringLiteralCompletions: (call, editingArgument, candidatesOutArray)=>runWithInferenceBlockedFromSourceNode(editingArgument, ()=>getResolvedSignatureWorker(call, candidatesOutArray, /*argumentCount*/ void 0, 32 /* IsForStringLiteralArgumentCompletions */ )), + getResolvedSignatureForStringLiteralCompletions: (call, editingArgument, candidatesOutArray, checkMode = 32 /* IsForStringLiteralArgumentCompletions */ )=>{ + if (checkMode & 32 /* IsForStringLiteralArgumentCompletions */ ) return runWithInferenceBlockedFromSourceNode(editingArgument, ()=>getResolvedSignatureWorker(call, candidatesOutArray, /*argumentCount*/ void 0, checkMode & -33 /* IsForStringLiteralArgumentCompletions */ )); + return runWithoutResolvedSignatureCaching(editingArgument, ()=>getResolvedSignatureWorker(call, candidatesOutArray, /*argumentCount*/ void 0, checkMode & -33 /* IsForStringLiteralArgumentCompletions */ )); + }, getResolvedSignatureForSignatureHelp: (node, candidatesOutArray, argumentCount)=>runWithoutResolvedSignatureCaching(node, ()=>getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 16 /* IsForSignatureHelp */ )), getExpandedParameters: getExpandedParameters, hasEffectiveRestParameter: hasEffectiveRestParameter, @@ -43882,7 +44319,10 @@ ${lanes.join("\n")} createIndexInfo: createIndexInfo, getAnyType: ()=>anyType, getStringType: ()=>stringType, + getStringLiteralType: getStringLiteralType, getNumberType: ()=>numberType, + getNumberLiteralType: getNumberLiteralType, + getBigIntType: ()=>bigintType, createPromiseType: createPromiseType, createArrayType: createArrayType, getElementTypeOfArrayType: getElementTypeOfArrayType, @@ -43953,7 +44393,7 @@ ${lanes.join("\n")} Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */ )); diagnostics2 = addRange(diagnostics2, suggestionDiagnostics.getDiagnostics(file.fileName)); checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), (containingNode, kind, diag2)=>{ - if (!containsParseError(containingNode) && !unusedIsError(kind, !!(containingNode.flags & 16777216 /* Ambient */ ))) (diagnostics2 || (diagnostics2 = [])).push({ + if (!containsParseError(containingNode) && !unusedIsError(kind, !!(containingNode.flags & 33554432 /* Ambient */ ))) (diagnostics2 || (diagnostics2 = [])).push({ ...diag2, category: 2 /* Suggestion */ }); @@ -43980,11 +44420,21 @@ ${lanes.join("\n")} typeHasCallOrConstructSignatures: typeHasCallOrConstructSignatures }; function runWithoutResolvedSignatureCaching(node, fn) { - const containingCall = findAncestor(node, isCallLikeExpression); - const containingCallResolvedSignature = containingCall && getNodeLinks(containingCall).resolvedSignature; - if (containingCall) getNodeLinks(containingCall).resolvedSignature = void 0; + const cachedSignatures = []; + while(node){ + if (isCallLikeExpression(node)) { + const nodeLinks2 = getNodeLinks(node); + const resolvedSignature = nodeLinks2.resolvedSignature; + cachedSignatures.push([ + nodeLinks2, + resolvedSignature + ]); + nodeLinks2.resolvedSignature = void 0; + } + node = node.parent; + } const result = fn(); - if (containingCall) getNodeLinks(containingCall).resolvedSignature = containingCallResolvedSignature; + for (const [nodeLinks2, resolvedSignature] of cachedSignatures)nodeLinks2.resolvedSignature = resolvedSignature; return result; } function runWithInferenceBlockedFromSourceNode(node, fn) { @@ -44017,6 +44467,7 @@ ${lanes.join("\n")} } var tupleTypes = /* @__PURE__ */ new Map(); var unionTypes = /* @__PURE__ */ new Map(); + var unionOfUnionTypes = /* @__PURE__ */ new Map(); var intersectionTypes = /* @__PURE__ */ new Map(); var stringLiteralTypes = /* @__PURE__ */ new Map(); var numberLiteralTypes = /* @__PURE__ */ new Map(); @@ -44119,25 +44570,25 @@ ${lanes.join("\n")} if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false); return t; }, ()=>"(unreliable reporter)"); - var emptyObjectType = createAnonymousType(void 0, emptySymbols, emptyArray, emptyArray, emptyArray); - var emptyJsxObjectType = createAnonymousType(void 0, emptySymbols, emptyArray, emptyArray, emptyArray); + var emptyObjectType = createAnonymousType(/*symbol*/ void 0, emptySymbols, emptyArray, emptyArray, emptyArray); + var emptyJsxObjectType = createAnonymousType(/*symbol*/ void 0, emptySymbols, emptyArray, emptyArray, emptyArray); emptyJsxObjectType.objectFlags |= 2048 /* JsxAttributes */ ; var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */ , "__type" /* Type */ ); emptyTypeLiteralSymbol.members = createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, emptyArray); - var unknownEmptyObjectType = createAnonymousType(void 0, emptySymbols, emptyArray, emptyArray, emptyArray); + var unknownEmptyObjectType = createAnonymousType(/*symbol*/ void 0, emptySymbols, emptyArray, emptyArray, emptyArray); var unknownUnionType = strictNullChecks ? getUnionType([ undefinedType, nullType, unknownEmptyObjectType ]) : unknownType; - var emptyGenericType = createAnonymousType(void 0, emptySymbols, emptyArray, emptyArray, emptyArray); + var emptyGenericType = createAnonymousType(/*symbol*/ void 0, emptySymbols, emptyArray, emptyArray, emptyArray); emptyGenericType.instantiations = /* @__PURE__ */ new Map(); - var anyFunctionType = createAnonymousType(void 0, emptySymbols, emptyArray, emptyArray, emptyArray); + var anyFunctionType = createAnonymousType(/*symbol*/ void 0, emptySymbols, emptyArray, emptyArray, emptyArray); anyFunctionType.objectFlags |= 262144 /* NonInferrableType */ ; - var noConstraintType = createAnonymousType(void 0, emptySymbols, emptyArray, emptyArray, emptyArray); - var circularConstraintType = createAnonymousType(void 0, emptySymbols, emptyArray, emptyArray, emptyArray); - var resolvingDefaultType = createAnonymousType(void 0, emptySymbols, emptyArray, emptyArray, emptyArray); + var noConstraintType = createAnonymousType(/*symbol*/ void 0, emptySymbols, emptyArray, emptyArray, emptyArray); + var circularConstraintType = createAnonymousType(/*symbol*/ void 0, emptySymbols, emptyArray, emptyArray, emptyArray); + var resolvingDefaultType = createAnonymousType(/*symbol*/ void 0, emptySymbols, emptyArray, emptyArray, emptyArray); var markerSuperType = createTypeParameter(); var markerSubType = createTypeParameter(); markerSubType.constraint = markerSuperType; @@ -44146,10 +44597,10 @@ ${lanes.join("\n")} var markerSubTypeForCheck = createTypeParameter(); markerSubTypeForCheck.constraint = markerSuperTypeForCheck; var noTypePredicate = createTypePredicate(1 /* Identifier */ , "<>", 0, anyType); - var anySignature = createSignature(void 0, void 0, void 0, emptyArray, anyType, /*resolvedTypePredicate*/ void 0, 0, 0 /* None */ ); - var unknownSignature = createSignature(void 0, void 0, void 0, emptyArray, errorType, /*resolvedTypePredicate*/ void 0, 0, 0 /* None */ ); - var resolvingSignature = createSignature(void 0, void 0, void 0, emptyArray, anyType, /*resolvedTypePredicate*/ void 0, 0, 0 /* None */ ); - var silentNeverSignature = createSignature(void 0, void 0, void 0, emptyArray, silentNeverType, /*resolvedTypePredicate*/ void 0, 0, 0 /* None */ ); + var anySignature = createSignature(/*declaration*/ void 0, /*typeParameters*/ void 0, /*thisParameter*/ void 0, emptyArray, anyType, /*resolvedTypePredicate*/ void 0, 0, 0 /* None */ ); + var unknownSignature = createSignature(/*declaration*/ void 0, /*typeParameters*/ void 0, /*thisParameter*/ void 0, emptyArray, errorType, /*resolvedTypePredicate*/ void 0, 0, 0 /* None */ ); + var resolvingSignature = createSignature(/*declaration*/ void 0, /*typeParameters*/ void 0, /*thisParameter*/ void 0, emptyArray, anyType, /*resolvedTypePredicate*/ void 0, 0, 0 /* None */ ); + var silentNeverSignature = createSignature(/*declaration*/ void 0, /*typeParameters*/ void 0, /*thisParameter*/ void 0, emptyArray, silentNeverType, /*resolvedTypePredicate*/ void 0, 0, 0 /* None */ ); var enumNumberIndexInfo = createIndexInfo(numberType, stringType, /*isReadonly*/ true); var iterationTypesCache = /* @__PURE__ */ new Map(); var noIterationTypes = { @@ -44174,7 +44625,7 @@ ${lanes.join("\n")} getGlobalIterableType: getGlobalAsyncIterableType, getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType, getGlobalGeneratorType: getGlobalAsyncGeneratorType, - resolveIterationType: getAwaitedType, + resolveIterationType: (type, errorNode)=>getAwaitedType(type, errorNode, Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member), mustHaveANextMethodDiagnostic: Diagnostics.An_async_iterator_must_have_a_next_method, mustBeAMethodDiagnostic: Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method, mustHaveAValueDiagnostic: Diagnostics.The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property @@ -44194,7 +44645,7 @@ ${lanes.join("\n")} }; var amalgamatedDuplicates; var reverseMappedCache = /* @__PURE__ */ new Map(); - var inInferTypeForHomomorphicMappedType = false; + var homomorphicMappedTypeInferenceStack = []; var ambientModulesCache; var patternAmbientModules; var patternAmbientModuleAugmentations; @@ -44235,6 +44686,8 @@ ${lanes.join("\n")} var deferredGlobalImportMetaType; var deferredGlobalImportMetaExpressionType; var deferredGlobalImportCallOptionsType; + var deferredGlobalDisposableType; + var deferredGlobalAsyncDisposableType; var deferredGlobalExtractSymbol; var deferredGlobalOmitSymbol; var deferredGlobalAwaitedSymbol; @@ -44274,6 +44727,8 @@ ${lanes.join("\n")} var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; + var resolutionStart = 0; + var inVarianceComputation = false; var suggestionCount = 0; var maximumSuggestionCount = 10; var mergedSymbols = []; @@ -44406,8 +44861,8 @@ ${lanes.join("\n")} getDiagnostics2(sourceFile, cancellationToken2); return emitResolver; } - function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) { - const diagnostic = location ? createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); + function lookupOrIssueError(location, message, ...args) { + const diagnostic = location ? createDiagnosticForNode(location, message, ...args) : createCompilerDiagnostic(message, ...args); const existing = diagnostics.lookup(diagnostic); if (existing) return existing; else { @@ -44415,16 +44870,16 @@ ${lanes.join("\n")} return diagnostic; } } - function errorSkippedOn(key, location, message, arg0, arg1, arg2, arg3) { - const diagnostic = error(location, message, arg0, arg1, arg2, arg3); + function errorSkippedOn(key, location, message, ...args) { + const diagnostic = error2(location, message, ...args); diagnostic.skippedOn = key; return diagnostic; } - function createError(location, message, arg0, arg1, arg2, arg3) { - return location ? createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); + function createError(location, message, ...args) { + return location ? createDiagnosticForNode(location, message, ...args) : createCompilerDiagnostic(message, ...args); } - function error(location, message, arg0, arg1, arg2, arg3) { - const diagnostic = createError(location, message, arg0, arg1, arg2, arg3); + function error2(location, message, ...args) { + const diagnostic = createError(location, message, ...args); diagnostics.add(diagnostic); return diagnostic; } @@ -44435,17 +44890,17 @@ ${lanes.join("\n")} category: 2 /* Suggestion */ }); } - function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) { + function errorOrSuggestion(isError, location, message, ...args) { if (location.pos < 0 || location.end < 0) { if (!isError) return; const file = getSourceFileOfNode(location); - addErrorOrSuggestion(isError, "message" in message ? createFileDiagnostic(file, 0, 0, message, arg0, arg1, arg2, arg3) : createDiagnosticForFileFromMessageChain(file, message)); + addErrorOrSuggestion(isError, "message" in message ? createFileDiagnostic(file, 0, 0, message, ...args) : createDiagnosticForFileFromMessageChain(file, message)); return; } - addErrorOrSuggestion(isError, "message" in message ? createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(location), location, message)); + addErrorOrSuggestion(isError, "message" in message ? createDiagnosticForNode(location, message, ...args) : createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(location), location, message)); } - function errorAndMaybeSuggestAwait(location, maybeMissingAwait, message, arg0, arg1, arg2, arg3) { - const diagnostic = error(location, message, arg0, arg1, arg2, arg3); + function errorAndMaybeSuggestAwait(location, maybeMissingAwait, message, ...args) { + const diagnostic = error2(location, message, ...args); if (maybeMissingAwait) { const related = createDiagnosticForNode(location, Diagnostics.Did_you_forget_to_use_await); addRelatedInfo(diagnostic, related); @@ -44459,11 +44914,12 @@ ${lanes.join("\n")} return diagnostic; } function isDeprecatedSymbol(symbol) { - if (length(symbol.declarations) > 1) { - const parentSymbol = getParentOfSymbol(symbol); - if (parentSymbol && parentSymbol.flags & 64 /* Interface */ ) return some(symbol.declarations, (d)=>!!(getCombinedNodeFlags(d) & 268435456 /* Deprecated */ )); - } - return !!(getDeclarationNodeFlagsFromSymbol(symbol) & 268435456 /* Deprecated */ ); + const parentSymbol = getParentOfSymbol(symbol); + if (parentSymbol && length(symbol.declarations) > 1) return parentSymbol.flags & 64 /* Interface */ ? some(symbol.declarations, isDeprecatedDeclaration2) : every(symbol.declarations, isDeprecatedDeclaration2); + return !!symbol.valueDeclaration && isDeprecatedDeclaration2(symbol.valueDeclaration) || length(symbol.declarations) && every(symbol.declarations, isDeprecatedDeclaration2); + } + function isDeprecatedDeclaration2(declaration) { + return !!(getCombinedNodeFlagsCached(declaration) & 536870912 /* Deprecated */ ); } function addDeprecatedSuggestion(location, declarations, deprecatedEntity) { const diagnostic = createDiagnosticForNode(location, Diagnostics._0_is_deprecated, deprecatedEntity); @@ -44475,7 +44931,7 @@ ${lanes.join("\n")} } function createSymbol(flags, name, checkFlags) { symbolCount++; - const symbol = new Symbol46(flags | 33554432 /* Transient */ , name); + const symbol = new Symbol47(flags | 33554432 /* Transient */ , name); symbol.links = new SymbolLinks(); symbol.links.checkFlags = checkFlags || 0 /* None */ ; return symbol; @@ -44550,7 +45006,7 @@ ${lanes.join("\n")} } if (!unidirectional) recordMergedSymbol(target, source); } else if (target.flags & 1024 /* NamespaceModule */ ) { - if (target !== globalThisSymbol) error(source.declarations && getNameOfDeclaration(source.declarations[0]), Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + if (target !== globalThisSymbol) error2(source.declarations && getNameOfDeclaration(source.declarations[0]), Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { const isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */ ); const isEitherBlockScoped = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */ ); @@ -44618,15 +45074,15 @@ ${lanes.join("\n")} }); } function mergeModuleAugmentation(moduleName) { - var _a2, _b, _c; + var _a, _b, _c; const moduleAugmentation = moduleName.parent; - if (((_a2 = moduleAugmentation.symbol.declarations) == null ? void 0 : _a2[0]) !== moduleAugmentation) { + if (((_a = moduleAugmentation.symbol.declarations) == null ? void 0 : _a[0]) !== moduleAugmentation) { Debug.assert(moduleAugmentation.symbol.declarations.length > 1); return; } if (isGlobalScopeAugmentation(moduleAugmentation)) mergeSymbolTable(globals, moduleAugmentation.symbol.exports); else { - const moduleNotFoundError = !(moduleName.parent.parent.flags & 16777216 /* Ambient */ ) ? Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found : void 0; + const moduleNotFoundError = !(moduleName.parent.parent.flags & 33554432 /* Ambient */ ) ? Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found : void 0; let mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true); if (!mainModule) return; mainModule = resolveExternalModuleSymbol(mainModule); @@ -44642,7 +45098,7 @@ ${lanes.join("\n")} } mergeSymbol(mainModule, moduleAugmentation.symbol); } - } else error(moduleName, Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); + } else error2(moduleName, Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); } } function addToSymbolTable(target, source, message) { @@ -44656,17 +45112,16 @@ ${lanes.join("\n")} } } function getSymbolLinks(symbol) { - var _a2; if (symbol.flags & 33554432 /* Transient */ ) return symbol.links; const id = getSymbolId(symbol); - return (_a2 = symbolLinks[id]) != null ? _a2 : symbolLinks[id] = new SymbolLinks(); + return symbolLinks[id] ?? (symbolLinks[id] = new SymbolLinks()); } function getNodeLinks(node) { const nodeId = getNodeId(node); return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks()); } function isGlobalSourceFile(node) { - return node.kind === 308 /* SourceFile */ && !isExternalOrCommonJsModule(node); + return node.kind === 312 /* SourceFile */ && !isExternalOrCommonJsModule(node); } function getSymbol2(symbols, name, meaning) { if (meaning) { @@ -44675,7 +45130,7 @@ ${lanes.join("\n")} Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */ ) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) return symbol; if (symbol.flags & 2097152 /* Alias */ ) { - const targetFlags = getAllSymbolFlags(symbol); + const targetFlags = getSymbolFlags(symbol); if (targetFlags & meaning) return symbol; } } @@ -44697,35 +45152,35 @@ ${lanes.join("\n")} const useFile = getSourceFileOfNode(usage); const declContainer = getEnclosingBlockScopeContainer(declaration); if (declarationFile !== useFile) { - if (moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator) || !outFile(compilerOptions) || isInTypeQuery(usage) || declaration.flags & 16777216 /* Ambient */ ) return true; + if (moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator) || !outFile(compilerOptions) || isInTypeQuery(usage) || declaration.flags & 33554432 /* Ambient */ ) return true; if (isUsedInFunctionOrInstanceProperty(usage, declaration)) return true; const sourceFiles = host.getSourceFiles(); return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); } if (declaration.pos <= usage.pos && !(isPropertyDeclaration(declaration) && isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) { - if (declaration.kind === 205 /* BindingElement */ ) { - const errorBindingElement = getAncestor(usage, 205 /* BindingElement */ ); + if (declaration.kind === 208 /* BindingElement */ ) { + const errorBindingElement = getAncestor(usage, 208 /* BindingElement */ ); if (errorBindingElement) return findAncestor(errorBindingElement, isBindingElement) !== findAncestor(declaration, isBindingElement) || declaration.pos < errorBindingElement.pos; - return isBlockScopedNameDeclaredBeforeUse(getAncestor(declaration, 257 /* VariableDeclaration */ ), usage); - } else if (declaration.kind === 257 /* VariableDeclaration */ ) return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); + return isBlockScopedNameDeclaredBeforeUse(getAncestor(declaration, 260 /* VariableDeclaration */ ), usage); + } else if (declaration.kind === 260 /* VariableDeclaration */ ) return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); else if (isClassDeclaration(declaration)) return !findAncestor(usage, (n)=>isComputedPropertyName(n) && n.parent.parent === declaration); else if (isPropertyDeclaration(declaration)) return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ false); - else if (isParameterPropertyDeclaration(declaration, declaration.parent)) return !(getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ && useDefineForClassFields && getContainingClass(declaration) === getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); + else if (isParameterPropertyDeclaration(declaration, declaration.parent)) return !(emitStandardClassFields && getContainingClass(declaration) === getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); return true; } - if (usage.parent.kind === 278 /* ExportSpecifier */ || usage.parent.kind === 274 /* ExportAssignment */ && usage.parent.isExportEquals) return true; - if (usage.kind === 274 /* ExportAssignment */ && usage.isExportEquals) return true; - if (!!(usage.flags & 8388608 /* JSDoc */ ) || isInTypeQuery(usage) || isInAmbientOrTypeNode(usage)) return true; + if (usage.parent.kind === 281 /* ExportSpecifier */ || usage.parent.kind === 277 /* ExportAssignment */ && usage.parent.isExportEquals) return true; + if (usage.kind === 277 /* ExportAssignment */ && usage.isExportEquals) return true; + if (!!(usage.flags & 16777216 /* JSDoc */ ) || isInTypeQuery(usage) || isInAmbientOrTypeNode(usage)) return true; if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ && useDefineForClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); + if (emitStandardClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); else return true; } return false; function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration2, usage2) { switch(declaration2.parent.parent.kind){ - case 240 /* VariableStatement */ : - case 245 /* ForStatement */ : - case 247 /* ForOfStatement */ : + case 243 /* VariableStatement */ : + case 248 /* ForStatement */ : + case 250 /* ForOfStatement */ : if (isSameScopeDescendentOf(usage2, declaration2, declContainer)) return true; break; } @@ -44742,7 +45197,7 @@ ${lanes.join("\n")} const initializerOfProperty = propertyDeclaration.initializer === current; if (initializerOfProperty) { if (isStatic(current.parent)) { - if (declaration2.kind === 171 /* MethodDeclaration */ ) return true; + if (declaration2.kind === 174 /* MethodDeclaration */ ) return true; if (isPropertyDeclaration(declaration2) && getContainingClass(usage2) === getContainingClass(declaration2)) { const propName = declaration2.name; if (isIdentifier(propName) || isPrivateIdentifier(propName)) { @@ -44752,7 +45207,7 @@ ${lanes.join("\n")} } } } else { - const isDeclarationInstanceProperty = declaration2.kind === 169 /* PropertyDeclaration */ && !isStatic(declaration2); + const isDeclarationInstanceProperty = declaration2.kind === 172 /* PropertyDeclaration */ && !isStatic(declaration2); if (!isDeclarationInstanceProperty || getContainingClass(usage2) !== getContainingClass(declaration2)) return true; } } @@ -44765,15 +45220,15 @@ ${lanes.join("\n")} const ancestorChangingReferenceScope = findAncestor(usage2, (node)=>{ if (node === declaration2) return "quit"; switch(node.kind){ - case 216 /* ArrowFunction */ : + case 219 /* ArrowFunction */ : return true; - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : return stopAtAnyPropertyDeclaration && (isPropertyDeclaration(declaration2) && node.parent === declaration2.parent || isParameterPropertyDeclaration(declaration2, declaration2.parent) && node.parent === declaration2.parent.parent) ? "quit" : true; - case 238 /* Block */ : + case 241 /* Block */ : switch(node.parent.kind){ - case 174 /* GetAccessor */ : - case 171 /* MethodDeclaration */ : - case 175 /* SetAccessor */ : + case 177 /* GetAccessor */ : + case 174 /* MethodDeclaration */ : + case 178 /* SetAccessor */ : return true; default: return false; @@ -44801,18 +45256,18 @@ ${lanes.join("\n")} } function requiresScopeChangeWorker(node) { switch(node.kind){ - case 216 /* ArrowFunction */ : - case 215 /* FunctionExpression */ : - case 259 /* FunctionDeclaration */ : - case 173 /* Constructor */ : + case 219 /* ArrowFunction */ : + case 218 /* FunctionExpression */ : + case 262 /* FunctionDeclaration */ : + case 176 /* Constructor */ : return false; - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 299 /* PropertyAssignment */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 303 /* PropertyAssignment */ : return requiresScopeChangeWorker(node.name); - case 169 /* PropertyDeclaration */ : - if (hasStaticModifier(node)) return target < 99 /* ESNext */ || !useDefineForClassFields; + case 172 /* PropertyDeclaration */ : + if (hasStaticModifier(node)) return !emitStandardClassFields; return requiresScopeChangeWorker(node.name); default: if (isNullishCoalesce(node) || isOptionalChain(node)) return target < 7 /* ES2020 */ ; @@ -44829,7 +45284,7 @@ ${lanes.join("\n")} return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSpellingSuggestions, getSymbol2); } function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSpellingSuggestions, lookup) { - var _a2, _b, _c; + var _a, _b, _c; const originalLocation = location; let result; let lastLocation; @@ -44842,48 +45297,52 @@ ${lanes.join("\n")} let isInExternalModule = false; loop: while(location){ if (name === "const" && isConstAssertion(location)) return void 0; + if (isModuleOrEnumDeclaration(location) && lastLocation && location.name === lastLocation) { + lastLocation = location; + location = location.parent; + } if (canHaveLocals(location) && location.locals && !isGlobalSourceFile(location)) { if (result = lookup(location.locals, name, meaning)) { let useResult = true; if (isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 323 /* JSDoc */ ) useResult = result.flags & 262144 /* TypeParameter */ ? lastLocation === location.type || lastLocation.kind === 166 /* Parameter */ || lastLocation.kind === 344 /* JSDocParameterTag */ || lastLocation.kind === 345 /* JSDocReturnTag */ || lastLocation.kind === 165 /* TypeParameter */ : false; + if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 327 /* JSDoc */ ) useResult = result.flags & 262144 /* TypeParameter */ ? lastLocation === location.type || lastLocation.kind === 169 /* Parameter */ || lastLocation.kind === 348 /* JSDocParameterTag */ || lastLocation.kind === 349 /* JSDocReturnTag */ || lastLocation.kind === 168 /* TypeParameter */ : false; if (meaning & result.flags & 3 /* Variable */ ) { if (useOuterVariableScopeInParameter(result, location, lastLocation)) useResult = false; - else if (result.flags & 1 /* FunctionScopedVariable */ ) useResult = lastLocation.kind === 166 /* Parameter */ || lastLocation === location.type && !!findAncestor(result.valueDeclaration, isParameter); + else if (result.flags & 1 /* FunctionScopedVariable */ ) useResult = lastLocation.kind === 169 /* Parameter */ || lastLocation === location.type && !!findAncestor(result.valueDeclaration, isParameter); } - } else if (location.kind === 191 /* ConditionalType */ ) useResult = lastLocation === location.trueType; + } else if (location.kind === 194 /* ConditionalType */ ) useResult = lastLocation === location.trueType; if (useResult) break loop; else result = void 0; } } withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation); switch(location.kind){ - case 308 /* SourceFile */ : + case 312 /* SourceFile */ : if (!isExternalOrCommonJsModule(location)) break; isInExternalModule = true; - case 264 /* ModuleDeclaration */ : - const moduleExports = ((_a2 = getSymbolOfDeclaration(location)) == null ? void 0 : _a2.exports) || emptySymbols; - if (location.kind === 308 /* SourceFile */ || isModuleDeclaration(location) && location.flags & 16777216 /* Ambient */ && !isGlobalScopeAugmentation(location)) { + case 267 /* ModuleDeclaration */ : + const moduleExports = ((_a = getSymbolOfDeclaration(location)) == null ? void 0 : _a.exports) || emptySymbols; + if (location.kind === 312 /* SourceFile */ || isModuleDeclaration(location) && location.flags & 33554432 /* Ambient */ && !isGlobalScopeAugmentation(location)) { if (result = moduleExports.get("default" /* Default */ )) { const localSymbol = getLocalSymbolForExportDefault(result); if (localSymbol && result.flags & meaning && localSymbol.escapedName === name) break loop; result = void 0; } const moduleExport = moduleExports.get(name); - if (moduleExport && moduleExport.flags === 2097152 /* Alias */ && (getDeclarationOfKind(moduleExport, 278 /* ExportSpecifier */ ) || getDeclarationOfKind(moduleExport, 277 /* NamespaceExport */ ))) break; + if (moduleExport && moduleExport.flags === 2097152 /* Alias */ && (getDeclarationOfKind(moduleExport, 281 /* ExportSpecifier */ ) || getDeclarationOfKind(moduleExport, 280 /* NamespaceExport */ ))) break; } if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */ ))) { if (isSourceFile(location) && location.commonJsModuleIndicator && !((_b = result.declarations) == null ? void 0 : _b.some(isJSDocTypeAlias))) result = void 0; else break loop; } break; - case 263 /* EnumDeclaration */ : + case 266 /* EnumDeclaration */ : if (result = lookup(((_c = getSymbolOfDeclaration(location)) == null ? void 0 : _c.exports) || emptySymbols, name, meaning & 8 /* EnumMember */ )) { - if (nameNotFoundMessage && getIsolatedModules(compilerOptions) && !(location.flags & 16777216 /* Ambient */ ) && getSourceFileOfNode(location) !== getSourceFileOfNode(result.valueDeclaration)) error(errorLocation, Diagnostics.Cannot_access_0_from_another_file_without_qualification_when_1_is_enabled_Use_2_instead, unescapeLeadingUnderscores(name), isolatedModulesLikeFlagName, `${unescapeLeadingUnderscores(getSymbolOfNode(location).escapedName)}.${unescapeLeadingUnderscores(name)}`); + if (nameNotFoundMessage && getIsolatedModules(compilerOptions) && !(location.flags & 33554432 /* Ambient */ ) && getSourceFileOfNode(location) !== getSourceFileOfNode(result.valueDeclaration)) error2(errorLocation, Diagnostics.Cannot_access_0_from_another_file_without_qualification_when_1_is_enabled_Use_2_instead, unescapeLeadingUnderscores(name), isolatedModulesLikeFlagName, `${unescapeLeadingUnderscores(getSymbolOfNode(location).escapedName)}.${unescapeLeadingUnderscores(name)}`); break loop; } break; - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : if (!isStatic(location)) { const ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { @@ -44894,16 +45353,16 @@ ${lanes.join("\n")} } } break; - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : - case 261 /* InterfaceDeclaration */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 264 /* InterfaceDeclaration */ : if (result = lookup(getSymbolOfDeclaration(location).members || emptySymbols, name, meaning & 788968 /* Type */ )) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { result = void 0; break; } if (lastLocation && isStatic(lastLocation)) { - if (nameNotFoundMessage) error(errorLocation, Diagnostics.Static_members_cannot_reference_class_type_parameters); + if (nameNotFoundMessage) error2(errorLocation, Diagnostics.Static_members_cannot_reference_class_type_parameters); return void 0; } break loop; @@ -44916,37 +45375,37 @@ ${lanes.join("\n")} } } break; - case 230 /* ExpressionWithTypeArguments */ : - if (lastLocation === location.expression && location.parent.token === 94 /* ExtendsKeyword */ ) { + case 233 /* ExpressionWithTypeArguments */ : + if (lastLocation === location.expression && location.parent.token === 96 /* ExtendsKeyword */ ) { const container = location.parent.parent; if (isClassLike(container) && (result = lookup(getSymbolOfDeclaration(container).members, name, meaning & 788968 /* Type */ ))) { - if (nameNotFoundMessage) error(errorLocation, Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); + if (nameNotFoundMessage) error2(errorLocation, Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); return void 0; } } break; - case 164 /* ComputedPropertyName */ : + case 167 /* ComputedPropertyName */ : grandparent = location.parent.parent; - if (isClassLike(grandparent) || grandparent.kind === 261 /* InterfaceDeclaration */ ) { + if (isClassLike(grandparent) || grandparent.kind === 264 /* InterfaceDeclaration */ ) { if (result = lookup(getSymbolOfDeclaration(grandparent).members, name, meaning & 788968 /* Type */ )) { - if (nameNotFoundMessage) error(errorLocation, Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); + if (nameNotFoundMessage) error2(errorLocation, Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return void 0; } } break; - case 216 /* ArrowFunction */ : + case 219 /* ArrowFunction */ : if (getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ) break; - case 171 /* MethodDeclaration */ : - case 173 /* Constructor */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 259 /* FunctionDeclaration */ : + case 174 /* MethodDeclaration */ : + case 176 /* Constructor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 262 /* FunctionDeclaration */ : if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 215 /* FunctionExpression */ : + case 218 /* FunctionExpression */ : if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -44959,27 +45418,27 @@ ${lanes.join("\n")} } } break; - case 167 /* Decorator */ : - if (location.parent && location.parent.kind === 166 /* Parameter */ ) location = location.parent; - if (location.parent && (isClassElement(location.parent) || location.parent.kind === 260 /* ClassDeclaration */ )) location = location.parent; + case 170 /* Decorator */ : + if (location.parent && location.parent.kind === 169 /* Parameter */ ) location = location.parent; + if (location.parent && (isClassElement(location.parent) || location.parent.kind === 263 /* ClassDeclaration */ )) location = location.parent; break; - case 349 /* JSDocTypedefTag */ : - case 341 /* JSDocCallbackTag */ : - case 343 /* JSDocEnumTag */ : + case 353 /* JSDocTypedefTag */ : + case 345 /* JSDocCallbackTag */ : + case 347 /* JSDocEnumTag */ : const root = getJSDocRoot(location); if (root) location = root.parent; break; - case 166 /* Parameter */ : + case 169 /* Parameter */ : if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && isBindingPattern(lastLocation))) { if (!associatedDeclarationForContainingInitializerOrBindingName) associatedDeclarationForContainingInitializerOrBindingName = location; } break; - case 205 /* BindingElement */ : + case 208 /* BindingElement */ : if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && isBindingPattern(lastLocation))) { if (isParameterDeclaration(location) && !associatedDeclarationForContainingInitializerOrBindingName) associatedDeclarationForContainingInitializerOrBindingName = location; } break; - case 192 /* InferType */ : + case 195 /* InferType */ : if (meaning & 262144 /* TypeParameter */ ) { const parameterName = location.typeParameter.name; if (parameterName && name === parameterName.escapedText) { @@ -44988,6 +45447,9 @@ ${lanes.join("\n")} } } break; + case 281 /* ExportSpecifier */ : + if (lastLocation && lastLocation === location.propertyName && location.parent.parent.moduleSpecifier) location = location.parent.parent.parent; + break; } if (isSelfReferenceLocation(location)) lastSelfReferenceLocation = location; lastLocation = location; @@ -45003,25 +45465,25 @@ ${lanes.join("\n")} } if (!result) { if (originalLocation && isInJSFile(originalLocation) && originalLocation.parent) { - if (isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) return requireSymbol; + if (isRequireCall(originalLocation.parent, /*requireStringLiteralLikeArgument*/ false)) return requireSymbol; } } function checkAndReportErrorForInvalidInitializer() { - if (propertyWithInvalidInitializer && !(useDefineForClassFields && getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */ )) { - error(errorLocation, errorLocation && propertyWithInvalidInitializer.type && textRangeContainsPositionInclusive(propertyWithInvalidInitializer.type, errorLocation.pos) ? Diagnostics.Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor : Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, declarationNameToString(propertyWithInvalidInitializer.name), diagnosticName(nameArg)); + if (propertyWithInvalidInitializer && !emitStandardClassFields) { + error2(errorLocation, errorLocation && propertyWithInvalidInitializer.type && textRangeContainsPositionInclusive(propertyWithInvalidInitializer.type, errorLocation.pos) ? Diagnostics.Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor : Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, declarationNameToString(propertyWithInvalidInitializer.name), diagnosticName(nameArg)); return true; } return false; } if (!result) { if (nameNotFoundMessage) addLazyDiagnostic(()=>{ - if (!errorLocation || !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 + if (!errorLocation || errorLocation.parent.kind !== 331 /* JSDocLink */ && !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 !checkAndReportErrorForInvalidInitializer() && !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && !checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { let suggestion; let suggestedLib; if (nameArg) { suggestedLib = getSuggestedLibForNonExistentName(nameArg); - if (suggestedLib) error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), suggestedLib); + if (suggestedLib) error2(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), suggestedLib); } if (!suggestedLib && getSpellingSuggestions && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); @@ -45036,7 +45498,7 @@ ${lanes.join("\n")} if (suggestion.valueDeclaration) addRelatedInfo(diagnostic, createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestionName)); } } - if (!suggestion && !suggestedLib && nameArg) error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); + if (!suggestion && !suggestedLib && nameArg) error2(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); suggestionCount++; } }); @@ -45047,22 +45509,22 @@ ${lanes.join("\n")} const exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */ ) checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } - if (result && isInExternalModule && (meaning & 111551 /* Value */ ) === 111551 /* Value */ && !(originalLocation.flags & 8388608 /* JSDoc */ )) { + if (result && isInExternalModule && (meaning & 111551 /* Value */ ) === 111551 /* Value */ && !(originalLocation.flags & 16777216 /* JSDoc */ )) { const merged = getMergedSymbol(result); if (length(merged.declarations) && every(merged.declarations, (d)=>isNamespaceExportDeclaration(d) || isSourceFile(d) && !!d.symbol.globalExports)) errorOrSuggestion(!compilerOptions.allowUmdGlobalAccess, errorLocation, Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, unescapeLeadingUnderscores(name)); } if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */ ) === 111551 /* Value */ ) { const candidate = getMergedSymbol(getLateBoundSymbol(result)); const root = getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName); - if (candidate === getSymbolOfDeclaration(associatedDeclarationForContainingInitializerOrBindingName)) error(errorLocation, Diagnostics.Parameter_0_cannot_reference_itself, declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name)); - else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) error(errorLocation, Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), declarationNameToString(errorLocation)); + if (candidate === getSymbolOfDeclaration(associatedDeclarationForContainingInitializerOrBindingName)) error2(errorLocation, Diagnostics.Parameter_0_cannot_reference_itself, declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name)); + else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) error2(errorLocation, Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), declarationNameToString(errorLocation)); } if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */ && !(result.flags & 111551 /* Value */ ) && !isValidTypeOnlyAliasUseSite(errorLocation)) { const typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result, 111551 /* Value */ ); if (typeOnlyDeclaration) { - const message = typeOnlyDeclaration.kind === 278 /* ExportSpecifier */ || typeOnlyDeclaration.kind === 275 /* ExportDeclaration */ || typeOnlyDeclaration.kind === 277 /* NamespaceExport */ ? Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type : Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type; + const message = typeOnlyDeclaration.kind === 281 /* ExportSpecifier */ || typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ || typeOnlyDeclaration.kind === 280 /* NamespaceExport */ ? Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type : Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type; const unescapedName = unescapeLeadingUnderscores(name); - addTypeOnlyDeclarationRelatedInfo(error(errorLocation, message, unescapedName), typeOnlyDeclaration, unescapedName); + addTypeOnlyDeclarationRelatedInfo(error2(errorLocation, message, unescapedName), typeOnlyDeclaration, unescapedName); } } }); @@ -45070,22 +45532,22 @@ ${lanes.join("\n")} } function addTypeOnlyDeclarationRelatedInfo(diagnostic, typeOnlyDeclaration, unescapedName) { if (!typeOnlyDeclaration) return diagnostic; - return addRelatedInfo(diagnostic, createDiagnosticForNode(typeOnlyDeclaration, typeOnlyDeclaration.kind === 278 /* ExportSpecifier */ || typeOnlyDeclaration.kind === 275 /* ExportDeclaration */ || typeOnlyDeclaration.kind === 277 /* NamespaceExport */ ? Diagnostics._0_was_exported_here : Diagnostics._0_was_imported_here, unescapedName)); + return addRelatedInfo(diagnostic, createDiagnosticForNode(typeOnlyDeclaration, typeOnlyDeclaration.kind === 281 /* ExportSpecifier */ || typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ || typeOnlyDeclaration.kind === 280 /* NamespaceExport */ ? Diagnostics._0_was_exported_here : Diagnostics._0_was_imported_here, unescapedName)); } function getIsDeferredContext(location, lastLocation) { - if (location.kind !== 216 /* ArrowFunction */ && location.kind !== 215 /* FunctionExpression */ ) return isTypeQueryNode(location) || (isFunctionLikeDeclaration(location) || location.kind === 169 /* PropertyDeclaration */ && !isStatic(location)) && (!lastLocation || lastLocation !== location.name); + if (location.kind !== 219 /* ArrowFunction */ && location.kind !== 218 /* FunctionExpression */ ) return isTypeQueryNode(location) || (isFunctionLikeDeclaration(location) || location.kind === 172 /* PropertyDeclaration */ && !isStatic(location)) && (!lastLocation || lastLocation !== location.name); if (lastLocation && lastLocation === location.name) return false; if (location.asteriskToken || hasSyntacticModifier(location, 512 /* Async */ )) return true; return !getImmediatelyInvokedFunctionExpression(location); } function isSelfReferenceLocation(node) { switch(node.kind){ - case 259 /* FunctionDeclaration */ : - case 260 /* ClassDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 263 /* EnumDeclaration */ : - case 262 /* TypeAliasDeclaration */ : - case 264 /* ModuleDeclaration */ : + case 262 /* FunctionDeclaration */ : + case 263 /* ClassDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 266 /* EnumDeclaration */ : + case 265 /* TypeAliasDeclaration */ : + case 267 /* ModuleDeclaration */ : return true; default: return false; @@ -45096,7 +45558,7 @@ ${lanes.join("\n")} } function isTypeParameterSymbolDeclaredInContainer(symbol, container) { if (symbol.declarations) { - for (const decl of symbol.declarations)if (decl.kind === 165 /* TypeParameter */ ) { + for (const decl of symbol.declarations)if (decl.kind === 168 /* TypeParameter */ ) { const parent2 = isJSDocTemplateTag(decl.parent) ? getJSDocHost(decl.parent) : decl.parent; if (parent2 === container) return !(isJSDocTemplateTag(decl.parent) && find(decl.parent.parent.tags, isJSDocTypeAlias)); } @@ -45113,13 +45575,13 @@ ${lanes.join("\n")} if (!classSymbol) break; const constructorType = getTypeOfSymbol(classSymbol); if (getPropertyOfType(constructorType, name)) { - error(errorLocation, Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol)); + error2(errorLocation, Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol)); return true; } if (location === container && !isStatic(location)) { const instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; if (getPropertyOfType(instanceType, name)) { - error(errorLocation, Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); + error2(errorLocation, Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); return true; } } @@ -45131,17 +45593,17 @@ ${lanes.join("\n")} function checkAndReportErrorForExtendingInterface(errorLocation) { const expression = getEntityNameForExtendingInterface(errorLocation); if (expression && resolveEntityName(expression, 64 /* Interface */ , /*ignoreErrors*/ true)) { - error(errorLocation, Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, getTextOfNode(expression)); + error2(errorLocation, Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, getTextOfNode(expression)); return true; } return false; } function getEntityNameForExtendingInterface(node) { switch(node.kind){ - case 79 /* Identifier */ : - case 208 /* PropertyAccessExpression */ : + case 80 /* Identifier */ : + case 211 /* PropertyAccessExpression */ : return node.parent ? getEntityNameForExtendingInterface(node.parent) : void 0; - case 230 /* ExpressionWithTypeArguments */ : + case 233 /* ExpressionWithTypeArguments */ : if (isEntityNameExpression(node.expression)) return node.expression; default: return void 0; @@ -45158,11 +45620,11 @@ ${lanes.join("\n")} const propName = parent2.right.escapedText; const propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName); if (propType) { - error(parent2, Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, unescapeLeadingUnderscores(name), unescapeLeadingUnderscores(propName)); + error2(parent2, Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, unescapeLeadingUnderscores(name), unescapeLeadingUnderscores(propName)); return true; } } - error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, unescapeLeadingUnderscores(name)); + error2(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, unescapeLeadingUnderscores(name)); return true; } } @@ -45172,7 +45634,7 @@ ${lanes.join("\n")} if (meaning & 788584 /* Namespace */ ) { const symbol = resolveSymbol(resolveName(errorLocation, name, 111127 /* Value */ , /*nameNotFoundMessage*/ void 0, /*nameArg*/ void 0, /*isUse*/ false)); if (symbol && !(symbol.flags & 1920 /* Namespace */ )) { - error(errorLocation, Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, unescapeLeadingUnderscores(name)); + error2(errorLocation, Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, unescapeLeadingUnderscores(name)); return true; } } @@ -45182,8 +45644,8 @@ ${lanes.join("\n")} return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown"; } function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) { - if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 278 /* ExportSpecifier */ ) { - error(errorLocation, Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name); + if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 281 /* ExportSpecifier */ ) { + error2(errorLocation, Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name); return true; } return false; @@ -45191,17 +45653,17 @@ ${lanes.join("\n")} function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & 111551 /* Value */ ) { if (isPrimitiveTypeName(name)) { - if (isExtendedByInterface(errorLocation)) error(errorLocation, Diagnostics.An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_classes, unescapeLeadingUnderscores(name)); - else error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, unescapeLeadingUnderscores(name)); + if (isExtendedByInterface(errorLocation)) error2(errorLocation, Diagnostics.An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_classes, unescapeLeadingUnderscores(name)); + else error2(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, unescapeLeadingUnderscores(name)); return true; } const symbol = resolveSymbol(resolveName(errorLocation, name, 788544 /* Value */ , /*nameNotFoundMessage*/ void 0, /*nameArg*/ void 0, /*isUse*/ false)); - const allFlags = symbol && getAllSymbolFlags(symbol); + const allFlags = symbol && getSymbolFlags(symbol); if (symbol && allFlags !== void 0 && !(allFlags & 111551 /* Value */ )) { const rawName = unescapeLeadingUnderscores(name); - if (isES2015OrLaterConstructorName(name)) error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later, rawName); - else if (maybeMappedType(errorLocation, symbol)) error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0, rawName, rawName === "K" ? "P" : "K"); - else error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, rawName); + if (isES2015OrLaterConstructorName(name)) error2(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later, rawName); + else if (maybeMappedType(errorLocation, symbol)) error2(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0, rawName, rawName === "K" ? "P" : "K"); + else error2(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, rawName); return true; } } @@ -45211,7 +45673,7 @@ ${lanes.join("\n")} const grandparent = node.parent.parent; const parentOfGrandparent = grandparent.parent; if (grandparent && parentOfGrandparent) { - const isExtending = isHeritageClause(grandparent) && grandparent.token === 94 /* ExtendsKeyword */ ; + const isExtending = isHeritageClause(grandparent) && grandparent.token === 96 /* ExtendsKeyword */ ; const isInterface = isInterfaceDeclaration(parentOfGrandparent); return isExtending && isInterface; } @@ -45241,34 +45703,30 @@ ${lanes.join("\n")} if (meaning & 111127 /* Type */ ) { const symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ , /*nameNotFoundMessage*/ void 0, /*nameArg*/ void 0, /*isUse*/ false)); if (symbol) { - error(errorLocation, Diagnostics.Cannot_use_namespace_0_as_a_value, unescapeLeadingUnderscores(name)); + error2(errorLocation, Diagnostics.Cannot_use_namespace_0_as_a_value, unescapeLeadingUnderscores(name)); return true; } } else if (meaning & 788544 /* Value */ ) { const symbol = resolveSymbol(resolveName(errorLocation, name, 1536 /* Module */ , /*nameNotFoundMessage*/ void 0, /*nameArg*/ void 0, /*isUse*/ false)); if (symbol) { - error(errorLocation, Diagnostics.Cannot_use_namespace_0_as_a_type, unescapeLeadingUnderscores(name)); + error2(errorLocation, Diagnostics.Cannot_use_namespace_0_as_a_type, unescapeLeadingUnderscores(name)); return true; } } return false; } function checkResolvedBlockScopedVariable(result, errorLocation) { - var _a2; + var _a; Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */ )); if (result.flags & 67108881 /* Assignment */ && result.flags & 32 /* Class */ ) return; - const declaration = (_a2 = result.declarations) == null ? void 0 : _a2.find((d)=>isBlockOrCatchScoped(d) || isClassLike(d) || d.kind === 263 /* EnumDeclaration */ ); + const declaration = (_a = result.declarations) == null ? void 0 : _a.find((d)=>isBlockOrCatchScoped(d) || isClassLike(d) || d.kind === 266 /* EnumDeclaration */ ); if (declaration === void 0) return Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration"); - if (!(declaration.flags & 16777216 /* Ambient */ ) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { + if (!(declaration.flags & 33554432 /* Ambient */ ) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { let diagnosticMessage; const declarationName = declarationNameToString(getNameOfDeclaration(declaration)); - if (result.flags & 2 /* BlockScopedVariable */ ) diagnosticMessage = error(errorLocation, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName); - else if (result.flags & 32 /* Class */ ) diagnosticMessage = error(errorLocation, Diagnostics.Class_0_used_before_its_declaration, declarationName); - else if (result.flags & 256 /* RegularEnum */ ) diagnosticMessage = error(errorLocation, Diagnostics.Enum_0_used_before_its_declaration, declarationName); - else { - Debug.assert(!!(result.flags & 128 /* ConstEnum */ )); - if (shouldPreserveConstEnums(compilerOptions)) diagnosticMessage = error(errorLocation, Diagnostics.Enum_0_used_before_its_declaration, declarationName); - } + if (result.flags & 2 /* BlockScopedVariable */ ) diagnosticMessage = error2(errorLocation, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName); + else if (result.flags & 32 /* Class */ ) diagnosticMessage = error2(errorLocation, Diagnostics.Class_0_used_before_its_declaration, declarationName); + else if (result.flags & 256 /* RegularEnum */ ) diagnosticMessage = error2(errorLocation, Diagnostics.Enum_0_used_before_its_declaration, declarationName); if (diagnosticMessage) addRelatedInfo(diagnosticMessage, createDiagnosticForNode(declaration, Diagnostics._0_is_declared_here, declarationName)); } } @@ -45277,13 +45735,13 @@ ${lanes.join("\n")} } function getAnyImportSyntax(node) { switch(node.kind){ - case 268 /* ImportEqualsDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : return node; - case 270 /* ImportClause */ : + case 273 /* ImportClause */ : return node.parent; - case 271 /* NamespaceImport */ : + case 274 /* NamespaceImport */ : return node.parent.parent; - case 273 /* ImportSpecifier */ : + case 276 /* ImportSpecifier */ : return node.parent.parent.parent; default: return void 0; @@ -45293,7 +45751,7 @@ ${lanes.join("\n")} return symbol.declarations && findLast(symbol.declarations, isAliasSymbolDeclaration2); } function isAliasSymbolDeclaration2(node) { - return node.kind === 268 /* ImportEqualsDeclaration */ || node.kind === 267 /* NamespaceExportDeclaration */ || node.kind === 270 /* ImportClause */ && !!node.name || node.kind === 271 /* NamespaceImport */ || node.kind === 277 /* NamespaceExport */ || node.kind === 273 /* ImportSpecifier */ || node.kind === 278 /* ExportSpecifier */ || node.kind === 274 /* ExportAssignment */ && exportAssignmentIsAlias(node) || isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) || isAccessExpression(node) && isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 63 /* EqualsToken */ && isAliasableOrJsExpression(node.parent.right) || node.kind === 300 /* ShorthandPropertyAssignment */ || node.kind === 299 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) || node.kind === 257 /* VariableDeclaration */ && isVariableDeclarationInitializedToBareOrAccessedRequire(node) || node.kind === 205 /* BindingElement */ && isVariableDeclarationInitializedToBareOrAccessedRequire(node.parent.parent); + return node.kind === 271 /* ImportEqualsDeclaration */ || node.kind === 270 /* NamespaceExportDeclaration */ || node.kind === 273 /* ImportClause */ && !!node.name || node.kind === 274 /* NamespaceImport */ || node.kind === 280 /* NamespaceExport */ || node.kind === 276 /* ImportSpecifier */ || node.kind === 281 /* ExportSpecifier */ || node.kind === 277 /* ExportAssignment */ && exportAssignmentIsAlias(node) || isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) || isAccessExpression(node) && isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 64 /* EqualsToken */ && isAliasableOrJsExpression(node.parent.right) || node.kind === 304 /* ShorthandPropertyAssignment */ || node.kind === 303 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) || node.kind === 260 /* VariableDeclaration */ && isVariableDeclarationInitializedToBareOrAccessedRequire(node) || node.kind === 208 /* BindingElement */ && isVariableDeclarationInitializedToBareOrAccessedRequire(node.parent.parent); } function isAliasableOrJsExpression(e) { return isAliasableExpression(e) || isFunctionExpression(e) && isJSConstructor(e); @@ -45304,7 +45762,7 @@ ${lanes.join("\n")} const name = getLeftmostAccessExpression(commonJSPropertyAccess.expression).arguments[0]; return isIdentifier(commonJSPropertyAccess.name) ? resolveSymbol(getPropertyOfType(resolveExternalModuleTypeByLiteral(name), commonJSPropertyAccess.name.escapedText)) : void 0; } - if (isVariableDeclaration(node) || node.moduleReference.kind === 280 /* ExternalModuleReference */ ) { + if (isVariableDeclaration(node) || node.moduleReference.kind === 283 /* ExternalModuleReference */ ) { const immediate = resolveExternalModuleName(node, getExternalModuleRequireArgument(node) || getExternalModuleImportEqualsDeclarationExpression(node)); const resolved2 = resolveExternalModuleSymbol(immediate); markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved2, /*overwriteEmpty*/ false); @@ -45317,11 +45775,11 @@ ${lanes.join("\n")} function checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) { if (markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ void 0, resolved, /*overwriteEmpty*/ false) && !node.isTypeOnly) { const typeOnlyDeclaration = getTypeOnlyAliasDeclaration(getSymbolOfDeclaration(node)); - const isExport = typeOnlyDeclaration.kind === 278 /* ExportSpecifier */ || typeOnlyDeclaration.kind === 275 /* ExportDeclaration */ ; + const isExport = typeOnlyDeclaration.kind === 281 /* ExportSpecifier */ || typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ ; const message = isExport ? Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type : Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type; const relatedMessage = isExport ? Diagnostics._0_was_exported_here : Diagnostics._0_was_imported_here; - const name = typeOnlyDeclaration.kind === 275 /* ExportDeclaration */ ? "*" : unescapeLeadingUnderscores(typeOnlyDeclaration.name.escapedText); - addRelatedInfo(error(node.moduleReference, message), createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name)); + const name = typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ ? "*" : unescapeLeadingUnderscores(typeOnlyDeclaration.name.escapedText); + addRelatedInfo(error2(node.moduleReference, message), createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name)); } } function resolveExportByName(moduleSymbol, name, sourceNode, dontResolveAlias) { @@ -45365,11 +45823,11 @@ ${lanes.join("\n")} if (moduleSymbol) return getTargetofModuleDefault(moduleSymbol, node, dontResolveAlias); } function getTargetofModuleDefault(moduleSymbol, node, dontResolveAlias) { - var _a2; + var _a; let exportDefaultSymbol; if (isShorthandAmbientModuleSymbol(moduleSymbol)) exportDefaultSymbol = moduleSymbol; else exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */ , node, dontResolveAlias); - const file = (_a2 = moduleSymbol.declarations) == null ? void 0 : _a2.find(isSourceFile); + const file = (_a = moduleSymbol.declarations) == null ? void 0 : _a.find(isSourceFile); const specifier = getModuleSpecifierForImportOrExport(node); if (!specifier) return exportDefaultSymbol; const hasDefaultOnly = isOnlyImportedAsDefault(specifier); @@ -45379,44 +45837,44 @@ ${lanes.join("\n")} const compilerOptionName = moduleKind >= 5 /* ES2015 */ ? "allowSyntheticDefaultImports" : "esModuleInterop"; const exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */ ); const exportAssignment = exportEqualsSymbol.valueDeclaration; - const err = error(node.name, Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName); + const err = error2(node.name, Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName); if (exportAssignment) addRelatedInfo(err, createDiagnosticForNode(exportAssignment, Diagnostics.This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); } else if (isImportClause(node)) reportNonDefaultExport(moduleSymbol, node); else errorNoModuleMemberSymbol(moduleSymbol, moduleSymbol, node, isImportOrExportSpecifier(node) && node.propertyName || node.name); } else if (hasSyntheticDefault || hasDefaultOnly) { const resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); - markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteTypeOnly*/ false); + markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteEmpty*/ false); return resolved; } - markSymbolOfAliasDeclarationIfTypeOnly(node, exportDefaultSymbol, /*finalTarget*/ void 0, /*overwriteTypeOnly*/ false); + markSymbolOfAliasDeclarationIfTypeOnly(node, exportDefaultSymbol, /*finalTarget*/ void 0, /*overwriteEmpty*/ false); return exportDefaultSymbol; } function getModuleSpecifierForImportOrExport(node) { switch(node.kind){ - case 270 /* ImportClause */ : + case 273 /* ImportClause */ : return node.parent.moduleSpecifier; - case 268 /* ImportEqualsDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : return isExternalModuleReference(node.moduleReference) ? node.moduleReference.expression : void 0; - case 271 /* NamespaceImport */ : + case 274 /* NamespaceImport */ : return node.parent.parent.moduleSpecifier; - case 273 /* ImportSpecifier */ : + case 276 /* ImportSpecifier */ : return node.parent.parent.parent.moduleSpecifier; - case 278 /* ExportSpecifier */ : + case 281 /* ExportSpecifier */ : return node.parent.parent.moduleSpecifier; default: return Debug.assertNever(node); } } function reportNonDefaultExport(moduleSymbol, node) { - var _a2, _b, _c; - if ((_a2 = moduleSymbol.exports) == null ? void 0 : _a2.has(node.symbol.escapedName)) error(node.name, Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); + var _a, _b, _c; + if ((_a = moduleSymbol.exports) == null ? void 0 : _a.has(node.symbol.escapedName)) error2(node.name, Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); else { - const diagnostic = error(node.name, Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + const diagnostic = error2(node.name, Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); const exportStar = (_b = moduleSymbol.exports) == null ? void 0 : _b.get("__export" /* ExportStar */ ); if (exportStar) { const defaultExport = (_c = exportStar.declarations) == null ? void 0 : _c.find((decl)=>{ - var _a3, _b2; - return !!(isExportDeclaration(decl) && decl.moduleSpecifier && ((_b2 = (_a3 = resolveExternalModuleName(decl, decl.moduleSpecifier)) == null ? void 0 : _a3.exports) == null ? void 0 : _b2.has("default" /* Default */ ))); + var _a2, _b2; + return !!(isExportDeclaration(decl) && decl.moduleSpecifier && ((_b2 = (_a2 = resolveExternalModuleName(decl, decl.moduleSpecifier)) == null ? void 0 : _a2.exports) == null ? void 0 : _b2.has("default" /* Default */ ))); }); if (defaultExport) addRelatedInfo(diagnostic, createDiagnosticForNode(defaultExport, Diagnostics.export_Asterisk_does_not_re_export_a_default)); } @@ -45425,14 +45883,14 @@ ${lanes.join("\n")} function getTargetOfNamespaceImport(node, dontResolveAlias) { const moduleSpecifier = node.parent.parent.moduleSpecifier; const immediate = resolveExternalModuleName(node, moduleSpecifier); - const resolved = resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false); + const resolved = resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressInteropError*/ false); markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false); return resolved; } function getTargetOfNamespaceExport(node, dontResolveAlias) { const moduleSpecifier = node.parent.moduleSpecifier; const immediate = moduleSpecifier && resolveExternalModuleName(node, moduleSpecifier); - const resolved = moduleSpecifier && resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false); + const resolved = moduleSpecifier && resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressInteropError*/ false); markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false); return resolved; } @@ -45449,11 +45907,11 @@ ${lanes.join("\n")} return result; } function getExportOfModule(symbol, name, specifier, dontResolveAlias) { - var _a2; + var _a; if (symbol.flags & 1536 /* Module */ ) { const exportSymbol = getExportsOfSymbol(symbol).get(name.escapedText); const resolved = resolveSymbol(exportSymbol, dontResolveAlias); - const exportStarDeclaration = (_a2 = getSymbolLinks(symbol).typeOnlyExportStarMap) == null ? void 0 : _a2.get(name.escapedText); + const exportStarDeclaration = (_a = getSymbolLinks(symbol).typeOnlyExportStarMap) == null ? void 0 : _a.get(name.escapedText); markSymbolOfAliasDeclarationIfTypeOnly(specifier, exportSymbol, resolved, /*overwriteEmpty*/ false, exportStarDeclaration, name.escapedText); return resolved; } @@ -45465,7 +45923,7 @@ ${lanes.join("\n")} } } function getExternalModuleMember(node, specifier, dontResolveAlias = false) { - var _a2; + var _a; const moduleSpecifier = getExternalModuleRequireArgument(node) || node.moduleSpecifier; const moduleSymbol = resolveExternalModuleName(node, moduleSpecifier); const name = !isPropertyAccessExpression(specifier) && specifier.propertyName || specifier.name; @@ -45481,7 +45939,7 @@ ${lanes.join("\n")} symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); let symbolFromModule = getExportOfModule(targetSymbol, name, specifier, dontResolveAlias); if (symbolFromModule === void 0 && name.escapedText === "default" /* Default */ ) { - const file = (_a2 = moduleSymbol.declarations) == null ? void 0 : _a2.find(isSourceFile); + const file = (_a = moduleSymbol.declarations) == null ? void 0 : _a.find(isSourceFile); if (isOnlyImportedAsDefault(moduleSpecifier) || canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } const symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; @@ -45491,41 +45949,41 @@ ${lanes.join("\n")} } } function errorNoModuleMemberSymbol(moduleSymbol, targetSymbol, node, name) { - var _a2; + var _a; const moduleName = getFullyQualifiedName(moduleSymbol, node); const declarationName = declarationNameToString(name); const suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== void 0) { const suggestionName = symbolToString(suggestion); - const diagnostic = error(name, Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, moduleName, declarationName, suggestionName); + const diagnostic = error2(name, Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, moduleName, declarationName, suggestionName); if (suggestion.valueDeclaration) addRelatedInfo(diagnostic, createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestionName)); - } else if ((_a2 = moduleSymbol.exports) == null ? void 0 : _a2.has("default" /* Default */ )) error(name, Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); + } else if ((_a = moduleSymbol.exports) == null ? void 0 : _a.has("default" /* Default */ )) error2(name, Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); else reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName); } function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) { - var _a2, _b; - const localSymbol = (_b = (_a2 = tryCast(moduleSymbol.valueDeclaration, canHaveLocals)) == null ? void 0 : _a2.locals) == null ? void 0 : _b.get(name.escapedText); + var _a, _b; + const localSymbol = (_b = (_a = tryCast(moduleSymbol.valueDeclaration, canHaveLocals)) == null ? void 0 : _a.locals) == null ? void 0 : _b.get(name.escapedText); const exports = moduleSymbol.exports; if (localSymbol) { const exportedEqualsSymbol = exports == null ? void 0 : exports.get("export=" /* ExportEquals */ ); - if (exportedEqualsSymbol) getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) : error(name, Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + if (exportedEqualsSymbol) getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) : error2(name, Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); else { const exportedSymbol = exports ? find(symbolsToArray(exports), (symbol)=>!!getSymbolIfSameReference(symbol, localSymbol)) : void 0; - const diagnostic = exportedSymbol ? error(name, Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : error(name, Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); + const diagnostic = exportedSymbol ? error2(name, Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : error2(name, Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); if (localSymbol.declarations) addRelatedInfo(diagnostic, ...map(localSymbol.declarations, (decl, index)=>createDiagnosticForNode(decl, index === 0 ? Diagnostics._0_is_declared_here : Diagnostics.and_here, declarationName))); } - } else error(name, Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } else error2(name, Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); } function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) { if (moduleKind >= 5 /* ES2015 */ ) { const message = getESModuleInterop(compilerOptions) ? Diagnostics._0_can_only_be_imported_by_using_a_default_import : Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; - error(name, message, declarationName); + error2(name, message, declarationName); } else if (isInJSFile(node)) { const message = getESModuleInterop(compilerOptions) ? Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import : Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; - error(name, message, declarationName); + error2(name, message, declarationName); } else { const message = getESModuleInterop(compilerOptions) ? Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import : Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; - error(name, message, declarationName, declarationName, moduleName); + error2(name, message, declarationName, declarationName, moduleName); } } function getTargetOfImportSpecifier(node, dontResolveAlias) { @@ -45577,36 +46035,36 @@ ${lanes.join("\n")} return getNodeLinks(expression).resolvedSymbol; } function getTargetOfAccessExpression(node, dontRecursivelyResolve) { - if (!(isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 63 /* EqualsToken */ )) return void 0; + if (!(isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 64 /* EqualsToken */ )) return void 0; return getTargetOfAliasLikeExpression(node.parent.right, dontRecursivelyResolve); } function getTargetOfAliasDeclaration(node, dontRecursivelyResolve = false) { switch(node.kind){ - case 268 /* ImportEqualsDeclaration */ : - case 257 /* VariableDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : + case 260 /* VariableDeclaration */ : return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 270 /* ImportClause */ : + case 273 /* ImportClause */ : return getTargetOfImportClause(node, dontRecursivelyResolve); - case 271 /* NamespaceImport */ : + case 274 /* NamespaceImport */ : return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 277 /* NamespaceExport */ : + case 280 /* NamespaceExport */ : return getTargetOfNamespaceExport(node, dontRecursivelyResolve); - case 273 /* ImportSpecifier */ : - case 205 /* BindingElement */ : + case 276 /* ImportSpecifier */ : + case 208 /* BindingElement */ : return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 278 /* ExportSpecifier */ : + case 281 /* ExportSpecifier */ : return getTargetOfExportSpecifier(node, 901119 /* Namespace */ , dontRecursivelyResolve); - case 274 /* ExportAssignment */ : - case 223 /* BinaryExpression */ : + case 277 /* ExportAssignment */ : + case 226 /* BinaryExpression */ : return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 267 /* NamespaceExportDeclaration */ : + case 270 /* NamespaceExportDeclaration */ : return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); - case 300 /* ShorthandPropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : return resolveEntityName(node.name, 901119 /* Namespace */ , /*ignoreErrors*/ true, dontRecursivelyResolve); - case 299 /* PropertyAssignment */ : + case 303 /* PropertyAssignment */ : return getTargetOfAliasLikeExpression(node.initializer, dontRecursivelyResolve); - case 209 /* ElementAccessExpression */ : - case 208 /* PropertyAccessExpression */ : + case 212 /* ElementAccessExpression */ : + case 211 /* PropertyAccessExpression */ : return getTargetOfAccessExpression(node, dontRecursivelyResolve); default: return Debug.fail(); @@ -45628,7 +46086,7 @@ ${lanes.join("\n")} if (!node) return Debug.fail(); const target = getTargetOfAliasDeclaration(node); if (links.aliasTarget === resolvingSymbol) links.aliasTarget = target || unknownSymbol; - else error(node, Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); + else error2(node, Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); } else if (links.aliasTarget === resolvingSymbol) links.aliasTarget = unknownSymbol; return links.aliasTarget; } @@ -45637,11 +46095,16 @@ ${lanes.join("\n")} if (links.aliasTarget !== resolvingSymbol) return resolveAlias(symbol); return void 0; } - function getAllSymbolFlags(symbol) { - let flags = symbol.flags; + function getSymbolFlags(symbol, excludeTypeOnlyMeanings, excludeLocalMeanings) { + const typeOnlyDeclaration = excludeTypeOnlyMeanings && getTypeOnlyAliasDeclaration(symbol); + const typeOnlyDeclarationIsExportStar = typeOnlyDeclaration && isExportDeclaration(typeOnlyDeclaration); + const typeOnlyResolution = typeOnlyDeclaration && (typeOnlyDeclarationIsExportStar ? resolveExternalModuleName(typeOnlyDeclaration.moduleSpecifier, typeOnlyDeclaration.moduleSpecifier, /*ignoreErrors*/ true) : resolveAlias(typeOnlyDeclaration.symbol)); + const typeOnlyExportStarTargets = typeOnlyDeclarationIsExportStar && typeOnlyResolution ? getExportsOfModule(typeOnlyResolution) : void 0; + let flags = excludeLocalMeanings ? 0 /* None */ : symbol.flags; let seenSymbols; while(symbol.flags & 2097152 /* Alias */ ){ - const target = resolveAlias(symbol); + const target = getExportSymbolOfValueSymbolIfExported(resolveAlias(symbol)); + if (!typeOnlyDeclarationIsExportStar && target === typeOnlyResolution || (typeOnlyExportStarTargets == null ? void 0 : typeOnlyExportStarTargets.get(target.escapedName)) === target) break; if (target === unknownSymbol) return 67108863 /* All */ ; if (target === symbol || (seenSymbols == null ? void 0 : seenSymbols.has(target))) break; if (target.flags & 2097152 /* Alias */ ) { @@ -45674,11 +46137,11 @@ ${lanes.join("\n")} return markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, immediateTarget, overwriteEmpty) || markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, finalTarget, overwriteEmpty); } function markSymbolOfAliasDeclarationIfTypeOnlyWorker(aliasDeclarationLinks, target, overwriteEmpty) { - var _a2, _b, _c; + var _a; if (target && (aliasDeclarationLinks.typeOnlyDeclaration === void 0 || overwriteEmpty && aliasDeclarationLinks.typeOnlyDeclaration === false)) { - const exportSymbol = (_b = (_a2 = target.exports) == null ? void 0 : _a2.get("export=" /* ExportEquals */ )) != null ? _b : target; + const exportSymbol = ((_a = target.exports) == null ? void 0 : _a.get("export=" /* ExportEquals */ )) ?? target; const typeOnly = exportSymbol.declarations && find(exportSymbol.declarations, isTypeOnlyImportOrExportDeclaration); - aliasDeclarationLinks.typeOnlyDeclaration = (_c = typeOnly != null ? typeOnly : getSymbolLinks(exportSymbol).typeOnlyDeclaration) != null ? _c : false; + aliasDeclarationLinks.typeOnlyDeclaration = typeOnly ?? getSymbolLinks(exportSymbol).typeOnlyDeclaration ?? false; } return !!aliasDeclarationLinks.typeOnlyDeclaration; } @@ -45687,29 +46150,29 @@ ${lanes.join("\n")} const links = getSymbolLinks(symbol); if (include === void 0) return links.typeOnlyDeclaration || void 0; if (links.typeOnlyDeclaration) { - const resolved = links.typeOnlyDeclaration.kind === 275 /* ExportDeclaration */ ? resolveSymbol(getExportsOfModule(links.typeOnlyDeclaration.symbol.parent).get(links.typeOnlyExportStarName || symbol.escapedName)) : resolveAlias(links.typeOnlyDeclaration.symbol); - return getAllSymbolFlags(resolved) & include ? links.typeOnlyDeclaration : void 0; + const resolved = links.typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ ? resolveSymbol(getExportsOfModule(links.typeOnlyDeclaration.symbol.parent).get(links.typeOnlyExportStarName || symbol.escapedName)) : resolveAlias(links.typeOnlyDeclaration.symbol); + return getSymbolFlags(resolved) & include ? links.typeOnlyDeclaration : void 0; } return void 0; } function markExportAsReferenced(node) { - if (compilerOptions.verbatimModuleSyntax) return; + if (!canCollectSymbolAliasAccessabilityData) return; const symbol = getSymbolOfDeclaration(node); const target = resolveAlias(symbol); if (target) { - const markAlias = target === unknownSymbol || getAllSymbolFlags(target) & 111551 /* Value */ && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* Value */ ); + const markAlias = target === unknownSymbol || getSymbolFlags(symbol, /*excludeTypeOnlyMeanings*/ true) & 111551 /* Value */ && !isConstEnumOrConstEnumOnlyModule(target); if (markAlias) markAliasSymbolAsReferenced(symbol); } } function markAliasSymbolAsReferenced(symbol) { - Debug.assert(!compilerOptions.verbatimModuleSyntax); + Debug.assert(canCollectSymbolAliasAccessabilityData); const links = getSymbolLinks(symbol); if (!links.referenced) { links.referenced = true; const node = getDeclarationOfAliasSymbol(symbol); if (!node) return Debug.fail(); if (isInternalModuleImportEqualsDeclaration(node)) { - if (getAllSymbolFlags(resolveSymbol(symbol)) & 111551 /* Value */ ) checkExpressionCached(node.moduleReference); + if (getSymbolFlags(resolveSymbol(symbol)) & 111551 /* Value */ ) checkExpressionCached(node.moduleReference); } } } @@ -45718,10 +46181,10 @@ ${lanes.join("\n")} if (!links.constEnumReferenced) links.constEnumReferenced = true; } function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { - if (entityName.kind === 79 /* Identifier */ && isRightSideOfQualifiedNameOrPropertyAccess(entityName)) entityName = entityName.parent; - if (entityName.kind === 79 /* Identifier */ || entityName.parent.kind === 163 /* QualifiedName */ ) return resolveEntityName(entityName, 1920 /* Namespace */ , /*ignoreErrors*/ false, dontResolveAlias); + if (entityName.kind === 80 /* Identifier */ && isRightSideOfQualifiedNameOrPropertyAccess(entityName)) entityName = entityName.parent; + if (entityName.kind === 80 /* Identifier */ || entityName.parent.kind === 166 /* QualifiedName */ ) return resolveEntityName(entityName, 1920 /* Namespace */ , /*ignoreErrors*/ false, dontResolveAlias); else { - Debug.assert(entityName.parent.kind === 268 /* ImportEqualsDeclaration */ ); + Debug.assert(entityName.parent.kind === 271 /* ImportEqualsDeclaration */ ); return resolveEntityName(entityName, 901119 /* Namespace */ , /*ignoreErrors*/ false, dontResolveAlias); } } @@ -45734,7 +46197,7 @@ ${lanes.join("\n")} } function tryGetQualifiedNameAsValue(node) { let left = getFirstIdentifier(node); - let symbol = resolveName(left, left.escapedText, 111551 /* Value */ , void 0, left, /*isUse*/ true); + let symbol = resolveName(left, left.escapedText, 111551 /* Value */ , /*nameNotFoundMessage*/ void 0, left, /*isUse*/ true); if (!symbol) return void 0; while(isQualifiedName(left.parent)){ const type = getTypeOfSymbol(symbol); @@ -45748,14 +46211,14 @@ ${lanes.join("\n")} if (nodeIsMissing(name)) return void 0; const namespaceMeaning = 1920 /* Namespace */ | (isInJSFile(name) ? meaning & 111551 /* Value */ : 0); let symbol; - if (name.kind === 79 /* Identifier */ ) { + if (name.kind === 80 /* Identifier */ ) { const message = meaning === namespaceMeaning || nodeIsSynthesized(name) ? Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name)); const symbolFromJSPrototype = isInJSFile(name) && !nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : void 0; - symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? void 0 : message, name, /*isUse*/ true, false)); + symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? void 0 : message, name, /*isUse*/ true, /*excludeGlobals*/ false)); if (!symbol) return getMergedSymbol(symbolFromJSPrototype); - } else if (name.kind === 163 /* QualifiedName */ || name.kind === 208 /* PropertyAccessExpression */ ) { - const left = name.kind === 163 /* QualifiedName */ ? name.left : name.expression; - const right = name.kind === 163 /* QualifiedName */ ? name.right : name.name; + } else if (name.kind === 166 /* QualifiedName */ || name.kind === 211 /* PropertyAccessExpression */ ) { + const left = name.kind === 166 /* QualifiedName */ ? name.left : name.expression; + const right = name.kind === 166 /* QualifiedName */ ? name.right : name.name; let namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); if (!namespace || nodeIsMissing(right)) return void 0; else if (namespace === unknownSymbol) return namespace; @@ -45768,35 +46231,36 @@ ${lanes.join("\n")} } } symbol = getMergedSymbol(getSymbol2(getExportsOfSymbol(namespace), right.escapedText, meaning)); + if (!symbol && namespace.flags & 2097152 /* Alias */ ) symbol = getMergedSymbol(getSymbol2(getExportsOfSymbol(resolveAlias(namespace)), right.escapedText, meaning)); if (!symbol) { if (!ignoreErrors) { const namespaceName = getFullyQualifiedName(namespace); const declarationName = declarationNameToString(right); const suggestionForNonexistentModule = getSuggestedSymbolForNonexistentModule(right, namespace); if (suggestionForNonexistentModule) { - error(right, Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, namespaceName, declarationName, symbolToString(suggestionForNonexistentModule)); + error2(right, Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, namespaceName, declarationName, symbolToString(suggestionForNonexistentModule)); return void 0; } const containingQualifiedName = isQualifiedName(name) && getContainingQualifiedNameNode(name); const canSuggestTypeof = globalObjectType && meaning & 788968 /* Type */ && containingQualifiedName && !isTypeOfExpression(containingQualifiedName.parent) && tryGetQualifiedNameAsValue(containingQualifiedName); if (canSuggestTypeof) { - error(containingQualifiedName, Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, entityNameToString(containingQualifiedName)); + error2(containingQualifiedName, Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, entityNameToString(containingQualifiedName)); return void 0; } if (meaning & 1920 /* Namespace */ && isQualifiedName(name.parent)) { const exportedTypeSymbol = getMergedSymbol(getSymbol2(getExportsOfSymbol(namespace), right.escapedText, 788968 /* Type */ )); if (exportedTypeSymbol) { - error(name.parent.right, Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, symbolToString(exportedTypeSymbol), unescapeLeadingUnderscores(name.parent.right.escapedText)); + error2(name.parent.right, Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, symbolToString(exportedTypeSymbol), unescapeLeadingUnderscores(name.parent.right.escapedText)); return void 0; } } - error(right, Diagnostics.Namespace_0_has_no_exported_member_1, namespaceName, declarationName); + error2(right, Diagnostics.Namespace_0_has_no_exported_member_1, namespaceName, declarationName); } return void 0; } - } else throw Debug.assertNever(name, "Unknown entity name kind."); + } else Debug.assertNever(name, "Unknown entity name kind."); Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */ ) === 0, "Should never get an instantiated symbol here."); - if (!nodeIsSynthesized(name) && isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 274 /* ExportAssignment */ )) markSymbolOfAliasDeclarationIfTypeOnly(getAliasDeclarationFromName(name), symbol, /*finalTarget*/ void 0, /*overwriteEmpty*/ true); + if (!nodeIsSynthesized(name) && isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 277 /* ExportAssignment */ )) markSymbolOfAliasDeclarationIfTypeOnly(getAliasDeclarationFromName(name), symbol, /*finalTarget*/ void 0, /*overwriteEmpty*/ true); return symbol.flags & meaning || dontResolveAlias ? symbol : resolveAlias(symbol); } function resolveEntityNameFromAssignmentDeclaration(name, meaning) { @@ -45806,7 +46270,7 @@ ${lanes.join("\n")} } } function getAssignmentDeclarationLocation(node) { - const typeAlias = findAncestor(node, (node2)=>!(isJSDocNode(node2) || node2.flags & 8388608 /* JSDoc */ ) ? "quit" : isJSDocTypeAlias(node2)); + const typeAlias = findAncestor(node, (node2)=>!(isJSDocNode(node2) || node2.flags & 16777216 /* JSDoc */ ) ? "quit" : isJSDocTypeAlias(node2)); if (typeAlias) return; const host2 = getJSDocHost(node); if (host2 && isExpressionStatement(host2) && isPrototypePropertyAssignment(host2.expression)) { @@ -45851,38 +46315,41 @@ ${lanes.join("\n")} return isStringLiteralLike(moduleReferenceExpression) ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation) : void 0; } function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation = false) { - var _a2, _b, _c, _d, _e, _f, _g, _h, _i; + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j; if (startsWith(moduleReference, "@types/")) { const diag2 = Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; const withoutAtTypePrefix = removePrefix(moduleReference, "@types/"); - error(errorNode, diag2, withoutAtTypePrefix, moduleReference); + error2(errorNode, diag2, withoutAtTypePrefix, moduleReference); } const ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ true); if (ambientModule) return ambientModule; const currentSourceFile = getSourceFileOfNode(location); - const contextSpecifier = isStringLiteralLike(location) ? location : ((_a2 = findAncestor(location, isImportCall)) == null ? void 0 : _a2.arguments[0]) || ((_b = findAncestor(location, isImportDeclaration)) == null ? void 0 : _b.moduleSpecifier) || ((_c = findAncestor(location, isExternalModuleImportEqualsDeclaration)) == null ? void 0 : _c.moduleReference.expression) || ((_d = findAncestor(location, isExportDeclaration)) == null ? void 0 : _d.moduleSpecifier) || ((_e = isModuleDeclaration(location) ? location : location.parent && isModuleDeclaration(location.parent) && location.parent.name === location ? location.parent : void 0) == null ? void 0 : _e.name) || ((_f = isLiteralImportTypeNode(location) ? location : void 0) == null ? void 0 : _f.argument.literal); + const contextSpecifier = isStringLiteralLike(location) ? location : ((_a = findAncestor(location, isImportCall)) == null ? void 0 : _a.arguments[0]) || ((_b = findAncestor(location, isImportDeclaration)) == null ? void 0 : _b.moduleSpecifier) || ((_c = findAncestor(location, isExternalModuleImportEqualsDeclaration)) == null ? void 0 : _c.moduleReference.expression) || ((_d = findAncestor(location, isExportDeclaration)) == null ? void 0 : _d.moduleSpecifier) || ((_e = isModuleDeclaration(location) ? location : location.parent && isModuleDeclaration(location.parent) && location.parent.name === location ? location.parent : void 0) == null ? void 0 : _e.name) || ((_f = isLiteralImportTypeNode(location) ? location : void 0) == null ? void 0 : _f.argument.literal); const mode = contextSpecifier && isStringLiteralLike(contextSpecifier) ? getModeForUsageLocation(currentSourceFile, contextSpecifier) : currentSourceFile.impliedNodeFormat; const moduleResolutionKind = getEmitModuleResolutionKind(compilerOptions); const resolvedModule = getResolvedModule(currentSourceFile, moduleReference, mode); const resolutionDiagnostic = resolvedModule && getResolutionDiagnostic(compilerOptions, resolvedModule, currentSourceFile); const sourceFile = resolvedModule && (!resolutionDiagnostic || resolutionDiagnostic === Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set) && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { - if (resolutionDiagnostic) error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); + if (resolutionDiagnostic) error2(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); if (resolvedModule.resolvedUsingTsExtension && isDeclarationFileName(moduleReference)) { const importOrExport = ((_g = findAncestor(location, isImportDeclaration)) == null ? void 0 : _g.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration)); - if (importOrExport && !importOrExport.isTypeOnly || findAncestor(location, isImportCall)) error(errorNode, Diagnostics.A_declaration_file_cannot_be_imported_without_import_type_Did_you_mean_to_import_an_implementation_file_0_instead, getSuggestedImportSource(Debug.checkDefined(tryExtractTSExtension(moduleReference)))); + if (importOrExport && !importOrExport.isTypeOnly || findAncestor(location, isImportCall)) error2(errorNode, Diagnostics.A_declaration_file_cannot_be_imported_without_import_type_Did_you_mean_to_import_an_implementation_file_0_instead, getSuggestedImportSource(Debug.checkDefined(tryExtractTSExtension(moduleReference)))); } else if (resolvedModule.resolvedUsingTsExtension && !shouldAllowImportingTsExtension(compilerOptions, currentSourceFile.fileName)) { - const tsExtension = Debug.checkDefined(tryExtractTSExtension(moduleReference)); - error(errorNode, Diagnostics.An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled, tsExtension); + const importOrExport = ((_h = findAncestor(location, isImportDeclaration)) == null ? void 0 : _h.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration)); + if (!((importOrExport == null ? void 0 : importOrExport.isTypeOnly) || findAncestor(location, isImportTypeNode))) { + const tsExtension = Debug.checkDefined(tryExtractTSExtension(moduleReference)); + error2(errorNode, Diagnostics.An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled, tsExtension); + } } if (sourceFile.symbol) { if (resolvedModule.isExternalLibraryImport && !resolutionExtensionIsTSOrJson(resolvedModule.extension)) errorOnImplicitAnyModule(/*isError*/ false, errorNode, currentSourceFile, mode, resolvedModule, moduleReference); if (moduleResolutionKind === 3 /* Node16 */ || moduleResolutionKind === 99 /* NodeNext */ ) { const isSyncImport = currentSourceFile.impliedNodeFormat === 1 /* CommonJS */ && !findAncestor(location, isImportCall) || !!findAncestor(location, isImportEqualsDeclaration); const overrideClauseHost = findAncestor(location, (l)=>isImportTypeNode(l) || isExportDeclaration(l) || isImportDeclaration(l)); - const overrideClause = overrideClauseHost && isImportTypeNode(overrideClauseHost) ? (_h = overrideClauseHost.assertions) == null ? void 0 : _h.assertClause : overrideClauseHost == null ? void 0 : overrideClauseHost.assertClause; + const overrideClause = overrideClauseHost && isImportTypeNode(overrideClauseHost) ? (_i = overrideClauseHost.assertions) == null ? void 0 : _i.assertClause : overrideClauseHost == null ? void 0 : overrideClauseHost.assertClause; if (isSyncImport && sourceFile.impliedNodeFormat === 99 /* ESNext */ && !getResolutionModeOverrideForClause(overrideClause)) { - if (findAncestor(location, isImportEqualsDeclaration)) error(errorNode, Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead, moduleReference); + if (findAncestor(location, isImportEqualsDeclaration)) error2(errorNode, Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead, moduleReference); else { let diagnosticDetails; const ext = tryGetExtensionFromPath2(currentSourceFile.fileName); @@ -45901,7 +46368,7 @@ ${lanes.join("\n")} } return getMergedSymbol(sourceFile.symbol); } - if (moduleNotFoundError) error(errorNode, Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + if (moduleNotFoundError) error2(errorNode, Diagnostics.File_0_is_not_a_module, sourceFile.fileName); return void 0; } if (patternAmbientModules) { @@ -45915,7 +46382,7 @@ ${lanes.join("\n")} if (resolvedModule && !resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === void 0 || resolutionDiagnostic === Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { const diag2 = Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; - error(errorNode, diag2, moduleReference, resolvedModule.resolvedFileName); + error2(errorNode, diag2, moduleReference, resolvedModule.resolvedFileName); } else errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, currentSourceFile, mode, resolvedModule, moduleReference); return void 0; } @@ -45923,21 +46390,21 @@ ${lanes.join("\n")} if (resolvedModule) { const redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName); if (redirect) { - error(errorNode, Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName); + error2(errorNode, Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName); return void 0; } } - if (resolutionDiagnostic) error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); + if (resolutionDiagnostic) error2(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); else { const isExtensionlessRelativePathImport = pathIsRelative(moduleReference) && !hasExtension(moduleReference); const resolutionIsNode16OrNext = moduleResolutionKind === 3 /* Node16 */ || moduleResolutionKind === 99 /* NodeNext */ ; - if (!getResolveJsonModule(compilerOptions) && fileExtensionIs(moduleReference, ".json" /* Json */ ) && moduleResolutionKind !== 1 /* Classic */ && hasJsonModuleEmitEnabled(compilerOptions)) error(errorNode, Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); + if (!getResolveJsonModule(compilerOptions) && fileExtensionIs(moduleReference, ".json" /* Json */ ) && moduleResolutionKind !== 1 /* Classic */ && hasJsonModuleEmitEnabled(compilerOptions)) error2(errorNode, Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); else if (mode === 99 /* ESNext */ && resolutionIsNode16OrNext && isExtensionlessRelativePathImport) { const absoluteRef = getNormalizedAbsolutePath(moduleReference, getDirectoryPath(currentSourceFile.path)); - const suggestedExt = (_i = suggestedExtensions.find(([actualExt, _importExt])=>host.fileExists(absoluteRef + actualExt))) == null ? void 0 : _i[1]; - if (suggestedExt) error(errorNode, Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node16_or_nodenext_Did_you_mean_0, moduleReference + suggestedExt); - else error(errorNode, Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node16_or_nodenext_Consider_adding_an_extension_to_the_import_path); - } else error(errorNode, moduleNotFoundError, moduleReference); + const suggestedExt = (_j = suggestedExtensions.find(([actualExt, _importExt])=>host.fileExists(absoluteRef + actualExt))) == null ? void 0 : _j[1]; + if (suggestedExt) error2(errorNode, Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node16_or_nodenext_Did_you_mean_0, moduleReference + suggestedExt); + else error2(errorNode, Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node16_or_nodenext_Consider_adding_an_extension_to_the_import_path); + } else error2(errorNode, moduleNotFoundError, moduleReference); } } return void 0; @@ -45951,21 +46418,11 @@ ${lanes.join("\n")} return importSourceWithoutExtension; } } - function errorOnImplicitAnyModule(isError, errorNode, sourceFile, mode, { packageId: packageId , resolvedFileName: resolvedFileName }, moduleReference) { - var _a2, _b; + function errorOnImplicitAnyModule(isError, errorNode, sourceFile, mode, { packageId: packageId, resolvedFileName: resolvedFileName }, moduleReference) { let errorInfo; - if (!isExternalModuleNameRelative(moduleReference) && packageId) { - const node10Result = (_b = (_a2 = sourceFile.resolvedModules) == null ? void 0 : _a2.get(moduleReference, mode)) == null ? void 0 : _b.node10Result; - errorInfo = node10Result ? chainDiagnosticMessages(/*details*/ void 0, Diagnostics.There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The_1_library_may_need_to_update_its_package_json_or_typings, node10Result, node10Result.indexOf(nodeModulesPathPart + "@types/") > -1 ? `@types/${mangleScopedPackageName(packageId.name)}` : packageId.name) : typesPackageExists(packageId.name) ? chainDiagnosticMessages(/*details*/ void 0, Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, mangleScopedPackageName(packageId.name)) : packageBundlesTypes(packageId.name) ? chainDiagnosticMessages(/*details*/ void 0, Diagnostics.If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1, packageId.name, moduleReference) : chainDiagnosticMessages(/*details*/ void 0, Diagnostics.Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, mangleScopedPackageName(packageId.name)); - } + if (!isExternalModuleNameRelative(moduleReference) && packageId) errorInfo = createModuleNotFoundChain(sourceFile, host, moduleReference, mode, packageId.name); errorOrSuggestion(isError, errorNode, chainDiagnosticMessages(errorInfo, Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } - function typesPackageExists(packageName) { - return getPackagesMap().has(getTypesPackageName(packageName)); - } - function packageBundlesTypes(packageName) { - return !!getPackagesMap().get(packageName); - } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { if (moduleSymbol == null ? void 0 : moduleSymbol.exports) { const exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */ ), dontResolveAlias); @@ -45985,16 +46442,20 @@ ${lanes.join("\n")} if (name === "export=" /* ExportEquals */ ) return; merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s); }); + if (merged === exported) { + getSymbolLinks(merged).resolvedExports = void 0; + getSymbolLinks(merged).resolvedMembers = void 0; + } getSymbolLinks(merged).cjsExportMerged = merged; return links.cjsExportMerged = merged; } function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) { - var _a2; + var _a; const symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { - if (!suppressInteropError && !(symbol.flags & 1539 /* Variable */ ) && !getDeclarationOfKind(symbol, 308 /* SourceFile */ )) { + if (!suppressInteropError && !(symbol.flags & 1539 /* Variable */ ) && !getDeclarationOfKind(symbol, 312 /* SourceFile */ )) { const compilerOptionName = moduleKind >= 5 /* ES2015 */ ? "allowSyntheticDefaultImports" : "esModuleInterop"; - error(referencingLocation, Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName); + error2(referencingLocation, Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName); return symbol; } const referenceParent = referencingLocation.parent; @@ -46003,13 +46464,13 @@ ${lanes.join("\n")} const type = getTypeOfSymbol(symbol); const defaultOnlyType = getTypeWithSyntheticDefaultOnly(type, symbol, moduleSymbol, reference); if (defaultOnlyType) return cloneTypeAsModuleType(symbol, defaultOnlyType, referenceParent); - const targetFile = (_a2 = moduleSymbol == null ? void 0 : moduleSymbol.declarations) == null ? void 0 : _a2.find(isSourceFile); + const targetFile = (_a = moduleSymbol == null ? void 0 : moduleSymbol.declarations) == null ? void 0 : _a.find(isSourceFile); const isEsmCjsRef = targetFile && isESMFormatImportImportingCommonjsFormatFile(getUsageModeForExpression(reference), targetFile.impliedNodeFormat); if (getESModuleInterop(compilerOptions) || isEsmCjsRef) { let sigs = getSignaturesOfStructuredType(type, 0 /* Call */ ); if (!sigs || !sigs.length) sigs = getSignaturesOfStructuredType(type, 1 /* Construct */ ); if (sigs && sigs.length || getPropertyOfType(type, "default" /* Default */ , /*skipObjectFunctionPropertyAugment*/ true) || isEsmCjsRef) { - const moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol, reference); + const moduleType = type.flags & 3670016 /* StructuredType */ ? getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol, reference) : createDefaultPropertyWrapperForModule(symbol, symbol.parent); return cloneTypeAsModuleType(symbol, moduleType, referenceParent); } } @@ -46072,7 +46533,7 @@ ${lanes.join("\n")} return shouldTreatPropertiesOfExternalModuleAsExports(type) ? getPropertyOfType(type, memberName) : void 0; } function shouldTreatPropertiesOfExternalModuleAsExports(resolvedExternalModuleType) { - return !(resolvedExternalModuleType.flags & 134348796 /* Primitive */ || getObjectFlags(resolvedExternalModuleType) & 1 /* Class */ || // `isArrayOrTupleLikeType` is too expensive to use in this auto-imports hot path + return !(resolvedExternalModuleType.flags & 402784252 /* Primitive */ || getObjectFlags(resolvedExternalModuleType) & 1 /* Class */ || // `isArrayOrTupleLikeType` is too expensive to use in this auto-imports hot path isArrayType(resolvedExternalModuleType) || isTupleType(resolvedExternalModuleType)); } function getExportsOfSymbol(symbol) { @@ -46081,7 +46542,7 @@ ${lanes.join("\n")} function getExportsOfModule(moduleSymbol) { const links = getSymbolLinks(moduleSymbol); if (!links.resolvedExports) { - const { exports: exports , typeOnlyExportStarMap: typeOnlyExportStarMap } = getExportsOfModuleWorker(moduleSymbol); + const { exports: exports, typeOnlyExportStarMap: typeOnlyExportStarMap } = getExportsOfModuleWorker(moduleSymbol); links.resolvedExports = exports; links.typeOnlyExportStarMap = typeOnlyExportStarMap; } @@ -46130,14 +46591,14 @@ ${lanes.join("\n")} const exportedSymbols = visit(resolvedModule, node, isTypeOnly || node.isTypeOnly); extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable, node); } - lookupTable.forEach(({ exportsWithDuplicate: exportsWithDuplicate }, id)=>{ + lookupTable.forEach(({ exportsWithDuplicate: exportsWithDuplicate }, id)=>{ if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) return; for (const node of exportsWithDuplicate)diagnostics.add(createDiagnosticForNode(node, Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable.get(id).specifierText, unescapeLeadingUnderscores(id))); }); extendExportSymbols(symbols, nestedSymbols); } if (exportStar == null ? void 0 : exportStar.isTypeOnly) { - typeOnlyExportStarMap != null ? typeOnlyExportStarMap : typeOnlyExportStarMap = /* @__PURE__ */ new Map(); + typeOnlyExportStarMap ?? (typeOnlyExportStarMap = /* @__PURE__ */ new Map()); symbols.forEach((_, escapedName)=>typeOnlyExportStarMap.set(escapedName, exportStar)); } return symbols; @@ -46193,7 +46654,7 @@ ${lanes.join("\n")} const additionalContainers = mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); const reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); const objectLiteralContainer = getVariableDeclarationOfObjectLiteral(container, meaning); - if (enclosingDeclaration && container.flags & getQualifiedLeftMeaning(meaning) && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */ , /*externalOnly*/ false)) return append(concatenate(concatenate([ + if (enclosingDeclaration && container.flags & getQualifiedLeftMeaning(meaning) && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */ , /*useOnlyExternalAliasing*/ false)) return append(concatenate(concatenate([ container ], additionalContainers), reexportContainers), objectLiteralContainer); const firstVariableMatch = !(container.flags & getQualifiedLeftMeaning(meaning)) && container.flags & 788968 /* Type */ && getDeclaredTypeOfSymbol(container).flags & 524288 /* Object */ && meaning === 111551 /* Value */ ? forEachSymbolTableInScope(enclosingDeclaration, (t)=>{ @@ -46218,7 +46679,7 @@ ${lanes.join("\n")} if (hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) return getSymbolOfDeclaration(d.parent); if (isModuleBlock(d.parent) && d.parent.parent && resolveExternalModuleSymbol(getSymbolOfDeclaration(d.parent.parent)) === symbol) return getSymbolOfDeclaration(d.parent.parent); } - if (isClassExpression(d) && isBinaryExpression(d.parent) && d.parent.operatorToken.kind === 63 /* EqualsToken */ && isAccessExpression(d.parent.left) && isEntityNameExpression(d.parent.left.expression)) { + if (isClassExpression(d) && isBinaryExpression(d.parent) && d.parent.operatorToken.kind === 64 /* EqualsToken */ && isAccessExpression(d.parent.left) && isEntityNameExpression(d.parent.left.expression)) { if (isModuleExportsAccessExpression(d.parent.left) || isExportsIdentifier(d.parent.left.expression)) return getSymbolOfDeclaration(getSourceFileOfNode(d)); checkExpressionCached(d.parent.left.expression); return getNodeLinks(d.parent.left.expression).resolvedSymbol; @@ -46259,20 +46720,20 @@ ${lanes.join("\n")} return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */ ) !== 0 && symbol.exportSymbol || symbol); } function symbolIsValue(symbol, includeTypeOnlyMembers) { - return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && getAllSymbolFlags(symbol) & 111551 /* Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); + return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && getSymbolFlags(symbol, !includeTypeOnlyMembers) & 111551 /* Value */ ); } function findConstructorDeclaration(node) { const members = node.members; for (const member of members){ - if (member.kind === 173 /* Constructor */ && nodeIsPresent(member.body)) return member; + if (member.kind === 176 /* Constructor */ && nodeIsPresent(member.body)) return member; } } function createType(flags) { - var _a2; + var _a; const result = new Type27(checker, flags); typeCount++; result.id = typeCount; - (_a2 = tracing) == null || _a2.recordType(result); + (_a = tracing) == null || _a.recordType(result); return result; } function createTypeWithSymbol(flags, symbol) { @@ -46286,7 +46747,7 @@ ${lanes.join("\n")} function createIntrinsicType(kind, intrinsicName, objectFlags = 0 /* None */ ) { const type = createType(kind); type.intrinsicName = intrinsicName; - type.objectFlags = objectFlags; + type.objectFlags = objectFlags | 52953088 /* IsNeverIntersectionComputed */ ; return type; } function createObjectType(objectFlags, symbol) { @@ -46355,15 +46816,15 @@ ${lanes.join("\n")} if (result = callback(location.locals, /*ignoreQualification*/ void 0, /*isLocalNameLookup*/ true, location)) return result; } switch(location.kind){ - case 308 /* SourceFile */ : + case 312 /* SourceFile */ : if (!isExternalOrCommonJsModule(location)) break; - case 264 /* ModuleDeclaration */ : + case 267 /* ModuleDeclaration */ : const sym = getSymbolOfDeclaration(location); if (result = callback((sym == null ? void 0 : sym.exports) || emptySymbols, /*ignoreQualification*/ void 0, /*isLocalNameLookup*/ true, location)) return result; break; - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : - case 261 /* InterfaceDeclaration */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 264 /* InterfaceDeclaration */ : let table; (getSymbolOfDeclaration(location).members || emptySymbols).forEach((memberSymbol, key)=>{ if (memberSymbol.flags & 788968 /* Assignment */ ) (table || (table = createSymbolTable())).set(key, memberSymbol); @@ -46411,13 +46872,13 @@ ${lanes.join("\n")} symbol ]; const result2 = forEachEntry(symbols, (symbolFromSymbolTable)=>{ - if (symbolFromSymbolTable.flags & 2097152 /* Alias */ && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */ && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && isExternalModule(getSourceFileOfNode(enclosingDeclaration))) && (!useOnlyExternalAliasing || some(symbolFromSymbolTable.declarations, isExternalModuleImportEqualsDeclaration)) && (isLocalNameLookup ? !some(symbolFromSymbolTable.declarations, isNamespaceReexportDeclaration) : true) && (ignoreQualification || !getDeclarationOfKind(symbolFromSymbolTable, 278 /* ExportSpecifier */ ))) { + if (symbolFromSymbolTable.flags & 2097152 /* Alias */ && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */ && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && isExternalModule(getSourceFileOfNode(enclosingDeclaration))) && (!useOnlyExternalAliasing || some(symbolFromSymbolTable.declarations, isExternalModuleImportEqualsDeclaration)) && (isLocalNameLookup ? !some(symbolFromSymbolTable.declarations, isNamespaceReexportDeclaration) : true) && (ignoreQualification || !getDeclarationOfKind(symbolFromSymbolTable, 281 /* ExportSpecifier */ ))) { const resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); const candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification); if (candidate) return candidate; } if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) { - if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ void 0, ignoreQualification)) return [ + if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*resolvedAliasSymbol*/ void 0, ignoreQualification)) return [ symbol ]; } @@ -46441,9 +46902,9 @@ ${lanes.join("\n")} let symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName)); if (!symbolFromSymbolTable) return false; if (symbolFromSymbolTable === symbol) return true; - const shouldResolveAlias = symbolFromSymbolTable.flags & 2097152 /* Alias */ && !getDeclarationOfKind(symbolFromSymbolTable, 278 /* ExportSpecifier */ ); + const shouldResolveAlias = symbolFromSymbolTable.flags & 2097152 /* Alias */ && !getDeclarationOfKind(symbolFromSymbolTable, 281 /* ExportSpecifier */ ); symbolFromSymbolTable = shouldResolveAlias ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; - const flags = shouldResolveAlias ? getAllSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags; + const flags = shouldResolveAlias ? getSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags; if (flags & meaning) { qualify = true; return true; @@ -46455,10 +46916,10 @@ ${lanes.join("\n")} function isPropertyOrMethodDeclarationSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { for (const declaration of symbol.declarations)switch(declaration.kind){ - case 169 /* PropertyDeclaration */ : - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 172 /* PropertyDeclaration */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : continue; default: return false; @@ -46547,20 +47008,20 @@ ${lanes.join("\n")} return node && getSymbolOfDeclaration(node); } function hasExternalModuleSymbol(declaration) { - return isAmbientModule(declaration) || declaration.kind === 308 /* SourceFile */ && isExternalOrCommonJsModule(declaration); + return isAmbientModule(declaration) || declaration.kind === 312 /* SourceFile */ && isExternalOrCommonJsModule(declaration); } function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { - return isModuleWithStringLiteralName(declaration) || declaration.kind === 308 /* SourceFile */ && isExternalOrCommonJsModule(declaration); + return isModuleWithStringLiteralName(declaration) || declaration.kind === 312 /* SourceFile */ && isExternalOrCommonJsModule(declaration); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { let aliasesToMakeVisible; - if (!every(filter(symbol.declarations, (d)=>d.kind !== 79 /* Identifier */ ), getIsDeclarationVisible)) return void 0; + if (!every(filter(symbol.declarations, (d)=>d.kind !== 80 /* Identifier */ ), getIsDeclarationVisible)) return void 0; return { accessibility: 0 /* Accessible */ , aliasesToMakeVisible: aliasesToMakeVisible }; function getIsDeclarationVisible(declaration) { - var _a2, _b; + var _a, _b; if (!isDeclarationVisible(declaration)) { const anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && !hasSyntacticModifier(anyImportSyntax, 1 /* Export */ ) && // import clause without export @@ -46569,7 +47030,7 @@ ${lanes.join("\n")} isDeclarationVisible(declaration.parent.parent.parent)) return addVisibleAlias(declaration, declaration.parent.parent); else if (isLateVisibilityPaintedStatement(declaration) && !hasSyntacticModifier(declaration, 1 /* Export */ ) && isDeclarationVisible(declaration.parent)) return addVisibleAlias(declaration, declaration); else if (isBindingElement(declaration)) { - if (symbol.flags & 2097152 /* Alias */ && isInJSFile(declaration) && ((_a2 = declaration.parent) == null ? void 0 : _a2.parent) && isVariableDeclaration(declaration.parent.parent) && ((_b = declaration.parent.parent.parent) == null ? void 0 : _b.parent) && isVariableStatement(declaration.parent.parent.parent.parent) && !hasSyntacticModifier(declaration.parent.parent.parent.parent, 1 /* Export */ ) && declaration.parent.parent.parent.parent.parent && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) return addVisibleAlias(declaration, declaration.parent.parent.parent.parent); + if (symbol.flags & 2097152 /* Alias */ && isInJSFile(declaration) && ((_a = declaration.parent) == null ? void 0 : _a.parent) && isVariableDeclaration(declaration.parent.parent) && ((_b = declaration.parent.parent.parent) == null ? void 0 : _b.parent) && isVariableStatement(declaration.parent.parent.parent.parent) && !hasSyntacticModifier(declaration.parent.parent.parent.parent, 1 /* Export */ ) && declaration.parent.parent.parent.parent.parent && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) return addVisibleAlias(declaration, declaration.parent.parent.parent.parent); else if (symbol.flags & 2 /* BlockScopedVariable */ ) { const variableStatement = findAncestor(declaration, isVariableStatement); if (hasSyntacticModifier(variableStatement, 1 /* Export */ )) return true; @@ -46591,15 +47052,15 @@ ${lanes.join("\n")} } function isEntityNameVisible(entityName, enclosingDeclaration) { let meaning; - if (entityName.parent.kind === 183 /* TypeQuery */ || entityName.parent.kind === 230 /* ExpressionWithTypeArguments */ && !isPartOfTypeNode(entityName.parent) || entityName.parent.kind === 164 /* ComputedPropertyName */ ) meaning = 1160127 /* ExportValue */ ; - else if (entityName.kind === 163 /* QualifiedName */ || entityName.kind === 208 /* PropertyAccessExpression */ || entityName.parent.kind === 268 /* ImportEqualsDeclaration */ ) meaning = 1920 /* Namespace */ ; + if (entityName.parent.kind === 186 /* TypeQuery */ || entityName.parent.kind === 233 /* ExpressionWithTypeArguments */ && !isPartOfTypeNode(entityName.parent) || entityName.parent.kind === 167 /* ComputedPropertyName */ ) meaning = 1160127 /* ExportValue */ ; + else if (entityName.kind === 166 /* QualifiedName */ || entityName.kind === 211 /* PropertyAccessExpression */ || entityName.parent.kind === 271 /* ImportEqualsDeclaration */ ) meaning = 1920 /* Namespace */ ; else meaning = 788968 /* Type */ ; const firstIdentifier = getFirstIdentifier(entityName); - const symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ void 0, /*nameArg*/ void 0, /*isUse*/ false); + const symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nameNotFoundMessage*/ void 0, /*nameArg*/ void 0, /*isUse*/ false); if (symbol && symbol.flags & 262144 /* TypeParameter */ && meaning & 788968 /* Type */ ) return { accessibility: 0 /* Accessible */ }; - if (!symbol && isThisIdentifier(firstIdentifier) && isSymbolAccessible(getSymbolOfDeclaration(getThisContainer(firstIdentifier, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false)), firstIdentifier, meaning, /*computeAliases*/ false).accessibility === 0 /* Accessible */ ) return { + if (!symbol && isThisIdentifier(firstIdentifier) && isSymbolAccessible(getSymbolOfDeclaration(getThisContainer(firstIdentifier, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false)), firstIdentifier, meaning, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */ ) return { accessibility: 0 /* Accessible */ }; return symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true) || { @@ -46619,7 +47080,7 @@ ${lanes.join("\n")} return writer ? symbolToStringWorker(writer).getText() : usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer2) { const entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); - const printer = (enclosingDeclaration == null ? void 0 : enclosingDeclaration.kind) === 308 /* SourceFile */ ? createPrinterWithRemoveCommentsNeverAsciiEscape() : createPrinterWithRemoveComments(); + const printer = (enclosingDeclaration == null ? void 0 : enclosingDeclaration.kind) === 312 /* SourceFile */ ? createPrinterWithRemoveCommentsNeverAsciiEscape() : createPrinterWithRemoveComments(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */ , entity, /*sourceFile*/ sourceFile, writer2); return writer2; @@ -46629,8 +47090,8 @@ ${lanes.join("\n")} return writer ? signatureToStringWorker(writer).getText() : usingSingleLineStringWriter(signatureToStringWorker); function signatureToStringWorker(writer2) { let sigOutput; - if (flags & 262144 /* WriteArrowStyleSignature */ ) sigOutput = kind === 1 /* Construct */ ? 182 /* ConstructorType */ : 181 /* FunctionType */ ; - else sigOutput = kind === 1 /* Construct */ ? 177 /* ConstructSignature */ : 176 /* CallSignature */ ; + if (flags & 262144 /* WriteArrowStyleSignature */ ) sigOutput = kind === 1 /* Construct */ ? 185 /* ConstructorType */ : 184 /* FunctionType */ ; + else sigOutput = kind === 1 /* Construct */ ? 180 /* ConstructSignature */ : 179 /* CallSignature */ ; const sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70222336 /* WriteTypeParametersInQualifiedName */ ); const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); @@ -46702,7 +47163,7 @@ ${lanes.join("\n")} return symbolToExpression(symbol, context, meaning); } function withContext(enclosingDeclaration, flags, tracker, cb) { - Debug.assert(enclosingDeclaration === void 0 || (enclosingDeclaration.flags & 8 /* Synthesized */ ) === 0); + Debug.assert(enclosingDeclaration === void 0 || (enclosingDeclaration.flags & 16 /* Synthesized */ ) === 0); const moduleResolverHost = (tracker == null ? void 0 : tracker.trackSymbol) ? tracker.moduleResolverHost : flags & 134217728 /* DoNotIncludeSymbolChain */ ? createBasicNodeBuilderModuleSpecifierResolutionHost(host) : void 0; const context = { enclosingDeclaration: enclosingDeclaration, @@ -46731,7 +47192,7 @@ ${lanes.join("\n")} return typeNode; } function typeToTypeNodeWorker(type, context) { - var _a2, _b; + var _a, _b; if (cancellationToken && cancellationToken.throwIfCancellationRequested) cancellationToken.throwIfCancellationRequested(); const inTypeAlias = context.flags & 8388608 /* InTypeAlias */ ; context.flags &= -8388609 /* InTypeAlias */ ; @@ -46741,31 +47202,31 @@ ${lanes.join("\n")} return void 0; } context.approximateLength += 3; - return factory.createKeywordTypeNode(131 /* AnyKeyword */ ); + return factory.createKeywordTypeNode(133 /* AnyKeyword */ ); } if (!(context.flags & 536870912 /* NoTypeReduction */ )) type = getReducedType(type); if (type.flags & 1 /* Any */ ) { if (type.aliasSymbol) return factory.createTypeReferenceNode(symbolToEntityNameNode(type.aliasSymbol), mapToTypeNodes(type.aliasTypeArguments, context)); - if (type === unresolvedType) return addSyntheticLeadingComment(factory.createKeywordTypeNode(131 /* AnyKeyword */ ), 3 /* MultiLineCommentTrivia */ , "unresolved"); + if (type === unresolvedType) return addSyntheticLeadingComment(factory.createKeywordTypeNode(133 /* AnyKeyword */ ), 3 /* MultiLineCommentTrivia */ , "unresolved"); context.approximateLength += 3; - return factory.createKeywordTypeNode(type === intrinsicMarkerType ? 139 /* IntrinsicKeyword */ : 131 /* AnyKeyword */ ); + return factory.createKeywordTypeNode(type === intrinsicMarkerType ? 141 /* IntrinsicKeyword */ : 133 /* AnyKeyword */ ); } - if (type.flags & 2 /* Unknown */ ) return factory.createKeywordTypeNode(157 /* UnknownKeyword */ ); + if (type.flags & 2 /* Unknown */ ) return factory.createKeywordTypeNode(159 /* UnknownKeyword */ ); if (type.flags & 4 /* String */ ) { context.approximateLength += 6; - return factory.createKeywordTypeNode(152 /* StringKeyword */ ); + return factory.createKeywordTypeNode(154 /* StringKeyword */ ); } if (type.flags & 8 /* Number */ ) { context.approximateLength += 6; - return factory.createKeywordTypeNode(148 /* NumberKeyword */ ); + return factory.createKeywordTypeNode(150 /* NumberKeyword */ ); } if (type.flags & 64 /* BigInt */ ) { context.approximateLength += 6; - return factory.createKeywordTypeNode(160 /* BigIntKeyword */ ); + return factory.createKeywordTypeNode(163 /* BigIntKeyword */ ); } if (type.flags & 16 /* Boolean */ && !type.aliasSymbol) { context.approximateLength += 7; - return factory.createKeywordTypeNode(134 /* BooleanKeyword */ ); + return factory.createKeywordTypeNode(136 /* BooleanKeyword */ ); } if (type.flags & 1056 /* EnumLike */ ) { if (type.symbol.flags & 8 /* EnumMember */ ) { @@ -46784,12 +47245,12 @@ ${lanes.join("\n")} } if (type.flags & 128 /* StringLiteral */ ) { context.approximateLength += type.value.length + 2; - return factory.createLiteralTypeNode(setEmitFlags(factory.createStringLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */ )), 33554432 /* NoAsciiEscaping */ )); + return factory.createLiteralTypeNode(setEmitFlags(factory.createStringLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */ )), 16777216 /* NoAsciiEscaping */ )); } if (type.flags & 256 /* NumberLiteral */ ) { const value1 = type.value; context.approximateLength += ("" + value1).length; - return factory.createLiteralTypeNode(value1 < 0 ? factory.createPrefixUnaryExpression(40 /* MinusToken */ , factory.createNumericLiteral(-value1)) : factory.createNumericLiteral(value1)); + return factory.createLiteralTypeNode(value1 < 0 ? factory.createPrefixUnaryExpression(41 /* MinusToken */ , factory.createNumericLiteral(-value1)) : factory.createNumericLiteral(value1)); } if (type.flags & 2048 /* BigIntLiteral */ ) { context.approximateLength += pseudoBigIntToString(type.value).length + 1; @@ -46808,15 +47269,15 @@ ${lanes.join("\n")} if (context.tracker.reportInaccessibleUniqueSymbolError) context.tracker.reportInaccessibleUniqueSymbolError(); } context.approximateLength += 13; - return factory.createTypeOperatorNode(156 /* UniqueKeyword */ , factory.createKeywordTypeNode(153 /* SymbolKeyword */ )); + return factory.createTypeOperatorNode(158 /* UniqueKeyword */ , factory.createKeywordTypeNode(155 /* SymbolKeyword */ )); } if (type.flags & 16384 /* Void */ ) { context.approximateLength += 4; - return factory.createKeywordTypeNode(114 /* VoidKeyword */ ); + return factory.createKeywordTypeNode(116 /* VoidKeyword */ ); } if (type.flags & 32768 /* Undefined */ ) { context.approximateLength += 9; - return factory.createKeywordTypeNode(155 /* UndefinedKeyword */ ); + return factory.createKeywordTypeNode(157 /* UndefinedKeyword */ ); } if (type.flags & 65536 /* Null */ ) { context.approximateLength += 4; @@ -46824,20 +47285,20 @@ ${lanes.join("\n")} } if (type.flags & 131072 /* Never */ ) { context.approximateLength += 5; - return factory.createKeywordTypeNode(144 /* NeverKeyword */ ); + return factory.createKeywordTypeNode(146 /* NeverKeyword */ ); } if (type.flags & 4096 /* ESSymbol */ ) { context.approximateLength += 6; - return factory.createKeywordTypeNode(153 /* SymbolKeyword */ ); + return factory.createKeywordTypeNode(155 /* SymbolKeyword */ ); } if (type.flags & 67108864 /* NonPrimitive */ ) { context.approximateLength += 6; - return factory.createKeywordTypeNode(149 /* ObjectKeyword */ ); + return factory.createKeywordTypeNode(151 /* ObjectKeyword */ ); } if (isThisTypeParameter(type)) { if (context.flags & 4194304 /* InObjectTypeLiteral */ ) { if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */ )) context.encounteredError = true; - (_b = (_a2 = context.tracker).reportInaccessibleThisError) == null || _b.call(_a2); + (_b = (_a = context.tracker).reportInaccessibleThisError) == null || _b.call(_a); } context.approximateLength += 4; return factory.createThisTypeNode(); @@ -46895,7 +47356,7 @@ ${lanes.join("\n")} const indexedType = type.type; context.approximateLength += 6; const indexTypeNode = typeToTypeNodeHelper(indexedType, context); - return factory.createTypeOperatorNode(141 /* KeyOfKeyword */ , indexTypeNode); + return factory.createTypeOperatorNode(143 /* KeyOfKeyword */ , indexTypeNode); } if (type.flags & 134217728 /* TemplateLiteral */ ) { const texts = type.texts; @@ -46935,7 +47396,7 @@ ${lanes.join("\n")} context.inferTypeParameters = saveInferTypeParameters2; const trueTypeNode2 = typeToTypeNodeOrCircularityElision(instantiateType(getTypeFromTypeNode(type2.root.node.trueType), newMapper)); const falseTypeNode2 = typeToTypeNodeOrCircularityElision(instantiateType(getTypeFromTypeNode(type2.root.node.falseType), newMapper)); - return factory.createConditionalTypeNode(checkTypeNode, factory.createInferTypeNode(factory.createTypeParameterDeclaration(/*modifiers*/ void 0, factory.cloneNode(newTypeVariable.typeName))), factory.createConditionalTypeNode(factory.createTypeReferenceNode(factory.cloneNode(name)), typeToTypeNodeHelper(type2.checkType, context), factory.createConditionalTypeNode(newTypeVariable, extendsTypeNode2, trueTypeNode2, falseTypeNode2), factory.createKeywordTypeNode(144 /* NeverKeyword */ )), factory.createKeywordTypeNode(144 /* NeverKeyword */ )); + return factory.createConditionalTypeNode(checkTypeNode, factory.createInferTypeNode(factory.createTypeParameterDeclaration(/*modifiers*/ void 0, factory.cloneNode(newTypeVariable.typeName))), factory.createConditionalTypeNode(factory.createTypeReferenceNode(factory.cloneNode(name)), typeToTypeNodeHelper(type2.checkType, context), factory.createConditionalTypeNode(newTypeVariable, extendsTypeNode2, trueTypeNode2, falseTypeNode2), factory.createKeywordTypeNode(146 /* NeverKeyword */ )), factory.createKeywordTypeNode(146 /* NeverKeyword */ )); } const saveInferTypeParameters = context.inferTypeParameters; context.inferTypeParameters = type2.root.inferTypeParameters; @@ -46946,9 +47407,9 @@ ${lanes.join("\n")} return factory.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } function typeToTypeNodeOrCircularityElision(type2) { - var _a3, _b2, _c; + var _a2, _b2, _c; if (type2.flags & 1048576 /* Union */ ) { - if ((_a3 = context.visitedTypes) == null ? void 0 : _a3.has(getTypeId(type2))) { + if ((_a2 = context.visitedTypes) == null ? void 0 : _a2.has(getTypeId(type2))) { if (!(context.flags & 131072 /* AllowAnonymousIdentifier */ )) { context.encounteredError = true; (_c = (_b2 = context.tracker) == null ? void 0 : _b2.reportCyclicStructureError) == null || _c.call(_b2); @@ -46959,22 +47420,32 @@ ${lanes.join("\n")} } return typeToTypeNodeHelper(type2, context); } + function isMappedTypeHomomorphic(type2) { + return !!getHomomorphicTypeVariable(type2); + } function isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type2) { - return isMappedTypeWithKeyofConstraintDeclaration(type2) && !(getModifiersTypeFromMappedType(type2).flags & 262144 /* TypeParameter */ ); + return !!type2.target && isMappedTypeHomomorphic(type2.target) && !isMappedTypeHomomorphic(type2); } function createMappedTypeNodeFromType(type2) { + var _a2; Debug.assert(!!(type2.flags & 524288 /* Object */ )); const readonlyToken = type2.declaration.readonlyToken ? factory.createToken(type2.declaration.readonlyToken.kind) : void 0; const questionToken = type2.declaration.questionToken ? factory.createToken(type2.declaration.questionToken.kind) : void 0; let appropriateConstraintTypeNode; let newTypeVariable; + const needsModifierPreservingWrapper = !isMappedTypeWithKeyofConstraintDeclaration(type2) && !(getModifiersTypeFromMappedType(type2).flags & 2 /* Unknown */ ) && context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && !(getConstraintTypeFromMappedType(type2).flags & 262144 /* TypeParameter */ && ((_a2 = getConstraintOfTypeParameter(getConstraintTypeFromMappedType(type2))) == null ? void 0 : _a2.flags) & 4194304 /* Index */ ); if (isMappedTypeWithKeyofConstraintDeclaration(type2)) { if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type2) && context.flags & 4 /* GenerateNamesForShadowedTypeParams */ ) { const newParam = createTypeParameter(createSymbol(262144 /* TypeParameter */ , "T")); const name = typeParameterToName(newParam, context); newTypeVariable = factory.createTypeReferenceNode(name); } - appropriateConstraintTypeNode = factory.createTypeOperatorNode(141 /* KeyOfKeyword */ , newTypeVariable || typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context)); + appropriateConstraintTypeNode = factory.createTypeOperatorNode(143 /* KeyOfKeyword */ , newTypeVariable || typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context)); + } else if (needsModifierPreservingWrapper) { + const newParam = createTypeParameter(createSymbol(262144 /* TypeParameter */ , "T")); + const name = typeParameterToName(newParam, context); + newTypeVariable = factory.createTypeReferenceNode(name); + appropriateConstraintTypeNode = newTypeVariable; } else appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type2), context); const typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type2), context, appropriateConstraintTypeNode); const nameTypeNode = type2.declaration.nameType ? typeToTypeNodeHelper(getNameTypeFromMappedType(type2), context) : void 0; @@ -46984,19 +47455,19 @@ ${lanes.join("\n")} const result = setEmitFlags(mappedTypeNode, 1 /* SingleLine */ ); if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type2) && context.flags & 4 /* GenerateNamesForShadowedTypeParams */ ) { const originalConstraint = instantiateType(getConstraintOfTypeParameter(getTypeFromTypeNode(type2.declaration.typeParameter.constraint.type)) || unknownType, type2.mapper); - return factory.createConditionalTypeNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context), factory.createInferTypeNode(factory.createTypeParameterDeclaration(/*modifiers*/ void 0, factory.cloneNode(newTypeVariable.typeName), originalConstraint.flags & 2 /* Unknown */ ? void 0 : typeToTypeNodeHelper(originalConstraint, context))), result, factory.createKeywordTypeNode(144 /* NeverKeyword */ )); - } + return factory.createConditionalTypeNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context), factory.createInferTypeNode(factory.createTypeParameterDeclaration(/*modifiers*/ void 0, factory.cloneNode(newTypeVariable.typeName), originalConstraint.flags & 2 /* Unknown */ ? void 0 : typeToTypeNodeHelper(originalConstraint, context))), result, factory.createKeywordTypeNode(146 /* NeverKeyword */ )); + } else if (needsModifierPreservingWrapper) return factory.createConditionalTypeNode(typeToTypeNodeHelper(getConstraintTypeFromMappedType(type2), context), factory.createInferTypeNode(factory.createTypeParameterDeclaration(/*modifiers*/ void 0, factory.cloneNode(newTypeVariable.typeName), factory.createTypeOperatorNode(143 /* KeyOfKeyword */ , typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context)))), result, factory.createKeywordTypeNode(146 /* NeverKeyword */ )); return result; } function createAnonymousTypeNode(type2) { - var _a3, _b2; + var _a2, _b2; const typeId = type2.id; const symbol = type2.symbol; if (symbol) { const isInstanceType = isClassInstanceSide(type2) ? 788968 /* Type */ : 111551 /* Value */ ; if (isJSConstructor(symbol.valueDeclaration)) return symbolToTypeNode(symbol, context, isInstanceType); - else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration && isClassLike(symbol.valueDeclaration) && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && (!isClassDeclaration(symbol.valueDeclaration) || isSymbolAccessible(symbol, context.enclosingDeclaration, isInstanceType, /*computeAliases*/ false).accessibility !== 0 /* Accessible */ )) || symbol.flags & 896 /* ValueModule */ || shouldWriteTypeOfFunctionSymbol()) return symbolToTypeNode(symbol, context, isInstanceType); - else if ((_a3 = context.visitedTypes) == null ? void 0 : _a3.has(typeId)) { + else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration && isClassLike(symbol.valueDeclaration) && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && (!isClassDeclaration(symbol.valueDeclaration) || isSymbolAccessible(symbol, context.enclosingDeclaration, isInstanceType, /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== 0 /* Accessible */ )) || symbol.flags & 896 /* ValueModule */ || shouldWriteTypeOfFunctionSymbol()) return symbolToTypeNode(symbol, context, isInstanceType); + else if ((_a2 = context.visitedTypes) == null ? void 0 : _a2.has(typeId)) { const typeAlias = getTypeAliasForTypeLiteral(type2); if (typeAlias) return symbolToTypeNode(typeAlias, context, 788968 /* Type */ ); else return createElidedInformationPlaceholder(context); @@ -47015,17 +47486,17 @@ ${lanes.join("\n")} return createTypeNodeFromObjectType(type2); } function shouldWriteTypeOfFunctionSymbol() { - var _a4; + var _a3; const isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ ) && // typeof static method some(symbol.declarations, (declaration)=>isStatic(declaration)); const isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */ ) && (symbol.parent || // is exported function symbol - forEach(symbol.declarations, (declaration)=>declaration.parent.kind === 308 /* SourceFile */ || declaration.parent.kind === 265 /* ModuleBlock */ )); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) return (!!(context.flags & 4096 /* UseTypeOfFunction */ ) || ((_a4 = context.visitedTypes) == null ? void 0 : _a4.has(typeId))) && // it is type of the symbol uses itself recursively + forEach(symbol.declarations, (declaration)=>declaration.parent.kind === 312 /* SourceFile */ || declaration.parent.kind === 268 /* ModuleBlock */ )); + if (isStaticMethodSymbol || isNonLocalFunctionSymbol) return (!!(context.flags & 4096 /* UseTypeOfFunction */ ) || ((_a3 = context.visitedTypes) == null ? void 0 : _a3.has(typeId))) && // it is type of the symbol uses itself recursively (!(context.flags & 8 /* UseStructuralFallback */ ) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); } } function visitAndTransformType(type2, transform2) { - var _a3, _b2; + var _a2, _b2; const typeId = type2.id; const isConstructorObject = getObjectFlags(type2) & 16 /* Anonymous */ && type2.symbol && type2.symbol.flags & 32 /* Class */ ; const id = getObjectFlags(type2) & 4 /* Reference */ && type2.node ? "N" + getNodeId(type2.node) : type2.flags & 16777216 /* Conditional */ ? "N" + getNodeId(type2.root.node) : type2.symbol ? (isConstructorObject ? "+" : "") + getSymbolId(type2.symbol) : void 0; @@ -47034,7 +47505,7 @@ ${lanes.join("\n")} const links = context.enclosingDeclaration && getNodeLinks(context.enclosingDeclaration); const key = `${getTypeId(type2)}|${context.flags}`; if (links) links.serializedTypes || (links.serializedTypes = /* @__PURE__ */ new Map()); - const cachedResult = (_a3 = links == null ? void 0 : links.serializedTypes) == null ? void 0 : _a3.get(key); + const cachedResult = (_a2 = links == null ? void 0 : links.serializedTypes) == null ? void 0 : _a2.get(key); if (cachedResult) { if (cachedResult.truncating) context.truncating = true; context.approximateLength += cachedResult.addedLength; @@ -47063,7 +47534,7 @@ ${lanes.join("\n")} return setTextRange(factory.cloneNode(visitEachChild(node, deepCloneOrReuseNode, nullTransformationContext, deepCloneOrReuseNodes)), node); } function deepCloneOrReuseNodes(nodes, visitor, test, start, count) { - if (nodes && nodes.length === 0) return setTextRange(factory.createNodeArray(/*nodes*/ void 0, nodes.hasTrailingComma), nodes); + if (nodes && nodes.length === 0) return setTextRange(factory.createNodeArray(/*elements*/ void 0, nodes.hasTrailingComma), nodes); return visitNodes2(nodes, visitor, test, start, count); } } @@ -47077,12 +47548,12 @@ ${lanes.join("\n")} } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { const signature = resolved.callSignatures[0]; - const signatureNode = signatureToSignatureDeclarationHelper(signature, 181 /* FunctionType */ , context); + const signatureNode = signatureToSignatureDeclarationHelper(signature, 184 /* FunctionType */ , context); return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { const signature = resolved.constructSignatures[0]; - const signatureNode = signatureToSignatureDeclarationHelper(signature, 182 /* ConstructorType */ , context); + const signatureNode = signatureToSignatureDeclarationHelper(signature, 185 /* ConstructorType */ , context); return signatureNode; } } @@ -47115,28 +47586,27 @@ ${lanes.join("\n")} } const elementType = typeToTypeNodeHelper(typeArguments[0], context); const arrayType = factory.createArrayTypeNode(elementType); - return type2.target === globalArrayType ? arrayType : factory.createTypeOperatorNode(146 /* ReadonlyKeyword */ , arrayType); + return type2.target === globalArrayType ? arrayType : factory.createTypeOperatorNode(148 /* ReadonlyKeyword */ , arrayType); } else if (type2.target.objectFlags & 8 /* Tuple */ ) { typeArguments = sameMap(typeArguments, (t, i)=>removeMissingType(t, !!(type2.target.elementFlags[i] & 2 /* Optional */ ))); if (typeArguments.length > 0) { const arity = getTypeReferenceArity(type2); const tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); if (tupleConstituentNodes) { - if (type2.target.labeledElementDeclarations) for(let i = 0; i < tupleConstituentNodes.length; i++){ + const { labeledElementDeclarations: labeledElementDeclarations } = type2.target; + for(let i = 0; i < tupleConstituentNodes.length; i++){ const flags = type2.target.elementFlags[i]; - tupleConstituentNodes[i] = factory.createNamedTupleMember(flags & 12 /* Variable */ ? factory.createToken(25 /* DotDotDotToken */ ) : void 0, factory.createIdentifier(unescapeLeadingUnderscores(getTupleElementLabel(type2.target.labeledElementDeclarations[i]))), flags & 2 /* Optional */ ? factory.createToken(57 /* QuestionToken */ ) : void 0, flags & 4 /* Rest */ ? factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]); - } - else for(let i = 0; i < Math.min(arity, tupleConstituentNodes.length); i++){ - const flags = type2.target.elementFlags[i]; - tupleConstituentNodes[i] = flags & 12 /* Variable */ ? factory.createRestTypeNode(flags & 4 /* Rest */ ? factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]) : flags & 2 /* Optional */ ? factory.createOptionalTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]; + const labeledElementDeclaration = labeledElementDeclarations == null ? void 0 : labeledElementDeclarations[i]; + if (labeledElementDeclaration) tupleConstituentNodes[i] = factory.createNamedTupleMember(flags & 12 /* Variable */ ? factory.createToken(26 /* DotDotDotToken */ ) : void 0, factory.createIdentifier(unescapeLeadingUnderscores(getTupleElementLabel(labeledElementDeclaration))), flags & 2 /* Optional */ ? factory.createToken(58 /* QuestionToken */ ) : void 0, flags & 4 /* Rest */ ? factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]); + else tupleConstituentNodes[i] = flags & 12 /* Variable */ ? factory.createRestTypeNode(flags & 4 /* Rest */ ? factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]) : flags & 2 /* Optional */ ? factory.createOptionalTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]; } const tupleTypeNode = setEmitFlags(factory.createTupleTypeNode(tupleConstituentNodes), 1 /* SingleLine */ ); - return type2.target.readonly ? factory.createTypeOperatorNode(146 /* ReadonlyKeyword */ , tupleTypeNode) : tupleTypeNode; + return type2.target.readonly ? factory.createTypeOperatorNode(148 /* ReadonlyKeyword */ , tupleTypeNode) : tupleTypeNode; } } if (context.encounteredError || context.flags & 524288 /* AllowEmptyTuple */ ) { const tupleTypeNode = setEmitFlags(factory.createTupleTypeNode([]), 1 /* SingleLine */ ); - return type2.target.readonly ? factory.createTypeOperatorNode(146 /* ReadonlyKeyword */ , tupleTypeNode) : tupleTypeNode; + return type2.target.readonly ? factory.createTypeOperatorNode(148 /* ReadonlyKeyword */ , tupleTypeNode) : tupleTypeNode; } context.encounteredError = true; return void 0; @@ -47214,10 +47684,10 @@ ${lanes.join("\n")} factory.createPropertySignature(/*modifiers*/ void 0, "...", /*questionToken*/ void 0, /*type*/ void 0) ]; const typeElements = []; - for (const signature of resolvedType.callSignatures)typeElements.push(signatureToSignatureDeclarationHelper(signature, 176 /* CallSignature */ , context)); + for (const signature of resolvedType.callSignatures)typeElements.push(signatureToSignatureDeclarationHelper(signature, 179 /* CallSignature */ , context)); for (const signature of resolvedType.constructSignatures){ if (signature.flags & 4 /* Abstract */ ) continue; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 177 /* ConstructSignature */ , context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 180 /* ConstructSignature */ , context)); } for (const info of resolvedType.indexInfos)typeElements.push(indexInfoToIndexSignatureDeclarationHelper(info, context, resolvedType.objectFlags & 1024 /* ReverseMapped */ ? createElidedInformationPlaceholder(context) : void 0)); const properties = resolvedType.properties; @@ -47242,14 +47712,14 @@ ${lanes.join("\n")} function createElidedInformationPlaceholder(context) { context.approximateLength += 3; if (!(context.flags & 1 /* NoTruncation */ )) return factory.createTypeReferenceNode(factory.createIdentifier("..."), /*typeArguments*/ void 0); - return factory.createKeywordTypeNode(131 /* AnyKeyword */ ); + return factory.createKeywordTypeNode(133 /* AnyKeyword */ ); } function shouldUsePlaceholderForProperty(propertySymbol, context) { - var _a2; - return !!(getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */ ) && (contains(context.reverseMappedStack, propertySymbol) || ((_a2 = context.reverseMappedStack) == null ? void 0 : _a2[0]) && !(getObjectFlags(last(context.reverseMappedStack).links.propertyType) & 16 /* Anonymous */ )); + var _a; + return !!(getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */ ) && (contains(context.reverseMappedStack, propertySymbol) || ((_a = context.reverseMappedStack) == null ? void 0 : _a[0]) && !(getObjectFlags(last(context.reverseMappedStack).links.propertyType) & 16 /* Anonymous */ )); } function addPropertyToElementList(propertySymbol, context, typeElements) { - var _a2; + var _a; const propertyIsReverseMapped = !!(getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */ ); const propertyType = shouldUsePlaceholderForProperty(propertySymbol, context) ? anyType : getNonMissingTypeOfSymbol(propertySymbol); const saveEnclosingDeclaration = context.enclosingDeclaration; @@ -47265,42 +47735,42 @@ ${lanes.join("\n")} } } else context.tracker.reportNonSerializableProperty(symbolToString(propertySymbol)); } - context.enclosingDeclaration = propertySymbol.valueDeclaration || ((_a2 = propertySymbol.declarations) == null ? void 0 : _a2[0]) || saveEnclosingDeclaration; + context.enclosingDeclaration = propertySymbol.valueDeclaration || ((_a = propertySymbol.declarations) == null ? void 0 : _a[0]) || saveEnclosingDeclaration; const propertyName = getPropertyNameNodeForSymbol(propertySymbol, context); context.enclosingDeclaration = saveEnclosingDeclaration; context.approximateLength += symbolName(propertySymbol).length + 1; - const optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? factory.createToken(57 /* QuestionToken */ ) : void 0; + const optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */ ) : void 0; if (propertySymbol.flags & 8208 /* Method */ && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) { const signatures = getSignaturesOfType(filterType(propertyType, (t)=>!(t.flags & 32768 /* Undefined */ )), 0 /* Call */ ); for (const signature of signatures){ - const methodDeclaration = signatureToSignatureDeclarationHelper(signature, 170 /* MethodSignature */ , context, { + const methodDeclaration = signatureToSignatureDeclarationHelper(signature, 173 /* MethodSignature */ , context, { name: propertyName, questionToken: optionalToken }); typeElements.push(preserveCommentsOn(methodDeclaration)); } - } else { - let propertyTypeNode; - if (shouldUsePlaceholderForProperty(propertySymbol, context)) propertyTypeNode = createElidedInformationPlaceholder(context); - else { - if (propertyIsReverseMapped) { - context.reverseMappedStack || (context.reverseMappedStack = []); - context.reverseMappedStack.push(propertySymbol); - } - propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : factory.createKeywordTypeNode(131 /* AnyKeyword */ ); - if (propertyIsReverseMapped) context.reverseMappedStack.pop(); + if (signatures.length || !optionalToken) return; + } + let propertyTypeNode; + if (shouldUsePlaceholderForProperty(propertySymbol, context)) propertyTypeNode = createElidedInformationPlaceholder(context); + else { + if (propertyIsReverseMapped) { + context.reverseMappedStack || (context.reverseMappedStack = []); + context.reverseMappedStack.push(propertySymbol); } - const modifiers = isReadonlySymbol(propertySymbol) ? [ - factory.createToken(146 /* ReadonlyKeyword */ ) - ] : void 0; - if (modifiers) context.approximateLength += 9; - const propertySignature = factory.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode); - typeElements.push(preserveCommentsOn(propertySignature)); + propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : factory.createKeywordTypeNode(133 /* AnyKeyword */ ); + if (propertyIsReverseMapped) context.reverseMappedStack.pop(); } + const modifiers = isReadonlySymbol(propertySymbol) ? [ + factory.createToken(148 /* ReadonlyKeyword */ ) + ] : void 0; + if (modifiers) context.approximateLength += 9; + const propertySignature = factory.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode); + typeElements.push(preserveCommentsOn(propertySignature)); function preserveCommentsOn(node) { - var _a3; - if (some(propertySymbol.declarations, (d)=>d.kind === 351 /* JSDocPropertyTag */ )) { - const d = (_a3 = propertySymbol.declarations) == null ? void 0 : _a3.find((d2)=>d2.kind === 351 /* JSDocPropertyTag */ ); + var _a2; + if (some(propertySymbol.declarations, (d)=>d.kind === 355 /* JSDocPropertyTag */ )) { + const d = (_a2 = propertySymbol.declarations) == null ? void 0 : _a2.find((d2)=>d2.kind === 355 /* JSDocPropertyTag */ ); const commentText = getTextOfJSDocComment(d.comment); if (commentText) setSyntheticLeadingComments(node, [ { @@ -47328,7 +47798,7 @@ ${lanes.join("\n")} ]; } const mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */ ); - const seenNames = mayHaveNameCollisions ? createUnderscoreEscapedMultiMap() : void 0; + const seenNames = mayHaveNameCollisions ? createMultiMap() : void 0; const result = []; let i = 0; for (const type of types){ @@ -47371,13 +47841,13 @@ ${lanes.join("\n")} if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */ )) context.encounteredError = true; context.approximateLength += name.length + 4; return factory.createIndexSignature(indexInfo.isReadonly ? [ - factory.createToken(146 /* ReadonlyKeyword */ ) + factory.createToken(148 /* ReadonlyKeyword */ ) ] : void 0, [ indexingParameter ], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context, options) { - var _a2, _b, _c, _d, _e; + var _a; const suppressAny = context.flags & 256 /* SuppressAnyReturnType */ ; if (suppressAny) context.flags &= -257 /* SuppressAnyReturnType */ ; context.approximateLength += 3; @@ -47390,7 +47860,7 @@ ${lanes.join("\n")} if (context.enclosingDeclaration && signature.declaration && signature.declaration !== context.enclosingDeclaration && !isInJSFile(signature.declaration) && some(expandedParams)) { const existingFakeScope = getNodeLinks(context.enclosingDeclaration).fakeScopeForSignatureDeclaration ? context.enclosingDeclaration : void 0; Debug.assertOptionalNode(existingFakeScope, isBlock); - const locals = (_a2 = existingFakeScope == null ? void 0 : existingFakeScope.locals) != null ? _a2 : createSymbolTable(); + const locals = (existingFakeScope == null ? void 0 : existingFakeScope.locals) ?? createSymbolTable(); let newLocals; for (const param of expandedParams)if (!locals.has(param.escapedName)) { newLocals = append(newLocals, param.escapedName); @@ -47416,28 +47886,32 @@ ${lanes.join("\n")} } } } - const parameters = (some(expandedParams, (p)=>p !== expandedParams[expandedParams.length - 1] && !!(getCheckFlags(p) & 32768 /* RestParameter */ )) ? signature.parameters : expandedParams).map((parameter)=>symbolToParameterDeclaration(parameter, context, kind === 173 /* Constructor */ , options == null ? void 0 : options.privateSymbolVisitor, options == null ? void 0 : options.bundledImports)); + const parameters = (some(expandedParams, (p)=>p !== expandedParams[expandedParams.length - 1] && !!(getCheckFlags(p) & 32768 /* RestParameter */ )) ? signature.parameters : expandedParams).map((parameter)=>symbolToParameterDeclaration(parameter, context, kind === 176 /* Constructor */ , options == null ? void 0 : options.privateSymbolVisitor, options == null ? void 0 : options.bundledImports)); const thisParameter = context.flags & 33554432 /* OmitThisParameter */ ? void 0 : tryGetThisParameterDeclaration(signature, context); if (thisParameter) parameters.unshift(thisParameter); let returnTypeNode; const typePredicate = getTypePredicateOfSignature(signature); if (typePredicate) { - const assertsModifier = typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? factory.createToken(129 /* AssertsKeyword */ ) : void 0; - const parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? setEmitFlags(factory.createIdentifier(typePredicate.parameterName), 33554432 /* NoAsciiEscaping */ ) : factory.createThisTypeNode(); + const assertsModifier = typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? factory.createToken(131 /* AssertsKeyword */ ) : void 0; + const parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? setEmitFlags(factory.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */ ) : factory.createThisTypeNode(); const typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = factory.createTypePredicateNode(assertsModifier, parameterName, typeNode); } else { const returnType = getReturnTypeOfSignature(signature); if (returnType && !(suppressAny && isTypeAny(returnType))) returnTypeNode = serializeReturnTypeForSignature(context, returnType, signature, options == null ? void 0 : options.privateSymbolVisitor, options == null ? void 0 : options.bundledImports); - else if (!suppressAny) returnTypeNode = factory.createKeywordTypeNode(131 /* AnyKeyword */ ); + else if (!suppressAny) returnTypeNode = factory.createKeywordTypeNode(133 /* AnyKeyword */ ); } let modifiers = options == null ? void 0 : options.modifiers; - if (kind === 182 /* ConstructorType */ && signature.flags & 4 /* Abstract */ ) { + if (kind === 185 /* ConstructorType */ && signature.flags & 4 /* Abstract */ ) { const flags = modifiersToFlags(modifiers); modifiers = factory.createModifiersFromModifierFlags(flags | 256 /* Abstract */ ); } - const node = kind === 176 /* CallSignature */ ? factory.createCallSignature(typeParameters, parameters, returnTypeNode) : kind === 177 /* ConstructSignature */ ? factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : kind === 170 /* MethodSignature */ ? factory.createMethodSignature(modifiers, (_b = options == null ? void 0 : options.name) != null ? _b : factory.createIdentifier(""), options == null ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : kind === 171 /* MethodDeclaration */ ? factory.createMethodDeclaration(modifiers, /*asteriskToken*/ void 0, (_c = options == null ? void 0 : options.name) != null ? _c : factory.createIdentifier(""), /*questionToken*/ void 0, typeParameters, parameters, returnTypeNode, /*body*/ void 0) : kind === 173 /* Constructor */ ? factory.createConstructorDeclaration(modifiers, parameters, /*body*/ void 0) : kind === 174 /* GetAccessor */ ? factory.createGetAccessorDeclaration(modifiers, (_d = options == null ? void 0 : options.name) != null ? _d : factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ void 0) : kind === 175 /* SetAccessor */ ? factory.createSetAccessorDeclaration(modifiers, (_e = options == null ? void 0 : options.name) != null ? _e : factory.createIdentifier(""), parameters, /*body*/ void 0) : kind === 178 /* IndexSignature */ ? factory.createIndexSignature(modifiers, parameters, returnTypeNode) : kind === 320 /* JSDocFunctionType */ ? factory.createJSDocFunctionType(parameters, returnTypeNode) : kind === 181 /* FunctionType */ ? factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode != null ? returnTypeNode : factory.createTypeReferenceNode(factory.createIdentifier(""))) : kind === 182 /* ConstructorType */ ? factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode != null ? returnTypeNode : factory.createTypeReferenceNode(factory.createIdentifier(""))) : kind === 259 /* FunctionDeclaration */ ? factory.createFunctionDeclaration(modifiers, /*asteriskToken*/ void 0, (options == null ? void 0 : options.name) ? cast(options.name, isIdentifier) : factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ void 0) : kind === 215 /* FunctionExpression */ ? factory.createFunctionExpression(modifiers, /*asteriskToken*/ void 0, (options == null ? void 0 : options.name) ? cast(options.name, isIdentifier) : factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, factory.createBlock([])) : kind === 216 /* ArrowFunction */ ? factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ void 0, factory.createBlock([])) : Debug.assertNever(kind); + const node = kind === 179 /* CallSignature */ ? factory.createCallSignature(typeParameters, parameters, returnTypeNode) : kind === 180 /* ConstructSignature */ ? factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : kind === 173 /* MethodSignature */ ? factory.createMethodSignature(modifiers, (options == null ? void 0 : options.name) ?? factory.createIdentifier(""), options == null ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : kind === 174 /* MethodDeclaration */ ? factory.createMethodDeclaration(modifiers, /*asteriskToken*/ void 0, (options == null ? void 0 : options.name) ?? factory.createIdentifier(""), /*questionToken*/ void 0, typeParameters, parameters, returnTypeNode, /*body*/ void 0) : kind === 176 /* Constructor */ ? factory.createConstructorDeclaration(modifiers, parameters, /*body*/ void 0) : kind === 177 /* GetAccessor */ ? factory.createGetAccessorDeclaration(modifiers, (options == null ? void 0 : options.name) ?? factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ void 0) : kind === 178 /* SetAccessor */ ? factory.createSetAccessorDeclaration(modifiers, (options == null ? void 0 : options.name) ?? factory.createIdentifier(""), parameters, /*body*/ void 0) : kind === 181 /* IndexSignature */ ? factory.createIndexSignature(modifiers, parameters, returnTypeNode) : kind === 324 /* JSDocFunctionType */ ? factory.createJSDocFunctionType(parameters, returnTypeNode) : kind === 184 /* FunctionType */ ? factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode ?? factory.createTypeReferenceNode(factory.createIdentifier(""))) : kind === 185 /* ConstructorType */ ? factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode ?? factory.createTypeReferenceNode(factory.createIdentifier(""))) : kind === 262 /* FunctionDeclaration */ ? factory.createFunctionDeclaration(modifiers, /*asteriskToken*/ void 0, (options == null ? void 0 : options.name) ? cast(options.name, isIdentifier) : factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ void 0) : kind === 218 /* FunctionExpression */ ? factory.createFunctionExpression(modifiers, /*asteriskToken*/ void 0, (options == null ? void 0 : options.name) ? cast(options.name, isIdentifier) : factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, factory.createBlock([])) : kind === 219 /* ArrowFunction */ ? factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ void 0, factory.createBlock([])) : Debug.assertNever(kind); if (typeArguments) node.typeArguments = factory.createNodeArray(typeArguments); + if (((_a = signature.declaration) == null ? void 0 : _a.kind) === 330 /* JSDocSignature */ && signature.declaration.parent.kind === 346 /* JSDocOverloadTag */ ) { + const comment = getTextOfNode(signature.declaration.parent.parent, /*includeTrivia*/ true).slice(2, -2).split(/\r\n|\n|\r/).map((line)=>line.replace(/^\s+/, " ")).join("\n"); + addSyntheticLeadingComment(node, 3 /* MultiLineCommentTrivia */ , comment, /*hasTrailingNewLine*/ true); + } cleanup == null || cleanup(); return node; } @@ -47445,7 +47919,7 @@ ${lanes.join("\n")} if (signature.thisParameter) return symbolToParameterDeclaration(signature.thisParameter, context); if (signature.declaration && isInJSFile(signature.declaration)) { const thisTag = getJSDocThisTag(signature.declaration); - if (thisTag && thisTag.typeExpression) return factory.createParameterDeclaration(/* modifiers */ void 0, /* dotDotDotToken */ void 0, "this", /* questionToken */ void 0, typeToTypeNodeHelper(getTypeFromTypeNode(thisTag.typeExpression), context)); + if (thisTag && thisTag.typeExpression) return factory.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, "this", /*questionToken*/ void 0, typeToTypeNodeHelper(getTypeFromTypeNode(thisTag.typeExpression), context)); } } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { @@ -47463,17 +47937,17 @@ ${lanes.join("\n")} return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) { - let parameterDeclaration = getDeclarationOfKind(parameterSymbol, 166 /* Parameter */ ); - if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) parameterDeclaration = getDeclarationOfKind(parameterSymbol, 344 /* JSDocParameterTag */ ); + let parameterDeclaration = getDeclarationOfKind(parameterSymbol, 169 /* Parameter */ ); + if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) parameterDeclaration = getDeclarationOfKind(parameterSymbol, 348 /* JSDocParameterTag */ ); let parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) parameterType = getOptionalType(parameterType); const parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports); const modifiers = !(context.flags & 8192 /* OmitParameterModifiers */ ) && preserveModifierFlags && parameterDeclaration && canHaveModifiers(parameterDeclaration) ? map(getModifiers(parameterDeclaration), factory.cloneNode) : void 0; const isRest = parameterDeclaration && isRestParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & 32768 /* RestParameter */ ; - const dotDotDotToken = isRest ? factory.createToken(25 /* DotDotDotToken */ ) : void 0; - const name = parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === 79 /* Identifier */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name), 33554432 /* NoAsciiEscaping */ ) : parameterDeclaration.name.kind === 163 /* QualifiedName */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name.right), 33554432 /* NoAsciiEscaping */ ) : cloneBindingName(parameterDeclaration.name) : symbolName(parameterSymbol) : symbolName(parameterSymbol); + const dotDotDotToken = isRest ? factory.createToken(26 /* DotDotDotToken */ ) : void 0; + const name = parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === 80 /* Identifier */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */ ) : parameterDeclaration.name.kind === 166 /* QualifiedName */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */ ) : cloneBindingName(parameterDeclaration.name) : symbolName(parameterSymbol) : symbolName(parameterSymbol); const isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & 16384 /* OptionalParameter */ ; - const questionToken = isOptional ? factory.createToken(57 /* QuestionToken */ ) : void 0; + const questionToken = isOptional ? factory.createToken(58 /* QuestionToken */ ) : void 0; const parameterNode = factory.createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, /*initializer*/ void 0); context.approximateLength += symbolName(parameterSymbol).length + 3; return parameterNode; @@ -47484,14 +47958,14 @@ ${lanes.join("\n")} let visited = visitEachChild(node2, elideInitializerAndSetEmitFlags, nullTransformationContext, /*nodesVisitor*/ void 0, elideInitializerAndSetEmitFlags); if (isBindingElement(visited)) visited = factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name, /*initializer*/ void 0); if (!nodeIsSynthesized(visited)) visited = factory.cloneNode(visited); - return setEmitFlags(visited, 33554433 /* NoAsciiEscaping */ ); + return setEmitFlags(visited, 16777217 /* NoAsciiEscaping */ ); } } } function trackComputedName(accessExpression, enclosingDeclaration, context) { if (!context.tracker.canTrackSymbol) return; const firstIdentifier = getFirstIdentifier(accessExpression); - const name = resolveName(firstIdentifier, firstIdentifier.escapedText, 1160127 /* ExportValue */ , /*nodeNotFoundErrorMessage*/ void 0, /*nameArg*/ void 0, /*isUse*/ true); + const name = resolveName(firstIdentifier, firstIdentifier.escapedText, 1160127 /* ExportValue */ , /*nameNotFoundMessage*/ void 0, /*nameArg*/ void 0, /*isUse*/ true); if (name) context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */ ); } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { @@ -47562,11 +48036,11 @@ ${lanes.join("\n")} return typeParameterNodes; } function lookupTypeParameterNodes(chain, index, context) { - var _a2; + var _a; Debug.assert(chain && 0 <= index && index < chain.length); const symbol = chain[index]; const symbolId = getSymbolId(symbol); - if ((_a2 = context.typeParameterSymbolList) == null ? void 0 : _a2.has(symbolId)) return void 0; + if ((_a = context.typeParameterSymbolList) == null ? void 0 : _a.has(symbolId)) return void 0; (context.typeParameterSymbolList || (context.typeParameterSymbolList = /* @__PURE__ */ new Set())).add(symbolId); let typeParameterNodes; if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < chain.length - 1) { @@ -47584,11 +48058,10 @@ ${lanes.join("\n")} return top; } function getSpecifierForModuleSymbol(symbol, context, overrideImportMode) { - var _a2; - let file = getDeclarationOfKind(symbol, 308 /* SourceFile */ ); + let file = getDeclarationOfKind(symbol, 312 /* SourceFile */ ); if (!file) { const equivalentFileSymbol = firstDefined(symbol.declarations, (d)=>getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol)); - if (equivalentFileSymbol) file = getDeclarationOfKind(equivalentFileSymbol, 308 /* SourceFile */ ); + if (equivalentFileSymbol) file = getDeclarationOfKind(equivalentFileSymbol, 312 /* SourceFile */ ); } if (file && file.moduleName !== void 0) return file.moduleName; if (!file) { @@ -47609,7 +48082,7 @@ ${lanes.join("\n")} let specifier = links.specifierCache && links.specifierCache.get(cacheKey); if (!specifier) { const isBundle2 = !!outFile(compilerOptions); - const { moduleResolverHost: moduleResolverHost } = context.tracker; + const { moduleResolverHost: moduleResolverHost } = context.tracker; const specifierCompilerOptions = isBundle2 ? { ...compilerOptions, baseUrl: moduleResolverHost.getCommonSourceDirectory() @@ -47620,7 +48093,7 @@ ${lanes.join("\n")} }, { overrideImportMode: overrideImportMode })); - (_a2 = links.specifierCache) != null ? _a2 : links.specifierCache = /* @__PURE__ */ new Map(); + links.specifierCache ?? (links.specifierCache = /* @__PURE__ */ new Map()); links.specifierCache.set(cacheKey, specifier); } return specifier; @@ -47630,7 +48103,7 @@ ${lanes.join("\n")} return symbol.parent ? factory.createQualifiedName(symbolToEntityNameNode(symbol.parent), identifier) : identifier; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { - var _a2, _b, _c, _d; + var _a, _b, _c, _d; const chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ )); const isTypeOf = meaning === 111551 /* Value */ ; if (some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { @@ -47646,7 +48119,7 @@ ${lanes.join("\n")} assertion = factory.createImportTypeAssertionContainer(factory.createAssertClause(factory.createNodeArray([ factory.createAssertEntry(factory.createStringLiteral("resolution-mode"), factory.createStringLiteral("import")) ]))); - (_b = (_a2 = context.tracker).reportImportTypeNodeResolutionModeOverride) == null || _b.call(_a2); + (_b = (_a = context.tracker).reportImportTypeNodeResolutionModeOverride) == null || _b.call(_a); } } if (!specifier) specifier = getSpecifierForModuleSymbol(chain[0], context); @@ -47726,7 +48199,7 @@ ${lanes.join("\n")} if (isIndexedAccessTypeNode(LHS)) return factory.createIndexedAccessTypeNode(LHS, factory.createLiteralTypeNode(factory.createStringLiteral(symbolName2))); else return factory.createIndexedAccessTypeNode(factory.createTypeReferenceNode(LHS, typeParameterNodes), factory.createLiteralTypeNode(factory.createStringLiteral(symbolName2))); } - const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 33554432 /* NoAsciiEscaping */ ); + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */ ); if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; if (index > stopper) { @@ -47738,7 +48211,7 @@ ${lanes.join("\n")} } } function typeParameterShadowsNameInScope(escapedName, context, type) { - const result = resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */ , /*nameNotFoundArg*/ void 0, escapedName, /*isUse*/ false); + const result = resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */ , /*nameNotFoundMessage*/ void 0, escapedName, /*isUse*/ false); if (result) { if (result.flags & 262144 /* TypeParameter */ && result === type.symbol) return false; return true; @@ -47746,16 +48219,16 @@ ${lanes.join("\n")} return false; } function typeParameterToName(type, context) { - var _a2, _b; + var _a, _b; if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) { const cached = context.typeParameterNames.get(getTypeId(type)); if (cached) return cached; } let result = symbolToName(type.symbol, context, 788968 /* Type */ , /*expectsIdentifier*/ true); - if (!(result.kind & 79 /* Identifier */ )) return factory.createIdentifier("(Missing type parameter)"); + if (!(result.kind & 80 /* Identifier */ )) return factory.createIdentifier("(Missing type parameter)"); if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ ) { const rawtext = result.escapedText; - let i = ((_a2 = context.typeParameterNamesByTextNextNameCount) == null ? void 0 : _a2.get(rawtext)) || 0; + let i = ((_a = context.typeParameterNamesByTextNextNameCount) == null ? void 0 : _a.get(rawtext)) || 0; let text = rawtext; while(((_b = context.typeParameterNamesByText) == null ? void 0 : _b.has(text)) || typeParameterShadowsNameInScope(text, context, type)){ i++; @@ -47782,7 +48255,7 @@ ${lanes.join("\n")} if (index === 0) context.flags |= 16777216 /* InInitialEntityName */ ; const symbolName2 = getNameOfSymbolAsWritten(symbol2, context); if (index === 0) context.flags ^= 16777216 /* InInitialEntityName */ ; - const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 33554432 /* NoAsciiEscaping */ ); + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */ ); if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; return index > 0 ? factory.createQualifiedName(createEntityNameFromSymbolChain(chain2, index - 1), identifier) : identifier; @@ -47800,7 +48273,7 @@ ${lanes.join("\n")} let firstChar = symbolName2.charCodeAt(0); if (isSingleOrDoubleQuote(firstChar) && some(symbol2.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) return factory.createStringLiteral(getSpecifierForModuleSymbol(symbol2, context)); if (index === 0 || canUsePropertyAccess(symbolName2, languageVersion)) { - const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 33554432 /* NoAsciiEscaping */ ); + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */ ); if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; return index > 0 ? factory.createPropertyAccessExpression(createExpressionFromSymbolChain(chain2, index - 1), identifier) : identifier; @@ -47813,7 +48286,7 @@ ${lanes.join("\n")} if (isSingleOrDoubleQuote(firstChar) && !(symbol2.flags & 8 /* EnumMember */ )) expression = factory.createStringLiteral(stripQuotes(symbolName2).replace(/\\./g, (s)=>s.substring(1)), firstChar === 39 /* singleQuote */ ); else if ("" + +symbolName2 === symbolName2) expression = factory.createNumericLiteral(+symbolName2); if (!expression) { - const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 33554432 /* NoAsciiEscaping */ ); + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */ ); if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; expression = identifier; @@ -47917,7 +48390,7 @@ ${lanes.join("\n")} node: node }; } - const sym = resolveEntityName(leftmost, 67108863 /* All */ , /*ignoreErrors*/ true, /*dontResolveALias*/ true); + const sym = resolveEntityName(leftmost, 67108863 /* All */ , /*ignoreErrors*/ true, /*dontResolveAlias*/ true); if (sym) { if (isSymbolAccessible(sym, context.enclosingDeclaration, 67108863 /* All */ , /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== 0 /* Accessible */ ) introducesError = true; else { @@ -47930,7 +48403,7 @@ ${lanes.join("\n")} name.symbol = sym; return { introducesError: introducesError, - node: setEmitFlags(setOriginalNode(name, node), 33554432 /* NoAsciiEscaping */ ) + node: setEmitFlags(setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */ ) }; } } @@ -47947,15 +48420,15 @@ ${lanes.join("\n")} if (hadError) return void 0; return transformed === existing ? setTextRange(factory.cloneNode(existing), existing) : transformed; function visitExistingNodeTreeSymbols(node) { - if (isJSDocAllType(node) || node.kind === 322 /* JSDocNamepathType */ ) return factory.createKeywordTypeNode(131 /* AnyKeyword */ ); - if (isJSDocUnknownType(node)) return factory.createKeywordTypeNode(157 /* UnknownKeyword */ ); + if (isJSDocAllType(node) || node.kind === 326 /* JSDocNamepathType */ ) return factory.createKeywordTypeNode(133 /* AnyKeyword */ ); + if (isJSDocUnknownType(node)) return factory.createKeywordTypeNode(159 /* UnknownKeyword */ ); if (isJSDocNullableType(node)) return factory.createUnionTypeNode([ visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode), factory.createLiteralTypeNode(factory.createNull()) ]); if (isJSDocOptionalType(node)) return factory.createUnionTypeNode([ visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode), - factory.createKeywordTypeNode(155 /* UndefinedKeyword */ ) + factory.createKeywordTypeNode(157 /* UndefinedKeyword */ ) ]); if (isJSDocNonNullableType(node)) return visitNode(node.type, visitExistingNodeTreeSymbols); if (isJSDocVariadicType(node)) return factory.createArrayTypeNode(visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode)); @@ -47963,19 +48436,19 @@ ${lanes.join("\n")} const name = isIdentifier(t.name) ? t.name : t.name.right; const typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode(node), name.escapedText); const overrideTypeNode = typeViaParent && t.typeExpression && getTypeFromTypeNode(t.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : void 0; - return factory.createPropertySignature(/*modifiers*/ void 0, name, t.isBracketed || t.typeExpression && isJSDocOptionalType(t.typeExpression.type) ? factory.createToken(57 /* QuestionToken */ ) : void 0, overrideTypeNode || t.typeExpression && visitNode(t.typeExpression.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(131 /* AnyKeyword */ )); + return factory.createPropertySignature(/*modifiers*/ void 0, name, t.isBracketed || t.typeExpression && isJSDocOptionalType(t.typeExpression.type) ? factory.createToken(58 /* QuestionToken */ ) : void 0, overrideTypeNode || t.typeExpression && visitNode(t.typeExpression.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */ )); })); - if (isTypeReferenceNode(node) && isIdentifier(node.typeName) && node.typeName.escapedText === "") return setOriginalNode(factory.createKeywordTypeNode(131 /* AnyKeyword */ ), node); + if (isTypeReferenceNode(node) && isIdentifier(node.typeName) && node.typeName.escapedText === "") return setOriginalNode(factory.createKeywordTypeNode(133 /* AnyKeyword */ ), node); if ((isExpressionWithTypeArguments(node) || isTypeReferenceNode(node)) && isJSDocIndexSignature(node)) return factory.createTypeLiteralNode([ factory.createIndexSignature(/*modifiers*/ void 0, [ - factory.createParameterDeclaration(/*modifiers*/ void 0, /*dotdotdotToken*/ void 0, "x", /*questionToken*/ void 0, visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols, isTypeNode)) + factory.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, "x", /*questionToken*/ void 0, visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols, isTypeNode)) ], visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols, isTypeNode)) ]); if (isJSDocFunctionType(node)) { if (isJSDocConstructSignature(node)) { let newTypeNode; - return factory.createConstructorTypeNode(/*modifiers*/ void 0, visitNodes2(node.typeParameters, visitExistingNodeTreeSymbols, isTypeParameterDeclaration), mapDefined(node.parameters, (p, i)=>p.name && isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode = p.type, void 0) : factory.createParameterDeclaration(/*modifiers*/ void 0, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode), /*initializer*/ void 0)), visitNode(newTypeNode || node.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(131 /* AnyKeyword */ )); - } else return factory.createFunctionTypeNode(visitNodes2(node.typeParameters, visitExistingNodeTreeSymbols, isTypeParameterDeclaration), map(node.parameters, (p, i)=>factory.createParameterDeclaration(/*modifiers*/ void 0, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode), /*initializer*/ void 0)), visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(131 /* AnyKeyword */ )); + return factory.createConstructorTypeNode(/*modifiers*/ void 0, visitNodes2(node.typeParameters, visitExistingNodeTreeSymbols, isTypeParameterDeclaration), mapDefined(node.parameters, (p, i)=>p.name && isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode = p.type, void 0) : factory.createParameterDeclaration(/*modifiers*/ void 0, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode), /*initializer*/ void 0)), visitNode(newTypeNode || node.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */ )); + } else return factory.createFunctionTypeNode(visitNodes2(node.typeParameters, visitExistingNodeTreeSymbols, isTypeParameterDeclaration), map(node.parameters, (p, i)=>factory.createParameterDeclaration(/*modifiers*/ void 0, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode), /*initializer*/ void 0)), visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */ )); } if (isTypeReferenceNode(node) && isInJSDoc(node) && (!existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(node, getTypeFromTypeNode(node)) || getIntendedTypeFromJSDocTypeReference(node) || unknownSymbol === resolveTypeReferenceName(node, 788968 /* Type */ , /*ignoreErrors*/ true))) return setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node); if (isLiteralImportTypeNode(node)) { @@ -47986,14 +48459,14 @@ ${lanes.join("\n")} return factory.updateImportTypeNode(node, factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.assertions, node.qualifier, visitNodes2(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode), node.isTypeOf); } if (isEntityName(node) || isEntityNameExpression(node)) { - const { introducesError: introducesError , node: result } = trackExistingEntityName(node, context, includePrivateSymbol); + const { introducesError: introducesError, node: result } = trackExistingEntityName(node, context, includePrivateSymbol); hadError = hadError || introducesError; if (result !== node) return result; } if (file && isTupleTypeNode(node) && getLineAndCharacterOfPosition(file, node.pos).line === getLineAndCharacterOfPosition(file, node.end).line) setEmitFlags(node, 1 /* SingleLine */ ); return visitEachChild(node, visitExistingNodeTreeSymbols, nullTransformationContext); function getEffectiveDotDotDotForParameter(p) { - return p.dotDotDotToken || (p.type && isJSDocVariadicType(p.type) ? factory.createToken(25 /* DotDotDotToken */ ) : void 0); + return p.dotDotDotToken || (p.type && isJSDocVariadicType(p.type) ? factory.createToken(26 /* DotDotDotToken */ ) : void 0); } function getNameForJSDocFunctionParameter(p, index) { return p.name && isIdentifier(p.name) && p.name.escapedText === "this" ? "this" : getEffectiveDotDotDotForParameter(p) ? `args` : `arg${index}`; @@ -48022,8 +48495,8 @@ ${lanes.join("\n")} } } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { - const serializePropertySymbolForClass = makeSerializePropertySymbol(factory.createPropertyDeclaration, 171 /* MethodDeclaration */ , /*useAcessors*/ true); - const serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol((mods, name, question, type)=>factory.createPropertySignature(mods, name, question, type), 170 /* MethodSignature */ , /*useAcessors*/ false); + const serializePropertySymbolForClass = makeSerializePropertySymbol(factory.createPropertyDeclaration, 174 /* MethodDeclaration */ , /*useAccessors*/ true); + const serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol((mods, name, question, type)=>factory.createPropertySignature(mods, name, question, type), 173 /* MethodSignature */ , /*useAccessors*/ false); const enclosingDeclaration = context.enclosingDeclaration; let results = []; const visitedSymbols = /* @__PURE__ */ new Set(); @@ -48038,12 +48511,12 @@ ${lanes.join("\n")} const tracker = { ...oldcontext.tracker.inner, trackSymbol: (sym, decl, meaning)=>{ - var _a2; - const accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeAliases*/ false); + var _a; + const accessibleResult = isSymbolAccessible(sym, decl, meaning, /*shouldComputeAliasesToMakeVisible*/ false); if (accessibleResult.accessibility === 0 /* Accessible */ ) { const chain = lookupSymbolChainWorker(sym, context, meaning); if (!(sym.flags & 4 /* Property */ )) includePrivateSymbol(chain[0]); - } else if ((_a2 = oldcontext.tracker.inner) == null ? void 0 : _a2.trackSymbol) return oldcontext.tracker.inner.trackSymbol(sym, decl, meaning); + } else if ((_a = oldcontext.tracker.inner) == null ? void 0 : _a.trackSymbol) return oldcontext.tracker.inner.trackSymbol(sym, decl, meaning); return false; } }; @@ -48061,7 +48534,7 @@ ${lanes.join("\n")} visitSymbolTable(symbolTable); return mergeRedundantStatements(results); function isIdentifierAndNotUndefined(node) { - return !!node && node.kind === 79 /* Identifier */ ; + return !!node && node.kind === 80 /* Identifier */ ; } function getNamesOfDeclaration(statement) { if (isVariableStatement(statement)) return filter(map(statement.declarationList.declarations, getNameOfDeclaration), isIdentifierAndNotUndefined); @@ -48080,7 +48553,7 @@ ${lanes.join("\n")} if (length(excessExports)) { ns = factory.updateModuleDeclaration(ns, ns.modifiers, ns.name, body = factory.updateModuleBlock(body, factory.createNodeArray([ ...ns.body.statements, - factory.createExportDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, factory.createNamedExports(map(flatMap(excessExports, (e)=>getNamesOfDeclaration(e)), (id)=>factory.createExportSpecifier(/*isTypeOnly*/ false, /*alias*/ void 0, id))), /*moduleSpecifier*/ void 0) + factory.createExportDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, factory.createNamedExports(map(flatMap(excessExports, (e)=>getNamesOfDeclaration(e)), (id)=>factory.createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ void 0, id))), /*moduleSpecifier*/ void 0) ]))); statements = [ ...statements.slice(0, nsIndex), @@ -48184,7 +48657,7 @@ ${lanes.join("\n")} } } function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) { - var _a2, _b, _c, _d; + var _a, _b, _c, _d; const symbolName2 = unescapeLeadingUnderscores(symbol.escapedName); const isDefault = symbol.escapedName === "default" /* Default */ ; if (isPrivate && !(context.flags & 131072 /* AllowAnonymousIdentifier */ ) && isStringANonContextualKeyword(symbolName2) && !isDefault) { @@ -48199,7 +48672,7 @@ ${lanes.join("\n")} const isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol); if (symbol.flags & 8208 /* Method */ || isConstMergedWithNSPrintableAsSignatureMerge) serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName2), modifierFlags); if (symbol.flags & 524288 /* TypeAlias */ ) serializeTypeAlias(symbol, symbolName2, modifierFlags); - if (symbol.flags & 7 /* Property */ && symbol.escapedName !== "export=" /* ExportEquals */ && !(symbol.flags & 4194304 /* Prototype */ ) && !(symbol.flags & 32 /* Class */ ) && !(symbol.flags & 8192 /* Method */ ) && !isConstMergedWithNSPrintableAsSignatureMerge) { + if (symbol.flags & 98311 /* Accessor */ && symbol.escapedName !== "export=" /* ExportEquals */ && !(symbol.flags & 4194304 /* Prototype */ ) && !(symbol.flags & 32 /* Class */ ) && !(symbol.flags & 8192 /* Method */ ) && !isConstMergedWithNSPrintableAsSignatureMerge) { if (propertyAsAlias) { const createdExport = serializeMaybeAliasAssignment(symbol); if (createdExport) { @@ -48211,7 +48684,7 @@ ${lanes.join("\n")} const localName = getInternalSymbolName(symbol, symbolName2); if (!(symbol.flags & 16 /* Function */ ) && isTypeRepresentableAsFunctionNamespaceMerge(type, symbol)) serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags); else { - const flags = !(symbol.flags & 2 /* BlockScopedVariable */ ) ? ((_a2 = symbol.parent) == null ? void 0 : _a2.valueDeclaration) && isSourceFile((_b = symbol.parent) == null ? void 0 : _b.valueDeclaration) ? 2 /* Const */ : void 0 : isConstVariable(symbol) ? 2 /* Const */ : 1 /* Let */ ; + const flags = !(symbol.flags & 2 /* BlockScopedVariable */ ) ? ((_a = symbol.parent) == null ? void 0 : _a.valueDeclaration) && isSourceFile((_b = symbol.parent) == null ? void 0 : _b.valueDeclaration) ? 2 /* Const */ : void 0 : isConstantVariable(symbol) ? 2 /* Const */ : 1 /* Let */ ; const name = needsPostExportDefault || !(symbol.flags & 4 /* Property */ ) ? localName : getUnusedName(localName, symbol); let textRange = symbol.declarations && find(symbol.declarations, (d)=>isVariableDeclaration(d)); if (textRange && isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) textRange = textRange.parent.parent; @@ -48254,7 +48727,7 @@ ${lanes.join("\n")} addResult(factory.createExportDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ node.isTypeOnly, /*exportClause*/ void 0, factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */ ); } } - if (needsPostExportDefault) addResult(factory.createExportAssignment(/*modifiers*/ void 0, /*isExportAssignment*/ false, factory.createIdentifier(getInternalSymbolName(symbol, symbolName2))), 0 /* None */ ); + if (needsPostExportDefault) addResult(factory.createExportAssignment(/*modifiers*/ void 0, /*isExportEquals*/ false, factory.createIdentifier(getInternalSymbolName(symbol, symbolName2))), 0 /* None */ ); else if (needsExportDeclaration) addResult(factory.createExportDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, factory.createNamedExports([ factory.createExportSpecifier(/*isTypeOnly*/ false, getInternalSymbolName(symbol, symbolName2), symbolName2) ])), 0 /* None */ ); @@ -48274,18 +48747,18 @@ ${lanes.join("\n")} let newModifierFlags = 0 /* None */ ; const enclosingDeclaration2 = context.enclosingDeclaration && (isJSDocTypeAlias(context.enclosingDeclaration) ? getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); if (additionalModifierFlags & 1 /* Export */ && enclosingDeclaration2 && (isExportingScope(enclosingDeclaration2) || isModuleDeclaration(enclosingDeclaration2)) && canHaveExportModifier(node)) newModifierFlags |= 1 /* Export */ ; - if (addingDeclare && !(newModifierFlags & 1 /* Export */ ) && (!enclosingDeclaration2 || !(enclosingDeclaration2.flags & 16777216 /* Ambient */ )) && (isEnumDeclaration(node) || isVariableStatement(node) || isFunctionDeclaration(node) || isClassDeclaration(node) || isModuleDeclaration(node))) newModifierFlags |= 2 /* Ambient */ ; + if (addingDeclare && !(newModifierFlags & 1 /* Export */ ) && (!enclosingDeclaration2 || !(enclosingDeclaration2.flags & 33554432 /* Ambient */ )) && (isEnumDeclaration(node) || isVariableStatement(node) || isFunctionDeclaration(node) || isClassDeclaration(node) || isModuleDeclaration(node))) newModifierFlags |= 2 /* Ambient */ ; if (additionalModifierFlags & 1024 /* Default */ && (isClassDeclaration(node) || isInterfaceDeclaration(node) || isFunctionDeclaration(node))) newModifierFlags |= 1024 /* Default */ ; if (newModifierFlags) node = factory.updateModifiers(node, newModifierFlags | getEffectiveModifierFlags(node)); } results.push(node); } function serializeTypeAlias(symbol, symbolName2, modifierFlags) { - var _a2; + var _a; const aliasType = getDeclaredTypeOfTypeAlias(symbol); const typeParams = getSymbolLinks(symbol).typeParameters; const typeParamDecls = map(typeParams, (p)=>typeParameterToDeclaration(p, context)); - const jsdocAliasDecl = (_a2 = symbol.declarations) == null ? void 0 : _a2.find(isJSDocTypeAlias); + const jsdocAliasDecl = (_a = symbol.declarations) == null ? void 0 : _a.find(isJSDocTypeAlias); const commentText = getTextOfJSDocComment(jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : void 0); const oldFlags = context.flags; context.flags |= 8388608 /* InTypeAlias */ ; @@ -48311,11 +48784,11 @@ ${lanes.join("\n")} const baseTypes = getBaseTypes(interfaceType); const baseType = length(baseTypes) ? getIntersectionType(baseTypes) : void 0; const members = flatMap(getPropertiesOfType(interfaceType), (p)=>serializePropertySymbolForInterface(p, baseType)); - const callSignatures = serializeSignatures(0 /* Call */ , interfaceType, baseType, 176 /* CallSignature */ ); - const constructSignatures = serializeSignatures(1 /* Construct */ , interfaceType, baseType, 177 /* ConstructSignature */ ); + const callSignatures = serializeSignatures(0 /* Call */ , interfaceType, baseType, 179 /* CallSignature */ ); + const constructSignatures = serializeSignatures(1 /* Construct */ , interfaceType, baseType, 180 /* ConstructSignature */ ); const indexSignatures = serializeIndexSignatures(interfaceType, baseType); const heritageClauses = !length(baseTypes) ? void 0 : [ - factory.createHeritageClause(94 /* ExtendsKeyword */ , mapDefined(baseTypes, (b)=>trySerializeAsTypeReference(b, 111551 /* Value */ ))) + factory.createHeritageClause(96 /* ExtendsKeyword */ , mapDefined(baseTypes, (b)=>trySerializeAsTypeReference(b, 111551 /* Value */ ))) ]; addResult(factory.createInterfaceDeclaration(/*modifiers*/ void 0, getInternalSymbolName(symbol, symbolName2), typeParamDecls, heritageClauses, [ ...indexSignatures, @@ -48325,10 +48798,11 @@ ${lanes.join("\n")} ]), modifierFlags); } function getNamespaceMembersForSerialization(symbol) { - return !symbol.exports ? [] : filter(arrayFrom(symbol.exports.values()), isNamespaceMember); + const exports = getExportsOfSymbol(symbol); + return !exports ? [] : filter(arrayFrom(exports.values()), (m)=>isNamespaceMember(m) && isIdentifierText(m.escapedName, 99 /* ESNext */ )); } function isTypeOnlyNamespace(symbol) { - return every(getNamespaceMembersForSerialization(symbol), (m)=>!(getAllSymbolFlags(resolveSymbol(m)) & 111551 /* Value */ )); + return every(getNamespaceMembersForSerialization(symbol), (m)=>!(getSymbolFlags(resolveSymbol(m)) & 111551 /* Value */ )); } function serializeModule(symbol, symbolName2, modifierFlags) { const members = getNamespaceMembersForSerialization(symbol); @@ -48344,12 +48818,12 @@ ${lanes.join("\n")} const localName = getInternalSymbolName(symbol, symbolName2); const nsBody = factory.createModuleBlock([ factory.createExportDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, factory.createNamedExports(mapDefined(filter(mergedMembers, (n)=>n.escapedName !== "export=" /* ExportEquals */ ), (s)=>{ - var _a2, _b; + var _a, _b; const name = unescapeLeadingUnderscores(s.escapedName); const localName2 = getInternalSymbolName(s, name); const aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s); if (containingFile && (aliasDecl ? containingFile !== getSourceFileOfNode(aliasDecl) : !some(s.declarations, (d)=>getSourceFileOfNode(d) === containingFile))) { - (_b = (_a2 = context.tracker) == null ? void 0 : _a2.reportNonlocalAugmentation) == null || _b.call(_a2, containingFile, symbol, s); + (_b = (_a = context.tracker) == null ? void 0 : _a.reportNonlocalAugmentation) == null || _b.call(_a, containingFile, symbol, s); return void 0; } const target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true); @@ -48358,7 +48832,7 @@ ${lanes.join("\n")} return factory.createExportSpecifier(/*isTypeOnly*/ false, name === targetName ? void 0 : targetName, name); }))) ]); - addResult(factory.createModuleDeclaration(/*modifiers*/ void 0, factory.createIdentifier(localName), nsBody, 16 /* Namespace */ ), 0 /* None */ ); + addResult(factory.createModuleDeclaration(/*modifiers*/ void 0, factory.createIdentifier(localName), nsBody, 32 /* Namespace */ ), 0 /* None */ ); } } function serializeEnum(symbol, symbolName2, modifierFlags) { @@ -48370,7 +48844,7 @@ ${lanes.join("\n")} function serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags) { const signatures = getSignaturesOfType(type, 0 /* Call */ ); for (const sig of signatures){ - const decl = signatureToSignatureDeclarationHelper(sig, 259 /* FunctionDeclaration */ , context, { + const decl = signatureToSignatureDeclarationHelper(sig, 262 /* FunctionDeclaration */ , context, { name: factory.createIdentifier(localName), privateSymbolVisitor: includePrivateSymbol, bundledImports: bundled @@ -48393,7 +48867,7 @@ ${lanes.join("\n")} if (length(props)) { const localVsRemoteMap = arrayToMultiMap(props, (p)=>!length(p.declarations) || some(p.declarations, (d)=>getSourceFileOfNode(d) === getSourceFileOfNode(context.enclosingDeclaration)) ? "local" : "remote"); const localProps = localVsRemoteMap.get("local") || emptyArray; - let fakespace = parseNodeFactory.createModuleDeclaration(/*modifiers*/ void 0, factory.createIdentifier(localName), factory.createModuleBlock([]), 16 /* Namespace */ ); + let fakespace = parseNodeFactory.createModuleDeclaration(/*modifiers*/ void 0, factory.createIdentifier(localName), factory.createModuleBlock([]), 32 /* Namespace */ ); setParent(fakespace, enclosingDeclaration); fakespace.locals = createSymbolTable(props); fakespace.symbol = props[0].parent; @@ -48431,7 +48905,7 @@ ${lanes.join("\n")} if (isEntityNameExpression(expr)) { if (isIdentifier(expr) && idText(expr) === "") return cleanup(/*result*/ void 0); let introducesError; - ({ introducesError: introducesError , node: expr } = trackExistingEntityName(expr, context, includePrivateSymbol)); + ({ introducesError: introducesError, node: expr } = trackExistingEntityName(expr, context, includePrivateSymbol)); if (introducesError) return cleanup(/*result*/ void 0); } return cleanup(factory.createExpressionWithTypeArguments(expr, map(e.typeArguments, (a)=>serializeExistingTypeNode(context, a, includePrivateSymbol, bundled) || typeToTypeNodeHelper(getTypeFromTypeNode(a), context)))); @@ -48444,13 +48918,13 @@ ${lanes.join("\n")} return void 0; } function serializeAsClass(symbol, localName, modifierFlags) { - var _a2, _b; - const originalDecl = (_a2 = symbol.declarations) == null ? void 0 : _a2.find(isClassLike); + var _a, _b; + const originalDecl = (_a = symbol.declarations) == null ? void 0 : _a.find(isClassLike); const oldEnclosing = context.enclosingDeclaration; context.enclosingDeclaration = originalDecl || oldEnclosing; const localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); const typeParamDecls = map(localParams, (p)=>typeParameterToDeclaration(p, context)); - const classType = getDeclaredTypeOfClassOrInterface(symbol); + const classType = getTypeWithThisArgument(getDeclaredTypeOfClassOrInterface(symbol)); const baseTypes = getBaseTypes(classType); const originalImplements = originalDecl && getEffectiveImplementsTypeNodes(originalDecl); const implementsExpressions = originalImplements && sanitizeJSDocImplements(originalImplements) || mapDefined(getImplementsTypes(classType), serializeImplementedType); @@ -48459,10 +48933,10 @@ ${lanes.join("\n")} const staticBaseType = isClass ? getBaseConstructorTypeOfClass(staticType) : anyType; const heritageClauses = [ ...!length(baseTypes) ? [] : [ - factory.createHeritageClause(94 /* ExtendsKeyword */ , map(baseTypes, (b)=>serializeBaseType(b, staticBaseType, localName))) + factory.createHeritageClause(96 /* ExtendsKeyword */ , map(baseTypes, (b)=>serializeBaseType(b, staticBaseType, localName))) ], ...!length(implementsExpressions) ? [] : [ - factory.createHeritageClause(117 /* ImplementsKeyword */ , implementsExpressions) + factory.createHeritageClause(119 /* ImplementsKeyword */ , implementsExpressions) ] ]; const symbolProps = getNonInheritedProperties(classType, baseTypes, getPropertiesOfType(classType)); @@ -48482,7 +48956,7 @@ ${lanes.join("\n")} const isNonConstructableClassLikeInJsFile = !isClass && !!symbol.valueDeclaration && isInJSFile(symbol.valueDeclaration) && !some(getSignaturesOfType(staticType, 1 /* Construct */ )); const constructors = isNonConstructableClassLikeInJsFile ? [ factory.createConstructorDeclaration(factory.createModifiersFromModifierFlags(8 /* Private */ ), [], /*body*/ void 0) - ] : serializeSignatures(1 /* Construct */ , staticType, staticBaseType, 173 /* Constructor */ ); + ] : serializeSignatures(1 /* Construct */ , staticType, staticBaseType, 176 /* Constructor */ ); const indexSignatures = serializeIndexSignatures(classType, baseTypes[0]); context.enclosingDeclaration = oldEnclosing; addResult(setTextRange(factory.createClassDeclaration(/*modifiers*/ void 0, localName, typeParamDecls, heritageClauses, [ @@ -48508,7 +48982,7 @@ ${lanes.join("\n")} }); } function serializeAsAlias(symbol, localName, modifierFlags) { - var _a2, _b, _c, _d, _e; + var _a, _b, _c, _d, _e; const node = getDeclarationOfAliasSymbol(symbol); if (!node) return Debug.fail(); const target = getMergedSymbol(getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true)); @@ -48518,21 +48992,21 @@ ${lanes.join("\n")} const targetName = getInternalSymbolName(target, verbatimTargetName); includePrivateSymbol(target); switch(node.kind){ - case 205 /* BindingElement */ : - if (((_b = (_a2 = node.parent) == null ? void 0 : _a2.parent) == null ? void 0 : _b.kind) === 257 /* VariableDeclaration */ ) { + case 208 /* BindingElement */ : + if (((_b = (_a = node.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.kind) === 260 /* VariableDeclaration */ ) { const specifier2 = getSpecifierForModuleSymbol(target.parent || target, context); - const { propertyName: propertyName } = node; + const { propertyName: propertyName } = node; addResult(factory.createImportDeclaration(/*modifiers*/ void 0, factory.createImportClause(/*isTypeOnly*/ false, /*name*/ void 0, factory.createNamedImports([ factory.createImportSpecifier(/*isTypeOnly*/ false, propertyName && isIdentifier(propertyName) ? factory.createIdentifier(idText(propertyName)) : void 0, factory.createIdentifier(localName)) - ])), factory.createStringLiteral(specifier2), /*importClause*/ void 0), 0 /* None */ ); + ])), factory.createStringLiteral(specifier2), /*assertClause*/ void 0), 0 /* None */ ); break; } Debug.failBadSyntaxKind(((_c = node.parent) == null ? void 0 : _c.parent) || node, "Unhandled binding element grandparent kind in declaration serialization"); break; - case 300 /* ShorthandPropertyAssignment */ : - if (((_e = (_d = node.parent) == null ? void 0 : _d.parent) == null ? void 0 : _e.kind) === 223 /* BinaryExpression */ ) serializeExportSpecifier(unescapeLeadingUnderscores(symbol.escapedName), targetName); + case 304 /* ShorthandPropertyAssignment */ : + if (((_e = (_d = node.parent) == null ? void 0 : _d.parent) == null ? void 0 : _e.kind) === 226 /* BinaryExpression */ ) serializeExportSpecifier(unescapeLeadingUnderscores(symbol.escapedName), targetName); break; - case 257 /* VariableDeclaration */ : + case 260 /* VariableDeclaration */ : if (isPropertyAccessExpression(node.initializer)) { const initializer = node.initializer; const uniqueName = factory.createUniqueName(localName); @@ -48541,7 +49015,7 @@ ${lanes.join("\n")} addResult(factory.createImportEqualsDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, factory.createIdentifier(localName), factory.createQualifiedName(uniqueName, initializer.name)), modifierFlags); break; } - case 268 /* ImportEqualsDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : if (target.escapedName === "export=" /* ExportEquals */ && some(target.declarations, (d)=>isSourceFile(d) && isJsonSourceFile(d))) { serializeMaybeAliasAssignment(symbol); break; @@ -48549,45 +49023,45 @@ ${lanes.join("\n")} const isLocalImport = !(target.flags & 512 /* ValueModule */ ) && !isVariableDeclaration(node); addResult(factory.createImportEqualsDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, factory.createIdentifier(localName), isLocalImport ? symbolToName(target, context, 67108863 /* All */ , /*expectsIdentifier*/ false) : factory.createExternalModuleReference(factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)))), isLocalImport ? modifierFlags : 0 /* None */ ); break; - case 267 /* NamespaceExportDeclaration */ : + case 270 /* NamespaceExportDeclaration */ : addResult(factory.createNamespaceExportDeclaration(idText(node.name)), 0 /* None */ ); break; - case 270 /* ImportClause */ : + case 273 /* ImportClause */ : { const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context); const specifier2 = bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.moduleSpecifier; addResult(factory.createImportDeclaration(/*modifiers*/ void 0, factory.createImportClause(/*isTypeOnly*/ false, factory.createIdentifier(localName), /*namedBindings*/ void 0), specifier2, node.parent.assertClause), 0 /* None */ ); break; } - case 271 /* NamespaceImport */ : + case 274 /* NamespaceImport */ : { const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context); const specifier2 = bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.parent.moduleSpecifier; - addResult(factory.createImportDeclaration(/*modifiers*/ void 0, factory.createImportClause(/*isTypeOnly*/ false, /*importClause*/ void 0, factory.createNamespaceImport(factory.createIdentifier(localName))), specifier2, node.parent.parent.assertClause), 0 /* None */ ); + addResult(factory.createImportDeclaration(/*modifiers*/ void 0, factory.createImportClause(/*isTypeOnly*/ false, /*name*/ void 0, factory.createNamespaceImport(factory.createIdentifier(localName))), specifier2, node.parent.parent.assertClause), 0 /* None */ ); break; } - case 277 /* NamespaceExport */ : + case 280 /* NamespaceExport */ : addResult(factory.createExportDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, factory.createNamespaceExport(factory.createIdentifier(localName)), factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */ ); break; - case 273 /* ImportSpecifier */ : + case 276 /* ImportSpecifier */ : { const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context); const specifier2 = bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.parent.parent.moduleSpecifier; - addResult(factory.createImportDeclaration(/*modifiers*/ void 0, factory.createImportClause(/*isTypeOnly*/ false, /*importClause*/ void 0, factory.createNamedImports([ + addResult(factory.createImportDeclaration(/*modifiers*/ void 0, factory.createImportClause(/*isTypeOnly*/ false, /*name*/ void 0, factory.createNamedImports([ factory.createImportSpecifier(/*isTypeOnly*/ false, localName !== verbatimTargetName ? factory.createIdentifier(verbatimTargetName) : void 0, factory.createIdentifier(localName)) ])), specifier2, node.parent.parent.parent.assertClause), 0 /* None */ ); break; } - case 278 /* ExportSpecifier */ : + case 281 /* ExportSpecifier */ : const specifier = node.parent.parent.moduleSpecifier; serializeExportSpecifier(unescapeLeadingUnderscores(symbol.escapedName), specifier ? verbatimTargetName : targetName, specifier && isStringLiteralLike(specifier) ? factory.createStringLiteral(specifier.text) : void 0); break; - case 274 /* ExportAssignment */ : + case 277 /* ExportAssignment */ : serializeMaybeAliasAssignment(symbol); break; - case 223 /* BinaryExpression */ : - case 208 /* PropertyAccessExpression */ : - case 209 /* ElementAccessExpression */ : + case 226 /* BinaryExpression */ : + case 211 /* PropertyAccessExpression */ : + case 212 /* ElementAccessExpression */ : if (symbol.escapedName === "default" /* Default */ || symbol.escapedName === "export=" /* ExportEquals */ ) serializeMaybeAliasAssignment(symbol); else serializeExportSpecifier(localName, targetName); break; @@ -48601,6 +49075,7 @@ ${lanes.join("\n")} ]), specifier), 0 /* None */ ); } function serializeMaybeAliasAssignment(symbol) { + var _a; if (symbol.flags & 4194304 /* Prototype */ ) return false; const name = unescapeLeadingUnderscores(symbol.escapedName); const isExportEquals = name === "export=" /* ExportEquals */ ; @@ -48634,7 +49109,7 @@ ${lanes.join("\n")} else { const statement = factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ factory.createVariableDeclaration(varName, /*exclamationToken*/ void 0, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled)) - ], 2 /* Const */ )); + ], ((_a = context.enclosingDeclaration) == null ? void 0 : _a.kind) === 267 /* ModuleDeclaration */ ? 1 /* Let */ : 2 /* Const */ )); addResult(statement, target && target.flags & 4 /* Property */ && target.escapedName === "export=" /* ExportEquals */ ? 2 /* Ambient */ : name === varName ? 1 /* Export */ : 0 /* None */ ); } if (isExportAssignmentCompatibleSymbolName) { @@ -48655,14 +49130,14 @@ ${lanes.join("\n")} } function makeSerializePropertySymbol(createProperty2, methodKind, useAccessors) { return function serializePropertySymbol(p, isStatic2, baseType) { - var _a2, _b, _c, _d, _e; + var _a, _b, _c, _d, _e; const modifierFlags = getDeclarationModifierFlagsFromSymbol(p); const isPrivate = !!(modifierFlags & 8 /* Private */ ); if (isStatic2 && p.flags & 2887656 /* Alias */ ) return []; - if (p.flags & 4194304 /* Prototype */ || baseType && getPropertyOfType(baseType, p.escapedName) && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p) && (p.flags & 16777216 /* Optional */ ) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */ ) && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName))) return []; + if (p.flags & 4194304 /* Prototype */ || p.escapedName === "constructor" || baseType && getPropertyOfType(baseType, p.escapedName) && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p) && (p.flags & 16777216 /* Optional */ ) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */ ) && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName))) return []; const flag = modifierFlags & -513 /* Async */ | (isStatic2 ? 32 /* Static */ : 0); const name = getPropertyNameNodeForSymbol(p, context); - const firstPropertyLikeDecl = (_a2 = p.declarations) == null ? void 0 : _a2.find(or(isPropertyDeclaration, isAccessor, isVariableDeclaration, isPropertySignature, isBinaryExpression, isPropertyAccessExpression)); + const firstPropertyLikeDecl = (_a = p.declarations) == null ? void 0 : _a.find(or(isPropertyDeclaration, isAccessor, isVariableDeclaration, isPropertySignature, isBinaryExpression, isPropertyAccessExpression)); if (p.flags & 98304 /* Accessor */ && useAccessors) { const result = []; if (p.flags & 65536 /* SetAccessor */ ) result.push(setTextRange(factory.createSetAccessorDeclaration(factory.createModifiersFromModifierFlags(flag), name, [ @@ -48673,18 +49148,18 @@ ${lanes.join("\n")} result.push(setTextRange(factory.createGetAccessorDeclaration(factory.createModifiersFromModifierFlags(flag), name, [], isPrivate2 ? void 0 : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), /*body*/ void 0), ((_c = p.declarations) == null ? void 0 : _c.find(isGetAccessor)) || firstPropertyLikeDecl)); } return result; - } else if (p.flags & 98311 /* Accessor */ ) return setTextRange(createProperty2(factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? factory.createToken(57 /* QuestionToken */ ) : void 0, isPrivate ? void 0 : serializeTypeForDeclaration(context, getWriteTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 + } else if (p.flags & 98311 /* Accessor */ ) return setTextRange(createProperty2(factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */ ) : void 0, isPrivate ? void 0 : serializeTypeForDeclaration(context, getWriteTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 // interface members can't have initializers, however class members _can_ /*initializer*/ void 0), ((_d = p.declarations) == null ? void 0 : _d.find(or(isPropertyDeclaration, isVariableDeclaration))) || firstPropertyLikeDecl); if (p.flags & 8208 /* Function */ ) { const type = getTypeOfSymbol(p); const signatures = getSignaturesOfType(type, 0 /* Call */ ); - if (flag & 8 /* Private */ ) return setTextRange(createProperty2(factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? factory.createToken(57 /* QuestionToken */ ) : void 0, /*type*/ void 0, /*initializer*/ void 0), ((_e = p.declarations) == null ? void 0 : _e.find(isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]); + if (flag & 8 /* Private */ ) return setTextRange(createProperty2(factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */ ) : void 0, /*type*/ void 0, /*initializer*/ void 0), ((_e = p.declarations) == null ? void 0 : _e.find(isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]); const results2 = []; for (const sig of signatures){ const decl = signatureToSignatureDeclarationHelper(sig, methodKind, context, { name: name, - questionToken: p.flags & 16777216 /* Optional */ ? factory.createToken(57 /* QuestionToken */ ) : void 0, + questionToken: p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */ ) : void 0, modifiers: flag ? factory.createModifiersFromModifierFlags(flag) : void 0 }); const location = sig.declaration && isPrototypePropertyAssignment(sig.declaration.parent) ? sig.declaration.parent : sig.declaration; @@ -48748,7 +49223,7 @@ ${lanes.join("\n")} factory.createVariableDeclaration(tempName, /*exclamationToken*/ void 0, typeToTypeNodeHelper(staticType, context)) ], 2 /* Const */ )); addResult(statement, 0 /* None */ ); - return factory.createExpressionWithTypeArguments(factory.createIdentifier(tempName), /*typeArgs*/ void 0); + return factory.createExpressionWithTypeArguments(factory.createIdentifier(tempName), /*typeArguments*/ void 0); } function trySerializeAsTypeReference(t, flags) { let typeArgs; @@ -48762,10 +49237,10 @@ ${lanes.join("\n")} function serializeImplementedType(t) { const ref = trySerializeAsTypeReference(t, 788968 /* Type */ ); if (ref) return ref; - if (t.symbol) return factory.createExpressionWithTypeArguments(symbolToExpression(t.symbol, context, 788968 /* Type */ ), /*typeArgs*/ void 0); + if (t.symbol) return factory.createExpressionWithTypeArguments(symbolToExpression(t.symbol, context, 788968 /* Type */ ), /*typeArguments*/ void 0); } function getUnusedName(input, symbol) { - var _a2, _b; + var _a, _b; const id = symbol ? getSymbolId(symbol) : void 0; if (id) { if (context.remappedSymbolNames.has(id)) return context.remappedSymbolNames.get(id); @@ -48773,7 +49248,7 @@ ${lanes.join("\n")} if (symbol) input = getNameCandidateWorker(symbol, input); let i = 0; const original = input; - while((_a2 = context.usedSymbolNames) == null ? void 0 : _a2.has(input)){ + while((_a = context.usedSymbolNames) == null ? void 0 : _a.has(input)){ i++; input = `${original}_${i}`; } @@ -48806,7 +49281,7 @@ ${lanes.join("\n")} function typePredicateToString(typePredicate, enclosingDeclaration, flags = 16384 /* UseAliasDefinedOutsideCurrentScope */ , writer) { return writer ? typePredicateToStringWorker(writer).getText() : usingSingleLineStringWriter(typePredicateToStringWorker); function typePredicateToStringWorker(writer2) { - const predicate = factory.createTypePredicateNode(typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? factory.createToken(129 /* AssertsKeyword */ ) : void 0, typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? factory.createIdentifier(typePredicate.parameterName) : factory.createThisTypeNode(), typePredicate.type && nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70222336 /* WriteTypeParametersInQualifiedName */ )); + const predicate = factory.createTypePredicateNode(typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? factory.createToken(131 /* AssertsKeyword */ ) : void 0, typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? factory.createIdentifier(typePredicate.parameterName) : factory.createThisTypeNode(), typePredicate.type && nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70222336 /* WriteTypeParametersInQualifiedName */ )); const printer = createPrinterWithRemoveComments(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */ , predicate, /*sourceFile*/ sourceFile, writer2); @@ -48851,10 +49326,10 @@ ${lanes.join("\n")} return void 0; } function isTopLevelInExternalModuleAugmentation(node) { - return node && node.parent && node.parent.kind === 265 /* ModuleBlock */ && isExternalModuleAugmentation(node.parent.parent); + return node && node.parent && node.parent.kind === 268 /* ModuleBlock */ && isExternalModuleAugmentation(node.parent.parent); } function isDefaultBindingContext(location) { - return location.kind === 308 /* SourceFile */ || isAmbientModule(location); + return location.kind === 312 /* SourceFile */ || isAmbientModule(location); } function getNameOfSymbolFromNameType(symbol, context) { const nameType = getSymbolLinks(symbol).nameType; @@ -48888,13 +49363,13 @@ ${lanes.join("\n")} return declarationNameToString(name2); } if (!declaration) declaration = symbol.declarations[0]; - if (declaration.parent && declaration.parent.kind === 257 /* VariableDeclaration */ ) return declarationNameToString(declaration.parent.name); + if (declaration.parent && declaration.parent.kind === 260 /* VariableDeclaration */ ) return declarationNameToString(declaration.parent.name); switch(declaration.kind){ - case 228 /* ClassExpression */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : + case 231 /* ClassExpression */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */ )) context.encounteredError = true; - return declaration.kind === 228 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; + return declaration.kind === 231 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; } } const name = getNameOfSymbolFromNameType(symbol, context); @@ -48909,58 +49384,58 @@ ${lanes.join("\n")} return false; function determineIfDeclarationIsVisible() { switch(node.kind){ - case 341 /* JSDocCallbackTag */ : - case 349 /* JSDocTypedefTag */ : - case 343 /* JSDocEnumTag */ : + case 345 /* JSDocCallbackTag */ : + case 353 /* JSDocTypedefTag */ : + case 347 /* JSDocEnumTag */ : return !!(node.parent && node.parent.parent && node.parent.parent.parent && isSourceFile(node.parent.parent.parent)); - case 205 /* BindingElement */ : + case 208 /* BindingElement */ : return isDeclarationVisible(node.parent.parent); - case 257 /* VariableDeclaration */ : + case 260 /* VariableDeclaration */ : if (isBindingPattern(node.name) && !node.name.elements.length) return false; - case 264 /* ModuleDeclaration */ : - case 260 /* ClassDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 262 /* TypeAliasDeclaration */ : - case 259 /* FunctionDeclaration */ : - case 263 /* EnumDeclaration */ : - case 268 /* ImportEqualsDeclaration */ : + case 267 /* ModuleDeclaration */ : + case 263 /* ClassDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 265 /* TypeAliasDeclaration */ : + case 262 /* FunctionDeclaration */ : + case 266 /* EnumDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : if (isExternalModuleAugmentation(node)) return true; const parent2 = getDeclarationContainer(node); - if (!(getCombinedModifierFlags(node) & 1 /* Export */ ) && !(node.kind !== 268 /* ImportEqualsDeclaration */ && parent2.kind !== 308 /* SourceFile */ && parent2.flags & 16777216 /* Ambient */ )) return isGlobalSourceFile(parent2); + if (!(getCombinedModifierFlagsCached(node) & 1 /* Export */ ) && !(node.kind !== 271 /* ImportEqualsDeclaration */ && parent2.kind !== 312 /* SourceFile */ && parent2.flags & 33554432 /* Ambient */ )) return isGlobalSourceFile(parent2); return isDeclarationVisible(parent2); - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : if (hasEffectiveModifier(node, 24 /* Protected */ )) return false; - case 173 /* Constructor */ : - case 177 /* ConstructSignature */ : - case 176 /* CallSignature */ : - case 178 /* IndexSignature */ : - case 166 /* Parameter */ : - case 265 /* ModuleBlock */ : - case 181 /* FunctionType */ : - case 182 /* ConstructorType */ : - case 184 /* TypeLiteral */ : - case 180 /* TypeReference */ : - case 185 /* ArrayType */ : - case 186 /* TupleType */ : - case 189 /* UnionType */ : - case 190 /* IntersectionType */ : - case 193 /* ParenthesizedType */ : - case 199 /* NamedTupleMember */ : + case 176 /* Constructor */ : + case 180 /* ConstructSignature */ : + case 179 /* CallSignature */ : + case 181 /* IndexSignature */ : + case 169 /* Parameter */ : + case 268 /* ModuleBlock */ : + case 184 /* FunctionType */ : + case 185 /* ConstructorType */ : + case 187 /* TypeLiteral */ : + case 183 /* TypeReference */ : + case 188 /* ArrayType */ : + case 189 /* TupleType */ : + case 192 /* UnionType */ : + case 193 /* IntersectionType */ : + case 196 /* ParenthesizedType */ : + case 202 /* NamedTupleMember */ : return isDeclarationVisible(node.parent); - case 270 /* ImportClause */ : - case 271 /* NamespaceImport */ : - case 273 /* ImportSpecifier */ : + case 273 /* ImportClause */ : + case 274 /* NamespaceImport */ : + case 276 /* ImportSpecifier */ : return false; - case 165 /* TypeParameter */ : - case 308 /* SourceFile */ : - case 267 /* NamespaceExportDeclaration */ : + case 168 /* TypeParameter */ : + case 312 /* SourceFile */ : + case 270 /* NamespaceExportDeclaration */ : return true; - case 274 /* ExportAssignment */ : + case 277 /* ExportAssignment */ : return false; default: return false; @@ -48969,8 +49444,8 @@ ${lanes.join("\n")} } function collectLinkedAliases(node, setVisibility) { let exportSymbol; - if (node.parent && node.parent.kind === 274 /* ExportAssignment */ ) exportSymbol = resolveName(node, node.escapedText, 2998271 /* Alias */ , /*nameNotFoundMessage*/ void 0, node, /*isUse*/ false); - else if (node.parent.kind === 278 /* ExportSpecifier */ ) exportSymbol = getTargetOfExportSpecifier(node.parent, 2998271 /* Alias */ ); + if (node.parent && node.parent.kind === 277 /* ExportAssignment */ ) exportSymbol = resolveName(node, node.escapedText, 2998271 /* Alias */ , /*nameNotFoundMessage*/ void 0, node, /*isUse*/ false); + else if (node.parent.kind === 281 /* ExportSpecifier */ ) exportSymbol = getTargetOfExportSpecifier(node.parent, 2998271 /* Alias */ ); let result; let visited; if (exportSymbol) { @@ -48990,7 +49465,7 @@ ${lanes.join("\n")} if (isInternalModuleImportEqualsDeclaration(declaration)) { const internalModuleReference = declaration.moduleReference; const firstIdentifier = getFirstIdentifier(internalModuleReference); - const importSymbol = resolveName(declaration, firstIdentifier.escapedText, 901119 /* Namespace */ , void 0, void 0, /*isUse*/ false); + const importSymbol = resolveName(declaration, firstIdentifier.escapedText, 901119 /* Namespace */ , /*nameNotFoundMessage*/ void 0, /*nameArg*/ void 0, /*isUse*/ false); if (importSymbol && visited) { if (tryAddToSet(visited, getSymbolId(importSymbol))) buildVisibleNodeList(importSymbol.declarations); } @@ -49001,7 +49476,7 @@ ${lanes.join("\n")} function pushTypeResolution(target, propertyName) { const resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { - const { length: length2 } = resolutionTargets; + const { length: length2 } = resolutionTargets; for(let i = resolutionCycleStartIndex; i < length2; i++)resolutionResults[i] = false; return false; } @@ -49011,7 +49486,7 @@ ${lanes.join("\n")} return true; } function findResolutionCycleStartIndex(target, propertyName) { - for(let i = resolutionTargets.length - 1; i >= 0; i--){ + for(let i = resolutionTargets.length - 1; i >= resolutionStart; i--){ if (resolutionTargetHasProperty(resolutionTargets[i], resolutionPropertyNames[i])) return -1; if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) return i; } @@ -49050,12 +49525,12 @@ ${lanes.join("\n")} function getDeclarationContainer(node) { return findAncestor(getRootDeclaration(node), (node2)=>{ switch(node2.kind){ - case 257 /* VariableDeclaration */ : - case 258 /* VariableDeclarationList */ : - case 273 /* ImportSpecifier */ : - case 272 /* NamedImports */ : - case 271 /* NamespaceImport */ : - case 270 /* ImportClause */ : + case 260 /* VariableDeclaration */ : + case 261 /* VariableDeclarationList */ : + case 276 /* ImportSpecifier */ : + case 275 /* NamedImports */ : + case 274 /* NamespaceImport */ : + case 273 /* ImportClause */ : return false; default: return true; @@ -49071,8 +49546,13 @@ ${lanes.join("\n")} return prop ? getTypeOfSymbol(prop) : void 0; } function getTypeOfPropertyOrIndexSignature(type, name) { - var _a2; - return getTypeOfPropertyOfType(type, name) || ((_a2 = getApplicableIndexInfoForName(type, name)) == null ? void 0 : _a2.type) || unknownType; + var _a; + return getTypeOfPropertyOfType(type, name) || ((_a = getApplicableIndexInfoForName(type, name)) == null ? void 0 : _a.type) || unknownType; + } + function getTypeOfPropertyOrIndexSignatureOfType(type, name) { + var _a; + let propType; + return getTypeOfPropertyOfType(type, name) || (propType = (_a = getApplicableIndexInfoForName(type, name)) == null ? void 0 : _a.type) && addOptionality(propType, /*isProperty*/ true, /*isOptional*/ true); } function isTypeAny(type) { return type && (type.flags & 1 /* Any */ ) !== 0; @@ -49146,21 +49626,21 @@ ${lanes.join("\n")} function getParentElementAccess(node) { const ancestor = node.parent.parent; switch(ancestor.kind){ - case 205 /* BindingElement */ : - case 299 /* PropertyAssignment */ : + case 208 /* BindingElement */ : + case 303 /* PropertyAssignment */ : return getSyntheticElementAccess(ancestor); - case 206 /* ArrayLiteralExpression */ : + case 209 /* ArrayLiteralExpression */ : return getSyntheticElementAccess(node.parent); - case 257 /* VariableDeclaration */ : + case 260 /* VariableDeclaration */ : return ancestor.initializer; - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : return ancestor.right; } } function getDestructuringPropertyName(node) { const parent2 = node.parent; - if (node.kind === 205 /* BindingElement */ && parent2.kind === 203 /* ObjectBindingPattern */ ) return getLiteralPropertyNameText(node.propertyName || node.name); - if (node.kind === 299 /* PropertyAssignment */ || node.kind === 300 /* ShorthandPropertyAssignment */ ) return getLiteralPropertyNameText(node.name); + if (node.kind === 208 /* BindingElement */ && parent2.kind === 206 /* ObjectBindingPattern */ ) return getLiteralPropertyNameText(node.propertyName || node.name); + if (node.kind === 303 /* PropertyAssignment */ || node.kind === 304 /* ShorthandPropertyAssignment */ ) return getLiteralPropertyNameText(node.name); return "" + parent2.elements.indexOf(node); } function getLiteralPropertyNameText(name) { @@ -49175,14 +49655,14 @@ ${lanes.join("\n")} function getBindingElementTypeFromParentType(declaration, parentType) { if (isTypeAny(parentType)) return parentType; const pattern = declaration.parent; - if (strictNullChecks && declaration.flags & 16777216 /* Ambient */ && isParameterDeclaration(declaration)) parentType = getNonNullableType(parentType); + if (strictNullChecks && declaration.flags & 33554432 /* Ambient */ && isParameterDeclaration(declaration)) parentType = getNonNullableType(parentType); else if (strictNullChecks && pattern.parent.initializer && !(getTypeFacts(getTypeOfInitializer(pattern.parent.initializer)) & 65536 /* EQUndefined */ )) parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */ ); let type; - if (pattern.kind === 203 /* ObjectBindingPattern */ ) { + if (pattern.kind === 206 /* ObjectBindingPattern */ ) { if (declaration.dotDotDotToken) { parentType = getReducedType(parentType); if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { - error(declaration, Diagnostics.Rest_types_may_only_be_created_from_object_types); + error2(declaration, Diagnostics.Rest_types_may_only_be_created_from_object_types); return errorType; } const literalMembers = []; @@ -49198,7 +49678,7 @@ ${lanes.join("\n")} const elementType = checkIteratedTypeOrElementType(65 /* Destructuring */ | (declaration.dotDotDotToken ? 0 : 128 /* PossiblyOutOfBounds */ ), parentType, undefinedType, pattern); const index = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - const baseConstraint = getBaseConstraintOrType(parentType); + const baseConstraint = mapType(parentType, (t)=>t.flags & 58982400 /* InstantiableNonPrimitive */ ? getBaseConstraintOrType(t) : t); type = everyType(baseConstraint, isTupleType) ? mapType(baseConstraint, (t)=>sliceTupleType(t, index)) : createArrayType(elementType); } else if (isArrayLikeType(parentType)) { const indexType = getNumberLiteralType(index); @@ -49221,21 +49701,21 @@ ${lanes.join("\n")} } function isNullOrUndefined3(node) { const expr = skipParentheses(node, /*excludeJSDocTypeAssertions*/ true); - return expr.kind === 104 /* NullKeyword */ || expr.kind === 79 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; + return expr.kind === 106 /* NullKeyword */ || expr.kind === 80 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; } function isEmptyArrayLiteral2(node) { const expr = skipParentheses(node, /*excludeJSDocTypeAssertions*/ true); - return expr.kind === 206 /* ArrayLiteralExpression */ && expr.elements.length === 0; + return expr.kind === 209 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, isProperty = false, isOptional = true) { return strictNullChecks && isOptional ? getOptionalType(type, isProperty) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality, checkMode) { - if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === 246 /* ForInStatement */ ) { + if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === 249 /* ForInStatement */ ) { const indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression, /*checkMode*/ checkMode))); return indexType.flags & 4456448 /* Index */ ? getExtractStringType(indexType) : stringType; } - if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === 247 /* ForOfStatement */ ) { + if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === 250 /* ForOfStatement */ ) { const forOfStatement = declaration.parent.parent; return checkRightHandSideOfForOf(forOfStatement) || anyType; } @@ -49248,14 +49728,14 @@ ${lanes.join("\n")} return useUnknownInCatchVariables ? unknownType : anyType; } if (declaredType) return addOptionality(declaredType, isProperty, isOptional); - if ((noImplicitAny || isInJSFile(declaration)) && isVariableDeclaration(declaration) && !isBindingPattern(declaration.name) && !(getCombinedModifierFlags(declaration) & 1 /* Export */ ) && !(declaration.flags & 16777216 /* Ambient */ )) { - if (!(getCombinedNodeFlags(declaration) & 2 /* Const */ ) && (!declaration.initializer || isNullOrUndefined3(declaration.initializer))) return autoType; + if ((noImplicitAny || isInJSFile(declaration)) && isVariableDeclaration(declaration) && !isBindingPattern(declaration.name) && !(getCombinedModifierFlagsCached(declaration) & 1 /* Export */ ) && !(declaration.flags & 33554432 /* Ambient */ )) { + if (!(getCombinedNodeFlagsCached(declaration) & 6 /* Constant */ ) && (!declaration.initializer || isNullOrUndefined3(declaration.initializer))) return autoType; if (declaration.initializer && isEmptyArrayLiteral2(declaration.initializer)) return autoArrayType; } if (isParameter(declaration)) { const func = declaration.parent; - if (func.kind === 175 /* SetAccessor */ && hasBindableName(func)) { - const getter = getDeclarationOfKind(getSymbolOfDeclaration(declaration.parent), 174 /* GetAccessor */ ); + if (func.kind === 178 /* SetAccessor */ && hasBindableName(func)) { + const getter = getDeclarationOfKind(getSymbolOfDeclaration(declaration.parent), 177 /* GetAccessor */ ); if (getter) { const getterSignature = getSignatureFromDeclaration(getter); const thisParameter = getAccessorThisParameter(func); @@ -49299,7 +49779,7 @@ ${lanes.join("\n")} const links = getSymbolLinks(symbol); if (links.isConstructorDeclaredProperty === void 0) { links.isConstructorDeclaredProperty = false; - links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && every(symbol.declarations, (declaration)=>isBinaryExpression(declaration) && isPossiblyAliasedThisProperty(declaration) && (declaration.left.kind !== 209 /* ElementAccessExpression */ || isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && !getAnnotatedTypeForAssignmentDeclaration(/*declaredType*/ void 0, declaration, symbol, declaration)); + links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && every(symbol.declarations, (declaration)=>isBinaryExpression(declaration) && isPossiblyAliasedThisProperty(declaration) && (declaration.left.kind !== 212 /* ElementAccessExpression */ || isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && !getAnnotatedTypeForAssignmentDeclaration(/*declaredType*/ void 0, declaration, symbol, declaration)); } return links.isConstructorDeclaredProperty; } @@ -49313,7 +49793,7 @@ ${lanes.join("\n")} if (!symbol.declarations) return; for (const declaration of symbol.declarations){ const container = getThisContainer(declaration, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false); - if (container && (container.kind === 173 /* Constructor */ || isJSConstructor(container))) return container; + if (container && (container.kind === 176 /* Constructor */ || isJSConstructor(container))) return container; } } function getFlowTypeFromCommonJSExport(symbol) { @@ -49335,7 +49815,7 @@ ${lanes.join("\n")} setParent(reference, staticBlock); reference.flowNode = staticBlock.returnFlowNode; const flowType = getFlowTypeOfProperty(reference, symbol); - if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) error(symbol.valueDeclaration, Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) error2(symbol.valueDeclaration, Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); if (everyType(flowType, isNullableType)) continue; return convertAutoToAny(flowType); } @@ -49347,7 +49827,7 @@ ${lanes.join("\n")} setParent(reference, constructor); reference.flowNode = constructor.returnFlowNode; const flowType = getFlowTypeOfProperty(reference, symbol); - if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) error(symbol.valueDeclaration, Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) error2(symbol.valueDeclaration, Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); return everyType(flowType, isNullableType) ? void 0 : convertAutoToAny(flowType); } function getFlowTypeOfProperty(reference, prop) { @@ -49398,19 +49878,19 @@ ${lanes.join("\n")} } } const widened = getWidenedType(addOptionality(type, /*isProperty*/ false, definedInMethod && !definedInConstructor)); - if (symbol.valueDeclaration && filterType(widened, (t)=>!!(t.flags & -98305 /* Nullable */ )) === neverType) { + if (symbol.valueDeclaration && isInJSFile(symbol.valueDeclaration) && filterType(widened, (t)=>!!(t.flags & -98305 /* Nullable */ )) === neverType) { reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } return widened; } function getJSContainerObjectType(decl, symbol, init) { - var _a2, _b; + var _a, _b; if (!isInJSFile(decl) || !init || !isObjectLiteralExpression(init) || init.properties.length) return void 0; const exports = createSymbolTable(); while(isBinaryExpression(decl) || isPropertyAccessExpression(decl)){ const s2 = getSymbolOfNode(decl); - if ((_a2 = s2 == null ? void 0 : s2.exports) == null ? void 0 : _a2.size) mergeSymbolTable(exports, s2.exports); + if ((_a = s2 == null ? void 0 : s2.exports) == null ? void 0 : _a.size) mergeSymbolTable(exports, s2.exports); decl = isBinaryExpression(decl) ? decl.parent : decl.parent.parent; } const s = getSymbolOfNode(decl); @@ -49420,14 +49900,14 @@ ${lanes.join("\n")} return type; } function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) { - var _a2; + var _a; const typeNode = getEffectiveTypeAnnotationNode(expression.parent); if (typeNode) { const type = getWidenedType(getTypeFromTypeNode(typeNode)); if (!declaredType) return type; else if (!isErrorType(declaredType) && !isErrorType(type) && !isTypeIdenticalTo(declaredType, type)) errorNextVariableOrPropertyDeclarationMustHaveSameType(/*firstDeclaration*/ void 0, declaredType, declaration, type); } - if ((_a2 = symbol.parent) == null ? void 0 : _a2.valueDeclaration) { + if ((_a = symbol.parent) == null ? void 0 : _a.valueDeclaration) { const typeNode2 = getEffectiveTypeAnnotationNode(symbol.parent.valueDeclaration); if (typeNode2) { const annotationSymbol = getPropertyOfType(getTypeFromTypeNode(typeNode2), symbol.escapedName); @@ -49464,15 +49944,15 @@ ${lanes.join("\n")} const initialSize = members.size; if (resolvedSymbol && !resolvedSymbol.exports) resolvedSymbol.exports = createSymbolTable(); (resolvedSymbol || symbol).exports.forEach((s, name)=>{ - var _a2; + var _a; const exportedMember = members.get(name); if (exportedMember && exportedMember !== s && !(s.flags & 2097152 /* Alias */ )) { if (s.flags & 111551 /* Value */ && exportedMember.flags & 111551 /* Value */ ) { if (s.valueDeclaration && exportedMember.valueDeclaration && getSourceFileOfNode(s.valueDeclaration) !== getSourceFileOfNode(exportedMember.valueDeclaration)) { const unescapedName = unescapeLeadingUnderscores(s.escapedName); - const exportedMemberName = ((_a2 = tryCast(exportedMember.valueDeclaration, isNamedDeclaration)) == null ? void 0 : _a2.name) || exportedMember.valueDeclaration; - addRelatedInfo(error(s.valueDeclaration, Diagnostics.Duplicate_identifier_0, unescapedName), createDiagnosticForNode(exportedMemberName, Diagnostics._0_was_also_declared_here, unescapedName)); - addRelatedInfo(error(exportedMemberName, Diagnostics.Duplicate_identifier_0, unescapedName), createDiagnosticForNode(s.valueDeclaration, Diagnostics._0_was_also_declared_here, unescapedName)); + const exportedMemberName = ((_a = tryCast(exportedMember.valueDeclaration, isNamedDeclaration)) == null ? void 0 : _a.name) || exportedMember.valueDeclaration; + addRelatedInfo(error2(s.valueDeclaration, Diagnostics.Duplicate_identifier_0, unescapedName), createDiagnosticForNode(exportedMemberName, Diagnostics._0_was_also_declared_here, unescapedName)); + addRelatedInfo(error2(exportedMemberName, Diagnostics.Duplicate_identifier_0, unescapedName), createDiagnosticForNode(s.valueDeclaration, Diagnostics._0_was_also_declared_here, unescapedName)); } const union = createSymbol(s.flags | exportedMember.flags, name); union.links.type = getUnionType([ @@ -49509,11 +49989,11 @@ ${lanes.join("\n")} return type; } function containsSameNamedThisProperty(thisProperty, expression) { - return isPropertyAccessExpression(thisProperty) && thisProperty.expression.kind === 108 /* ThisKeyword */ && forEachChildRecursively(expression, (n)=>isMatchingReference(thisProperty, n)); + return isPropertyAccessExpression(thisProperty) && thisProperty.expression.kind === 110 /* ThisKeyword */ && forEachChildRecursively(expression, (n)=>isMatchingReference(thisProperty, n)); } function isDeclarationInConstructor(expression) { const thisContainer = getThisContainer(expression, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false); - return thisContainer.kind === 173 /* Constructor */ || thisContainer.kind === 259 /* FunctionDeclaration */ || thisContainer.kind === 215 /* FunctionExpression */ && !isPrototypePropertyAssignment(thisContainer.parent); + return thisContainer.kind === 176 /* Constructor */ || thisContainer.kind === 262 /* FunctionDeclaration */ || thisContainer.kind === 218 /* FunctionExpression */ && !isPrototypePropertyAssignment(thisContainer.parent); } function getConstructorDefinedThisAssignmentTypes(types, declarations) { Debug.assert(types.length === declarations.length); @@ -49554,7 +50034,7 @@ ${lanes.join("\n")} symbol.links.bindingElement = e; members.set(symbol.escapedName, symbol); }); - const result = createAnonymousType(void 0, members, emptyArray, emptyArray, stringIndexInfo ? [ + const result = createAnonymousType(/*symbol*/ void 0, members, emptyArray, emptyArray, stringIndexInfo ? [ stringIndexInfo ] : emptyArray); result.objectFlags |= objectFlags; @@ -49567,7 +50047,7 @@ ${lanes.join("\n")} function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors2) { const elements = pattern.elements; const lastElement = lastOrUndefined(elements); - const restElement = lastElement && lastElement.kind === 205 /* BindingElement */ && lastElement.dotDotDotToken ? lastElement : void 0; + const restElement = lastElement && lastElement.kind === 208 /* BindingElement */ && lastElement.dotDotDotToken ? lastElement : void 0; if (elements.length === 0 || elements.length === 1 && restElement) return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; const elementTypes = map(elements, (e)=>isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors2)); const minLength = findLastIndex(elements, (e)=>!(e === restElement || isOmittedExpression(e) || hasDefaultValue(e)), elements.length - 1) + 1; @@ -49581,7 +50061,7 @@ ${lanes.join("\n")} return result; } function getTypeFromBindingPattern(pattern, includePatternInType = false, reportErrors2 = false) { - return pattern.kind === 203 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors2) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors2); + return pattern.kind === 206 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors2) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors2); } function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors2) { return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true, 0 /* Normal */ ), declaration, reportErrors2); @@ -49606,7 +50086,7 @@ ${lanes.join("\n")} } function declarationBelongsToPrivateAmbientMember(declaration) { const root = getRootDeclaration(declaration); - const memberDeclaration = root.kind === 166 /* Parameter */ ? root.parent : root; + const memberDeclaration = root.kind === 169 /* Parameter */ ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function tryGetTypeFromEffectiveTypeNode(node) { @@ -49657,7 +50137,7 @@ ${lanes.join("\n")} return reportCircularityError(symbol); } let type; - if (declaration.kind === 274 /* ExportAssignment */ ) type = widenTypeForVariableLikeDeclaration(tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionCached(declaration.expression), declaration); + if (declaration.kind === 277 /* ExportAssignment */ ) type = widenTypeForVariableLikeDeclaration(tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionCached(declaration.expression), declaration); else if (isBinaryExpression(declaration) || isInJSFile(declaration) && (isCallExpression(declaration) || (isPropertyAccessExpression(declaration) || isBindableStaticElementAccessExpression(declaration)) && isBinaryExpression(declaration.parent))) type = getWidenedTypeForAssignmentDeclaration(symbol); else if (isPropertyAccessExpression(declaration) || isElementAccessExpression(declaration) || isIdentifier(declaration) || isStringLiteralLike(declaration) || isNumericLiteral(declaration) || isClassDeclaration(declaration) || isFunctionDeclaration(declaration) || isMethodDeclaration(declaration) && !isObjectLiteralMethod(declaration) || isMethodSignature(declaration) || isSourceFile(declaration)) { if (symbol.flags & 9136 /* ValueModule */ ) return getTypeOfFuncClassEnumModule(symbol); @@ -49666,7 +50146,7 @@ ${lanes.join("\n")} else if (isJsxAttribute(declaration)) type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); else if (isShorthandPropertyAssignment(declaration)) type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */ ); else if (isObjectLiteralMethod(declaration)) type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */ ); - else if (isParameter(declaration) || isPropertyDeclaration(declaration) || isPropertySignature(declaration) || isVariableDeclaration(declaration) || isBindingElement(declaration) || isJSDocPropertyLikeTag(declaration)) type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); + else if (isParameter(declaration) || isPropertyDeclaration(declaration) || isPropertySignature(declaration) || isVariableDeclaration(declaration) || isBindingElement(declaration) || isJSDocPropertyLikeTag(declaration)) type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); else if (isEnumDeclaration(declaration)) type = getTypeOfFuncClassEnumModule(symbol); else if (isEnumMember(declaration)) type = getTypeOfEnumMember(symbol); else return Debug.fail("Unhandled declaration kind! " + Debug.formatSyntaxKind(declaration.kind) + " for " + Debug.formatSymbol(symbol)); @@ -49678,13 +50158,13 @@ ${lanes.join("\n")} } function getAnnotatedAccessorTypeNode(accessor) { if (accessor) switch(accessor.kind){ - case 174 /* GetAccessor */ : + case 177 /* GetAccessor */ : const getterTypeAnnotation = getEffectiveReturnTypeNode(accessor); return getterTypeAnnotation; - case 175 /* SetAccessor */ : + case 178 /* SetAccessor */ : const setterTypeAnnotation = getEffectiveSetAccessorTypeAnnotationNode(accessor); return setterTypeAnnotation; - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : Debug.assert(hasAccessorModifier(accessor)); const accessorTypeAnnotation = getEffectiveTypeAnnotationNode(accessor); return accessorTypeAnnotation; @@ -49706,10 +50186,10 @@ ${lanes.join("\n")} const links = getSymbolLinks(symbol); if (!links.type) { if (!pushTypeResolution(symbol, 0 /* Type */ )) return errorType; - const getter = getDeclarationOfKind(symbol, 174 /* GetAccessor */ ); - const setter = getDeclarationOfKind(symbol, 175 /* SetAccessor */ ); - const accessor = tryCast(getDeclarationOfKind(symbol, 169 /* PropertyDeclaration */ ), isAutoAccessorPropertyDeclaration); - let type = getter && isInJSFile(getter) && getTypeForDeclarationFromJSDocComment(getter) || getAnnotatedAccessorType(getter) || getAnnotatedAccessorType(setter) || getAnnotatedAccessorType(accessor) || getter && getter.body && getReturnTypeFromBody(getter) || accessor && accessor.initializer && getWidenedTypeForVariableLikeDeclaration(accessor, /*includeOptionality*/ true); + const getter = getDeclarationOfKind(symbol, 177 /* GetAccessor */ ); + const setter = getDeclarationOfKind(symbol, 178 /* SetAccessor */ ); + const accessor = tryCast(getDeclarationOfKind(symbol, 172 /* PropertyDeclaration */ ), isAutoAccessorPropertyDeclaration); + let type = getter && isInJSFile(getter) && getTypeForDeclarationFromJSDocComment(getter) || getAnnotatedAccessorType(getter) || getAnnotatedAccessorType(setter) || getAnnotatedAccessorType(accessor) || getter && getter.body && getReturnTypeFromBody(getter) || accessor && accessor.initializer && getWidenedTypeForVariableLikeDeclaration(accessor, /*reportErrors*/ true); if (!type) { if (setter && !isPrivateWithinAmbient(setter)) errorOrSuggestion(noImplicitAny, setter, Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); else if (getter && !isPrivateWithinAmbient(getter)) errorOrSuggestion(noImplicitAny, getter, Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); @@ -49717,10 +50197,10 @@ ${lanes.join("\n")} type = anyType; } if (!popTypeResolution()) { - if (getAnnotatedAccessorTypeNode(getter)) error(getter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); - else if (getAnnotatedAccessorTypeNode(setter)) error(setter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); - else if (getAnnotatedAccessorTypeNode(accessor)) error(setter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); - else if (getter && noImplicitAny) error(getter, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); + if (getAnnotatedAccessorTypeNode(getter)) error2(getter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + else if (getAnnotatedAccessorTypeNode(setter)) error2(setter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + else if (getAnnotatedAccessorTypeNode(accessor)) error2(setter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + else if (getter && noImplicitAny) error2(getter, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); type = anyType; } links.type = type; @@ -49728,14 +50208,13 @@ ${lanes.join("\n")} return links.type; } function getWriteTypeOfAccessors(symbol) { - var _a2; const links = getSymbolLinks(symbol); if (!links.writeType) { if (!pushTypeResolution(symbol, 8 /* WriteType */ )) return errorType; - const setter = (_a2 = getDeclarationOfKind(symbol, 175 /* SetAccessor */ )) != null ? _a2 : tryCast(getDeclarationOfKind(symbol, 169 /* PropertyDeclaration */ ), isAutoAccessorPropertyDeclaration); + const setter = getDeclarationOfKind(symbol, 178 /* SetAccessor */ ) ?? tryCast(getDeclarationOfKind(symbol, 172 /* PropertyDeclaration */ ), isAutoAccessorPropertyDeclaration); let writeType = getAnnotatedAccessorType(setter); if (!popTypeResolution()) { - if (getAnnotatedAccessorTypeNode(setter)) error(setter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + if (getAnnotatedAccessorTypeNode(setter)) error2(setter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); writeType = anyType; } links.writeType = writeType || getTypeOfAccessors(symbol); @@ -49765,7 +50244,7 @@ ${lanes.join("\n")} function getTypeOfFuncClassEnumModuleWorker(symbol) { const declaration = symbol.valueDeclaration; if (symbol.flags & 1536 /* Module */ && isShorthandAmbientModuleSymbol(symbol)) return anyType; - else if (declaration && (declaration.kind === 223 /* BinaryExpression */ || isAccessExpression(declaration) && declaration.parent.kind === 223 /* BinaryExpression */ )) return getWidenedTypeForAssignmentDeclaration(symbol); + else if (declaration && (declaration.kind === 226 /* BinaryExpression */ || isAccessExpression(declaration) && declaration.parent.kind === 226 /* BinaryExpression */ )) return getWidenedTypeForAssignmentDeclaration(symbol); else if (symbol.flags & 512 /* ValueModule */ && declaration && isSourceFile(declaration) && declaration.commonJsModuleIndicator) { const resolvedModule = resolveExternalModuleSymbol(symbol); if (resolvedModule !== symbol) { @@ -49783,7 +50262,7 @@ ${lanes.join("\n")} type, baseTypeVariable ]) : type; - } else return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type; + } else return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type, /*isProperty*/ true) : type; } function getTypeOfEnumMember(symbol) { const links = getSymbolLinks(symbol); @@ -49793,9 +50272,9 @@ ${lanes.join("\n")} const links = getSymbolLinks(symbol); if (!links.type) { const targetSymbol = resolveAlias(symbol); - const exportSymbol = symbol.declarations && getTargetOfAliasDeclaration(getDeclarationOfAliasSymbol(symbol), /*dontResolveAlias*/ true); + const exportSymbol = symbol.declarations && getTargetOfAliasDeclaration(getDeclarationOfAliasSymbol(symbol), /*dontRecursivelyResolve*/ true); const declaredType = firstDefined(exportSymbol == null ? void 0 : exportSymbol.declarations, (d)=>isExportAssignment(d) ? tryGetTypeFromEffectiveTypeNode(d) : void 0); - links.type = (exportSymbol == null ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType : getAllSymbolFlags(targetSymbol) & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; + links.type = (exportSymbol == null ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType : getSymbolFlags(targetSymbol) & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } return links.type; } @@ -49810,10 +50289,10 @@ ${lanes.join("\n")} function reportCircularityError(symbol) { const declaration = symbol.valueDeclaration; if (getEffectiveTypeAnnotationNode(declaration)) { - error(symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + error2(symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); return errorType; } - if (noImplicitAny && (declaration.kind !== 166 /* Parameter */ || declaration.initializer)) error(symbol.valueDeclaration, Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + if (noImplicitAny && (declaration.kind !== 169 /* Parameter */ || declaration.initializer)) error2(symbol.valueDeclaration, Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); return anyType; } function getTypeOfSymbolWithDeferredType(symbol) { @@ -49889,39 +50368,39 @@ ${lanes.join("\n")} } if (!node) return void 0; switch(node.kind){ - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : - case 261 /* InterfaceDeclaration */ : - case 176 /* CallSignature */ : - case 177 /* ConstructSignature */ : - case 170 /* MethodSignature */ : - case 181 /* FunctionType */ : - case 182 /* ConstructorType */ : - case 320 /* JSDocFunctionType */ : - case 259 /* FunctionDeclaration */ : - case 171 /* MethodDeclaration */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - case 262 /* TypeAliasDeclaration */ : - case 348 /* JSDocTemplateTag */ : - case 349 /* JSDocTypedefTag */ : - case 343 /* JSDocEnumTag */ : - case 341 /* JSDocCallbackTag */ : - case 197 /* MappedType */ : - case 191 /* ConditionalType */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 264 /* InterfaceDeclaration */ : + case 179 /* CallSignature */ : + case 180 /* ConstructSignature */ : + case 173 /* MethodSignature */ : + case 184 /* FunctionType */ : + case 185 /* ConstructorType */ : + case 324 /* JSDocFunctionType */ : + case 262 /* FunctionDeclaration */ : + case 174 /* MethodDeclaration */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + case 265 /* TypeAliasDeclaration */ : + case 352 /* JSDocTemplateTag */ : + case 353 /* JSDocTypedefTag */ : + case 347 /* JSDocEnumTag */ : + case 345 /* JSDocCallbackTag */ : + case 200 /* MappedType */ : + case 194 /* ConditionalType */ : { const outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 197 /* MappedType */ ) return append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node.typeParameter))); - else if (node.kind === 191 /* ConditionalType */ ) return concatenate(outerTypeParameters, getInferTypeParameters(node)); + if (node.kind === 200 /* MappedType */ ) return append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node.typeParameter))); + else if (node.kind === 194 /* ConditionalType */ ) return concatenate(outerTypeParameters, getInferTypeParameters(node)); const outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, getEffectiveTypeParameterDeclarations(node)); - const thisType = includeThisTypes && (node.kind === 260 /* ClassDeclaration */ || node.kind === 228 /* ClassExpression */ || node.kind === 261 /* InterfaceDeclaration */ || isJSConstructor(node)) && getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(node)).thisType; + const thisType = includeThisTypes && (node.kind === 263 /* ClassDeclaration */ || node.kind === 231 /* ClassExpression */ || node.kind === 264 /* InterfaceDeclaration */ || isJSConstructor(node)) && getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(node)).thisType; return thisType ? append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } - case 344 /* JSDocParameterTag */ : + case 348 /* JSDocParameterTag */ : const paramSymbol = getParameterSymbolFromJSDoc(node); if (paramSymbol) node = paramSymbol.valueDeclaration; break; - case 323 /* JSDoc */ : + case 327 /* JSDoc */ : { const outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); return node.tags ? appendTypeParameters(outerTypeParameters, flatMap(node.tags, (t)=>isJSDocTemplateTag(t) ? t.typeParameters : void 0)) : outerTypeParameters; @@ -49930,12 +50409,12 @@ ${lanes.join("\n")} } } function getOuterTypeParametersOfClassOrInterface(symbol) { - var _a2; - const declaration = symbol.flags & 32 /* Class */ || symbol.flags & 16 /* Function */ ? symbol.valueDeclaration : (_a2 = symbol.declarations) == null ? void 0 : _a2.find((decl)=>{ - if (decl.kind === 261 /* InterfaceDeclaration */ ) return true; - if (decl.kind !== 257 /* VariableDeclaration */ ) return false; + var _a; + const declaration = symbol.flags & 32 /* Class */ || symbol.flags & 16 /* Function */ ? symbol.valueDeclaration : (_a = symbol.declarations) == null ? void 0 : _a.find((decl)=>{ + if (decl.kind === 264 /* InterfaceDeclaration */ ) return true; + if (decl.kind !== 260 /* VariableDeclaration */ ) return false; const initializer = decl.initializer; - return !!initializer && (initializer.kind === 215 /* FunctionExpression */ || initializer.kind === 216 /* ArrowFunction */ ); + return !!initializer && (initializer.kind === 218 /* FunctionExpression */ || initializer.kind === 219 /* ArrowFunction */ ); }); Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); return getOuterTypeParameters(declaration); @@ -49943,7 +50422,7 @@ ${lanes.join("\n")} function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { if (!symbol.declarations) return; let result; - for (const node of symbol.declarations)if (node.kind === 261 /* InterfaceDeclaration */ || node.kind === 260 /* ClassDeclaration */ || node.kind === 228 /* ClassExpression */ || isJSConstructor(node) || isTypeAlias(node)) { + for (const node of symbol.declarations)if (node.kind === 264 /* InterfaceDeclaration */ || node.kind === 263 /* ClassDeclaration */ || node.kind === 231 /* ClassExpression */ || isJSConstructor(node) || isTypeAlias(node)) { const declaration = node; result = appendTypeParameters(result, getEffectiveTypeParameterDeclarations(declaration)); } @@ -49999,11 +50478,11 @@ ${lanes.join("\n")} } if (baseConstructorType.flags & 2621440 /* Intersection */ ) resolveStructuredTypeMembers(baseConstructorType); if (!popTypeResolution()) { - error(type.symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); + error2(type.symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); return type.resolvedBaseConstructorType = errorType; } if (!(baseConstructorType.flags & 1 /* Any */ ) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { - const err = error(baseTypeNode.expression, Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + const err = error2(baseTypeNode.expression, Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); if (baseConstructorType.flags & 262144 /* TypeParameter */ ) { const constraint = getConstraintFromTypeParameter(baseConstructorType); let ctorReturn = unknownType; @@ -50037,7 +50516,7 @@ ${lanes.join("\n")} return resolvedImplementsTypes; } function reportCircularBaseType(node, type) { - error(node, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ void 0, 2 /* WriteArrayAsGenericType */ )); + error2(node, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ void 0, 2 /* WriteArrayAsGenericType */ )); } function getBaseTypes(type) { if (!type.baseTypesResolved) { @@ -50050,7 +50529,7 @@ ${lanes.join("\n")} if (type.symbol.flags & 64 /* Interface */ ) resolveBaseTypesOfInterface(type); } else Debug.fail("type must be class or interface"); if (!popTypeResolution() && type.symbol.declarations) { - for (const declaration of type.symbol.declarations)if (declaration.kind === 260 /* ClassDeclaration */ || declaration.kind === 261 /* InterfaceDeclaration */ ) reportCircularBaseType(declaration, type); + for (const declaration of type.symbol.declarations)if (declaration.kind === 263 /* ClassDeclaration */ || declaration.kind === 264 /* InterfaceDeclaration */ ) reportCircularBaseType(declaration, type); } } type.baseTypesResolved = true; @@ -50073,7 +50552,7 @@ ${lanes.join("\n")} else { const constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); if (!constructors.length) { - error(baseTypeNode.expression, Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); + error2(baseTypeNode.expression, Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); return type.resolvedBaseTypes = emptyArray; } baseType = getReturnTypeOfSignature(constructors[0]); @@ -50087,7 +50566,7 @@ ${lanes.join("\n")} return type.resolvedBaseTypes = emptyArray; } if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) { - error(type.symbol.valueDeclaration, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ void 0, 2 /* WriteArrayAsGenericType */ )); + error2(type.symbol.valueDeclaration, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ void 0, 2 /* WriteArrayAsGenericType */ )); return type.resolvedBaseTypes = emptyArray; } if (type.resolvedBaseTypes === resolvingEmptyArray) type.members = void 0; @@ -50114,7 +50593,7 @@ ${lanes.join("\n")} function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; if (type.symbol.declarations) for (const declaration of type.symbol.declarations){ - if (declaration.kind === 261 /* InterfaceDeclaration */ && getInterfaceBaseTypeNodes(declaration)) for (const node of getInterfaceBaseTypeNodes(declaration)){ + if (declaration.kind === 264 /* InterfaceDeclaration */ && getInterfaceBaseTypeNodes(declaration)) for (const node of getInterfaceBaseTypeNodes(declaration)){ const baseType = getReducedType(getTypeFromTypeNode(node)); if (!isErrorType(baseType)) { if (isValidBaseType(baseType)) { @@ -50124,15 +50603,15 @@ ${lanes.join("\n")} ]; else type.resolvedBaseTypes.push(baseType); } else reportCircularBaseType(declaration, type); - } else error(node, Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); + } else error2(node, Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); } } } } function isThislessInterface(symbol) { if (!symbol.declarations) return true; - for (const declaration of symbol.declarations)if (declaration.kind === 261 /* InterfaceDeclaration */ ) { - if (declaration.flags & 128 /* ContainsThis */ ) return false; + for (const declaration of symbol.declarations)if (declaration.kind === 264 /* InterfaceDeclaration */ ) { + if (declaration.flags & 256 /* ContainsThis */ ) return false; const baseTypeNodes = getInterfaceBaseTypeNodes(declaration); if (baseTypeNodes) { for (const node of baseTypeNodes)if (isEntityNameExpression(node.expression)) { @@ -50173,11 +50652,11 @@ ${lanes.join("\n")} return links.declaredType; } function getDeclaredTypeOfTypeAlias(symbol) { - var _a2; + var _a; const links = getSymbolLinks(symbol); if (!links.declaredType) { if (!pushTypeResolution(symbol, 2 /* DeclaredType */ )) return errorType; - const declaration = Debug.checkDefined((_a2 = symbol.declarations) == null ? void 0 : _a2.find(isTypeAlias), "Type alias symbol with no valid declaration found"); + const declaration = Debug.checkDefined((_a = symbol.declarations) == null ? void 0 : _a.find(isTypeAlias), "Type alias symbol with no valid declaration found"); const typeNode = isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; let type = typeNode ? getTypeFromTypeNode(typeNode) : errorType; if (popTypeResolution()) { @@ -50189,8 +50668,8 @@ ${lanes.join("\n")} } } else { type = errorType; - if (declaration.kind === 343 /* JSDocEnumTag */ ) error(declaration.typeExpression.type, Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); - else error(isNamedDeclaration(declaration) ? declaration.name || declaration : declaration, Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + if (declaration.kind === 347 /* JSDocEnumTag */ ) error2(declaration.typeExpression.type, Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + else error2(isNamedDeclaration(declaration) ? declaration.name || declaration : declaration, Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } links.declaredType = type; } @@ -50204,7 +50683,7 @@ ${lanes.join("\n")} if (!links.declaredType) { const memberTypeList = []; if (symbol.declarations) { - for (const declaration of symbol.declarations)if (declaration.kind === 263 /* EnumDeclaration */ ) { + for (const declaration of symbol.declarations)if (declaration.kind === 266 /* EnumDeclaration */ ) { for (const member of declaration.members)if (hasBindableName(member)) { const memberSymbol = getSymbolOfDeclaration(member); const value1 = getEnumMemberValue(member); @@ -50262,22 +50741,22 @@ ${lanes.join("\n")} } function isThislessType(node) { switch(node.kind){ - case 131 /* AnyKeyword */ : - case 157 /* UnknownKeyword */ : - case 152 /* StringKeyword */ : - case 148 /* NumberKeyword */ : - case 160 /* BigIntKeyword */ : - case 134 /* BooleanKeyword */ : - case 153 /* SymbolKeyword */ : - case 149 /* ObjectKeyword */ : - case 114 /* VoidKeyword */ : - case 155 /* UndefinedKeyword */ : - case 144 /* NeverKeyword */ : - case 198 /* LiteralType */ : + case 133 /* AnyKeyword */ : + case 159 /* UnknownKeyword */ : + case 154 /* StringKeyword */ : + case 150 /* NumberKeyword */ : + case 163 /* BigIntKeyword */ : + case 136 /* BooleanKeyword */ : + case 155 /* SymbolKeyword */ : + case 151 /* ObjectKeyword */ : + case 116 /* VoidKeyword */ : + case 157 /* UndefinedKeyword */ : + case 146 /* NeverKeyword */ : + case 201 /* LiteralType */ : return true; - case 185 /* ArrayType */ : + case 188 /* ArrayType */ : return isThislessType(node.elementType); - case 180 /* TypeReference */ : + case 183 /* TypeReference */ : return !node.typeArguments || node.typeArguments.every(isThislessType); } return false; @@ -50293,20 +50772,20 @@ ${lanes.join("\n")} function isThislessFunctionLikeDeclaration(node) { const returnType = getEffectiveReturnTypeNode(node); const typeParameters = getEffectiveTypeParameterDeclarations(node); - return (node.kind === 173 /* Constructor */ || !!returnType && isThislessType(returnType)) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter); + return (node.kind === 176 /* Constructor */ || !!returnType && isThislessType(returnType)) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter); } function isThisless(symbol) { if (symbol.declarations && symbol.declarations.length === 1) { const declaration = symbol.declarations[0]; if (declaration) switch(declaration.kind){ - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : return isThislessVariableLikeDeclaration(declaration); - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 173 /* Constructor */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 176 /* Constructor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : return isThislessFunctionLikeDeclaration(declaration); } } @@ -50318,7 +50797,14 @@ ${lanes.join("\n")} return result; } function addInheritedMembers(symbols, baseSymbols) { - for (const s of baseSymbols)if (!symbols.has(s.escapedName) && !isStaticPrivateIdentifierProperty(s)) symbols.set(s.escapedName, s); + for (const base of baseSymbols){ + if (isStaticPrivateIdentifierProperty(base)) continue; + const derived = symbols.get(base.escapedName); + if (!derived || derived.valueDeclaration && isBinaryExpression(derived.valueDeclaration) && !isConstructorDeclaredProperty(derived) && !getContainingClassStaticBlock(derived.valueDeclaration)) { + symbols.set(base.escapedName, base); + symbols.set(base.escapedName, base); + } + } } function isStaticPrivateIdentifierProperty(s) { return !!s.valueDeclaration && isPrivateIdentifierClassElementDeclaration(s.valueDeclaration) && isStatic(s.valueDeclaration); @@ -50337,9 +50823,6 @@ ${lanes.join("\n")} } return type; } - function isTypeUsableAsPropertyName(type) { - return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */ ); - } function isLateBindableName(node) { if (!isComputedPropertyName(node) && !isElementAccessExpression(node)) return false; const expr = isComputedPropertyName(node) ? node.expression : node.argumentExpression; @@ -50358,11 +50841,6 @@ ${lanes.join("\n")} function isNonBindableDynamicName(node) { return isDynamicName(node) && !isLateBindableName(node); } - function getPropertyNameFromType(type) { - if (type.flags & 8192 /* UniqueESSymbol */ ) return type.escapedName; - if (type.flags & 384 /* NumberLiteral */ ) return escapeLeadingUnderscores("" + type.value); - return Debug.fail(); - } function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { Debug.assert(!!(getCheckFlags(symbol) & 4096 /* Late */ ), "Expected a late-bound symbol."); symbol.flags |= symbolFlags; @@ -50391,8 +50869,8 @@ ${lanes.join("\n")} if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) { const declarations = earlySymbol ? concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; const name = !(type.flags & 8192 /* UniqueESSymbol */ ) && unescapeLeadingUnderscores(memberName) || declarationNameToString(declName); - forEach(declarations, (declaration)=>error(getNameOfDeclaration(declaration) || declaration, Diagnostics.Property_0_was_also_declared_here, name)); - error(declName || decl, Diagnostics.Duplicate_property_0, name); + forEach(declarations, (declaration)=>error2(getNameOfDeclaration(declaration) || declaration, Diagnostics.Property_0_was_also_declared_here, name)); + error2(declName || decl, Diagnostics.Duplicate_property_0, name); lateSymbol = createSymbol(0 /* None */ , memberName, 4096 /* Late */ ); } lateSymbol.links.nameType = type; @@ -50405,6 +50883,7 @@ ${lanes.join("\n")} return links.resolvedSymbol; } function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) { + var _a, _b, _c; const links = getSymbolLinks(symbol); if (!links[resolutionKind]) { const isStatic2 = resolutionKind === "resolvedExports" /* resolvedExports */ ; @@ -50419,7 +50898,7 @@ ${lanes.join("\n")} } } } - const assignments = symbol.assignmentDeclarationMembers; + const assignments = (((_a = symbol.valueDeclaration) == null ? void 0 : _a.kind) === 219 /* ArrowFunction */ || ((_b = symbol.valueDeclaration) == null ? void 0 : _b.kind) === 218 /* FunctionExpression */ ) && ((_c = getSymbolOfNode(symbol.valueDeclaration.parent)) == null ? void 0 : _c.assignmentDeclarationMembers) || symbol.assignmentDeclarationMembers; if (assignments) { const decls = arrayFrom(assignments.values()); for (const member of decls){ @@ -50453,12 +50932,9 @@ ${lanes.join("\n")} if (getObjectFlags(type) & 4 /* Reference */ ) { const target = type.target; const typeArguments = getTypeArguments(type); - if (length(target.typeParameters) === length(typeArguments)) { - const ref = createTypeReference(target, concatenate(typeArguments, [ - thisArgument || target.thisType - ])); - return needApparentType ? getApparentType(ref) : ref; - } + return length(target.typeParameters) === length(typeArguments) ? createTypeReference(target, concatenate(typeArguments, [ + thisArgument || target.thisType + ])) : type; } else if (type.flags & 2097152 /* Intersection */ ) { const types = sameMap(type.types, (t)=>getTypeWithThisArgument(t, thisArgument, needApparentType)); return types !== type.types ? getIntersectionType(types) : type; @@ -50532,7 +51008,7 @@ ${lanes.join("\n")} return sig; } function cloneSignature(sig) { - const result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ void 0, /*resolvedTypePredicate*/ void 0, sig.minArgumentCount, sig.flags & 39 /* PropagatingFlags */ ); + const result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ void 0, /*resolvedTypePredicate*/ void 0, sig.minArgumentCount, sig.flags & 167 /* PropagatingFlags */ ); result.target = sig.target; result.mapper = sig.mapper; result.compositeSignatures = sig.compositeSignatures; @@ -50562,21 +51038,21 @@ ${lanes.join("\n")} function getExpandedParameters(sig, skipUnionExpanding) { if (signatureHasRestParameter(sig)) { const restIndex = sig.parameters.length - 1; + const restName = sig.parameters[restIndex].escapedName; const restType = getTypeOfSymbol(sig.parameters[restIndex]); if (isTupleType(restType)) return [ - expandSignatureParametersWithTupleMembers(restType, restIndex) + expandSignatureParametersWithTupleMembers(restType, restIndex, restName) ]; - else if (!skipUnionExpanding && restType.flags & 1048576 /* Union */ && every(restType.types, isTupleType)) return map(restType.types, (t)=>expandSignatureParametersWithTupleMembers(t, restIndex)); + else if (!skipUnionExpanding && restType.flags & 1048576 /* Union */ && every(restType.types, isTupleType)) return map(restType.types, (t)=>expandSignatureParametersWithTupleMembers(t, restIndex, restName)); } return [ sig.parameters ]; - function expandSignatureParametersWithTupleMembers(restType, restIndex) { + function expandSignatureParametersWithTupleMembers(restType, restIndex, restName) { const elementTypes = getTypeArguments(restType); - const associatedNames = restType.target.labeledElementDeclarations; + const associatedNames = getUniqAssociatedNamesFromTupleType(restType, restName); const restParams = map(elementTypes, (t, i)=>{ - const tupleLabelName = !!associatedNames && getTupleElementLabel(associatedNames[i]); - const name = tupleLabelName || getParameterNameAtPosition(sig, restIndex + i, restType); + const name = associatedNames && associatedNames[i] ? associatedNames[i] : getParameterNameAtPosition(sig, restIndex + i, restType); const flags = restType.target.elementFlags[i]; const checkFlags = flags & 12 /* Variable */ ? 32768 /* RestParameter */ : flags & 2 /* Optional */ ? 16384 /* OptionalParameter */ : 0; const symbol = createSymbol(1 /* FunctionScopedVariable */ , name, checkFlags); @@ -50585,6 +51061,20 @@ ${lanes.join("\n")} }); return concatenate(sig.parameters.slice(0, restIndex), restParams); } + function getUniqAssociatedNamesFromTupleType(type, restName) { + const associatedNamesMap = /* @__PURE__ */ new Map(); + return map(type.target.labeledElementDeclarations, (labeledElement, i)=>{ + const name = getTupleElementLabel(labeledElement, i, restName); + const prevCounter = associatedNamesMap.get(name); + if (prevCounter === void 0) { + associatedNamesMap.set(name, 1); + return name; + } else { + associatedNamesMap.set(name, prevCounter + 1); + return `${name}_${prevCounter}`; + } + }); + } } function getDefaultConstructSignatures(classType) { const baseConstructorType = getBaseConstructorTypeOfClass(classType); @@ -50592,7 +51082,7 @@ ${lanes.join("\n")} const declaration = getClassLikeDeclarationOfSymbol(classType.symbol); const isAbstract = !!declaration && hasSyntacticModifier(declaration, 256 /* Abstract */ ); if (baseSignatures.length === 0) return [ - createSignature(void 0, classType.localTypeParameters, void 0, emptyArray, classType, /*resolvedTypePredicate*/ void 0, 0, isAbstract ? 4 /* Abstract */ : 0 /* None */ ) + createSignature(/*declaration*/ void 0, classType.localTypeParameters, /*thisParameter*/ void 0, emptyArray, classType, /*resolvedTypePredicate*/ void 0, 0, isAbstract ? 4 /* Abstract */ : 0 /* None */ ) ]; const baseTypeNode = getBaseTypeNodeOfClass(classType); const isJavaScript = isInJSFile(baseTypeNode); @@ -50735,7 +51225,7 @@ ${lanes.join("\n")} const params = combineUnionParameters(left, right, paramMapper); const thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter, paramMapper); const minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); - const result = createSignature(declaration, typeParams, thisParam, params, /*resolvedReturnType*/ void 0, /*resolvedTypePredicate*/ void 0, minArgCount, (left.flags | right.flags) & 39 /* PropagatingFlags */ ); + const result = createSignature(declaration, typeParams, thisParam, params, /*resolvedReturnType*/ void 0, /*resolvedTypePredicate*/ void 0, minArgCount, (left.flags | right.flags) & 167 /* PropagatingFlags */ ); result.compositeKind = 1048576 /* Union */ ; result.compositeSignatures = concatenate(left.compositeKind !== 2097152 /* Intersection */ && left.compositeSignatures || [ left @@ -50851,18 +51341,15 @@ ${lanes.join("\n")} setStructuredTypeMembers(type, members2, callSignatures, constructSignatures, indexInfos2); return; } - let members = emptySymbols; + let members = getExportsOfSymbol(symbol); let indexInfos; - if (symbol.exports) { - members = getExportsOfSymbol(symbol); - if (symbol === globalThisSymbol) { - const varsOnly = /* @__PURE__ */ new Map(); - members.forEach((p)=>{ - var _a2; - if (!(p.flags & 418 /* BlockScoped */ ) && !(p.flags & 512 /* ValueModule */ && ((_a2 = p.declarations) == null ? void 0 : _a2.length) && every(p.declarations, isAmbientModule))) varsOnly.set(p.escapedName, p); - }); - members = varsOnly; - } + if (symbol === globalThisSymbol) { + const varsOnly = /* @__PURE__ */ new Map(); + members.forEach((p)=>{ + var _a; + if (!(p.flags & 418 /* BlockScoped */ ) && !(p.flags & 512 /* ValueModule */ && ((_a = p.declarations) == null ? void 0 : _a.length) && every(p.declarations, isAmbientModule))) varsOnly.set(p.escapedName, p); + }); + members = varsOnly; } let baseConstructorIndexInfo; setStructuredTypeMembers(type, members, emptyArray, emptyArray, emptyArray); @@ -50885,7 +51372,7 @@ ${lanes.join("\n")} if (symbol.flags & 32 /* Class */ ) { const classType = getDeclaredTypeOfClassOrInterface(symbol); let constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */ )) : emptyArray; - if (symbol.flags & 16 /* Function */ ) constructSignatures = addRange(constructSignatures.slice(), mapDefined(type.callSignatures, (sig)=>isJSConstructor(sig.declaration) ? createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType, /*resolvedTypePredicate*/ void 0, sig.minArgumentCount, sig.flags & 39 /* PropagatingFlags */ ) : void 0)); + if (symbol.flags & 16 /* Function */ ) constructSignatures = addRange(constructSignatures.slice(), mapDefined(type.callSignatures, (sig)=>isJSConstructor(sig.declaration) ? createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType, /*resolvedTypePredicate*/ void 0, sig.minArgumentCount, sig.flags & 167 /* PropagatingFlags */ ) : void 0)); if (!constructSignatures.length) constructSignatures = getDefaultConstructSignatures(classType); type.constructSignatures = constructSignatures; } @@ -51029,7 +51516,7 @@ ${lanes.join("\n")} const propType = instantiateType(templateType, mapper); let type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 49152 /* Void */ ) ? getOptionalType(propType, /*isProperty*/ true) : symbol.links.checkFlags & 524288 /* StripOptional */ ? removeMissingOrUndefinedType(propType) : propType; if (!popTypeResolution()) { - error(currentNode, Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(mappedType)); + error2(currentNode, Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(mappedType)); type = errorType; } symbol.links.type = type; @@ -51053,7 +51540,7 @@ ${lanes.join("\n")} } function isMappedTypeWithKeyofConstraintDeclaration(type) { const constraintDeclaration = getConstraintDeclarationForMappedType(type); - return constraintDeclaration.kind === 195 /* TypeOperator */ && constraintDeclaration.operator === 141 /* KeyOfKeyword */ ; + return constraintDeclaration.kind === 198 /* TypeOperator */ && constraintDeclaration.operator === 143 /* KeyOfKeyword */ ; } function getModifiersTypeFromMappedType(type) { if (!type.modifiersType) { @@ -51069,7 +51556,7 @@ ${lanes.join("\n")} } function getMappedTypeModifiers(type) { const declaration = type.declaration; - return (declaration.readonlyToken ? declaration.readonlyToken.kind === 40 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) | (declaration.questionToken ? declaration.questionToken.kind === 40 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0); + return (declaration.readonlyToken ? declaration.readonlyToken.kind === 41 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) | (declaration.questionToken ? declaration.questionToken.kind === 41 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0); } function getMappedTypeOptionality(type) { const modifiers = getMappedTypeModifiers(type); @@ -51149,7 +51636,7 @@ ${lanes.join("\n")} function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { const list = obj.properties; return list.some((property)=>{ - const nameType = property.name && getLiteralTypeFromPropertyName(property.name); + const nameType = property.name && (isJsxNamespacedName(property.name) ? getStringLiteralType(getTextOfJsxAttributeName(property.name)) : getLiteralTypeFromPropertyName(property.name)); const name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : void 0; const expected = name === void 0 ? void 0 : getTypeOfPropertyOfType(contextualType, name); return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected); @@ -51160,7 +51647,7 @@ ${lanes.join("\n")} if (!(unionType.flags & 1048576 /* Union */ )) return getAugmentedPropertiesOfType(unionType); const props = createSymbolTable(); for (const memberType of types){ - for (const { escapedName: escapedName } of getAugmentedPropertiesOfType(memberType))if (!props.has(escapedName)) { + for (const { escapedName: escapedName } of getAugmentedPropertiesOfType(memberType))if (!props.has(escapedName)) { const prop = createUnionOrIntersectionProperty(unionType, escapedName); if (prop) props.set(escapedName, prop); } @@ -51173,9 +51660,9 @@ ${lanes.join("\n")} function getConstraintOfTypeParameter(typeParameter) { return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : void 0; } - function isConstTypeVariable(type) { - var _a2; - return !!(type.flags & 262144 /* TypeParameter */ && some((_a2 = type.symbol) == null ? void 0 : _a2.declarations, (d)=>hasSyntacticModifier(d, 2048 /* Const */ )) || isGenericTupleType(type) && findIndex(getTypeArguments(type), (t, i)=>!!(type.target.elementFlags[i] & 8 /* Variadic */ ) && isConstTypeVariable(t)) >= 0 || type.flags & 8388608 /* IndexedAccess */ && isConstTypeVariable(type.objectType)); + function isConstTypeVariable(type, depth = 0) { + var _a; + return depth < 5 && !!(type && (type.flags & 262144 /* TypeParameter */ && some((_a = type.symbol) == null ? void 0 : _a.declarations, (d)=>hasSyntacticModifier(d, 2048 /* Const */ )) || type.flags & 1048576 /* Union */ && some(type.types, (t)=>isConstTypeVariable(t, depth)) || type.flags & 8388608 /* IndexedAccess */ && isConstTypeVariable(type.objectType, depth + 1) || type.flags & 16777216 /* Conditional */ && isConstTypeVariable(getConstraintOfConditionalType(type), depth + 1) || type.flags & 33554432 /* Substitution */ && isConstTypeVariable(type.baseType, depth) || isGenericTupleType(type) && findIndex(getElementTypes(type), (t, i)=>!!(type.target.elementFlags[i] & 8 /* Variadic */ ) && isConstTypeVariable(t, depth)) >= 0)); } function getConstraintOfIndexedAccess(type) { return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : void 0; @@ -51185,7 +51672,7 @@ ${lanes.join("\n")} return simplified !== type ? simplified : getConstraintOfType(type); } function getConstraintFromIndexedAccess(type) { - if (isMappedTypeGenericIndexedAccess(type)) return substituteIndexedMappedType(type.objectType, type.indexType); + if (isMappedTypeGenericIndexedAccess(type) || isGenericMappedType(type.objectType)) return substituteIndexedMappedType(type.objectType, type.indexType); const indexConstraint = getSimplifiedTypeOrConstraint(type.indexType); if (indexConstraint && indexConstraint !== type.indexType) { const indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint, type.accessFlags); @@ -51207,14 +51694,19 @@ ${lanes.join("\n")} return type.resolvedDefaultConstraint; } function getConstraintOfDistributiveConditionalType(type) { + if (type.resolvedConstraintOfDistributive !== void 0) return type.resolvedConstraintOfDistributive || void 0; if (type.root.isDistributive && type.restrictiveInstantiation !== type) { const simplified = getSimplifiedType(type.checkType, /*writing*/ false); const constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint && constraint !== type.checkType) { const instantiated = getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper)); - if (!(instantiated.flags & 131072 /* Never */ )) return instantiated; + if (!(instantiated.flags & 131072 /* Never */ )) { + type.resolvedConstraintOfDistributive = instantiated; + return instantiated; + } } } + type.resolvedConstraintOfDistributive = false; return void 0; } function getConstraintFromConditionalType(type) { @@ -51245,7 +51737,7 @@ ${lanes.join("\n")} return void 0; } function getBaseConstraintOfType(type) { - if (type.flags & 464781312 /* StringMapping */ ) { + if (type.flags & 464781312 /* StringMapping */ || isGenericTupleType(type)) { const constraint = getResolvedBaseConstraint(type); return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : void 0; } @@ -51260,7 +51752,7 @@ ${lanes.join("\n")} function getResolvedBaseConstraint(type) { if (type.resolvedBaseConstraint) return type.resolvedBaseConstraint; const stack = []; - return type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type); + return type.resolvedBaseConstraint = getImmediateBaseConstraint(type); function getImmediateBaseConstraint(t) { if (!t.immediateBaseConstraint) { if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */ )) return circularConstraintType; @@ -51275,7 +51767,7 @@ ${lanes.join("\n")} if (t.flags & 262144 /* TypeParameter */ ) { const errorNode = getConstraintDeclaration(t); if (errorNode) { - const diagnostic = error(errorNode, Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t)); + const diagnostic = error2(errorNode, Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t)); if (currentNode && !isNodeDescendantOf(errorNode, currentNode) && !isNodeDescendantOf(currentNode, errorNode)) addRelatedInfo(diagnostic, createDiagnosticForNode(currentNode, Diagnostics.Circularity_originates_in_type_at_this_location)); } } @@ -51330,11 +51822,18 @@ ${lanes.join("\n")} return constraint && getBaseConstraint(constraint); } if (t.flags & 33554432 /* Substitution */ ) return getBaseConstraint(getSubstitutionIntersection(t)); + if (isGenericTupleType(t)) { + const newElements = map(getElementTypes(t), (v, i)=>{ + const constraint = v.flags & 262144 /* TypeParameter */ && t.target.elementFlags[i] & 8 /* Variadic */ && getBaseConstraint(v) || v; + return constraint !== v && everyType(constraint, (c)=>isArrayOrTupleType(c) && !isGenericTupleType(c)) ? constraint : v; + }); + return createTupleType(newElements, t.target.elementFlags, t.target.readonly, t.target.labeledElementDeclarations); + } return t; } } - function getApparentTypeOfIntersectionType(type) { - return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true)); + function getApparentTypeOfIntersectionType(type, thisArgument) { + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, thisArgument, /*needApparentType*/ true)); } function getResolvedTypeParameterDefault(typeParameter) { if (!typeParameter.default) { @@ -51367,7 +51866,7 @@ ${lanes.join("\n")} const typeVariable = getHomomorphicTypeVariable(type); if (typeVariable && !type.declaration.nameType) { const constraint = getConstraintOfTypeParameter(typeVariable); - if (constraint && isArrayOrTupleType(constraint)) return instantiateType(type, prependTypeMapping(typeVariable, constraint, type.mapper)); + if (constraint && everyType(constraint, isArrayOrTupleType)) return instantiateType(type, prependTypeMapping(typeVariable, constraint, type.mapper)); } return type; } @@ -51376,14 +51875,15 @@ ${lanes.join("\n")} return !!(type.flags & 8388608 /* IndexedAccess */ && getObjectFlags(objectType = type.objectType) & 32 /* Mapped */ && !isGenericMappedType(objectType) && isGenericIndexType(type.indexType) && !(getMappedTypeModifiers(objectType) & 8 /* ExcludeOptional */ ) && !objectType.declaration.nameType); } function getApparentType(type) { - const t = !(type.flags & 465829888 /* Instantiable */ ) ? type : getBaseConstraintOfType(type) || unknownType; - return getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : t.flags & 402653316 /* StringLike */ ? globalStringType : t.flags & 296 /* NumberLike */ ? globalNumberType : t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType() : t.flags & 528 /* BooleanLike */ ? globalBooleanType : t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType() : t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType : t.flags & 4194304 /* Index */ ? keyofConstraintType : t.flags & 2 /* Unknown */ && !strictNullChecks ? emptyObjectType : t; + const t = type.flags & 465829888 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type; + const objectFlags = getObjectFlags(t); + return objectFlags & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : objectFlags & 4 /* Reference */ && t !== type ? getTypeWithThisArgument(t, type) : t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t, type) : t.flags & 402653316 /* StringLike */ ? globalStringType : t.flags & 296 /* NumberLike */ ? globalNumberType : t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType() : t.flags & 528 /* BooleanLike */ ? globalBooleanType : t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType() : t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType : t.flags & 4194304 /* Index */ ? keyofConstraintType : t.flags & 2 /* Unknown */ && !strictNullChecks ? emptyObjectType : t; } function getReducedApparentType(type) { return getReducedType(getApparentType(getReducedType(type))); } function createUnionOrIntersectionProperty(containingType, name, skipObjectFunctionPropertyAugment) { - var _a2, _b, _c; + var _a, _b, _c; let singleProp; let propSet; let indexTypes; @@ -51399,7 +51899,7 @@ ${lanes.join("\n")} const modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop) { if (prop.flags & 106500 /* ClassMember */ ) { - optionalFlag != null ? optionalFlag : optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */ ; + optionalFlag ?? (optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */ ); if (isUnion) optionalFlag |= prop.flags & 16777216 /* Optional */ ; else optionalFlag &= prop.flags; } @@ -51435,7 +51935,7 @@ ${lanes.join("\n")} if (!singleProp || isUnion && (propSet || checkFlags & 48 /* Partial */ ) && checkFlags & 1536 /* ContainsProtected */ && !(propSet && getCommonDeclarationsOfSymbols(propSet.values()))) return void 0; if (!propSet && !(checkFlags & 16 /* ReadPartial */ ) && !indexTypes) { if (mergedInstantiations) { - const links = (_a2 = tryCast(singleProp, isTransientSymbol)) == null ? void 0 : _a2.links; + const links = (_a = tryCast(singleProp, isTransientSymbol)) == null ? void 0 : _a.links; const clone2 = createSymbolWithType(singleProp, links == null ? void 0 : links.type); clone2.parent = (_c = (_b = singleProp.valueDeclaration) == null ? void 0 : _b.symbol) == null ? void 0 : _c.parent; clone2.links.containingType = containingType; @@ -51465,12 +51965,12 @@ ${lanes.join("\n")} const writeType = getWriteTypeOfSymbol(prop); if (writeTypes || writeType !== type) writeTypes = append(!writeTypes ? propTypes.slice() : writeTypes, writeType); else if (type !== firstType) checkFlags |= 64 /* HasNonUniformType */ ; - if (isLiteralType(type) || isPatternLiteralType(type) || type === uniqueLiteralType) checkFlags |= 128 /* HasLiteralType */ ; + if (isLiteralType(type) || isPatternLiteralType(type)) checkFlags |= 128 /* HasLiteralType */ ; if (type.flags & 131072 /* Never */ && type !== uniqueLiteralType) checkFlags |= 131072 /* HasNeverType */ ; propTypes.push(type); } addRange(propTypes, indexTypes); - const result = createSymbol(4 /* Property */ | (optionalFlag != null ? optionalFlag : 0), name, syntheticFlag | checkFlags); + const result = createSymbol(4 /* Property */ | (optionalFlag ?? 0), name, syntheticFlag | checkFlags); result.links.containingType = containingType; if (!hasNonUniformValueDeclaration && firstValueDeclaration) { result.valueDeclaration = firstValueDeclaration; @@ -51490,8 +51990,8 @@ ${lanes.join("\n")} return result; } function getUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment) { - var _a2, _b; - let property = ((_a2 = type.propertyCacheWithoutObjectFunctionPropertyAugment) == null ? void 0 : _a2.get(name)) || !skipObjectFunctionPropertyAugment ? (_b = type.propertyCache) == null ? void 0 : _b.get(name) : void 0; + var _a, _b; + let property = ((_a = type.propertyCacheWithoutObjectFunctionPropertyAugment) == null ? void 0 : _a.get(name)) || !skipObjectFunctionPropertyAugment ? (_b = type.propertyCache) == null ? void 0 : _b.get(name) : void 0; if (!property) { property = createUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment); if (property) { @@ -51544,6 +52044,13 @@ ${lanes.join("\n")} function isConflictingPrivateProperty(prop) { return !prop.valueDeclaration && !!(getCheckFlags(prop) & 1024 /* ContainsPrivate */ ); } + function isGenericReducibleType(type) { + return !!(type.flags & 1048576 /* Union */ && type.objectFlags & 16777216 /* ContainsIntersections */ && some(type.types, isGenericReducibleType) || type.flags & 2097152 /* Intersection */ && isReducibleIntersection(type)); + } + function isReducibleIntersection(type) { + const uniqueFilled = type.uniqueLiteralFilledInstantiation || (type.uniqueLiteralFilledInstantiation = instantiateType(type, uniqueLiteralMapper)); + return getReducedType(uniqueFilled) !== uniqueFilled; + } function elaborateNeverIntersection(errorInfo, type) { if (type.flags & 2097152 /* Intersection */ && getObjectFlags(type) & 33554432 /* IsNeverIntersection */ ) { const neverProp = find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); @@ -51578,7 +52085,29 @@ ${lanes.join("\n")} return emptyArray; } function getSignaturesOfType(type, kind) { - return getSignaturesOfStructuredType(getReducedApparentType(type), kind); + const result = getSignaturesOfStructuredType(getReducedApparentType(type), kind); + if (kind === 0 /* Call */ && !length(result) && type.flags & 1048576 /* Union */ ) { + if (type.arrayFallbackSignatures) return type.arrayFallbackSignatures; + let memberName; + if (everyType(type, (t)=>{ + var _a; + return !!((_a = t.symbol) == null ? void 0 : _a.parent) && isArrayOrTupleSymbol(t.symbol.parent) && (!memberName ? (memberName = t.symbol.escapedName, true) : memberName === t.symbol.escapedName); + })) { + const arrayArg = mapType(type, (t)=>getMappedType((isReadonlyArraySymbol(t.symbol.parent) ? globalReadonlyArrayType : globalArrayType).typeParameters[0], t.mapper)); + const arrayType = createArrayType(arrayArg, someType(type, (t)=>isReadonlyArraySymbol(t.symbol.parent))); + return type.arrayFallbackSignatures = getSignaturesOfType(getTypeOfPropertyOfType(arrayType, memberName), kind); + } + type.arrayFallbackSignatures = result; + } + return result; + } + function isArrayOrTupleSymbol(symbol) { + if (!symbol || !globalArrayType.symbol || !globalReadonlyArrayType.symbol) return false; + return !!getSymbolIfSameReference(symbol, globalArrayType.symbol) || !!getSymbolIfSameReference(symbol, globalReadonlyArrayType.symbol); + } + function isReadonlyArraySymbol(symbol) { + if (!symbol || !globalReadonlyArrayType.symbol) return false; + return !!getSymbolIfSameReference(symbol, globalReadonlyArrayType.symbol); } function findIndexInfo(indexInfos, keyType) { return find(indexInfos, (info)=>info.keyType === keyType); @@ -51615,8 +52144,8 @@ ${lanes.join("\n")} return findIndexInfo(getIndexInfosOfType(type), keyType); } function getIndexTypeOfType(type, keyType) { - var _a2; - return (_a2 = getIndexInfoOfType(type, keyType)) == null ? void 0 : _a2.type; + var _a; + return (_a = getIndexInfoOfType(type, keyType)) == null ? void 0 : _a.type; } function getApplicableIndexInfos(type, keyType) { return getIndexInfosOfType(type).filter((info)=>isApplicableIndexType(keyType, info.keyType)); @@ -51628,10 +52157,10 @@ ${lanes.join("\n")} return getApplicableIndexInfo(type, isLateBoundName(name) ? esSymbolType : getStringLiteralType(unescapeLeadingUnderscores(name))); } function getTypeParametersFromDeclaration(declaration) { - var _a2; + var _a; let result; for (const node of getEffectiveTypeParameterDeclarations(declaration))result = appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol)); - return (result == null ? void 0 : result.length) ? result : isFunctionDeclaration(declaration) ? (_a2 = getSignatureOfTypeTag(declaration)) == null ? void 0 : _a2.typeParameters : void 0; + return (result == null ? void 0 : result.length) ? result : isFunctionDeclaration(declaration) ? (_a = getSignatureOfTypeTag(declaration)) == null ? void 0 : _a.typeParameters : void 0; } function symbolsToArray(symbols) { const result = []; @@ -51710,19 +52239,19 @@ ${lanes.join("\n")} let paramSymbol = param.symbol; const type = isJSDocParameterTag(param) ? param.typeExpression && param.typeExpression.type : param.type; if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */ ) && !isBindingPattern(param.name)) { - const resolvedSymbol = resolveName(param, paramSymbol.escapedName, 111551 /* Value */ , void 0, void 0, /*isUse*/ false); + const resolvedSymbol = resolveName(param, paramSymbol.escapedName, 111551 /* Value */ , /*nameNotFoundMessage*/ void 0, /*nameArg*/ void 0, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this" /* This */ ) { hasThisParameter2 = true; thisParameter = param.symbol; } else parameters.push(paramSymbol); - if (type && type.kind === 198 /* LiteralType */ ) flags |= 2 /* HasLiteralTypes */ ; + if (type && type.kind === 201 /* LiteralType */ ) flags |= 2 /* HasLiteralTypes */ ; const isOptionalParameter2 = isOptionalJSDocPropertyLikeTag(param) || param.initializer || param.questionToken || isRestParameter(param) || iife && parameters.length > iife.arguments.length && !type || isJSDocOptionalParameter(param); if (!isOptionalParameter2) minArgumentCount = parameters.length; } - if ((declaration.kind === 174 /* GetAccessor */ || declaration.kind === 175 /* SetAccessor */ ) && hasBindableName(declaration) && (!hasThisParameter2 || !thisParameter)) { - const otherKind = declaration.kind === 174 /* GetAccessor */ ? 175 /* SetAccessor */ : 174 /* GetAccessor */ ; + if ((declaration.kind === 177 /* GetAccessor */ || declaration.kind === 178 /* SetAccessor */ ) && hasBindableName(declaration) && (!hasThisParameter2 || !thisParameter)) { + const otherKind = declaration.kind === 177 /* GetAccessor */ ? 178 /* SetAccessor */ : 177 /* GetAccessor */ ; const other = getDeclarationOfKind(getSymbolOfDeclaration(declaration), otherKind); if (other) thisParameter = getAnnotatedAccessorThisParameter(other); } @@ -51730,7 +52259,8 @@ ${lanes.join("\n")} const thisTag = getJSDocThisTag(declaration); if (thisTag && thisTag.typeExpression) thisParameter = createSymbolWithType(createSymbol(1 /* FunctionScopedVariable */ , "this" /* This */ ), getTypeFromTypeNode(thisTag.typeExpression)); } - const classType = declaration.kind === 173 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : void 0; + const hostDeclaration = isJSDocSignature(declaration) ? getEffectiveJSDocHost(declaration) : declaration; + const classType = hostDeclaration && isConstructorDeclaration(hostDeclaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(hostDeclaration.parent.symbol)) : void 0; const typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); if (hasRestParameter(declaration) || isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) flags |= 1 /* HasRestParameter */ ; if (isConstructorTypeNode(declaration) && hasSyntacticModifier(declaration, 256 /* Abstract */ ) || isConstructorDeclaration(declaration) && hasSyntacticModifier(declaration.parent, 256 /* Abstract */ )) flags |= 4 /* Abstract */ ; @@ -51784,17 +52314,17 @@ ${lanes.join("\n")} function traverse(node) { if (!node) return false; switch(node.kind){ - case 79 /* Identifier */ : + case 80 /* Identifier */ : return node.escapedText === argumentsSymbol.escapedName && getReferencedValueSymbol(node) === argumentsSymbol; - case 169 /* PropertyDeclaration */ : - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - return node.name.kind === 164 /* ComputedPropertyName */ && traverse(node.name); - case 208 /* PropertyAccessExpression */ : - case 209 /* ElementAccessExpression */ : + case 172 /* PropertyDeclaration */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + return node.name.kind === 167 /* ComputedPropertyName */ && traverse(node.name); + case 211 /* PropertyAccessExpression */ : + case 212 /* ElementAccessExpression */ : return traverse(node.expression); - case 299 /* PropertyAssignment */ : + case 303 /* PropertyAssignment */ : return traverse(node.initializer); default: return !nodeStartsNewLexicalEnvironment(node) && !isPartOfTypeNode(node) && !!forEachChild(node, traverse); @@ -51860,7 +52390,7 @@ ${lanes.join("\n")} function createTypePredicateFromTypePredicateNode(node, signature) { const parameterName = node.parameterName; const type = node.type && getTypeFromTypeNode(node.type); - return parameterName.kind === 194 /* ThisType */ ? createTypePredicate(node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */ , /*parameterName*/ void 0, /*parameterIndex*/ void 0, type) : createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */ , parameterName.escapedText, findIndex(signature.parameters, (p)=>p.escapedName === parameterName.escapedText), type); + return parameterName.kind === 197 /* ThisType */ ? createTypePredicate(node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */ , /*parameterName*/ void 0, /*parameterIndex*/ void 0, type) : createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */ , parameterName.escapedText, findIndex(signature.parameters, (p)=>p.escapedName === parameterName.escapedText), type); } function getUnionOrIntersectionType(types, kind, unionReduction) { return kind !== 2097152 /* Intersection */ ? getUnionType(types, unionReduction) : getIntersectionType(types); @@ -51874,12 +52404,12 @@ ${lanes.join("\n")} if (!popTypeResolution()) { if (signature.declaration) { const typeNode = getEffectiveReturnTypeNode(signature.declaration); - if (typeNode) error(typeNode, Diagnostics.Return_type_annotation_circularly_references_itself); + if (typeNode) error2(typeNode, Diagnostics.Return_type_annotation_circularly_references_itself); else if (noImplicitAny) { const declaration = signature.declaration; const name = getNameOfDeclaration(declaration); - if (name) error(name, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, declarationNameToString(name)); - else error(declaration, Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + if (name) error2(name, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, declarationNameToString(name)); + else error2(declaration, Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); } } type = anyType; @@ -51889,25 +52419,25 @@ ${lanes.join("\n")} return signature.resolvedReturnType; } function getReturnTypeFromAnnotation(declaration) { - if (declaration.kind === 173 /* Constructor */ ) return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); + if (declaration.kind === 176 /* Constructor */ ) return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); + const typeNode = getEffectiveReturnTypeNode(declaration); if (isJSDocSignature(declaration)) { const root = getJSDocRoot(declaration); - if (root && isConstructorDeclaration(root.parent)) return getDeclaredTypeOfClassOrInterface(getMergedSymbol(root.parent.parent.symbol)); + if (root && isConstructorDeclaration(root.parent) && !typeNode) return getDeclaredTypeOfClassOrInterface(getMergedSymbol(root.parent.parent.symbol)); } if (isJSDocConstructSignature(declaration)) return getTypeFromTypeNode(declaration.parameters[0].type); - const typeNode = getEffectiveReturnTypeNode(declaration); if (typeNode) return getTypeFromTypeNode(typeNode); - if (declaration.kind === 174 /* GetAccessor */ && hasBindableName(declaration)) { + if (declaration.kind === 177 /* GetAccessor */ && hasBindableName(declaration)) { const jsDocType = isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) return jsDocType; - const setter = getDeclarationOfKind(getSymbolOfDeclaration(declaration), 175 /* SetAccessor */ ); + const setter = getDeclarationOfKind(getSymbolOfDeclaration(declaration), 178 /* SetAccessor */ ); const setterType = getAnnotatedAccessorType(setter); if (setterType) return setterType; } return getReturnTypeOfTypeTag(declaration); } function isResolvingReturnTypeOfSignature(signature) { - return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */ ) >= 0; + return signature.compositeSignatures && some(signature.compositeSignatures, isResolvingReturnTypeOfSignature) || !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */ ) >= 0; } function getRestTypeOfSignature(signature) { return tryGetRestTypeOfSignature(signature) || anyType; @@ -51973,10 +52503,10 @@ ${lanes.join("\n")} return signature; } function getOrCreateTypeFromSignature(signature) { - var _a2; + var _a; if (!signature.isolatedSignatureType) { - const kind = (_a2 = signature.declaration) == null ? void 0 : _a2.kind; - const isConstructor = kind === void 0 || kind === 173 /* Constructor */ || kind === 177 /* ConstructSignature */ || kind === 182 /* ConstructorType */ ; + const kind = (_a = signature.declaration) == null ? void 0 : _a.kind; + const isConstructor = kind === void 0 || kind === 176 /* Constructor */ || kind === 180 /* ConstructSignature */ || kind === 185 /* ConstructorType */ ; const type = createObjectType(16 /* Anonymous */ ); type.members = emptySymbols; type.properties = emptyArray; @@ -52029,12 +52559,12 @@ ${lanes.join("\n")} return mapDefined(filter(type.symbol && type.symbol.declarations, isTypeParameterDeclaration), getEffectiveConstraintOfTypeParameter)[0]; } function getInferredTypeParameterConstraint(typeParameter, omitTypeReferences) { - var _a2; + var _a; let inferences; - if ((_a2 = typeParameter.symbol) == null ? void 0 : _a2.declarations) { - for (const declaration of typeParameter.symbol.declarations)if (declaration.parent.kind === 192 /* InferType */ ) { + if ((_a = typeParameter.symbol) == null ? void 0 : _a.declarations) { + for (const declaration of typeParameter.symbol.declarations)if (declaration.parent.kind === 195 /* InferType */ ) { const [childTypeParameter = declaration.parent, grandParent] = walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent); - if (grandParent.kind === 180 /* TypeReference */ && !omitTypeReferences) { + if (grandParent.kind === 183 /* TypeReference */ && !omitTypeReferences) { const typeReference = grandParent; const typeParameters = getTypeParametersForTypeReferenceOrImport(typeReference); if (typeParameters) { @@ -52050,10 +52580,10 @@ ${lanes.join("\n")} } } } - } else if (grandParent.kind === 166 /* Parameter */ && grandParent.dotDotDotToken || grandParent.kind === 188 /* RestType */ || grandParent.kind === 199 /* NamedTupleMember */ && grandParent.dotDotDotToken) inferences = append(inferences, createArrayType(unknownType)); - else if (grandParent.kind === 201 /* TemplateLiteralTypeSpan */ ) inferences = append(inferences, stringType); - else if (grandParent.kind === 165 /* TypeParameter */ && grandParent.parent.kind === 197 /* MappedType */ ) inferences = append(inferences, keyofConstraintType); - else if (grandParent.kind === 197 /* MappedType */ && grandParent.type && skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === 191 /* ConditionalType */ && grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === 197 /* MappedType */ && grandParent.parent.checkType.type) { + } else if (grandParent.kind === 169 /* Parameter */ && grandParent.dotDotDotToken || grandParent.kind === 191 /* RestType */ || grandParent.kind === 202 /* NamedTupleMember */ && grandParent.dotDotDotToken) inferences = append(inferences, createArrayType(unknownType)); + else if (grandParent.kind === 204 /* TemplateLiteralTypeSpan */ ) inferences = append(inferences, stringType); + else if (grandParent.kind === 168 /* TypeParameter */ && grandParent.parent.kind === 200 /* MappedType */ ) inferences = append(inferences, keyofConstraintType); + else if (grandParent.kind === 200 /* MappedType */ && grandParent.type && skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === 194 /* ConditionalType */ && grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === 200 /* MappedType */ && grandParent.parent.checkType.type) { const checkMappedType2 = grandParent.parent.checkType; const nodeType = getTypeFromTypeNode(checkMappedType2.type); inferences = append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(checkMappedType2.typeParameter)), checkMappedType2.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType2.typeParameter.constraint) : keyofConstraintType))); @@ -52072,7 +52602,7 @@ ${lanes.join("\n")} if (!constraintDeclaration) typeParameter.constraint = getInferredTypeParameterConstraint(typeParameter) || noConstraintType; else { let type = getTypeFromTypeNode(constraintDeclaration); - if (type.flags & 1 /* Any */ && !isErrorType(type)) type = constraintDeclaration.parent.parent.kind === 197 /* MappedType */ ? keyofConstraintType : unknownType; + if (type.flags & 1 /* Any */ && !isErrorType(type)) type = constraintDeclaration.parent.parent.kind === 200 /* MappedType */ ? keyofConstraintType : unknownType; typeParameter.constraint = type; } } @@ -52080,7 +52610,7 @@ ${lanes.join("\n")} return typeParameter.constraint === noConstraintType ? void 0 : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - const tp = getDeclarationOfKind(typeParameter.symbol, 165 /* TypeParameter */ ); + const tp = getDeclarationOfKind(typeParameter.symbol, 168 /* TypeParameter */ ); const host2 = isJSDocTemplateTag(tp.parent) ? getEffectiveContainerForJSDocTemplateTag(tp.parent) : tp.parent; return host2 && getSymbolOfNode(host2); } @@ -52147,17 +52677,17 @@ ${lanes.join("\n")} return type; } function getTypeArguments(type) { - var _a2, _b; + var _a, _b; if (!type.resolvedTypeArguments) { - if (!pushTypeResolution(type, 6 /* ResolvedTypeArguments */ )) return ((_a2 = type.target.localTypeParameters) == null ? void 0 : _a2.map(()=>errorType)) || emptyArray; + if (!pushTypeResolution(type, 6 /* ResolvedTypeArguments */ )) return ((_a = type.target.localTypeParameters) == null ? void 0 : _a.map(()=>errorType)) || emptyArray; const node = type.node; - const typeArguments = !node ? emptyArray : node.kind === 180 /* TypeReference */ ? concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments2(node, type.target.localTypeParameters)) : node.kind === 185 /* ArrayType */ ? [ + const typeArguments = !node ? emptyArray : node.kind === 183 /* TypeReference */ ? concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments2(node, type.target.localTypeParameters)) : node.kind === 188 /* ArrayType */ ? [ getTypeFromTypeNode(node.elementType) ] : map(node.elements, getTypeFromTypeNode); if (popTypeResolution()) type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; else { type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) == null ? void 0 : _b.map(()=>errorType)) || emptyArray; - error(type.node || currentNode, type.target.symbol ? Diagnostics.Type_arguments_for_0_circularly_reference_themselves : Diagnostics.Tuple_type_arguments_circularly_reference_themselves, type.target.symbol && symbolToString(type.target.symbol)); + error2(type.node || currentNode, type.target.symbol ? Diagnostics.Type_arguments_for_0_circularly_reference_themselves : Diagnostics.Tuple_type_arguments_circularly_reference_themselves, type.target.symbol && symbolToString(type.target.symbol)); } } return type.resolvedTypeArguments; @@ -52177,10 +52707,10 @@ ${lanes.join("\n")} const missingAugmentsTag = isJs && isExpressionWithTypeArguments(node) && !isJSDocAugmentsTag(node.parent); const diag2 = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag : Diagnostics.Generic_type_0_requires_1_type_argument_s : missingAugmentsTag ? Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag : Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; const typeStr = typeToString(type, /*enclosingDeclaration*/ void 0, 2 /* WriteArrayAsGenericType */ ); - error(node, diag2, typeStr, minTypeArgumentCount, typeParameters.length); + error2(node, diag2, typeStr, minTypeArgumentCount, typeParameters.length); if (!isJs) return errorType; } - if (node.kind === 180 /* TypeReference */ && isDeferredTypeReferenceNode(node, length(node.typeArguments) !== typeParameters.length)) return createDeferredTypeReference(type, node, /*mapper*/ void 0); + if (node.kind === 183 /* TypeReference */ && isDeferredTypeReferenceNode(node, length(node.typeArguments) !== typeParameters.length)) return createDeferredTypeReference(type, node, /*mapper*/ void 0); const typeArguments = concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgumentsFromTypeReferenceNode(node), typeParameters, minTypeArgumentCount, isJs)); return createTypeReference(type, typeArguments); } @@ -52215,7 +52745,7 @@ ${lanes.join("\n")} const numTypeArguments = length(node.typeArguments); const minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) { - error(node, minTypeArgumentCount === typeParameters.length ? Diagnostics.Generic_type_0_requires_1_type_argument_s : Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); + error2(node, minTypeArgumentCount === typeParameters.length ? Diagnostics.Generic_type_0_requires_1_type_argument_s : Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return errorType; } const aliasSymbol = getAliasSymbolForTypeNode(node); @@ -52237,15 +52767,15 @@ ${lanes.join("\n")} return checkNoTypeArguments(node, symbol) ? type : errorType; } function isLocalTypeAlias(symbol) { - var _a2; - const declaration = (_a2 = symbol.declarations) == null ? void 0 : _a2.find(isTypeAlias); + var _a; + const declaration = (_a = symbol.declarations) == null ? void 0 : _a.find(isTypeAlias); return !!(declaration && getContainingFunction(declaration)); } function getTypeReferenceName(node) { switch(node.kind){ - case 180 /* TypeReference */ : + case 183 /* TypeReference */ : return node.typeName; - case 230 /* ExpressionWithTypeArguments */ : + case 233 /* ExpressionWithTypeArguments */ : const expr = node.expression; if (isEntityNameExpression(expr)) return expr; } @@ -52255,10 +52785,10 @@ ${lanes.join("\n")} return symbol.parent ? `${getSymbolPath(symbol.parent)}.${symbol.escapedName}` : symbol.escapedName; } function getUnresolvedSymbolForEntityName(name) { - const identifier = name.kind === 163 /* QualifiedName */ ? name.right : name.kind === 208 /* PropertyAccessExpression */ ? name.name : name; + const identifier = name.kind === 166 /* QualifiedName */ ? name.right : name.kind === 211 /* PropertyAccessExpression */ ? name.name : name; const text = identifier.escapedText; if (text) { - const parentSymbol = name.kind === 163 /* QualifiedName */ ? getUnresolvedSymbolForEntityName(name.left) : name.kind === 208 /* PropertyAccessExpression */ ? getUnresolvedSymbolForEntityName(name.expression) : void 0; + const parentSymbol = name.kind === 166 /* QualifiedName */ ? getUnresolvedSymbolForEntityName(name.left) : name.kind === 211 /* PropertyAccessExpression */ ? getUnresolvedSymbolForEntityName(name.expression) : void 0; const path = parentSymbol ? `${getSymbolPath(parentSymbol)}.${text}` : text; let result = unresolvedSymbols.get(path); if (!result) { @@ -52299,7 +52829,7 @@ ${lanes.join("\n")} const valueType = getTypeOfSymbol(symbol); let typeType = valueType; if (symbol.valueDeclaration) { - const isImportTypeWithQualifier = node.kind === 202 /* ImportType */ && node.qualifier; + const isImportTypeWithQualifier = node.kind === 205 /* ImportType */ && node.qualifier; if (valueType.symbol && valueType.symbol !== symbol && isImportTypeWithQualifier) typeType = getTypeReferenceType(node, valueType.symbol); } links.resolvedJSDocType = typeType; @@ -52324,7 +52854,7 @@ ${lanes.join("\n")} ]); } function isUnaryTupleTypeNode(node) { - return node.kind === 186 /* TupleType */ && node.elements.length === 1; + return node.kind === 189 /* TupleType */ && node.elements.length === 1; } function getImpliedConstraint(type, checkNode, extendsNode) { return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elements[0], extendsNode.elements[0]) : getActualTypeVariable(getTypeFromTypeNode(checkNode)) === getActualTypeVariable(type) ? getTypeFromTypeNode(extendsNode) : void 0; @@ -52332,13 +52862,13 @@ ${lanes.join("\n")} function getConditionalFlowTypeOfType(type, node) { let constraints; let covariant = true; - while(node && !isStatement(node) && node.kind !== 323 /* JSDoc */ ){ + while(node && !isStatement(node) && node.kind !== 327 /* JSDoc */ ){ const parent2 = node.parent; - if (parent2.kind === 166 /* Parameter */ ) covariant = !covariant; - if ((covariant || type.flags & 8650752 /* TypeVariable */ ) && parent2.kind === 191 /* ConditionalType */ && node === parent2.trueType) { + if (parent2.kind === 169 /* Parameter */ ) covariant = !covariant; + if ((covariant || type.flags & 8650752 /* TypeVariable */ ) && parent2.kind === 194 /* ConditionalType */ && node === parent2.trueType) { const constraint = getImpliedConstraint(type, parent2.checkType, parent2.extendsType); if (constraint) constraints = append(constraints, constraint); - } else if (type.flags & 262144 /* TypeParameter */ && parent2.kind === 197 /* MappedType */ && node === parent2.type) { + } else if (type.flags & 262144 /* TypeParameter */ && parent2.kind === 200 /* MappedType */ && node === parent2.type) { const mappedType = getTypeFromTypeNode(parent2); if (getTypeParameterFromMappedType(mappedType) === getActualTypeVariable(type)) { const typeParameter = getHomomorphicTypeVariable(mappedType); @@ -52356,11 +52886,11 @@ ${lanes.join("\n")} return constraints ? getSubstitutionType(type, getIntersectionType(constraints)) : type; } function isJSDocTypeReference(node) { - return !!(node.flags & 8388608 /* JSDoc */ ) && (node.kind === 180 /* TypeReference */ || node.kind === 202 /* ImportType */ ); + return !!(node.flags & 16777216 /* JSDoc */ ) && (node.kind === 183 /* TypeReference */ || node.kind === 205 /* ImportType */ ); } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { - error(node, Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? declarationNameToString(node.typeName) : anon); + error2(node, Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? declarationNameToString(node.typeName) : anon); return false; } return true; @@ -52403,7 +52933,7 @@ ${lanes.join("\n")} const indexInfo = indexed === stringType || indexed === numberType ? [ createIndexInfo(indexed, target, /*isReadonly*/ false) ] : emptyArray; - return createAnonymousType(void 0, emptySymbols, emptyArray, emptyArray, indexInfo); + return createAnonymousType(/*symbol*/ void 0, emptySymbols, emptyArray, emptyArray, indexInfo); } return anyType; } @@ -52459,20 +52989,20 @@ ${lanes.join("\n")} function getTypeDeclaration(symbol2) { const declarations = symbol2.declarations; if (declarations) for (const declaration of declarations)switch(declaration.kind){ - case 260 /* ClassDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 263 /* EnumDeclaration */ : + case 263 /* ClassDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 266 /* EnumDeclaration */ : return declaration; } } if (!symbol) return arity ? emptyGenericType : emptyObjectType; const type = getDeclaredTypeOfSymbol(symbol); if (!(type.flags & 524288 /* Object */ )) { - error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbolName(symbol)); + error2(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbolName(symbol)); return arity ? emptyGenericType : emptyObjectType; } if (length(type.typeParameters) !== arity) { - error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbolName(symbol), arity); + error2(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbolName(symbol), arity); return arity ? emptyGenericType : emptyObjectType; } return type; @@ -52489,14 +53019,14 @@ ${lanes.join("\n")} getDeclaredTypeOfSymbol(symbol); if (length(getSymbolLinks(symbol).typeParameters) !== arity) { const decl = symbol.declarations && find(symbol.declarations, isTypeAliasDeclaration); - error(decl, Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbolName(symbol), arity); + error2(decl, Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbolName(symbol), arity); return void 0; } } return symbol; } function getGlobalSymbol(name, meaning, diagnostic) { - return resolveName(void 0, name, meaning, diagnostic, name, /*isUse*/ false, /*excludeGlobals*/ false, /*getSpellingSuggestions*/ false); + return resolveName(/*location*/ void 0, name, meaning, diagnostic, name, /*isUse*/ false, /*excludeGlobals*/ false, /*getSpellingSuggestions*/ false); } function getGlobalType(name, arity, reportErrors2) { const symbol = getGlobalTypeSymbol(name, reportErrors2); @@ -52580,6 +53110,12 @@ ${lanes.join("\n")} function getGlobalIteratorReturnResultType(reportErrors2) { return deferredGlobalIteratorReturnResultType || (deferredGlobalIteratorReturnResultType = getGlobalType("IteratorReturnResult", /*arity*/ 1, reportErrors2)) || emptyGenericType; } + function getGlobalDisposableType(reportErrors2) { + return deferredGlobalDisposableType || (deferredGlobalDisposableType = getGlobalType("Disposable", /*arity*/ 0, reportErrors2)) || emptyObjectType; + } + function getGlobalAsyncDisposableType(reportErrors2) { + return deferredGlobalAsyncDisposableType || (deferredGlobalAsyncDisposableType = getGlobalType("AsyncDisposable", /*arity*/ 0, reportErrors2)) || emptyObjectType; + } function getGlobalTypeOrUndefined(name, arity = 0) { const symbol = getGlobalSymbol(name, 788968 /* Type */ , /*diagnostic*/ void 0); return symbol && getTypeOfGlobalSymbol(symbol, arity); @@ -52600,36 +53136,28 @@ ${lanes.join("\n")} return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, /*reportErrors*/ false)) || emptyObjectType; } function getGlobalClassDecoratorContextType(reportErrors2) { - var _a2; - return (_a2 = deferredGlobalClassDecoratorContextType != null ? deferredGlobalClassDecoratorContextType : deferredGlobalClassDecoratorContextType = getGlobalType("ClassDecoratorContext", /*arity*/ 1, reportErrors2)) != null ? _a2 : emptyGenericType; + return deferredGlobalClassDecoratorContextType ?? (deferredGlobalClassDecoratorContextType = getGlobalType("ClassDecoratorContext", /*arity*/ 1, reportErrors2)) ?? emptyGenericType; } function getGlobalClassMethodDecoratorContextType(reportErrors2) { - var _a2; - return (_a2 = deferredGlobalClassMethodDecoratorContextType != null ? deferredGlobalClassMethodDecoratorContextType : deferredGlobalClassMethodDecoratorContextType = getGlobalType("ClassMethodDecoratorContext", /*arity*/ 2, reportErrors2)) != null ? _a2 : emptyGenericType; + return deferredGlobalClassMethodDecoratorContextType ?? (deferredGlobalClassMethodDecoratorContextType = getGlobalType("ClassMethodDecoratorContext", /*arity*/ 2, reportErrors2)) ?? emptyGenericType; } function getGlobalClassGetterDecoratorContextType(reportErrors2) { - var _a2; - return (_a2 = deferredGlobalClassGetterDecoratorContextType != null ? deferredGlobalClassGetterDecoratorContextType : deferredGlobalClassGetterDecoratorContextType = getGlobalType("ClassGetterDecoratorContext", /*arity*/ 2, reportErrors2)) != null ? _a2 : emptyGenericType; + return deferredGlobalClassGetterDecoratorContextType ?? (deferredGlobalClassGetterDecoratorContextType = getGlobalType("ClassGetterDecoratorContext", /*arity*/ 2, reportErrors2)) ?? emptyGenericType; } function getGlobalClassSetterDecoratorContextType(reportErrors2) { - var _a2; - return (_a2 = deferredGlobalClassSetterDecoratorContextType != null ? deferredGlobalClassSetterDecoratorContextType : deferredGlobalClassSetterDecoratorContextType = getGlobalType("ClassSetterDecoratorContext", /*arity*/ 2, reportErrors2)) != null ? _a2 : emptyGenericType; + return deferredGlobalClassSetterDecoratorContextType ?? (deferredGlobalClassSetterDecoratorContextType = getGlobalType("ClassSetterDecoratorContext", /*arity*/ 2, reportErrors2)) ?? emptyGenericType; } function getGlobalClassAccessorDecoratorContextType(reportErrors2) { - var _a2; - return (_a2 = deferredGlobalClassAccessorDecoratorContextType != null ? deferredGlobalClassAccessorDecoratorContextType : deferredGlobalClassAccessorDecoratorContextType = getGlobalType("ClassAccessorDecoratorContext", /*arity*/ 2, reportErrors2)) != null ? _a2 : emptyGenericType; + return deferredGlobalClassAccessorDecoratorContextType ?? (deferredGlobalClassAccessorDecoratorContextType = getGlobalType("ClassAccessorDecoratorContext", /*arity*/ 2, reportErrors2)) ?? emptyGenericType; } function getGlobalClassAccessorDecoratorTargetType(reportErrors2) { - var _a2; - return (_a2 = deferredGlobalClassAccessorDecoratorTargetType != null ? deferredGlobalClassAccessorDecoratorTargetType : deferredGlobalClassAccessorDecoratorTargetType = getGlobalType("ClassAccessorDecoratorTarget", /*arity*/ 2, reportErrors2)) != null ? _a2 : emptyGenericType; + return deferredGlobalClassAccessorDecoratorTargetType ?? (deferredGlobalClassAccessorDecoratorTargetType = getGlobalType("ClassAccessorDecoratorTarget", /*arity*/ 2, reportErrors2)) ?? emptyGenericType; } function getGlobalClassAccessorDecoratorResultType(reportErrors2) { - var _a2; - return (_a2 = deferredGlobalClassAccessorDecoratorResultType != null ? deferredGlobalClassAccessorDecoratorResultType : deferredGlobalClassAccessorDecoratorResultType = getGlobalType("ClassAccessorDecoratorResult", /*arity*/ 2, reportErrors2)) != null ? _a2 : emptyGenericType; + return deferredGlobalClassAccessorDecoratorResultType ?? (deferredGlobalClassAccessorDecoratorResultType = getGlobalType("ClassAccessorDecoratorResult", /*arity*/ 2, reportErrors2)) ?? emptyGenericType; } function getGlobalClassFieldDecoratorContextType(reportErrors2) { - var _a2; - return (_a2 = deferredGlobalClassFieldDecoratorContextType != null ? deferredGlobalClassFieldDecoratorContextType : deferredGlobalClassFieldDecoratorContextType = getGlobalType("ClassFieldDecoratorContext", /*arity*/ 2, reportErrors2)) != null ? _a2 : emptyGenericType; + return deferredGlobalClassFieldDecoratorContextType ?? (deferredGlobalClassFieldDecoratorContextType = getGlobalType("ClassFieldDecoratorContext", /*arity*/ 2, reportErrors2)) ?? emptyGenericType; } function getGlobalNaNSymbol() { return deferredGlobalNaNSymbol || (deferredGlobalNaNSymbol = getGlobalValueSymbol("NaN", /*reportErrors*/ false)); @@ -52658,11 +53186,11 @@ ${lanes.join("\n")} } function getTupleElementFlags(node) { switch(node.kind){ - case 187 /* OptionalType */ : + case 190 /* OptionalType */ : return 2 /* Optional */ ; - case 188 /* RestType */ : + case 191 /* RestType */ : return getRestTypeElementFlags(node); - case 199 /* NamedTupleMember */ : + case 202 /* NamedTupleMember */ : return node.questionToken ? 2 /* Optional */ : node.dotDotDotToken ? getRestTypeElementFlags(node) : 1 /* Required */ ; default: return 1 /* Required */ ; @@ -52676,55 +53204,57 @@ ${lanes.join("\n")} const elementType = getArrayElementTypeNode(node); if (elementType) return readonly ? globalReadonlyArrayType : globalArrayType; const elementFlags = map(node.elements, getTupleElementFlags); - const missingName = some(node.elements, (e)=>e.kind !== 199 /* NamedTupleMember */ ); - return getTupleTargetType(elementFlags, readonly, /*associatedNames*/ missingName ? void 0 : node.elements); + return getTupleTargetType(elementFlags, readonly, map(node.elements, memberIfLabeledElementDeclaration)); + } + function memberIfLabeledElementDeclaration(member) { + return isNamedTupleMember(member) || isParameter(member) ? member : void 0; } function isDeferredTypeReferenceNode(node, hasDefaultTypeArguments) { - return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 185 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) : node.kind === 186 /* TupleType */ ? some(node.elements, mayResolveTypeAlias) : hasDefaultTypeArguments || some(node.typeArguments, mayResolveTypeAlias)); + return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 188 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) : node.kind === 189 /* TupleType */ ? some(node.elements, mayResolveTypeAlias) : hasDefaultTypeArguments || some(node.typeArguments, mayResolveTypeAlias)); } function isResolvedByTypeAlias(node) { const parent2 = node.parent; switch(parent2.kind){ - case 193 /* ParenthesizedType */ : - case 199 /* NamedTupleMember */ : - case 180 /* TypeReference */ : - case 189 /* UnionType */ : - case 190 /* IntersectionType */ : - case 196 /* IndexedAccessType */ : - case 191 /* ConditionalType */ : - case 195 /* TypeOperator */ : - case 185 /* ArrayType */ : - case 186 /* TupleType */ : + case 196 /* ParenthesizedType */ : + case 202 /* NamedTupleMember */ : + case 183 /* TypeReference */ : + case 192 /* UnionType */ : + case 193 /* IntersectionType */ : + case 199 /* IndexedAccessType */ : + case 194 /* ConditionalType */ : + case 198 /* TypeOperator */ : + case 188 /* ArrayType */ : + case 189 /* TupleType */ : return isResolvedByTypeAlias(parent2); - case 262 /* TypeAliasDeclaration */ : + case 265 /* TypeAliasDeclaration */ : return true; } return false; } function mayResolveTypeAlias(node) { switch(node.kind){ - case 180 /* TypeReference */ : + case 183 /* TypeReference */ : return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node, 788968 /* Type */ ).flags & 524288 /* TypeAlias */ ); - case 183 /* TypeQuery */ : + case 186 /* TypeQuery */ : return true; - case 195 /* TypeOperator */ : - return node.operator !== 156 /* UniqueKeyword */ && mayResolveTypeAlias(node.type); - case 193 /* ParenthesizedType */ : - case 187 /* OptionalType */ : - case 199 /* NamedTupleMember */ : - case 319 /* JSDocOptionalType */ : - case 317 /* JSDocNullableType */ : - case 318 /* JSDocNonNullableType */ : - case 312 /* JSDocTypeExpression */ : + case 198 /* TypeOperator */ : + return node.operator !== 158 /* UniqueKeyword */ && mayResolveTypeAlias(node.type); + case 196 /* ParenthesizedType */ : + case 190 /* OptionalType */ : + case 202 /* NamedTupleMember */ : + case 323 /* JSDocOptionalType */ : + case 321 /* JSDocNullableType */ : + case 322 /* JSDocNonNullableType */ : + case 316 /* JSDocTypeExpression */ : return mayResolveTypeAlias(node.type); - case 188 /* RestType */ : - return node.type.kind !== 185 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType); - case 189 /* UnionType */ : - case 190 /* IntersectionType */ : + case 191 /* RestType */ : + return node.type.kind !== 188 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType); + case 192 /* UnionType */ : + case 193 /* IntersectionType */ : return some(node.types, mayResolveTypeAlias); - case 196 /* IndexedAccessType */ : + case 199 /* IndexedAccessType */ : return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType); - case 191 /* ConditionalType */ : + case 194 /* ConditionalType */ : return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) || mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType); } return false; @@ -52734,9 +53264,9 @@ ${lanes.join("\n")} if (!links.resolvedType) { const target = getArrayOrTupleTargetType(node); if (target === emptyGenericType) links.resolvedType = emptyObjectType; - else if (!(node.kind === 186 /* TupleType */ && some(node.elements, (e)=>!!(getTupleElementFlags(e) & 8 /* Variadic */ ))) && isDeferredTypeReferenceNode(node)) links.resolvedType = node.kind === 186 /* TupleType */ && node.elements.length === 0 ? target : createDeferredTypeReference(target, node, /*mapper*/ void 0); + else if (!(node.kind === 189 /* TupleType */ && some(node.elements, (e)=>!!(getTupleElementFlags(e) & 8 /* Variadic */ ))) && isDeferredTypeReferenceNode(node)) links.resolvedType = node.kind === 189 /* TupleType */ && node.elements.length === 0 ? target : createDeferredTypeReference(target, node, /*mapper*/ void 0); else { - const elementTypes = node.kind === 185 /* ArrayType */ ? [ + const elementTypes = node.kind === 188 /* ArrayType */ ? [ getTypeFromTypeNode(node.elementType) ] : map(node.elements, getTypeFromTypeNode); links.resolvedType = createNormalizedTypeReference(target, elementTypes); @@ -52745,15 +53275,16 @@ ${lanes.join("\n")} return links.resolvedType; } function isReadonlyTypeOperator(node) { - return isTypeOperatorNode(node) && node.operator === 146 /* ReadonlyKeyword */ ; + return isTypeOperatorNode(node) && node.operator === 148 /* ReadonlyKeyword */ ; } - function createTupleType(elementTypes, elementFlags, readonly = false, namedMemberDeclarations) { + function createTupleType(elementTypes, elementFlags, readonly = false, namedMemberDeclarations = []) { const tupleTarget = getTupleTargetType(elementFlags || map(elementTypes, (_)=>1 /* Required */ ), readonly, namedMemberDeclarations); return tupleTarget === emptyGenericType ? emptyObjectType : elementTypes.length ? createNormalizedTypeReference(tupleTarget, elementTypes) : tupleTarget; } function getTupleTargetType(elementFlags, readonly, namedMemberDeclarations) { if (elementFlags.length === 1 && elementFlags[0] & 4 /* Rest */ ) return readonly ? globalReadonlyArrayType : globalArrayType; - const key = map(elementFlags, (f)=>f & 1 /* Required */ ? "#" : f & 2 /* Optional */ ? "?" : f & 4 /* Rest */ ? "." : "*").join() + (readonly ? "R" : "") + (namedMemberDeclarations && namedMemberDeclarations.length ? "," + map(namedMemberDeclarations, getNodeId).join(",") : ""); + const memberIds = mapDefined(namedMemberDeclarations, (node)=>node ? getNodeId(node) : void 0); + const key = map(elementFlags, (f)=>f & 1 /* Required */ ? "#" : f & 2 /* Optional */ ? "?" : f & 4 /* Rest */ ? "." : "*").join() + (readonly ? "R" : "") + (memberIds.length ? "," + memberIds.join(",") : ""); let type = tupleTypes.get(key); if (!type) tupleTypes.set(key, type = createTupleTargetType(elementFlags, readonly, namedMemberDeclarations)); return type; @@ -52815,7 +53346,7 @@ ${lanes.join("\n")} return target.objectFlags & 8 /* Tuple */ ? createNormalizedTupleType(target, typeArguments) : createTypeReference(target, typeArguments); } function createNormalizedTupleType(target, elementTypes) { - var _a2, _b, _c; + var _a, _b, _c; if (!(target.combinedFlags & 14 /* NonRequired */ )) return createTypeReference(target, elementTypes); if (target.combinedFlags & 8 /* Variadic */ ) { const unionIndex = findIndex(elementTypes, (t, i)=>!!(target.elementFlags[i] & 8 /* Variadic */ && t.flags & 1179648 /* Union */ )); @@ -52823,7 +53354,7 @@ ${lanes.join("\n")} } const expandedTypes = []; const expandedFlags = []; - let expandedDeclarations = []; + const expandedDeclarations = []; let lastRequiredIndex = -1; let firstRestIndex = -1; let lastOptionalOrRestIndex = -1; @@ -52831,16 +53362,16 @@ ${lanes.join("\n")} const type = elementTypes[i]; const flags = target.elementFlags[i]; if (flags & 8 /* Variadic */ ) { - if (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type)) addElement(type, 8 /* Variadic */ , (_a2 = target.labeledElementDeclarations) == null ? void 0 : _a2[i]); + if (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type)) addElement(type, 8 /* Variadic */ , (_a = target.labeledElementDeclarations) == null ? void 0 : _a[i]); else if (isTupleType(type)) { - const elements = getTypeArguments(type); + const elements = getElementTypes(type); if (elements.length + expandedTypes.length >= 1e4) { - error(currentNode, isPartOfTypeNode(currentNode) ? Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent : Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent); + error2(currentNode, isPartOfTypeNode(currentNode) ? Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent : Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent); return errorType; } forEach(elements, (t, n)=>{ - var _a3; - return addElement(t, type.target.elementFlags[n], (_a3 = type.target.labeledElementDeclarations) == null ? void 0 : _a3[n]); + var _a2; + return addElement(t, type.target.elementFlags[n], (_a2 = type.target.labeledElementDeclarations) == null ? void 0 : _a2[n]); }); } else addElement(isArrayLikeType(type) && getIndexTypeOfType(type, numberType) || errorType, 4 /* Rest */ , (_b = target.labeledElementDeclarations) == null ? void 0 : _b[i]); } else addElement(type, flags, (_c = target.labeledElementDeclarations) == null ? void 0 : _c[i]); @@ -52850,7 +53381,7 @@ ${lanes.join("\n")} expandedTypes[firstRestIndex] = getUnionType(sameMap(expandedTypes.slice(firstRestIndex, lastOptionalOrRestIndex + 1), (t, i)=>expandedFlags[firstRestIndex + i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t)); expandedTypes.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex); expandedFlags.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex); - expandedDeclarations == null || expandedDeclarations.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex); + expandedDeclarations.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex); } const tupleTarget = getTupleTargetType(expandedFlags, target.readonly, expandedDeclarations); return tupleTarget === emptyGenericType ? emptyObjectType : expandedFlags.length ? createTypeReference(tupleTarget, expandedTypes) : tupleTarget; @@ -52860,8 +53391,7 @@ ${lanes.join("\n")} if (flags & 6 /* Rest */ ) lastOptionalOrRestIndex = expandedFlags.length; expandedTypes.push(flags & 2 /* Optional */ ? addOptionality(type, /*isProperty*/ true) : type); expandedFlags.push(flags); - if (expandedDeclarations && declaration) expandedDeclarations.push(declaration); - else expandedDeclarations = void 0; + expandedDeclarations.push(declaration); } } function sliceTupleType(type, index, endSkipCount = 0) { @@ -52879,6 +53409,14 @@ ${lanes.join("\n")} function getEndElementCount(type, flags) { return type.elementFlags.length - findLastIndex(type.elementFlags, (f)=>!(f & flags)) - 1; } + function getTotalFixedElementCount(type) { + return type.fixedLength + getEndElementCount(type, 3 /* Fixed */ ); + } + function getElementTypes(type) { + const typeArguments = getTypeArguments(type); + const arity = getTypeReferenceArity(type); + return typeArguments.length === arity ? typeArguments : typeArguments.slice(0, arity); + } function getTypeFromOptionalTypeNode(node) { return addOptionality(getTypeFromTypeNode(node.type), /*isProperty*/ true); } @@ -52898,9 +53436,8 @@ ${lanes.join("\n")} } function addTypeToUnion(typeSet, includes, type) { const flags = type.flags; - if (flags & 1048576 /* Union */ ) return addTypesToUnion(typeSet, includes | (isNamedUnionType(type) ? 1048576 /* Union */ : 0), type.types); if (!(flags & 131072 /* Never */ )) { - includes |= flags & 205258751 /* IncludesMask */ ; + includes |= flags & 473694207 /* IncludesMask */ ; if (flags & 465829888 /* Instantiable */ ) includes |= 33554432 /* IncludesInstantiable */ ; if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */ ; if (!strictNullChecks && flags & 98304 /* Nullable */ ) { @@ -52914,11 +53451,15 @@ ${lanes.join("\n")} return includes; } function addTypesToUnion(typeSet, includes, types) { - for (const type of types)includes = addTypeToUnion(typeSet, includes, type); + let lastType; + for (const type of types)if (type !== lastType) { + includes = type.flags & 1048576 /* Union */ ? addTypesToUnion(typeSet, includes | (isNamedUnionType(type) ? 1048576 /* Union */ : 0), type.types) : addTypeToUnion(typeSet, includes, type); + lastType = type; + } return includes; } function removeSubtypes(types, hasObjectTypes) { - var _a2; + var _a; if (types.length < 2) return types; const id = getTypeListId(types); const match = subtypeReductionCache.get(id); @@ -52941,10 +53482,10 @@ ${lanes.join("\n")} if (count === 1e5) { const estimatedCount = count / (len - i) * len; if (estimatedCount > 1e6) { - (_a2 = tracing) == null || _a2.instant(tracing.Phase.CheckTypes, "removeSubtypes_DepthLimit", { + (_a = tracing) == null || _a.instant(tracing.Phase.CheckTypes, "removeSubtypes_DepthLimit", { typeIds: types.map((t)=>t.id) }); - error(currentNode, Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); + error2(currentNode, Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); return void 0; } } @@ -53002,6 +53543,20 @@ ${lanes.join("\n")} function getUnionType(types, unionReduction = 1 /* Literal */ , aliasSymbol, aliasTypeArguments, origin) { if (types.length === 0) return neverType; if (types.length === 1) return types[0]; + if (types.length === 2 && !origin && (types[0].flags & 1048576 /* Union */ || types[1].flags & 1048576 /* Union */ )) { + const infix = unionReduction === 0 /* None */ ? "N" : unionReduction === 2 /* Subtype */ ? "S" : "L"; + const index = types[0].id < types[1].id ? 0 : 1; + const id = types[index].id + infix + types[1 - index].id + getAliasId(aliasSymbol, aliasTypeArguments); + let type = unionOfUnionTypes.get(id); + if (!type) { + type = getUnionTypeWorker(types, unionReduction, aliasSymbol, aliasTypeArguments, /*origin*/ void 0); + unionOfUnionTypes.set(id, type); + } + return type; + } + return getUnionTypeWorker(types, unionReduction, aliasSymbol, aliasTypeArguments, origin); + } + function getUnionTypeWorker(types, unionReduction, aliasSymbol, aliasTypeArguments, origin) { let typeSet = []; const includes = addTypesToUnion(typeSet, 0, types); if (unionReduction !== 0 /* None */ ) { @@ -53029,26 +53584,26 @@ ${lanes.join("\n")} origin = createOriginUnionOrIntersectionType(1048576 /* Union */ , reducedTypes); } } - const objectFlags = (includes & 36323363 /* NotPrimitiveUnion */ ? 0 : 32768 /* PrimitiveUnion */ ) | (includes & 2097152 /* Intersection */ ? 16777216 /* ContainsIntersections */ : 0); + const objectFlags = (includes & 36323331 /* NotPrimitiveUnion */ ? 0 : 32768 /* PrimitiveUnion */ ) | (includes & 2097152 /* Intersection */ ? 16777216 /* ContainsIntersections */ : 0); return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin); } function getUnionOrIntersectionTypePredicate(signatures, kind) { - let first2; + let last2; const types = []; for (const sig of signatures){ const pred = getTypePredicateOfSignature(sig); - if (!pred || pred.kind === 2 /* AssertsThis */ || pred.kind === 3 /* AssertsIdentifier */ ) { - if (kind !== 2097152 /* Intersection */ ) continue; - else return; + if (pred) { + if (pred.kind !== 0 /* This */ && pred.kind !== 1 /* Identifier */ || last2 && !typePredicateKindsMatch(last2, pred)) return void 0; + last2 = pred; + types.push(pred.type); + } else { + const returnType = kind !== 2097152 /* Intersection */ ? getReturnTypeOfSignature(sig) : void 0; + if (returnType !== falseType && returnType !== regularFalseType) return void 0; } - if (first2) { - if (!typePredicateKindsMatch(first2, pred)) return void 0; - } else first2 = pred; - types.push(pred.type); } - if (!first2) return void 0; + if (!last2) return void 0; const compositeType = getUnionOrIntersectionType(types, kind); - return createTypePredicate(first2.kind, first2.parameterName, first2.parameterIndex, compositeType); + return createTypePredicate(last2.kind, last2.parameterName, last2.parameterIndex, compositeType); } function typePredicateKindsMatch(a, b) { return a.kind === b.kind && a.parameterIndex === b.parameterIndex; @@ -53103,7 +53658,7 @@ ${lanes.join("\n")} typeSet.set(type.id.toString(), type); } } - includes |= flags & 205258751 /* IncludesMask */ ; + includes |= flags & 473694207 /* IncludesMask */ ; } return includes; } @@ -53122,7 +53677,7 @@ ${lanes.join("\n")} } function eachUnionContains(unionTypes2, type) { for (const u of unionTypes2)if (!containsType(u.types, type)) { - const primitive = type.flags & 128 /* StringLiteral */ ? stringType : type.flags & 256 /* NumberLiteral */ ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : void 0; + const primitive = type.flags & 128 /* StringLiteral */ ? stringType : type.flags & 288 /* NumberLiteral */ ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : void 0; if (!primitive || !containsType(u.types, primitive)) return false; } return true; @@ -53143,9 +53698,6 @@ ${lanes.join("\n")} } return false; } - function eachIsUnionContaining(types, flag) { - return every(types, (t)=>!!(t.flags & 1048576 /* Union */ ) && some(t.types, (tt)=>!!(tt.flags & flag))); - } function removeFromEach(types, flag) { for(let i = 0; i < types.length; i++)types[i] = filterType(types[i], (t)=>!(t.flags & flag)); } @@ -53202,14 +53754,14 @@ ${lanes.join("\n")} if (!result) { if (includes & 1048576 /* Union */ ) { if (intersectUnionsOfPrimitiveTypes(typeSet)) result = getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments); - else if (eachIsUnionContaining(typeSet, 32768 /* Undefined */ )) { + else if (every(typeSet, (t)=>!!(t.flags & 1048576 /* Union */ && t.types[0].flags & 32768 /* Undefined */ ))) { const containedUndefinedType = some(typeSet, containsMissingType) ? missingType : undefinedType; removeFromEach(typeSet, 32768 /* Undefined */ ); result = getUnionType([ getIntersectionType(typeSet), containedUndefinedType ], 1 /* Literal */ , aliasSymbol, aliasTypeArguments); - } else if (eachIsUnionContaining(typeSet, 65536 /* Null */ )) { + } else if (every(typeSet, (t)=>!!(t.flags & 1048576 /* Union */ && (t.types[0].flags & 65536 /* Null */ || t.types[1].flags & 65536 /* Null */ )))) { removeFromEach(typeSet, 65536 /* Null */ ); result = getUnionType([ getIntersectionType(typeSet), @@ -53230,14 +53782,14 @@ ${lanes.join("\n")} return reduceLeft(types, (n, t)=>t.flags & 1048576 /* Union */ ? n * t.types.length : t.flags & 131072 /* Never */ ? 0 : n, 1); } function checkCrossProductUnion(types) { - var _a2; + var _a; const size = getCrossProductUnionSize(types); if (size >= 1e5) { - (_a2 = tracing) == null || _a2.instant(tracing.Phase.CheckTypes, "checkCrossProductUnion_DepthLimit", { + (_a = tracing) == null || _a.instant(tracing.Phase.CheckTypes, "checkCrossProductUnion_DepthLimit", { typeIds: types.map((t)=>t.id), size: size }); - error(currentNode, Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); + error2(currentNode, Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); return false; } return true; @@ -53265,20 +53817,23 @@ ${lanes.join("\n")} function getConstituentCountOfTypes(types) { return reduceLeft(types, (n, t)=>n + getConstituentCount(t), 0); } + function areIntersectedTypesAvoidingPrimitiveReduction(t1, t2) { + return !!(t1.flags & 76 /* BigInt */ ) && t2 === emptyTypeLiteralType; + } function getTypeFromIntersectionTypeNode(node) { const links = getNodeLinks(node); if (!links.resolvedType) { const aliasSymbol = getAliasSymbolForTypeNode(node); const types = map(node.types, getTypeFromTypeNode); - const noSupertypeReduction = types.length === 2 && !!(types[0].flags & 76 /* BigInt */ ) && types[1] === emptyTypeLiteralType; + const noSupertypeReduction = types.length === 2 && (areIntersectedTypesAvoidingPrimitiveReduction(types[0], types[1]) || areIntersectedTypesAvoidingPrimitiveReduction(types[1], types[0])); links.resolvedType = getIntersectionType(types, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol), noSupertypeReduction); } return links.resolvedType; } - function createIndexType(type, stringsOnly) { + function createIndexType(type, indexFlags) { const result = createType(4194304 /* Index */ ); result.type = type; - result.stringsOnly = stringsOnly; + result.indexFlags = indexFlags; return result; } function createOriginIndexType(type) { @@ -53286,23 +53841,23 @@ ${lanes.join("\n")} result.type = type; return result; } - function getIndexTypeForGenericType(type, stringsOnly) { - return stringsOnly ? type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); + function getIndexTypeForGenericType(type, indexFlags) { + return indexFlags & 1 /* StringsOnly */ ? type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, 1 /* StringsOnly */ )) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, 0 /* None */ )); } - function getIndexTypeForMappedType(type, stringsOnly, noIndexSignatures) { + function getIndexTypeForMappedType(type, indexFlags) { const typeParameter = getTypeParameterFromMappedType(type); const constraintType = getConstraintTypeFromMappedType(type); const nameType = getNameTypeFromMappedType(type.target || type); - if (!nameType && !noIndexSignatures) return constraintType; + if (!nameType && !(indexFlags & 2 /* NoIndexSignatures */ )) return constraintType; const keyTypes = []; if (isMappedTypeWithKeyofConstraintDeclaration(type)) { if (!isGenericIndexType(constraintType)) { const modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); - forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType(modifiersType, 8576 /* StringOrNumberLiteralOrUnique */ , stringsOnly, addMemberForKeyType); - } else return getIndexTypeForGenericType(type, stringsOnly); + forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType(modifiersType, 8576 /* StringOrNumberLiteralOrUnique */ , !!(indexFlags & 1 /* StringsOnly */ ), addMemberForKeyType); + } else return getIndexTypeForGenericType(type, indexFlags); } else forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType); if (isGenericIndexType(constraintType)) forEachType(constraintType, addMemberForKeyType); - const result = noIndexSignatures ? filterType(getUnionType(keyTypes), (t)=>!(t.flags & 5 /* String */ )) : getUnionType(keyTypes); + const result = indexFlags & 2 /* NoIndexSignatures */ ? filterType(getUnionType(keyTypes), (t)=>!(t.flags & 5 /* String */ )) : getUnionType(keyTypes); if (result.flags & 1048576 /* Union */ && constraintType.flags & 1048576 /* Union */ && getTypeListId(result.types) === getTypeListId(constraintType.types)) return constraintType; return result; function addMemberForKeyType(keyType) { @@ -53314,12 +53869,17 @@ ${lanes.join("\n")} const typeVariable = getTypeParameterFromMappedType(mappedType); return isDistributive(getNameTypeFromMappedType(mappedType) || typeVariable); function isDistributive(type) { - return type.flags & 202375167 /* NonPrimitive */ ? true : type.flags & 16777216 /* Conditional */ ? type.root.isDistributive && type.checkType === typeVariable : type.flags & 137363456 /* TemplateLiteral */ ? every(type.types, isDistributive) : type.flags & 8388608 /* IndexedAccess */ ? isDistributive(type.objectType) && isDistributive(type.indexType) : type.flags & 33554432 /* Substitution */ ? isDistributive(type.baseType) && isDistributive(type.constraint) : type.flags & 268435456 /* StringMapping */ ? isDistributive(type.type) : false; + return type.flags & 470810623 /* NonPrimitive */ ? true : type.flags & 16777216 /* Conditional */ ? type.root.isDistributive && type.checkType === typeVariable : type.flags & 137363456 /* TemplateLiteral */ ? every(type.types, isDistributive) : type.flags & 8388608 /* IndexedAccess */ ? isDistributive(type.objectType) && isDistributive(type.indexType) : type.flags & 33554432 /* Substitution */ ? isDistributive(type.baseType) && isDistributive(type.constraint) : type.flags & 268435456 /* StringMapping */ ? isDistributive(type.type) : false; } } function getLiteralTypeFromPropertyName(name) { if (isPrivateIdentifier(name)) return neverType; - return isIdentifier(name) ? getStringLiteralType(unescapeLeadingUnderscores(name.escapedText)) : getRegularTypeOfLiteralType(isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name)); + if (isNumericLiteral(name)) return getRegularTypeOfLiteralType(checkExpression(name)); + if (isComputedPropertyName(name)) return getRegularTypeOfLiteralType(checkComputedPropertyName(name)); + const propertyName = getPropertyNameForPropertyNameNode(name); + if (propertyName !== void 0) return getStringLiteralType(unescapeLeadingUnderscores(propertyName)); + if (isExpression(name)) return getRegularTypeOfLiteralType(checkExpression(name)); + return neverType; } function getLiteralTypeFromProperty(prop, include, includeNonPublic) { if (includeNonPublic || !(getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ )) { @@ -53341,16 +53901,12 @@ ${lanes.join("\n")} const indexKeyTypes = map(getIndexInfosOfType(type), (info)=>info !== enumNumberIndexInfo && isKeyTypeIncluded(info.keyType, include) ? info.keyType === stringType && include & 8 /* Number */ ? stringOrNumberType : info.keyType : neverType); return getUnionType(concatenate(propertyTypes, indexKeyTypes), 1 /* Literal */ , /*aliasSymbol*/ void 0, /*aliasTypeArguments*/ void 0, origin); } - function isPossiblyReducibleByInstantiation(type) { - const uniqueFilled = getUniqueLiteralFilledInstantiation(type); - return getReducedType(uniqueFilled) !== uniqueFilled; - } - function shouldDeferIndexType(type) { - return !!(type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericTupleType(type) || isGenericMappedType(type) && !hasDistributiveNameType(type) || type.flags & 1048576 /* Union */ && some(type.types, isPossiblyReducibleByInstantiation) || type.flags & 2097152 /* Intersection */ && maybeTypeOfKind(type, 465829888 /* Instantiable */ ) && some(type.types, isEmptyAnonymousObjectType)); + function shouldDeferIndexType(type, indexFlags = 0 /* None */ ) { + return !!(type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericTupleType(type) || isGenericMappedType(type) && !hasDistributiveNameType(type) || type.flags & 1048576 /* Union */ && !(indexFlags & 4 /* NoReducibleCheck */ ) && isGenericReducibleType(type) || type.flags & 2097152 /* Intersection */ && maybeTypeOfKind(type, 465829888 /* Instantiable */ ) && some(type.types, isEmptyAnonymousObjectType)); } - function getIndexType(type, stringsOnly = keyofStringsOnly, noIndexSignatures) { + function getIndexType(type, indexFlags = defaultIndexFlags) { type = getReducedType(type); - return shouldDeferIndexType(type) ? getIndexTypeForGenericType(type, stringsOnly) : type.flags & 1048576 /* Union */ ? getIntersectionType(map(type.types, (t)=>getIndexType(t, stringsOnly, noIndexSignatures))) : type.flags & 2097152 /* Intersection */ ? getUnionType(map(type.types, (t)=>getIndexType(t, stringsOnly, noIndexSignatures))) : getObjectFlags(type) & 32 /* Mapped */ ? getIndexTypeForMappedType(type, stringsOnly, noIndexSignatures) : type === wildcardType ? wildcardType : type.flags & 2 /* Unknown */ ? neverType : type.flags & 131073 /* Never */ ? keyofConstraintType : getLiteralTypeFromProperties(type, (noIndexSignatures ? 128 /* StringLiteral */ : 402653316 /* StringLike */ ) | (stringsOnly ? 0 : 12584 /* ESSymbolLike */ ), stringsOnly === keyofStringsOnly && !noIndexSignatures); + return shouldDeferIndexType(type, indexFlags) ? getIndexTypeForGenericType(type, indexFlags) : type.flags & 1048576 /* Union */ ? getIntersectionType(map(type.types, (t)=>getIndexType(t, indexFlags))) : type.flags & 2097152 /* Intersection */ ? getUnionType(map(type.types, (t)=>getIndexType(t, indexFlags))) : getObjectFlags(type) & 32 /* Mapped */ ? getIndexTypeForMappedType(type, indexFlags) : type === wildcardType ? wildcardType : type.flags & 2 /* Unknown */ ? neverType : type.flags & 131073 /* Never */ ? keyofConstraintType : getLiteralTypeFromProperties(type, (indexFlags & 2 /* NoIndexSignatures */ ? 128 /* StringLiteral */ : 402653316 /* StringLike */ ) | (indexFlags & 1 /* StringsOnly */ ? 0 : 12584 /* ESSymbolLike */ ), indexFlags === defaultIndexFlags); } function getExtractStringType(type) { if (keyofStringsOnly) return type; @@ -53367,17 +53923,17 @@ ${lanes.join("\n")} function getTypeFromTypeOperatorNode(node) { const links = getNodeLinks(node); if (!links.resolvedType) switch(node.operator){ - case 141 /* KeyOfKeyword */ : + case 143 /* KeyOfKeyword */ : links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); break; - case 156 /* UniqueKeyword */ : - links.resolvedType = node.type.kind === 153 /* SymbolKeyword */ ? getESSymbolLikeTypeForNode(walkUpParenthesizedTypes(node.parent)) : errorType; + case 158 /* UniqueKeyword */ : + links.resolvedType = node.type.kind === 155 /* SymbolKeyword */ ? getESSymbolLikeTypeForNode(walkUpParenthesizedTypes(node.parent)) : errorType; break; - case 146 /* ReadonlyKeyword */ : + case 148 /* ReadonlyKeyword */ : links.resolvedType = getTypeFromTypeNode(node.type); break; default: - throw Debug.assertNever(node.operator); + Debug.assertNever(node.operator); } return links.resolvedType; } @@ -53408,27 +53964,20 @@ ${lanes.join("\n")} if (!type) templateLiteralTypes.set(id, type = createTemplateLiteralType(newTexts, newTypes)); return type; function addSpans(texts2, types2) { - const isTextsArray = isArray(texts2); for(let i = 0; i < types2.length; i++){ const t = types2[i]; - const addText = isTextsArray ? texts2[i + 1] : texts2; if (t.flags & 101248 /* Undefined */ ) { text += getTemplateStringForType(t) || ""; - text += addText; - if (!isTextsArray) return true; + text += texts2[i + 1]; } else if (t.flags & 134217728 /* TemplateLiteral */ ) { text += t.texts[0]; if (!addSpans(t.texts, t.types)) return false; - text += addText; - if (!isTextsArray) return true; + text += texts2[i + 1]; } else if (isGenericIndexType(t) || isPatternLiteralPlaceholderType(t)) { newTypes.push(t); newTexts.push(text); - text = addText; - } else if (t.flags & 2097152 /* Intersection */ ) { - const added = addSpans(texts2[i + 1], t.types); - if (!added) return false; - } else if (isTextsArray) return false; + text = texts2[i + 1]; + } else return false; } return true; } @@ -53438,6 +53987,7 @@ ${lanes.join("\n")} } function createTemplateLiteralType(texts, types) { const type = createType(134217728 /* TemplateLiteral */ ); + type.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */ ); type.texts = texts; type.types = types; return type; @@ -53544,26 +54094,25 @@ ${lanes.join("\n")} if (symbol.flags & 8208 /* Method */ ) { const parent2 = findAncestor(node.parent, (n)=>!isAccessExpression(n)) || node.parent; if (isCallLikeExpression(parent2)) return isCallOrNewExpression(parent2) && isIdentifier(node) && hasMatchingArgument(parent2, node); - return every(symbol.declarations, (d)=>!isFunctionLike(d) || !!(getCombinedNodeFlags(d) & 268435456 /* Deprecated */ )); + return every(symbol.declarations, (d)=>!isFunctionLike(d) || isDeprecatedDeclaration2(d)); } return true; } function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, accessNode, accessFlags) { - var _a2; - const accessExpression = accessNode && accessNode.kind === 209 /* ElementAccessExpression */ ? accessNode : void 0; + const accessExpression = accessNode && accessNode.kind === 212 /* ElementAccessExpression */ ? accessNode : void 0; const propName = accessNode && isPrivateIdentifier(accessNode) ? void 0 : getPropertyNameFromIndex(indexType, accessNode); if (propName !== void 0) { if (accessFlags & 256 /* Contextual */ ) return getTypeOfPropertyOfContextualType(objectType, propName) || anyType; const prop = getPropertyOfType(objectType, propName); if (prop) { if (accessFlags & 64 /* ReportDeprecated */ && accessNode && prop.declarations && isDeprecatedSymbol(prop) && isUncalledFunctionReference(accessNode, prop)) { - const deprecatedNode = (_a2 = accessExpression == null ? void 0 : accessExpression.argumentExpression) != null ? _a2 : isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode; + const deprecatedNode = (accessExpression == null ? void 0 : accessExpression.argumentExpression) ?? (isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode); addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName); } if (accessExpression) { markPropertyAsReferenced(prop, accessExpression, isSelfTypeAccess(accessExpression.expression, objectType.symbol)); if (isAssignmentToReadonlyEntity(accessExpression, prop, getAssignmentTargetKind(accessExpression))) { - error(accessExpression.argumentExpression, Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); + error2(accessExpression.argumentExpression, Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); return void 0; } if (accessFlags & 8 /* CacheSymbol */ ) getNodeLinks(accessNode).resolvedSymbol = prop; @@ -53581,21 +54130,15 @@ ${lanes.join("\n")} const indexNode = getIndexNodeForAccessExpression(accessNode); if (isTupleType(objectType)) { if (index < 0) { - error(indexNode, Diagnostics.A_tuple_type_cannot_be_indexed_with_a_negative_value); + error2(indexNode, Diagnostics.A_tuple_type_cannot_be_indexed_with_a_negative_value); return undefinedType; } - error(indexNode, Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), unescapeLeadingUnderscores(propName)); - } else error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType)); + error2(indexNode, Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), unescapeLeadingUnderscores(propName)); + } else error2(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType)); } if (index >= 0) { errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType)); - return mapType(objectType, (t)=>{ - const restType = getRestTypeOfTupleType(t) || undefinedType; - return accessFlags & 1 /* IncludeUndefined */ ? getUnionType([ - restType, - missingType - ]) : restType; - }); + return getTupleElementTypeOutOfStartCount(objectType, index, accessFlags & 1 /* IncludeUndefined */ ? missingType : void 0); } } } @@ -53604,12 +54147,12 @@ ${lanes.join("\n")} const indexInfo = getApplicableIndexInfo(objectType, indexType) || getIndexInfoOfType(objectType, stringType); if (indexInfo) { if (accessFlags & 2 /* NoIndexSignatures */ && indexInfo.keyType !== numberType) { - if (accessExpression) error(accessExpression, Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(originalObjectType)); + if (accessExpression) error2(accessExpression, Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(originalObjectType)); return void 0; } if (accessNode && indexInfo.keyType === stringType && !isTypeAssignableToKind(indexType, 12 /* Number */ )) { const indexNode = getIndexNodeForAccessExpression(accessNode); - error(indexNode, Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + error2(indexNode, Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); return accessFlags & 1 /* IncludeUndefined */ ? getUnionType([ indexInfo.type, missingType @@ -53636,28 +54179,28 @@ ${lanes.join("\n")} return getUnionType(append(types, undefinedType)); } } - if (objectType.symbol === globalThisSymbol && propName !== void 0 && globalThisSymbol.exports.has(propName) && globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */ ) error(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType)); + if (objectType.symbol === globalThisSymbol && propName !== void 0 && globalThisSymbol.exports.has(propName) && globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */ ) error2(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType)); else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !(accessFlags & 128 /* SuppressNoImplicitAnyError */ )) { if (propName !== void 0 && typeHasStaticProperty(propName, objectType)) { const typeName = typeToString(objectType); - error(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead, propName, typeName, typeName + "[" + getTextOfNode(accessExpression.argumentExpression) + "]"); - } else if (getIndexTypeOfType(objectType, numberType)) error(accessExpression.argumentExpression, Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); + error2(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead, propName, typeName, typeName + "[" + getTextOfNode(accessExpression.argumentExpression) + "]"); + } else if (getIndexTypeOfType(objectType, numberType)) error2(accessExpression.argumentExpression, Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); else { let suggestion; if (propName !== void 0 && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) { - if (suggestion !== void 0) error(accessExpression.argumentExpression, Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion); + if (suggestion !== void 0) error2(accessExpression.argumentExpression, Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion); } else { const suggestion2 = getSuggestionForNonexistentIndexSignature(objectType, accessExpression, indexType); - if (suggestion2 !== void 0) error(accessExpression, Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1, typeToString(objectType), suggestion2); + if (suggestion2 !== void 0) error2(accessExpression, Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1, typeToString(objectType), suggestion2); else { let errorInfo; - if (indexType.flags & 1024 /* EnumLiteral */ ) errorInfo = chainDiagnosticMessages(/* details */ void 0, Diagnostics.Property_0_does_not_exist_on_type_1, "[" + typeToString(indexType) + "]", typeToString(objectType)); + if (indexType.flags & 1024 /* EnumLiteral */ ) errorInfo = chainDiagnosticMessages(/*details*/ void 0, Diagnostics.Property_0_does_not_exist_on_type_1, "[" + typeToString(indexType) + "]", typeToString(objectType)); else if (indexType.flags & 8192 /* UniqueESSymbol */ ) { const symbolName2 = getFullyQualifiedName(indexType.symbol, accessExpression); - errorInfo = chainDiagnosticMessages(/* details */ void 0, Diagnostics.Property_0_does_not_exist_on_type_1, "[" + symbolName2 + "]", typeToString(objectType)); - } else if (indexType.flags & 128 /* StringLiteral */ ) errorInfo = chainDiagnosticMessages(/* details */ void 0, Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType)); - else if (indexType.flags & 256 /* NumberLiteral */ ) errorInfo = chainDiagnosticMessages(/* details */ void 0, Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType)); - else if (indexType.flags & 12 /* String */ ) errorInfo = chainDiagnosticMessages(/* details */ void 0, Diagnostics.No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1, typeToString(indexType), typeToString(objectType)); + errorInfo = chainDiagnosticMessages(/*details*/ void 0, Diagnostics.Property_0_does_not_exist_on_type_1, "[" + symbolName2 + "]", typeToString(objectType)); + } else if (indexType.flags & 128 /* StringLiteral */ ) errorInfo = chainDiagnosticMessages(/*details*/ void 0, Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType)); + else if (indexType.flags & 256 /* NumberLiteral */ ) errorInfo = chainDiagnosticMessages(/*details*/ void 0, Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType)); + else if (indexType.flags & 12 /* String */ ) errorInfo = chainDiagnosticMessages(/*details*/ void 0, Diagnostics.No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1, typeToString(indexType), typeToString(objectType)); errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1, typeToString(fullIndexType), typeToString(objectType)); diagnostics.add(createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(accessExpression), accessExpression, errorInfo)); } @@ -53670,20 +54213,21 @@ ${lanes.join("\n")} if (isJSLiteralType(objectType)) return anyType; if (accessNode) { const indexNode = getIndexNodeForAccessExpression(accessNode); - if (indexType.flags & 384 /* NumberLiteral */ ) error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); - else if (indexType.flags & 12 /* Number */ ) error(indexNode, Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); - else error(indexNode, Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + if (indexType.flags & 384 /* NumberLiteral */ ) error2(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); + else if (indexType.flags & 12 /* Number */ ) error2(indexNode, Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); + else error2(indexNode, Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } if (isTypeAny(indexType)) return indexType; return void 0; function errorIfWritingToReadonlyIndex(indexInfo) { - if (indexInfo && indexInfo.isReadonly && accessExpression && (isAssignmentTarget(accessExpression) || isDeleteTarget(accessExpression))) error(accessExpression, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + if (indexInfo && indexInfo.isReadonly && accessExpression && (isAssignmentTarget(accessExpression) || isDeleteTarget(accessExpression))) error2(accessExpression, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } } function getIndexNodeForAccessExpression(accessNode) { - return accessNode.kind === 209 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.kind === 196 /* IndexedAccessType */ ? accessNode.indexType : accessNode.kind === 164 /* ComputedPropertyName */ ? accessNode.expression : accessNode; + return accessNode.kind === 212 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.kind === 199 /* IndexedAccessType */ ? accessNode.indexType : accessNode.kind === 167 /* ComputedPropertyName */ ? accessNode.expression : accessNode; } function isPatternLiteralPlaceholderType(type) { + if (type.flags & 2097152 /* Intersection */ ) return some(type.types, (t)=>!!(t.flags & 101248 /* Undefined */ ) || isPatternLiteralPlaceholderType(t)); return !!(type.flags & 77 /* BigInt */ ) || isPatternLiteralType(type); } function isPatternLiteralType(type) { @@ -53699,7 +54243,7 @@ ${lanes.join("\n")} return !!(getGenericObjectFlags(type) & 8388608 /* IsGenericIndexType */ ); } function getGenericObjectFlags(type) { - if (type.flags & 3145728 /* UnionOrIntersection */ ) { + if (type.flags & 137363456 /* TemplateLiteral */ ) { if (!(type.objectFlags & 2097152 /* IsGenericTypeComputed */ )) type.objectFlags |= 2097152 /* IsGenericTypeComputed */ | reduceLeft(type.types, (flags, t)=>flags | getGenericObjectFlags(t), 0); return type.objectFlags & 12582912 /* IsGenericType */ ; } @@ -53707,7 +54251,7 @@ ${lanes.join("\n")} if (!(type.objectFlags & 2097152 /* IsGenericTypeComputed */ )) type.objectFlags |= 2097152 /* IsGenericTypeComputed */ | getGenericObjectFlags(type.baseType) | getGenericObjectFlags(type.constraint); return type.objectFlags & 12582912 /* IsGenericType */ ; } - return (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type) || isGenericTupleType(type) ? 4194304 /* IsGenericObjectType */ : 0) | (type.flags & 465829888 /* StringMapping */ && !isPatternLiteralType(type) ? 8388608 /* IsGenericIndexType */ : 0); + return (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type) || isGenericTupleType(type) ? 4194304 /* IsGenericObjectType */ : 0) | (type.flags & 331612160 /* StringMapping */ && !isPatternLiteralType(type) ? 8388608 /* IsGenericIndexType */ : 0); } function getSimplifiedType(type, writing) { return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type, writing) : type.flags & 16777216 /* Conditional */ ? getSimplifiedConditionalType(type, writing) : type; @@ -53791,9 +54335,10 @@ ${lanes.join("\n")} } function getIndexedAccessTypeOrUndefined(objectType, indexType, accessFlags = 0 /* None */ , accessNode, aliasSymbol, aliasTypeArguments) { if (objectType === wildcardType || indexType === wildcardType) return wildcardType; + objectType = getReducedType(objectType); if (isStringIndexSignatureOnlyType(objectType) && !(indexType.flags & 98304 /* Nullable */ ) && isTypeAssignableToKind(indexType, 12 /* Number */ )) indexType = stringType; if (compilerOptions.noUncheckedIndexedAccess && accessFlags & 32 /* ExpressionPosition */ ) accessFlags |= 1 /* IncludeUndefined */ ; - if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 196 /* IndexedAccessType */ ? isGenericTupleType(objectType) && !indexTypeLessThan(indexType, objectType.target.fixedLength) : isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, objectType.target.fixedLength)))) { + if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 199 /* IndexedAccessType */ ? isGenericTupleType(objectType) && !indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target)) : isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target))) || isGenericReducibleType(objectType))) { if (objectType.flags & 3 /* AnyOrUnknown */ ) return objectType; const persistentAccessFlags = accessFlags & 1 /* Persistent */ ; const id = objectType.id + "," + indexType.id + "," + persistentAccessFlags + getAliasId(aliasSymbol, aliasTypeArguments); @@ -53851,7 +54396,7 @@ ${lanes.join("\n")} return isTupleTypeNode(node) && length(node.elements) > 0 && !some(node.elements, (e)=>isOptionalTypeNode(e) || isRestTypeNode(e) || isNamedTupleMember(e) && !!(e.questionToken || e.dotDotDotToken)); } function isDeferredType(type, checkTuples) { - return isGenericType(type) || checkTuples && isTupleType(type) && some(getTypeArguments(type), isGenericType); + return isGenericType(type) || checkTuples && isTupleType(type) && some(getElementTypes(type), isGenericType); } function getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { let result; @@ -53859,15 +54404,15 @@ ${lanes.join("\n")} let tailCount = 0; while(true){ if (tailCount === 1e3) { - error(currentNode, Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); - result = errorType; - break; + error2(currentNode, Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); + return errorType; } - const checkTuples = isSimpleTupleType(root.node.checkType) && isSimpleTupleType(root.node.extendsType) && length(root.node.checkType.elements) === length(root.node.extendsType.elements); const checkType = instantiateType(getActualTypeVariable(root.checkType), mapper); - const checkTypeDeferred = isDeferredType(checkType, checkTuples); const extendsType = instantiateType(root.extendsType, mapper); + if (checkType === errorType || extendsType === errorType) return errorType; if (checkType === wildcardType || extendsType === wildcardType) return wildcardType; + const checkTuples = isSimpleTupleType(root.node.checkType) && isSimpleTupleType(root.node.extendsType) && length(root.node.checkType.elements) === length(root.node.extendsType.elements); + const checkTypeDeferred = isDeferredType(checkType, checkTuples); let combinedMapper; if (root.inferTypeParameters) { const freshParams = sameMap(root.inferTypeParameters, maybeCloneTypeParameter); @@ -53875,7 +54420,7 @@ ${lanes.join("\n")} const context = createInferenceContext(freshParams, /*signature*/ void 0, 0 /* None */ ); if (freshMapper) { const freshCombinedMapper = combineTypeMappers(mapper, freshMapper); - for (const p of freshParams)if (root.inferTypeParameters.indexOf(p) === -1) p.mapper = freshCombinedMapper; + for(let i = 0; i < freshParams.length; i++)if (freshParams[i] !== root.inferTypeParameters[i]) freshParams[i].mapper = freshCombinedMapper; } if (!checkTypeDeferred) inferTypes(context.inferences, checkType, instantiateType(extendsType, freshMapper), 1536 /* AlwaysStrict */ ); const innerMapper = combineTypeMappers(freshMapper, context.mapper); @@ -53995,21 +54540,21 @@ ${lanes.join("\n")} else return append(getIdentifierChain(node.left), node.right); } function getTypeFromImportTypeNode(node) { - var _a2; + var _a; const links = getNodeLinks(node); if (!links.resolvedType) { if (!isLiteralImportTypeNode(node)) { - error(node.argument, Diagnostics.String_literal_expected); + error2(node.argument, Diagnostics.String_literal_expected); links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - const targetMeaning = node.isTypeOf ? 111551 /* Value */ : node.flags & 8388608 /* JSDoc */ ? 900095 /* Type */ : 788968 /* Type */ ; + const targetMeaning = node.isTypeOf ? 111551 /* Value */ : node.flags & 16777216 /* JSDoc */ ? 900095 /* Type */ : 788968 /* Type */ ; const innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - const isExportEquals = !!((_a2 = innerModuleSymbol.exports) == null ? void 0 : _a2.get("export=" /* ExportEquals */ )); + const isExportEquals = !!((_a = innerModuleSymbol.exports) == null ? void 0 : _a.get("export=" /* ExportEquals */ )); const moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); if (!nodeIsMissing(node.qualifier)) { const nameStack = getIdentifierChain(node.qualifier); @@ -54020,9 +54565,9 @@ ${lanes.join("\n")} const mergedResolvedSymbol = getMergedSymbol(resolveSymbol(currentNamespace)); const symbolFromVariable = node.isTypeOf || isInJSFile(node) && isExportEquals ? getPropertyOfType(getTypeOfSymbol(mergedResolvedSymbol), current.escapedText, /*skipObjectFunctionPropertyAugment*/ false, /*includeTypeOnlyMembers*/ true) : void 0; const symbolFromModule = node.isTypeOf ? void 0 : getSymbol2(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning); - const next = symbolFromModule != null ? symbolFromModule : symbolFromVariable; + const next = symbolFromModule ?? symbolFromVariable; if (!next) { - error(current, Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), declarationNameToString(current)); + error2(current, Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), declarationNameToString(current)); return links.resolvedType = errorType; } getNodeLinks(current).resolvedSymbol = next; @@ -54033,7 +54578,7 @@ ${lanes.join("\n")} } else if (moduleSymbol.flags & targetMeaning) links.resolvedType = resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); else { const errorMessage = targetMeaning === 111551 /* Value */ ? Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; - error(node, errorMessage, node.argument.literal.text); + error2(node, errorMessage, node.argument.literal.text); links.resolvedSymbol = unknownSymbol; links.resolvedType = errorType; } @@ -54063,7 +54608,7 @@ ${lanes.join("\n")} } function getAliasSymbolForTypeNode(node) { let host2 = node.parent; - while(isParenthesizedTypeNode(host2) || isJSDocTypeExpression(host2) || isTypeOperatorNode(host2) && host2.operator === 146 /* ReadonlyKeyword */ )host2 = host2.parent; + while(isParenthesizedTypeNode(host2) || isJSDocTypeExpression(host2) || isTypeOperatorNode(host2) && host2.operator === 148 /* ReadonlyKeyword */ )host2 = host2.parent; return isTypeAlias(host2) ? getSymbolOfDeclaration(host2) : void 0; } function getTypeArgumentsForAliasSymbol(symbol) { @@ -54152,9 +54697,12 @@ ${lanes.join("\n")} const declarations = concatenate(leftProp.declarations, rightProp.declarations); const flags = 4 /* Property */ | leftProp.flags & 16777216 /* Optional */ ; const result = createSymbol(flags, leftProp.escapedName); - result.links.type = getUnionType([ - getTypeOfSymbol(leftProp), - removeMissingOrUndefinedType(rightType) + const leftType = getTypeOfSymbol(leftProp); + const leftTypeWithoutUndefined = removeMissingOrUndefinedType(leftType); + const rightTypeWithoutUndefined = removeMissingOrUndefinedType(rightType); + result.links.type = leftTypeWithoutUndefined === rightTypeWithoutUndefined ? leftType : getUnionType([ + leftType, + rightTypeWithoutUndefined ], 2 /* Subtype */ ); result.links.leftSpread = leftProp; result.links.rightSpread = rightProp; @@ -54169,8 +54717,8 @@ ${lanes.join("\n")} return spread; } function isSpreadableProperty(prop) { - var _a2; - return !some(prop.declarations, isPrivateIdentifierClassElementDeclaration) && (!(prop.flags & 106496 /* SetAccessor */ ) || !((_a2 = prop.declarations) == null ? void 0 : _a2.some((decl)=>isClassLike(decl.parent)))); + var _a; + return !some(prop.declarations, isPrivateIdentifierClassElementDeclaration) && (!(prop.flags & 106496 /* SetAccessor */ ) || !((_a = prop.declarations) == null ? void 0 : _a.some((decl)=>isClassLike(decl.parent)))); } function getSpreadSymbol(prop, readonly) { const isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */ ); @@ -54229,7 +54777,7 @@ ${lanes.join("\n")} return enumLiteralTypes.get(key) || (enumLiteralTypes.set(key, type = createLiteralType(flags, value1, symbol)), type); } function getTypeFromLiteralTypeNode(node) { - if (node.literal.kind === 104 /* NullKeyword */ ) return nullType; + if (node.literal.kind === 106 /* NullKeyword */ ) return nullType; const links = getNodeLinks(node); if (!links.resolvedType) links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); return links.resolvedType; @@ -54252,14 +54800,14 @@ ${lanes.join("\n")} function getThisType(node) { const container = getThisContainer(node, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false); const parent2 = container && container.parent; - if (parent2 && (isClassLike(parent2) || parent2.kind === 261 /* InterfaceDeclaration */ )) { + if (parent2 && (isClassLike(parent2) || parent2.kind === 264 /* InterfaceDeclaration */ )) { if (!isStatic(container) && (!isConstructorDeclaration(container) || isNodeDescendantOf(node, container.body))) return getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(parent2)).thisType; } if (parent2 && isObjectLiteralExpression(parent2) && isBinaryExpression(parent2.parent) && getAssignmentDeclarationKind(parent2.parent) === 6 /* Prototype */ ) return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent2.parent.left).parent).thisType; - const host2 = node.flags & 8388608 /* JSDoc */ ? getHostSignatureFromJSDoc(node) : void 0; + const host2 = node.flags & 16777216 /* JSDoc */ ? getHostSignatureFromJSDoc(node) : void 0; if (host2 && isFunctionExpression(host2) && isBinaryExpression(host2.parent) && getAssignmentDeclarationKind(host2.parent) === 3 /* PrototypeProperty */ ) return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(host2.parent.left).parent).thisType; if (isJSConstructor(container) && isNodeDescendantOf(node, container.body)) return getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(container)).thisType; - error(node, Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface); + error2(node, Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface); return errorType; } function getTypeFromThisTypeNode(node) { @@ -54272,15 +54820,15 @@ ${lanes.join("\n")} } function getArrayElementTypeNode(node) { switch(node.kind){ - case 193 /* ParenthesizedType */ : + case 196 /* ParenthesizedType */ : return getArrayElementTypeNode(node.type); - case 186 /* TupleType */ : + case 189 /* TupleType */ : if (node.elements.length === 1) { node = node.elements[0]; - if (node.kind === 188 /* RestType */ || node.kind === 199 /* NamedTupleMember */ && node.dotDotDotToken) return getArrayElementTypeNode(node.type); + if (node.kind === 191 /* RestType */ || node.kind === 202 /* NamedTupleMember */ && node.dotDotDotToken) return getArrayElementTypeNode(node.type); } break; - case 185 /* ArrayType */ : + case 188 /* ArrayType */ : return node.elementType; } return void 0; @@ -54294,94 +54842,94 @@ ${lanes.join("\n")} } function getTypeFromTypeNodeWorker(node) { switch(node.kind){ - case 131 /* AnyKeyword */ : - case 315 /* JSDocAllType */ : - case 316 /* JSDocUnknownType */ : + case 133 /* AnyKeyword */ : + case 319 /* JSDocAllType */ : + case 320 /* JSDocUnknownType */ : return anyType; - case 157 /* UnknownKeyword */ : + case 159 /* UnknownKeyword */ : return unknownType; - case 152 /* StringKeyword */ : + case 154 /* StringKeyword */ : return stringType; - case 148 /* NumberKeyword */ : + case 150 /* NumberKeyword */ : return numberType; - case 160 /* BigIntKeyword */ : + case 163 /* BigIntKeyword */ : return bigintType; - case 134 /* BooleanKeyword */ : + case 136 /* BooleanKeyword */ : return booleanType; - case 153 /* SymbolKeyword */ : + case 155 /* SymbolKeyword */ : return esSymbolType; - case 114 /* VoidKeyword */ : + case 116 /* VoidKeyword */ : return voidType; - case 155 /* UndefinedKeyword */ : + case 157 /* UndefinedKeyword */ : return undefinedType; - case 104 /* NullKeyword */ : + case 106 /* NullKeyword */ : return nullType; - case 144 /* NeverKeyword */ : + case 146 /* NeverKeyword */ : return neverType; - case 149 /* ObjectKeyword */ : - return node.flags & 262144 /* JavaScriptFile */ && !noImplicitAny ? anyType : nonPrimitiveType; - case 139 /* IntrinsicKeyword */ : + case 151 /* ObjectKeyword */ : + return node.flags & 524288 /* JavaScriptFile */ && !noImplicitAny ? anyType : nonPrimitiveType; + case 141 /* IntrinsicKeyword */ : return intrinsicMarkerType; - case 194 /* ThisType */ : - case 108 /* ThisKeyword */ : + case 197 /* ThisType */ : + case 110 /* ThisKeyword */ : return getTypeFromThisTypeNode(node); - case 198 /* LiteralType */ : + case 201 /* LiteralType */ : return getTypeFromLiteralTypeNode(node); - case 180 /* TypeReference */ : + case 183 /* TypeReference */ : return getTypeFromTypeReference(node); - case 179 /* TypePredicate */ : + case 182 /* TypePredicate */ : return node.assertsModifier ? voidType : booleanType; - case 230 /* ExpressionWithTypeArguments */ : + case 233 /* ExpressionWithTypeArguments */ : return getTypeFromTypeReference(node); - case 183 /* TypeQuery */ : + case 186 /* TypeQuery */ : return getTypeFromTypeQueryNode(node); - case 185 /* ArrayType */ : - case 186 /* TupleType */ : + case 188 /* ArrayType */ : + case 189 /* TupleType */ : return getTypeFromArrayOrTupleTypeNode(node); - case 187 /* OptionalType */ : + case 190 /* OptionalType */ : return getTypeFromOptionalTypeNode(node); - case 189 /* UnionType */ : + case 192 /* UnionType */ : return getTypeFromUnionTypeNode(node); - case 190 /* IntersectionType */ : + case 193 /* IntersectionType */ : return getTypeFromIntersectionTypeNode(node); - case 317 /* JSDocNullableType */ : + case 321 /* JSDocNullableType */ : return getTypeFromJSDocNullableTypeNode(node); - case 319 /* JSDocOptionalType */ : + case 323 /* JSDocOptionalType */ : return addOptionality(getTypeFromTypeNode(node.type)); - case 199 /* NamedTupleMember */ : + case 202 /* NamedTupleMember */ : return getTypeFromNamedTupleTypeNode(node); - case 193 /* ParenthesizedType */ : - case 318 /* JSDocNonNullableType */ : - case 312 /* JSDocTypeExpression */ : + case 196 /* ParenthesizedType */ : + case 322 /* JSDocNonNullableType */ : + case 316 /* JSDocTypeExpression */ : return getTypeFromTypeNode(node.type); - case 188 /* RestType */ : + case 191 /* RestType */ : return getTypeFromRestTypeNode(node); - case 321 /* JSDocVariadicType */ : + case 325 /* JSDocVariadicType */ : return getTypeFromJSDocVariadicType(node); - case 181 /* FunctionType */ : - case 182 /* ConstructorType */ : - case 184 /* TypeLiteral */ : - case 325 /* JSDocTypeLiteral */ : - case 320 /* JSDocFunctionType */ : - case 326 /* JSDocSignature */ : + case 184 /* FunctionType */ : + case 185 /* ConstructorType */ : + case 187 /* TypeLiteral */ : + case 329 /* JSDocTypeLiteral */ : + case 324 /* JSDocFunctionType */ : + case 330 /* JSDocSignature */ : return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 195 /* TypeOperator */ : + case 198 /* TypeOperator */ : return getTypeFromTypeOperatorNode(node); - case 196 /* IndexedAccessType */ : + case 199 /* IndexedAccessType */ : return getTypeFromIndexedAccessTypeNode(node); - case 197 /* MappedType */ : + case 200 /* MappedType */ : return getTypeFromMappedTypeNode(node); - case 191 /* ConditionalType */ : + case 194 /* ConditionalType */ : return getTypeFromConditionalTypeNode(node); - case 192 /* InferType */ : + case 195 /* InferType */ : return getTypeFromInferTypeNode(node); - case 200 /* TemplateLiteralType */ : + case 203 /* TemplateLiteralType */ : return getTypeFromTemplateTypeNode(node); - case 202 /* ImportType */ : + case 205 /* ImportType */ : return getTypeFromImportTypeNode(node); - case 79 /* Identifier */ : - case 163 /* QualifiedName */ : - case 208 /* PropertyAccessExpression */ : + case 80 /* Identifier */ : + case 166 /* QualifiedName */ : + case 211 /* PropertyAccessExpression */ : const symbol = getSymbolAtLocation(node); return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; default: @@ -54515,7 +55063,7 @@ ${lanes.join("\n")} mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); for (const tp of freshTypeParameters)tp.mapper = mapper; } - const result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), /*resolvedReturnType*/ void 0, /*resolvedTypePredicate*/ void 0, signature.minArgumentCount, signature.flags & 39 /* PropagatingFlags */ ); + const result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), /*resolvedReturnType*/ void 0, /*resolvedTypePredicate*/ void 0, signature.minArgumentCount, signature.flags & 167 /* PropagatingFlags */ ); result.target = signature; result.mapper = mapper; return result; @@ -54569,42 +55117,51 @@ ${lanes.join("\n")} const newMapper = createTypeMapper(typeParameters, typeArguments); result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper, newAliasSymbol, newAliasTypeArguments) : target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper, newAliasSymbol, newAliasTypeArguments) : instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments); target.instantiations.set(id, result); + const resultObjectFlags = getObjectFlags(result); + if (result.flags & 138117121 /* ObjectFlagsType */ && !(resultObjectFlags & 524288 /* CouldContainTypeVariablesComputed */ )) { + const resultCouldContainTypeVariables = some(typeArguments, couldContainTypeVariables); + if (!(getObjectFlags(result) & 524288 /* CouldContainTypeVariablesComputed */ )) { + if (resultObjectFlags & 52 /* Reference */ ) result.objectFlags |= 524288 /* CouldContainTypeVariablesComputed */ | (resultCouldContainTypeVariables ? 1048576 /* CouldContainTypeVariables */ : 0); + else result.objectFlags |= !resultCouldContainTypeVariables ? 524288 /* CouldContainTypeVariablesComputed */ : 0; + } + } } return result; } return type; } function maybeTypeParameterReference(node) { - return !(node.parent.kind === 180 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName || node.parent.kind === 202 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier); + return !(node.parent.kind === 183 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName || node.parent.kind === 205 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier); } function isTypeParameterPossiblyReferenced(tp, node) { if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { const container = tp.symbol.declarations[0].parent; for(let n = node; n !== container; n = n.parent){ - if (!n || n.kind === 238 /* Block */ || n.kind === 191 /* ConditionalType */ && forEachChild(n.extendsType, containsReference)) return true; + if (!n || n.kind === 241 /* Block */ || n.kind === 194 /* ConditionalType */ && forEachChild(n.extendsType, containsReference)) return true; } return containsReference(node); } return true; function containsReference(node2) { switch(node2.kind){ - case 194 /* ThisType */ : + case 197 /* ThisType */ : return !!tp.isThisType; - case 79 /* Identifier */ : + case 80 /* Identifier */ : return !tp.isThisType && isPartOfTypeNode(node2) && maybeTypeParameterReference(node2) && getTypeFromTypeNodeWorker(node2) === tp; - case 183 /* TypeQuery */ : + case 186 /* TypeQuery */ : const entityName = node2.exprName; const firstIdentifier = getFirstIdentifier(entityName); - const firstIdentifierSymbol = getResolvedSymbol(firstIdentifier); - const tpDeclaration = tp.symbol.declarations[0]; - let tpScope; - if (tpDeclaration.kind === 165 /* TypeParameter */ ) tpScope = tpDeclaration.parent; - else if (tp.isThisType) tpScope = tpDeclaration; - else return true; - if (firstIdentifierSymbol.declarations) return some(firstIdentifierSymbol.declarations, (idDecl)=>isNodeDescendantOf(idDecl, tpScope)) || some(node2.typeArguments, containsReference); + if (!isThisIdentifier(firstIdentifier)) { + const firstIdentifierSymbol = getResolvedSymbol(firstIdentifier); + const tpDeclaration = tp.symbol.declarations[0]; + const tpScope = tpDeclaration.kind === 168 /* TypeParameter */ ? tpDeclaration.parent : // Type parameter is a regular type parameter, e.g. foo + tp.isThisType ? tpDeclaration : // Type parameter is the this type, and its declaration is the class declaration. + void 0; + if (firstIdentifierSymbol.declarations && tpScope) return some(firstIdentifierSymbol.declarations, (idDecl)=>isNodeDescendantOf(idDecl, tpScope)) || some(node2.typeArguments, containsReference); + } return true; - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : return !node2.type && !!node2.body || some(node2.typeParameters, containsReference) || some(node2.parameters, containsReference) || !!node2.type && containsReference(node2.type); } return !!forEachChild(node2, containsReference); @@ -54642,12 +55199,13 @@ ${lanes.join("\n")} } function instantiateMappedGenericTupleType(tupleType, mappedType, typeVariable, mapper) { const elementFlags = tupleType.target.elementFlags; - const elementTypes = map(getTypeArguments(tupleType), (t, i)=>{ + const elementTypes = map(getElementTypes(tupleType), (t, i)=>{ const singleton = elementFlags[i] & 8 /* Variadic */ ? t : elementFlags[i] & 4 /* Rest */ ? createArrayType(t) : createTupleType([ t ], [ elementFlags[i] ]); + if (singleton === typeVariable) return mappedType; return instantiateMappedType(mappedType, prependTypeMapping(typeVariable, singleton, mapper)); }); const newReadonly = getModifiedReadonlyState(tupleType.target.readonly, getMappedTypeModifiers(mappedType)); @@ -54659,7 +55217,7 @@ ${lanes.join("\n")} } function instantiateMappedTupleType(tupleType, mappedType, mapper) { const elementFlags = tupleType.target.elementFlags; - const elementTypes = map(getTypeArguments(tupleType), (_, i)=>instantiateMappedTypeTemplate(mappedType, getStringLiteralType("" + i), !!(elementFlags[i] & 2 /* Optional */ ), mapper)); + const elementTypes = map(getElementTypes(tupleType), (_, i)=>instantiateMappedTypeTemplate(mappedType, getStringLiteralType("" + i), !!(elementFlags[i] & 2 /* Optional */ ), mapper)); const modifiers = getMappedTypeModifiers(mappedType); const newTupleModifiers = modifiers & 4 /* IncludeOptional */ ? map(elementFlags, (f)=>f & 1 /* Required */ ? 2 /* Optional */ : f) : modifiers & 8 /* ExcludeOptional */ ? map(elementFlags, (f)=>f & 2 /* Optional */ ? 1 /* Required */ : f) : elementFlags; const newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers); @@ -54672,7 +55230,7 @@ ${lanes.join("\n")} return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !maybeTypeOfKind(propType, 49152 /* Void */ ) ? getOptionalType(propType, /*isProperty*/ true) : strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */ ) : propType; } function instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments) { - const result = createObjectType(type.objectFlags | 64 /* Instantiated */ , type.symbol); + const result = createObjectType(type.objectFlags & -1572865 | 64 /* Instantiated */ , type.symbol); if (type.objectFlags & 32 /* Mapped */ ) { result.declaration = type.declaration; const origTypeParameter = getTypeParameterFromMappedType(type); @@ -54710,15 +55268,15 @@ ${lanes.join("\n")} return type && mapper ? instantiateTypeWithAlias(type, mapper, /*aliasSymbol*/ void 0, /*aliasTypeArguments*/ void 0) : type; } function instantiateTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) { - var _a2; + var _a; if (!couldContainTypeVariables(type)) return type; if (instantiationDepth === 100 || instantiationCount >= 5e6) { - (_a2 = tracing) == null || _a2.instant(tracing.Phase.CheckTypes, "instantiateType_DepthLimit", { + (_a = tracing) == null || _a.instant(tracing.Phase.CheckTypes, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); - error(currentNode, Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); + error2(currentNode, Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); return errorType; } totalInstantiationCount++; @@ -54783,14 +55341,11 @@ ${lanes.join("\n")} if (instantiated) return instantiated; return type; } - function getUniqueLiteralFilledInstantiation(type) { - return type.flags & 134479871 /* Never */ ? type : type.uniqueLiteralFilledInstantiation || (type.uniqueLiteralFilledInstantiation = instantiateType(type, uniqueLiteralMapper)); - } function getPermissiveInstantiation(type) { - return type.flags & 134479871 /* Never */ ? type : type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); + return type.flags & 402915327 /* Never */ ? type : type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); } function getRestrictiveInstantiation(type) { - if (type.flags & 134479871 /* Never */ ) return type; + if (type.flags & 402915327 /* Never */ ) return type; if (type.restrictiveInstantiation) return type.restrictiveInstantiation; type.restrictiveInstantiation = instantiateType(type, restrictiveMapper); type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation; @@ -54800,35 +55355,35 @@ ${lanes.join("\n")} return createIndexInfo(info.keyType, instantiateType(info.type, mapper), info.isReadonly, info.declaration); } function isContextSensitive(node) { - Debug.assert(node.kind !== 171 /* MethodDeclaration */ || isObjectLiteralMethod(node)); + Debug.assert(node.kind !== 174 /* MethodDeclaration */ || isObjectLiteralMethod(node)); switch(node.kind){ - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - case 171 /* MethodDeclaration */ : - case 259 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + case 174 /* MethodDeclaration */ : + case 262 /* FunctionDeclaration */ : return isContextSensitiveFunctionLikeDeclaration(node); - case 207 /* ObjectLiteralExpression */ : + case 210 /* ObjectLiteralExpression */ : return some(node.properties, isContextSensitive); - case 206 /* ArrayLiteralExpression */ : + case 209 /* ArrayLiteralExpression */ : return some(node.elements, isContextSensitive); - case 224 /* ConditionalExpression */ : + case 227 /* ConditionalExpression */ : return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 223 /* BinaryExpression */ : - return (node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */ ) && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 299 /* PropertyAssignment */ : + case 226 /* BinaryExpression */ : + return (node.operatorToken.kind === 57 /* BarBarToken */ || node.operatorToken.kind === 61 /* QuestionQuestionToken */ ) && (isContextSensitive(node.left) || isContextSensitive(node.right)); + case 303 /* PropertyAssignment */ : return isContextSensitive(node.initializer); - case 214 /* ParenthesizedExpression */ : + case 217 /* ParenthesizedExpression */ : return isContextSensitive(node.expression); - case 289 /* JsxAttributes */ : + case 292 /* JsxAttributes */ : return some(node.properties, isContextSensitive) || isJsxOpeningElement(node.parent) && some(node.parent.parent.children, isContextSensitive); - case 288 /* JsxAttribute */ : + case 291 /* JsxAttribute */ : { - const { initializer: initializer } = node; + const { initializer: initializer } = node; return !!initializer && isContextSensitive(initializer); } - case 291 /* JsxExpression */ : + case 294 /* JsxExpression */ : { - const { expression: expression } = node; + const { expression: expression } = node; return !!expression && isContextSensitive(expression); } } @@ -54838,7 +55393,9 @@ ${lanes.join("\n")} return hasContextSensitiveParameters(node) || hasContextSensitiveReturnExpression(node); } function hasContextSensitiveReturnExpression(node) { - return !node.typeParameters && !getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 238 /* Block */ && isContextSensitive(node.body); + if (node.typeParameters || getEffectiveReturnTypeNode(node) || !node.body) return false; + if (node.body.kind !== 241 /* Block */ ) return isContextSensitive(node.body); + return !!forEachReturnStatement(node.body, (statement)=>!!statement.expression && isContextSensitive(statement.expression)); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (isFunctionExpressionOrArrowFunction(func) || isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); @@ -54906,23 +55463,25 @@ ${lanes.join("\n")} if (!node || isOrHasGenericConditional(target)) return false; if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ void 0) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) return true; switch(node.kind){ - case 291 /* JsxExpression */ : - case 214 /* ParenthesizedExpression */ : + case 234 /* AsExpression */ : + if (!isConstAssertion(node)) break; + case 294 /* JsxExpression */ : + case 217 /* ParenthesizedExpression */ : return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : switch(node.operatorToken.kind){ - case 63 /* EqualsToken */ : - case 27 /* CommaToken */ : + case 64 /* EqualsToken */ : + case 28 /* CommaToken */ : return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); } break; - case 207 /* ObjectLiteralExpression */ : + case 210 /* ObjectLiteralExpression */ : return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 206 /* ArrayLiteralExpression */ : + case 209 /* ArrayLiteralExpression */ : return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 289 /* JsxAttributes */ : + case 292 /* JsxAttributes */ : return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 216 /* ArrowFunction */ : + case 219 /* ArrowFunction */ : return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer); } return false; @@ -54959,7 +55518,7 @@ ${lanes.join("\n")} const elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ void 0, containingMessageChain, errorOutputContainer); if (elaborated) return elaborated; const resultObj = errorOutputContainer || {}; - checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ void 0, containingMessageChain, resultObj); + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*headMessage*/ void 0, containingMessageChain, resultObj); if (resultObj.errors) { if (target.symbol && length(target.symbol.declarations)) addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], createDiagnosticForNode(target.symbol.declarations[0], Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); if ((getFunctionFlags(node) & 2 /* Async */ ) === 0 && !getTypeOfPropertyOfType(sourceReturn, "then") && checkTypeRelatedTo(createPromiseType(sourceReturn), targetReturn, relation, /*errorNode*/ void 0)) addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], createDiagnosticForNode(node, Diagnostics.Did_you_mean_to_mark_this_function_as_async)); @@ -54985,7 +55544,7 @@ ${lanes.join("\n")} function elaborateElementwise(iterator, source, target, relation, containingMessageChain, errorOutputContainer) { let reportedError = false; for (const value1 of iterator){ - const { errorNode: prop , innerExpression: next , nameType: nameType , errorMessage: errorMessage } = value1; + const { errorNode: prop, innerExpression: next, nameType: nameType, errorMessage: errorMessage } = value1; let targetPropType = getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType); if (!targetPropType || targetPropType.flags & 8388608 /* IndexedAccess */ ) continue; let sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType); @@ -55039,7 +55598,7 @@ ${lanes.join("\n")} const iterationType = nonTupleOrArrayLikeTargetParts !== neverType ? getIterationTypeOfIterable(13 /* ForOf */ , 0 /* Yield */ , nonTupleOrArrayLikeTargetParts, /*errorNode*/ void 0) : void 0; let reportedError = false; for(let status = iterator.next(); !status.done; status = iterator.next()){ - const { errorNode: prop , innerExpression: next , nameType: nameType , errorMessage: errorMessage } = status.value; + const { errorNode: prop, innerExpression: next, nameType: nameType, errorMessage: errorMessage } = status.value; let targetPropType = iterationType; const targetIndexedPropType = tupleOrArrayLikeTargetParts !== neverType ? getBestMatchIndexedAccessTypeOrUndefined(source, tupleOrArrayLikeTargetParts, nameType) : void 0; if (targetIndexedPropType && !(targetIndexedPropType.flags & 8388608 /* IndexedAccess */ )) targetPropType = iterationType ? getUnionType([ @@ -55078,11 +55637,11 @@ ${lanes.join("\n")} function* generateJsxAttributes(node) { if (!length(node.properties)) return; for (const prop of node.properties){ - if (isJsxSpreadAttribute(prop) || isHyphenatedJsxName(idText(prop.name))) continue; + if (isJsxSpreadAttribute(prop) || isHyphenatedJsxName(getTextOfJsxAttributeName(prop.name))) continue; yield { errorNode: prop.name, innerExpression: prop.initializer, - nameType: getStringLiteralType(idText(prop.name)) + nameType: getStringLiteralType(getTextOfJsxAttributeName(prop.name)) }; } } @@ -55099,13 +55658,13 @@ ${lanes.join("\n")} } function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) { switch(child.kind){ - case 291 /* JsxExpression */ : + case 294 /* JsxExpression */ : return { errorNode: child, innerExpression: child.expression, nameType: nameType }; - case 11 /* JsxText */ : + case 12 /* JsxText */ : if (child.containsOnlyTriviaWhiteSpaces) break; return { errorNode: child, @@ -55113,9 +55672,9 @@ ${lanes.join("\n")} nameType: nameType, errorMessage: getInvalidTextDiagnostic() }; - case 281 /* JsxElement */ : - case 282 /* JsxSelfClosingElement */ : - case 285 /* JsxFragment */ : + case 284 /* JsxElement */ : + case 285 /* JsxSelfClosingElement */ : + case 288 /* JsxFragment */ : return { errorNode: child, innerExpression: child, @@ -55155,7 +55714,7 @@ ${lanes.join("\n")} result = elaborateIterableOrArrayLikeTargetElementwise(children, realSource, arrayLikeTargetParts, relation, containingMessageChain, errorOutputContainer) || result; } else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) { result = true; - const diag2 = error(containingElement.openingElement.tagName, Diagnostics.This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided, childrenPropName, typeToString(childrenTargetType)); + const diag2 = error2(containingElement.openingElement.tagName, Diagnostics.This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided, childrenPropName, typeToString(childrenTargetType)); if (errorOutputContainer && errorOutputContainer.skipLogging) (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag2); } } else { @@ -55167,7 +55726,7 @@ ${lanes.join("\n")} }(), source, target, relation, containingMessageChain, errorOutputContainer) || result; } else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) { result = true; - const diag2 = error(containingElement.openingElement.tagName, Diagnostics.This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided, childrenPropName, typeToString(childrenTargetType)); + const diag2 = error2(containingElement.openingElement.tagName, Diagnostics.This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided, childrenPropName, typeToString(childrenTargetType)); if (errorOutputContainer && errorOutputContainer.skipLogging) (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag2); } } @@ -55183,7 +55742,7 @@ ${lanes.join("\n")} invalidTextDiagnostic = { ...diagnostic, key: "!!ALREADY FORMATTED!!", - message: formatMessage(/*_dummy*/ void 0, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) + message: formatMessage(/*dummy*/ void 0, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) }; } return invalidTextDiagnostic; @@ -55205,7 +55764,7 @@ ${lanes.join("\n")} } } function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) { - if (target.flags & 134479868 /* Never */ ) return false; + if (target.flags & 402915324 /* Never */ ) return false; if (isTupleLikeType(source)) return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer); pushContextualType(node, target, /*isCache*/ false); const tupleizedType = checkArrayLiteral(node, 1 /* Contextual */ , /*forceTuple*/ true); @@ -55220,17 +55779,17 @@ ${lanes.join("\n")} const type = getLiteralTypeFromProperty(getSymbolOfDeclaration(prop), 8576 /* StringOrNumberLiteralOrUnique */ ); if (!type || type.flags & 131072 /* Never */ ) continue; switch(prop.kind){ - case 175 /* SetAccessor */ : - case 174 /* GetAccessor */ : - case 171 /* MethodDeclaration */ : - case 300 /* ShorthandPropertyAssignment */ : + case 178 /* SetAccessor */ : + case 177 /* GetAccessor */ : + case 174 /* MethodDeclaration */ : + case 304 /* ShorthandPropertyAssignment */ : yield { errorNode: prop.name, innerExpression: void 0, nameType: type }; break; - case 299 /* PropertyAssignment */ : + case 303 /* PropertyAssignment */ : yield { errorNode: prop.name, innerExpression: prop.initializer, @@ -55244,14 +55803,14 @@ ${lanes.join("\n")} } } function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) { - if (target.flags & 134479868 /* Never */ ) return false; + if (target.flags & 402915324 /* Never */ ) return false; return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer); } function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); } function isSignatureAssignableTo(source, target, ignoreReturnTypes) { - return compareSignaturesRelated(source, target, ignoreReturnTypes ? 4 /* IgnoreReturnTypes */ : 0 /* None */ , /*reportErrors*/ false, /*errorReporter*/ void 0, /*errorReporter*/ void 0, compareTypesAssignable, /*reportUnreliableMarkers*/ void 0) !== 0 /* False */ ; + return compareSignaturesRelated(source, target, ignoreReturnTypes ? 4 /* IgnoreReturnTypes */ : 0 /* None */ , /*reportErrors*/ false, /*errorReporter*/ void 0, /*incompatibleErrorReporter*/ void 0, compareTypesAssignable, /*reportUnreliableMarkers*/ void 0) !== 0 /* False */ ; } function isTopSignature(s) { if (!s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && signatureHasRestParameter(s)) { @@ -55267,7 +55826,10 @@ ${lanes.join("\n")} if (checkMode & 16 /* StrictTopSignature */ && isTopSignature(source) && !isTopSignature(target)) return 0 /* False */ ; const targetCount = getParameterCount(target); const sourceHasMoreParameters = !hasEffectiveRestParameter(target) && (checkMode & 8 /* StrictArity */ ? hasEffectiveRestParameter(source) || getParameterCount(source) > targetCount : getMinArgumentCount(source) > targetCount); - if (sourceHasMoreParameters) return 0 /* False */ ; + if (sourceHasMoreParameters) { + if (reportErrors2 && !(checkMode & 8 /* StrictArity */ )) errorReporter(Diagnostics.Target_signature_provides_too_few_arguments_Expected_0_or_more_but_got_1, getMinArgumentCount(source), targetCount); + return 0 /* False */ ; + } if (source.typeParameters && source.typeParameters !== target.typeParameters) { target = getCanonicalSignature(target); source = instantiateSignatureInContextOf(source, target, /*inferenceContext*/ void 0, compareTypes); @@ -55277,7 +55839,7 @@ ${lanes.join("\n")} const targetRestType = getNonArrayRestType(target); if (sourceRestType || targetRestType) instantiateType(sourceRestType || targetRestType, reportUnreliableMarkers); const kind = target.declaration ? target.declaration.kind : 0 /* Unknown */ ; - const strictVariance = !(checkMode & 3 /* Callback */ ) && strictFunctionTypes && kind !== 171 /* MethodDeclaration */ && kind !== 170 /* MethodSignature */ && kind !== 173 /* Constructor */ ; + const strictVariance = !(checkMode & 3 /* Callback */ ) && strictFunctionTypes && kind !== 174 /* MethodDeclaration */ && kind !== 173 /* MethodSignature */ && kind !== 176 /* Constructor */ ; let result = -1 /* True */ ; const sourceThisType = getThisTypeOfSignature(source); if (sourceThisType && sourceThisType !== voidType) { @@ -55455,7 +56017,7 @@ ${lanes.join("\n")} } function getNormalizedType(type, writing) { while(true){ - const t = isFreshLiteralType(type) ? type.regularType : getObjectFlags(type) & 4 /* Reference */ ? type.node ? createTypeReference(type.target, getTypeArguments(type)) : getSingleBaseForNonAugmentingSubtype(type) || type : type.flags & 3145728 /* UnionOrIntersection */ ? getNormalizedUnionOrIntersectionType(type, writing) : type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : getSubstitutionIntersection(type) : type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : type; + const t = isFreshLiteralType(type) ? type.regularType : isGenericTupleType(type) ? getNormalizedTupleType(type, writing) : getObjectFlags(type) & 4 /* Reference */ ? type.node ? createTypeReference(type.target, getTypeArguments(type)) : getSingleBaseForNonAugmentingSubtype(type) || type : type.flags & 3145728 /* UnionOrIntersection */ ? getNormalizedUnionOrIntersectionType(type, writing) : type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : getSubstitutionIntersection(type) : type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : type; if (t === type) return t; type = t; } @@ -55469,11 +56031,17 @@ ${lanes.join("\n")} } return type; } + function getNormalizedTupleType(type, writing) { + const elements = getElementTypes(type); + const normalizedElements = sameMap(elements, (t)=>t.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(t, writing) : t); + return elements !== normalizedElements ? createNormalizedTupleType(type.target, normalizedElements) : type; + } function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { - var _a2; + var _a; let errorInfo; let relatedInfo; let maybeKeys; + let maybeKeysSet; let sourceStack; let targetStack; let maybeCount = 0; @@ -55488,13 +56056,13 @@ ${lanes.join("\n")} const result = isRelatedTo(source, target, 3 /* Both */ , /*reportErrors*/ !!errorNode, headMessage); if (incompatibleStack) reportIncompatibleStack(); if (overflow) { - (_a2 = tracing) == null || _a2.instant(tracing.Phase.CheckTypes, "checkTypeRelatedTo_DepthLimit", { + (_a = tracing) == null || _a.instant(tracing.Phase.CheckTypes, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: sourceDepth, targetDepth: targetDepth }); - const diag2 = error(errorNode || currentNode, Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); + const diag2 = error2(errorNode || currentNode, Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); if (errorOutputContainer) (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag2); } else if (errorInfo) { if (containingMessageChain) { @@ -55538,15 +56106,12 @@ ${lanes.join("\n")} relatedInfo: relatedInfo == null ? void 0 : relatedInfo.slice() }; } - function reportIncompatibleError(message, arg0, arg1, arg2, arg3) { + function reportIncompatibleError(message, ...args) { overrideNextErrorInfo++; lastSkippedInfo = void 0; (incompatibleStack || (incompatibleStack = [])).push([ message, - arg0, - arg1, - arg2, - arg3 + ...args ]); } function reportIncompatibleStack() { @@ -55556,7 +56121,7 @@ ${lanes.join("\n")} lastSkippedInfo = void 0; if (stack.length === 1) { reportError(...stack[0]); - if (info) reportRelationError(/*headMessage*/ void 0, ...info); + if (info) reportRelationError(/*message*/ void 0, ...info); return; } let path = ""; @@ -55620,13 +56185,13 @@ ${lanes.join("\n")} reportError(msg, ...args); msg.elidedInCompatabilityPyramid = originalValue; } - if (info) reportRelationError(/*headMessage*/ void 0, ...info); + if (info) reportRelationError(/*message*/ void 0, ...info); } - function reportError(message, arg0, arg1, arg2, arg3) { + function reportError(message, ...args) { Debug.assert(!!errorNode); if (incompatibleStack) reportIncompatibleStack(); if (message.elidedInCompatabilityPyramid) return; - errorInfo = chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3); + errorInfo = chainDiagnosticMessages(errorInfo, message, ...args); } function associateRelatedInfo(info) { Debug.assert(!!errorInfo); @@ -55696,7 +56261,8 @@ ${lanes.join("\n")} return isRelatedTo(source2, target2, 3 /* Both */ , reportErrors2); } function isRelatedTo(originalSource, originalTarget, recursionFlags = 3 /* Both */ , reportErrors2 = false, headMessage2, intersectionState = 0 /* None */ ) { - if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 134348796 /* Primitive */ ) { + if (originalSource === originalTarget) return -1 /* True */ ; + if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 402784252 /* Primitive */ ) { if (relation === comparableRelation && !(originalTarget.flags & 131072 /* Never */ ) && isSimpleTypeRelatedTo(originalTarget, originalSource, relation) || isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors2 ? reportError : void 0)) return -1 /* True */ ; if (reportErrors2) reportErrorResults(originalSource, originalTarget, originalSource, originalTarget, headMessage2); return 0 /* False */ ; @@ -55728,7 +56294,7 @@ ${lanes.join("\n")} return 0 /* False */ ; } } - const isPerformingCommonPropertyChecks = (relation !== comparableRelation || isUnitType(source2)) && !(intersectionState & 2 /* Target */ ) && source2.flags & 136970236 /* Intersection */ && source2 !== globalObjectType && target2.flags & 2621440 /* Intersection */ && isWeakType(target2) && (getPropertiesOfType(source2).length > 0 || typeHasCallOrConstructSignatures(source2)); + const isPerformingCommonPropertyChecks = (relation !== comparableRelation || isUnitType(source2)) && !(intersectionState & 2 /* Target */ ) && source2.flags & 405405692 /* Intersection */ && source2 !== globalObjectType && target2.flags & 2621440 /* Intersection */ && isWeakType(target2) && (getPropertiesOfType(source2).length > 0 || typeHasCallOrConstructSignatures(source2)); const isComparingJsxAttributes = !!(getObjectFlags(source2) & 2048 /* JsxAttributes */ ); if (isPerformingCommonPropertyChecks && !hasCommonProperties(source2, target2, isComparingJsxAttributes)) { if (reportErrors2) { @@ -55750,7 +56316,7 @@ ${lanes.join("\n")} return 0 /* False */ ; } function reportErrorResults(originalSource, originalTarget, source2, target2, headMessage2) { - var _a3, _b; + var _a2, _b; const sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); const targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); source2 = originalSource.aliasSymbol || sourceHasBase ? originalSource : source2; @@ -55762,7 +56328,7 @@ ${lanes.join("\n")} tryElaborateArrayLikeErrors(source2, target2, /*reportErrors*/ true); if (errorInfo !== currentError) maybeSuppress = !!errorInfo; } - if (source2.flags & 524288 /* Object */ && target2.flags & 134348796 /* Primitive */ ) tryElaborateErrorsForPrimitivesAndObjects(source2, target2); + if (source2.flags & 524288 /* Object */ && target2.flags & 402784252 /* Primitive */ ) tryElaborateErrorsForPrimitivesAndObjects(source2, target2); else if (source2.symbol && source2.flags & 524288 /* Object */ && globalObjectType === source2) reportError(Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); else if (getObjectFlags(source2) & 2048 /* JsxAttributes */ && target2.flags & 2097152 /* Intersection */ ) { const targetTypes = target2.types; @@ -55778,7 +56344,7 @@ ${lanes.join("\n")} return; } reportRelationError(headMessage2, source2, target2); - if (source2.flags & 262144 /* TypeParameter */ && ((_b = (_a3 = source2.symbol) == null ? void 0 : _a3.declarations) == null ? void 0 : _b[0]) && !getConstraintOfType(source2)) { + if (source2.flags & 262144 /* TypeParameter */ && ((_b = (_a2 = source2.symbol) == null ? void 0 : _a2.declarations) == null ? void 0 : _b[0]) && !getConstraintOfType(source2)) { const syntheticParam = cloneTypeParameter(source2); syntheticParam.constraint = instantiateType(target2, makeUnaryTypeMapper(source2, syntheticParam)); if (hasNonCircularBaseConstraint(syntheticParam)) { @@ -55807,16 +56373,16 @@ ${lanes.join("\n")} } function getTypeOfPropertyInTypes(types, name) { const appendPropType = (propTypes, type)=>{ - var _a3; + var _a2; type = getApparentType(type); const prop = type.flags & 3145728 /* UnionOrIntersection */ ? getPropertyOfUnionOrIntersectionType(type, name) : getPropertyOfObjectType(type, name); - const propType = prop && getTypeOfSymbol(prop) || ((_a3 = getApplicableIndexInfoForName(type, name)) == null ? void 0 : _a3.type) || undefinedType; + const propType = prop && getTypeOfSymbol(prop) || ((_a2 = getApplicableIndexInfoForName(type, name)) == null ? void 0 : _a2.type) || undefinedType; return append(propTypes, propType); }; return getUnionType(reduceLeft(types, appendPropType, /*initial*/ void 0) || emptyArray); } function hasExcessProperties(source2, target2, reportErrors2) { - var _a3; + var _a2; if (!isExcessPropertyCheckTarget(target2) || !noImplicitAny && getObjectFlags(target2) & 4096 /* JSLiteral */ ) return false; const isComparingJsxAttributes = !!(getObjectFlags(source2) & 2048 /* JsxAttributes */ ); if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target2) || !isComparingJsxAttributes && isEmptyObjectType(target2))) return false; @@ -55841,13 +56407,13 @@ ${lanes.join("\n")} if (suggestion) reportError(Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(errorTarget), suggestion); else reportError(Diagnostics.Property_0_does_not_exist_on_type_1, propName, typeToString(errorTarget)); } else { - const objectLiteralDeclaration = ((_a3 = source2.symbol) == null ? void 0 : _a3.declarations) && firstOrUndefined(source2.symbol.declarations); + const objectLiteralDeclaration = ((_a2 = source2.symbol) == null ? void 0 : _a2.declarations) && firstOrUndefined(source2.symbol.declarations); let suggestion; if (prop.valueDeclaration && findAncestor(prop.valueDeclaration, (d)=>d === objectLiteralDeclaration) && getSourceFileOfNode(objectLiteralDeclaration) === getSourceFileOfNode(errorNode)) { const propDeclaration = prop.valueDeclaration; Debug.assertNode(propDeclaration, isObjectLiteralElementLike); - errorNode = propDeclaration; const name = propDeclaration.name; + errorNode = name; if (isIdentifier(name)) suggestion = getSuggestionForNonexistentProperty(name, errorTarget); } if (suggestion !== void 0) reportError(Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(errorTarget), suggestion); @@ -55867,10 +56433,10 @@ ${lanes.join("\n")} return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration; } function unionOrIntersectionRelatedTo(source2, target2, reportErrors2, intersectionState) { - if (source2.flags & 1048576 /* Union */ ) return relation === comparableRelation ? someTypeRelatedToType(source2, target2, reportErrors2 && !(source2.flags & 134348796 /* Primitive */ ), intersectionState) : eachTypeRelatedToType(source2, target2, reportErrors2 && !(source2.flags & 134348796 /* Primitive */ ), intersectionState); - if (target2.flags & 1048576 /* Union */ ) return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source2), target2, reportErrors2 && !(source2.flags & 134348796 /* Primitive */ ) && !(target2.flags & 134348796 /* Primitive */ )); + if (source2.flags & 1048576 /* Union */ ) return relation === comparableRelation ? someTypeRelatedToType(source2, target2, reportErrors2 && !(source2.flags & 402784252 /* Primitive */ ), intersectionState) : eachTypeRelatedToType(source2, target2, reportErrors2 && !(source2.flags & 402784252 /* Primitive */ ), intersectionState); + if (target2.flags & 1048576 /* Union */ ) return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source2), target2, reportErrors2 && !(source2.flags & 402784252 /* Primitive */ ) && !(target2.flags & 402784252 /* Primitive */ )); if (target2.flags & 2097152 /* Intersection */ ) return typeRelatedToEachType(source2, target2, reportErrors2, 2 /* Target */ ); - if (relation === comparableRelation && target2.flags & 134348796 /* Primitive */ ) { + if (relation === comparableRelation && target2.flags & 402784252 /* Primitive */ ) { const constraints = sameMap(source2.types, (t)=>t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOfType(t) || unknownType : t); if (constraints !== source2.types) { source2 = getIntersectionType(constraints); @@ -55894,6 +56460,11 @@ ${lanes.join("\n")} const targetTypes = target2.types; if (target2.flags & 1048576 /* Union */ ) { if (containsType(targetTypes, source2)) return -1 /* True */ ; + if (relation !== comparableRelation && getObjectFlags(target2) & 32768 /* PrimitiveUnion */ && !(source2.flags & 1024 /* EnumLiteral */ ) && (source2.flags & 2688 /* BigIntLiteral */ || (relation === subtypeRelation || relation === strictSubtypeRelation) && source2.flags & 256 /* NumberLiteral */ )) { + const alternateForm = source2 === source2.regularType ? source2.freshType : source2.regularType; + const primitive = source2.flags & 128 /* StringLiteral */ ? stringType : source2.flags & 256 /* NumberLiteral */ ? numberType : source2.flags & 2048 /* BigIntLiteral */ ? bigintType : void 0; + return primitive && containsType(targetTypes, primitive) || alternateForm && containsType(targetTypes, alternateForm) ? -1 /* True */ : 0 /* False */ ; + } const match = getMatchingUnionConstituentForType(target2, source2); if (match) { const related = isRelatedTo(source2, match, 2 /* Target */ , /*reportErrors*/ false); @@ -55981,9 +56552,9 @@ ${lanes.join("\n")} return result2; } function recursiveTypeRelatedTo(source2, target2, reportErrors2, intersectionState, recursionFlags) { - var _a3, _b, _c; + var _a2, _b, _c; if (overflow) return 0 /* False */ ; - const id = getRelationKey(source2, target2, intersectionState, relation, /*ingnoreConstraints*/ false); + const id = getRelationKey(source2, target2, intersectionState, relation, /*ignoreConstraints*/ false); const entry = relation.get(id); if (entry !== void 0) { if (reportErrors2 && entry & 2 /* Failed */ && !(entry & 4 /* Reported */ )) ; @@ -55998,13 +56569,13 @@ ${lanes.join("\n")} } if (!maybeKeys) { maybeKeys = []; + maybeKeysSet = /* @__PURE__ */ new Set(); sourceStack = []; targetStack = []; } else { + if (maybeKeysSet.has(id)) return 3 /* Maybe */ ; const broadestEquivalentId = id.startsWith("*") ? getRelationKey(source2, target2, intersectionState, relation, /*ignoreConstraints*/ true) : void 0; - for(let i = 0; i < maybeCount; i++){ - if (id === maybeKeys[i] || broadestEquivalentId && broadestEquivalentId === maybeKeys[i]) return 3 /* Maybe */ ; - } + if (broadestEquivalentId && maybeKeysSet.has(broadestEquivalentId)) return 3 /* Maybe */ ; if (sourceDepth === 100 || targetDepth === 100) { overflow = true; return 0 /* False */ ; @@ -56012,6 +56583,7 @@ ${lanes.join("\n")} } const maybeStart = maybeCount; maybeKeys[maybeCount] = id; + maybeKeysSet.add(id); maybeCount++; const saveExpandingFlags = expandingFlags; if (recursionFlags & 1 /* Source */ ) { @@ -56035,7 +56607,7 @@ ${lanes.join("\n")} } let result2; if (expandingFlags === 3 /* Both */ ) { - (_a3 = tracing) == null || _a3.instant(tracing.Phase.CheckTypes, "recursiveTypeRelatedTo_DepthLimit", { + (_a2 = tracing) == null || _a2.instant(tracing.Phase.CheckTypes, "recursiveTypeRelatedTo_DepthLimit", { sourceId: source2.id, sourceIdStack: sourceStack.map((t)=>t.id), targetId: target2.id, @@ -56058,14 +56630,21 @@ ${lanes.join("\n")} expandingFlags = saveExpandingFlags; if (result2) { if (result2 === -1 /* True */ || sourceDepth === 0 && targetDepth === 0) { - if (result2 === -1 /* True */ || result2 === 3 /* Maybe */ ) for(let i = maybeStart; i < maybeCount; i++)relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags); - maybeCount = maybeStart; + if (result2 === -1 /* True */ || result2 === 3 /* Maybe */ ) resetMaybeStack(/*markAllAsSucceeded*/ true); + else resetMaybeStack(/*markAllAsSucceeded*/ false); } } else { relation.set(id, (reportErrors2 ? 4 /* Reported */ : 0) | 2 /* Failed */ | propagatingVarianceFlags); - maybeCount = maybeStart; + resetMaybeStack(/*markAllAsSucceeded*/ false); } return result2; + function resetMaybeStack(markAllAsSucceeded) { + for(let i = maybeStart; i < maybeCount; i++){ + maybeKeysSet.delete(maybeKeys[i]); + if (markAllAsSucceeded) relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags); + } + maybeCount = maybeStart; + } } function structuredTypeRelatedTo(source2, target2, reportErrors2, intersectionState) { const saveErrorInfo = captureErrorCalculationState(); @@ -56161,7 +56740,7 @@ ${lanes.join("\n")} } else { const constraint = getSimplifiedTypeOrConstraint(targetType); if (constraint) { - if (isRelatedTo(source2, getIndexType(constraint, target2.stringsOnly), 2 /* Target */ , reportErrors2) === -1 /* True */ ) return -1 /* True */ ; + if (isRelatedTo(source2, getIndexType(constraint, target2.indexFlags | 4 /* NoReducibleCheck */ ), 2 /* Target */ , reportErrors2) === -1 /* True */ ) return -1 /* True */ ; } else if (isGenericMappedType(targetType)) { const nameType = getNameTypeFromMappedType(targetType); const constraintType = getConstraintTypeFromMappedType(targetType); @@ -56194,7 +56773,7 @@ ${lanes.join("\n")} const constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, accessFlags); if (constraint) { if (reportErrors2 && originalErrorInfo) resetErrorInfo(saveErrorInfo); - if (result2 = isRelatedTo(source2, constraint, 2 /* Target */ , reportErrors2, /* headMessage */ void 0, intersectionState)) return result2; + if (result2 = isRelatedTo(source2, constraint, 2 /* Target */ , reportErrors2, /*headMessage*/ void 0, intersectionState)) return result2; if (reportErrors2 && originalErrorInfo && errorInfo) errorInfo = countMessageChainBreadth([ originalErrorInfo ]) <= countMessageChainBreadth([ @@ -56212,7 +56791,7 @@ ${lanes.join("\n")} if (!keysRemapped && templateType.flags & 8388608 /* IndexedAccess */ && templateType.objectType === source2 && templateType.indexType === getTypeParameterFromMappedType(target2)) return -1 /* True */ ; if (!isGenericMappedType(source2)) { const targetKeys = keysRemapped ? getNameTypeFromMappedType(target2) : getConstraintTypeFromMappedType(target2); - const sourceKeys = getIndexType(source2, /*stringsOnly*/ void 0, /*noIndexSignatures*/ true); + const sourceKeys = getIndexType(source2, 2 /* NoIndexSignatures */ ); const includeOptional = modifiers & 4 /* IncludeOptional */ ; const filteredByApplicability = includeOptional ? intersectTypes(targetKeys, sourceKeys) : void 0; if (includeOptional ? !(filteredByApplicability.flags & 131072 /* Never */ ) : isRelatedTo(targetKeys, sourceKeys, 3 /* Both */ )) { @@ -56237,7 +56816,7 @@ ${lanes.join("\n")} } else if (targetFlags & 16777216 /* Conditional */ ) { if (isDeeplyNestedType(target2, targetStack, targetDepth, 10)) return 3 /* Maybe */ ; const c = target2; - if (!c.root.inferTypeParameters && !isDistributionDependent(c.root)) { + if (!c.root.inferTypeParameters && !isDistributionDependent(c.root) && !(source2.flags & 16777216 /* Conditional */ && source2.root === c.root)) { const skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); const skipFalse = !skipTrue && isTypeAssignableTo(getRestrictiveInstantiation(c.checkType), getRestrictiveInstantiation(c.extendsType)); if (result2 = skipTrue ? -1 /* True */ : isRelatedTo(source2, getTrueTypeFromConditionalType(c), 2 /* Target */ , /*reportErrors*/ false, /*headMessage*/ void 0, intersectionState)) { @@ -56317,7 +56896,7 @@ ${lanes.join("\n")} } return 0 /* False */ ; } - const sourceIsPrimitive = !!(sourceFlags & 134348796 /* Primitive */ ); + const sourceIsPrimitive = !!(sourceFlags & 402784252 /* Primitive */ ); if (relation !== identityRelation) { source2 = getApparentType(source2); sourceFlags = source2.flags; @@ -56328,9 +56907,12 @@ ${lanes.join("\n")} if (variances === emptyArray) return 1 /* Unknown */ ; const varianceResult = relateVariances(getTypeArguments(source2), getTypeArguments(target2), variances, intersectionState); if (varianceResult !== void 0) return varianceResult; - } else if (isReadonlyArrayType(target2) ? isArrayOrTupleType(source2) : isArrayType(target2) && isTupleType(source2) && !source2.target.readonly) { + } else if (isReadonlyArrayType(target2) ? everyType(source2, isArrayOrTupleType) : isArrayType(target2) && everyType(source2, (t)=>isTupleType(t) && !t.target.readonly)) { if (relation !== identityRelation) return isRelatedTo(getIndexTypeOfType(source2, numberType) || anyType, getIndexTypeOfType(target2, numberType) || anyType, 3 /* Both */ , reportErrors2); else return 0 /* False */ ; + } else if (isGenericTupleType(source2) && isTupleType(target2) && !isGenericTupleType(target2)) { + const constraint = getBaseConstraintOrType(source2); + if (constraint !== source2) return isRelatedTo(constraint, target2, 1 /* Source */ , reportErrors2); } else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target2) && getObjectFlags(target2) & 8192 /* FreshLiteral */ && !isEmptyObjectType(source2)) return 0 /* False */ ; if (sourceFlags & 2621440 /* Intersection */ && targetFlags & 524288 /* Object */ ) { const reportStructuralErrors = reportErrors2 && errorInfo === saveErrorInfo.errorInfo && !sourceIsPrimitive; @@ -56392,7 +56974,7 @@ ${lanes.join("\n")} return 0 /* False */ ; } function typeRelatedToDiscriminatedType(source2, target2) { - var _a3; + var _a2; const sourceProperties = getPropertiesOfType(source2); const sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target2); if (!sourcePropertiesFiltered) return 0 /* False */ ; @@ -56400,7 +56982,7 @@ ${lanes.join("\n")} for (const sourceProperty of sourcePropertiesFiltered){ numCombinations *= countTypes(getNonMissingTypeOfSymbol(sourceProperty)); if (numCombinations > 25) { - (_a3 = tracing) == null || _a3.instant(tracing.Phase.CheckTypes, "typeRelatedToDiscriminatedType_DepthLimit", { + (_a2 = tracing) == null || _a2.instant(tracing.Phase.CheckTypes, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source2.id, targetId: target2.id, numCombinations: numCombinations @@ -56440,10 +57022,10 @@ ${lanes.join("\n")} for (const type of matchingTypes){ result2 &= propertiesRelatedTo(source2, type, /*reportErrors*/ false, excludedProperties, /*optionalsOnly*/ false, 0 /* None */ ); if (result2) { - result2 &= signaturesRelatedTo(source2, type, 0 /* Call */ , /*reportStructuralErrors*/ false, 0 /* None */ ); + result2 &= signaturesRelatedTo(source2, type, 0 /* Call */ , /*reportErrors*/ false, 0 /* None */ ); if (result2) { - result2 &= signaturesRelatedTo(source2, type, 1 /* Construct */ , /*reportStructuralErrors*/ false, 0 /* None */ ); - if (result2 && !(isTupleType(source2) && isTupleType(type))) result2 &= indexSignaturesRelatedTo(source2, type, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */ ); + result2 &= signaturesRelatedTo(source2, type, 1 /* Construct */ , /*reportErrors*/ false, 0 /* None */ ); + if (result2 && !(isTupleType(source2) && isTupleType(type))) result2 &= indexSignaturesRelatedTo(source2, type, /*sourceIsPrimitive*/ false, /*reportErrors*/ false, 0 /* None */ ); } } if (!result2) return result2; @@ -56640,7 +57222,7 @@ ${lanes.join("\n")} return result2; } function signaturesRelatedTo(source2, target2, kind, reportErrors2, intersectionState) { - var _a3, _b; + var _a2, _b; if (relation === identityRelation) return signaturesIdenticalTo(source2, target2, kind); if (target2 === anyFunctionType || source2 === anyFunctionType) return -1 /* True */ ; const sourceIsJSConstructor = source2.symbol && isJSConstructor(source2.symbol.valueDeclaration); @@ -56670,7 +57252,7 @@ ${lanes.join("\n")} const sourceSignature = first(sourceSignatures); const targetSignature = first(targetSignatures); result2 = signatureRelatedTo(sourceSignature, targetSignature, eraseGenerics, reportErrors2, intersectionState, incompatibleReporter(sourceSignature, targetSignature)); - if (!result2 && reportErrors2 && kind === 1 /* Construct */ && sourceObjectFlags & targetObjectFlags && (((_a3 = targetSignature.declaration) == null ? void 0 : _a3.kind) === 173 /* Constructor */ || ((_b = sourceSignature.declaration) == null ? void 0 : _b.kind) === 173 /* Constructor */ )) { + if (!result2 && reportErrors2 && kind === 1 /* Construct */ && sourceObjectFlags & targetObjectFlags && (((_a2 = targetSignature.declaration) == null ? void 0 : _a2.kind) === 176 /* Constructor */ || ((_b = sourceSignature.declaration) == null ? void 0 : _b.kind) === 176 /* Constructor */ )) { const constructSignatureToString = (signature)=>signatureToString(signature, /*enclosingDeclaration*/ void 0, 262144 /* WriteArrowStyleSignature */ , kind); reportError(Diagnostics.Type_0_is_not_assignable_to_type_1, constructSignatureToString(sourceSignature), constructSignatureToString(targetSignature)); reportError(Diagnostics.Types_of_construct_signatures_are_incompatible); @@ -56822,29 +57404,22 @@ ${lanes.join("\n")} return getPropertiesOfType(type).filter((targetProp)=>containsMissingType(getTypeOfSymbol(targetProp))); } function getBestMatchingType(source, target, isRelatedTo = compareTypesAssignable) { - return findMatchingDiscriminantType(source, target, isRelatedTo, /*skipPartial*/ true) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || findBestTypeForObjectLiteral(source, target) || findBestTypeForInvokable(source, target) || findMostOverlappyType(source, target); + return findMatchingDiscriminantType(source, target, isRelatedTo) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || findBestTypeForObjectLiteral(source, target) || findBestTypeForInvokable(source, target) || findMostOverlappyType(source, target); } - function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue, skipPartial) { - const discriminable = target.types.map((_)=>void 0); + function discriminateTypeByDiscriminableItems(target, discriminators, related) { + const types = target.types; + const include = types.map((t)=>t.flags & 402784252 /* Primitive */ ? 0 /* False */ : -1 /* True */ ); for (const [getDiscriminatingType, propertyName] of discriminators){ - const targetProp = getUnionOrIntersectionProperty(target, propertyName); - if (skipPartial && targetProp && getCheckFlags(targetProp) & 16 /* ReadPartial */ ) continue; - let i = 0; - for (const type of target.types){ - const targetType = getTypeOfPropertyOfType(type, propertyName); - if (targetType && related(getDiscriminatingType(), targetType)) discriminable[i] = discriminable[i] === void 0 ? true : discriminable[i]; - else discriminable[i] = false; - i++; + let matched = false; + for(let i = 0; i < types.length; i++)if (include[i]) { + const targetType = getTypeOfPropertyOrIndexSignatureOfType(types[i], propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) matched = true; + else include[i] = 3 /* Maybe */ ; } + for(let i = 0; i < types.length; i++)if (include[i] === 3 /* Maybe */ ) include[i] = matched ? 0 /* False */ : -1 /* True */ ; } - const match = discriminable.indexOf(/*searchElement*/ true); - if (match === -1) return defaultValue; - let nextMatch = discriminable.indexOf(/*searchElement*/ true, match + 1); - while(nextMatch !== -1){ - if (!isTypeIdenticalTo(target.types[match], target.types[nextMatch])) return defaultValue; - nextMatch = discriminable.indexOf(/*searchElement*/ true, nextMatch + 1); - } - return target.types[match]; + const filtered = contains(include, 0 /* False */ ) ? getUnionType(types.filter((_, i)=>include[i]), 0 /* None */ ) : target; + return filtered.flags & 131072 /* Never */ ? target : filtered; } function isWeakType(type) { if (type.flags & 524288 /* Object */ ) { @@ -56867,13 +57442,18 @@ ${lanes.join("\n")} return getVariancesWorker(symbol, getSymbolLinks(symbol).typeParameters); } function getVariancesWorker(symbol, typeParameters = emptyArray) { - var _a2, _b; + var _a, _b; const links = getSymbolLinks(symbol); if (!links.variances) { - (_a2 = tracing) == null || _a2.push(tracing.Phase.CheckTypes, "getVariancesWorker", { + (_a = tracing) == null || _a.push(tracing.Phase.CheckTypes, "getVariancesWorker", { arity: typeParameters.length, id: getTypeId(getDeclaredTypeOfSymbol(symbol)) }); + const oldVarianceComputation = inVarianceComputation; + if (!inVarianceComputation) { + inVarianceComputation = true; + resolutionStart = resolutionTargets.length; + } links.variances = emptyArray; const variances = []; for (const tp of typeParameters){ @@ -56896,6 +57476,10 @@ ${lanes.join("\n")} } variances.push(variance); } + if (!oldVarianceComputation) { + inVarianceComputation = false; + resolutionStart = 0; + } links.variances = variances; (_b = tracing) == null || _b.pop({ variances: variances.map(Debug.formatVariance) @@ -56915,8 +57499,8 @@ ${lanes.join("\n")} return markerTypes.has(getTypeId(type)); } function getTypeParameterModifiers(tp) { - var _a2; - return reduceLeft((_a2 = tp.symbol) == null ? void 0 : _a2.declarations, (modifiers, d)=>modifiers | getEffectiveModifierFlags(d), 0 /* None */ ) & 100352 /* Const */ ; + var _a; + return reduceLeft((_a = tp.symbol) == null ? void 0 : _a.declarations, (modifiers, d)=>modifiers | getEffectiveModifierFlags(d), 0 /* None */ ) & 100352 /* Const */ ; } function hasCovariantVoidArgument(typeArguments, variances) { for(let i = 0; i < variances.length; i++){ @@ -57023,7 +57607,7 @@ ${lanes.join("\n")} } function getRecursionIdentity(type) { if (type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) { - if (getObjectFlags(type) && 4 /* Reference */ && type.node) return type.node; + if (getObjectFlags(type) & 4 /* Reference */ && type.node) return type.node; if (type.symbol && !(getObjectFlags(type) & 16 /* Anonymous */ && type.symbol.flags & 32 /* Class */ )) return type.symbol; if (isTupleType(type)) return type.target; } @@ -57110,7 +57694,7 @@ ${lanes.join("\n")} let commonBaseType; for (const t of types)if (!(t.flags & 131072 /* Never */ )) { const baseType = getBaseTypeOfLiteralType(t); - commonBaseType != null ? commonBaseType : commonBaseType = baseType; + commonBaseType ?? (commonBaseType = baseType); if (baseType === t || baseType !== commonBaseType) return false; } return true; @@ -57152,7 +57736,7 @@ ${lanes.join("\n")} const target = type.target; if (getObjectFlags(target) & 1 /* Class */ ) { const baseTypeNode = getBaseTypeNodeOfClass(target); - if (baseTypeNode && baseTypeNode.expression.kind !== 79 /* Identifier */ && baseTypeNode.expression.kind !== 208 /* PropertyAccessExpression */ ) return void 0; + if (baseTypeNode && baseTypeNode.expression.kind !== 80 /* Identifier */ && baseTypeNode.expression.kind !== 211 /* PropertyAccessExpression */ ) return void 0; } const bases = getBaseTypes(target); if (bases.length !== 1) return void 0; @@ -57170,7 +57754,8 @@ ${lanes.join("\n")} return !!elementType && isEmptyLiteralType(elementType); } function isTupleLikeType(type) { - return isTupleType(type) || !!getPropertyOfType(type, "0"); + let lengthType; + return isTupleType(type) || !!getPropertyOfType(type, "0") || isArrayLikeType(type) && !!(lengthType = getTypeOfPropertyOfType(type, "length")) && everyType(lengthType, (t)=>!!(t.flags & 256 /* NumberLiteral */ )); } function isArrayOrTupleLikeType(type) { return isArrayLikeType(type) || isTupleLikeType(type); @@ -57178,16 +57763,7 @@ ${lanes.join("\n")} function getTupleElementType(type, index) { const propType = getTypeOfPropertyOfType(type, "" + index); if (propType) return propType; - if (everyType(type, isTupleType)) return mapType(type, (t)=>{ - const tupleType = t; - const restType = getRestTypeOfTupleType(tupleType); - if (!restType) return undefinedType; - if (compilerOptions.noUncheckedIndexedAccess && index >= tupleType.target.fixedLength + getEndElementCount(tupleType.target, 3 /* Fixed */ )) return getUnionType([ - restType, - undefinedType - ]); - return restType; - }); + if (everyType(type, isTupleType)) return getTupleElementTypeOutOfStartCount(type, index, compilerOptions.noUncheckedIndexedAccess ? undefinedType : void 0); return void 0; } function isNeitherUnitTypeNorNever(type) { @@ -57210,9 +57786,8 @@ ${lanes.join("\n")} return type.flags & 1056 /* EnumLike */ ? getBaseTypeOfEnumLikeType(type) : type.flags & 402653312 /* StringMapping */ ? stringType : type.flags & 256 /* NumberLiteral */ ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 512 /* BooleanLiteral */ ? booleanType : type.flags & 1048576 /* Union */ ? getBaseTypeOfLiteralTypeUnion(type) : type; } function getBaseTypeOfLiteralTypeUnion(type) { - var _a2; const key = `B${getTypeId(type)}`; - return (_a2 = getCachedType(key)) != null ? _a2 : setCachedType(key, mapType(type, getBaseTypeOfLiteralType)); + return getCachedType(key) ?? setCachedType(key, mapType(type, getBaseTypeOfLiteralType)); } function getBaseTypeOfLiteralTypeForComparison(type) { return type.flags & 402653312 /* StringMapping */ ? stringType : type.flags & 288 /* Enum */ ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 512 /* BooleanLiteral */ ? booleanType : type.flags & 1048576 /* Union */ ? mapType(type, getBaseTypeOfLiteralTypeForComparison) : type; @@ -57253,6 +57828,18 @@ ${lanes.join("\n")} function getRestTypeOfTupleType(type) { return getElementTypeOfSliceOfTupleType(type, type.target.fixedLength); } + function getTupleElementTypeOutOfStartCount(type, index, undefinedOrMissingType2) { + return mapType(type, (t)=>{ + const tupleType = t; + const restType = getRestTypeOfTupleType(tupleType); + if (!restType) return undefinedType; + if (undefinedOrMissingType2 && index >= getTotalFixedElementCount(tupleType.target)) return getUnionType([ + restType, + undefinedOrMissingType2 + ]); + return restType; + }); + } function getRestArrayTypeOfTupleType(type) { const restType = getRestTypeOfTupleType(type); return restType && createArrayType(restType); @@ -57273,7 +57860,7 @@ ${lanes.join("\n")} function isTupleTypeStructureMatching(t1, t2) { return getTypeReferenceArity(t1) === getTypeReferenceArity(t2) && every(t1.target.elementFlags, (f, i)=>(f & 12 /* Variable */ ) === (t2.target.elementFlags[i] & 12 /* Variable */ )); } - function isZeroBigInt({ value: value1 }) { + function isZeroBigInt({ value: value1 }) { return value1.base10Value === "0"; } function removeDefinitelyFalsyTypes(type) { @@ -57473,7 +58060,7 @@ ${lanes.join("\n")} if (isObjectLiteralType2(type)) for (const p of getPropertiesOfObjectType(type)){ const t = getTypeOfSymbol(p); if (getObjectFlags(t) & 65536 /* ContainsWideningType */ ) { - if (!reportWideningErrorsInType(t)) error(p.valueDeclaration, Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); + if (!reportWideningErrorsInType(t)) error2(p.valueDeclaration, Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); errorReported = true; } } @@ -57485,16 +58072,16 @@ ${lanes.join("\n")} if (isInJSFile(declaration) && !isCheckJsEnabledForFile(getSourceFileOfNode(declaration), compilerOptions)) return; let diagnostic; switch(declaration.kind){ - case 223 /* BinaryExpression */ : - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : + case 226 /* BinaryExpression */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : diagnostic = noImplicitAny ? Diagnostics.Member_0_implicitly_has_an_1_type : Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 166 /* Parameter */ : + case 169 /* Parameter */ : const param = declaration; if (isIdentifier(param.name)) { const originalKeywordKind = identifierToKeywordKind(param.name); - if ((isCallSignatureDeclaration(param.parent) || isMethodSignature(param.parent) || isFunctionTypeNode(param.parent)) && param.parent.parameters.indexOf(param) > -1 && (resolveName(param, param.name.escapedText, 788968 /* Type */ , void 0, param.name.escapedText, /*isUse*/ true) || originalKeywordKind && isTypeNodeKind(originalKeywordKind))) { + if ((isCallSignatureDeclaration(param.parent) || isMethodSignature(param.parent) || isFunctionTypeNode(param.parent)) && param.parent.parameters.indexOf(param) > -1 && (resolveName(param, param.name.escapedText, 788968 /* Type */ , /*nameNotFoundMessage*/ void 0, param.name.escapedText, /*isUse*/ true) || originalKeywordKind && isTypeNodeKind(originalKeywordKind))) { const newName = "arg" + param.parent.parameters.indexOf(param); const typeName = declarationNameToString(param.name) + (param.dotDotDotToken ? "[]" : ""); errorOrSuggestion(noImplicitAny, declaration, Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, typeName); @@ -57503,32 +58090,32 @@ ${lanes.join("\n")} } diagnostic = declaration.dotDotDotToken ? noImplicitAny ? Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : noImplicitAny ? Diagnostics.Parameter_0_implicitly_has_an_1_type : Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 205 /* BindingElement */ : + case 208 /* BindingElement */ : diagnostic = Diagnostics.Binding_element_0_implicitly_has_an_1_type; if (!noImplicitAny) return; break; - case 320 /* JSDocFunctionType */ : - error(declaration, Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + case 324 /* JSDocFunctionType */ : + error2(declaration, Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; - case 326 /* JSDocSignature */ : - if (noImplicitAny && isJSDocOverloadTag(declaration.parent)) error(declaration.parent.tagName, Diagnostics.This_overload_implicitly_returns_the_type_0_because_it_lacks_a_return_type_annotation, typeAsString); + case 330 /* JSDocSignature */ : + if (noImplicitAny && isJSDocOverloadTag(declaration.parent)) error2(declaration.parent.tagName, Diagnostics.This_overload_implicitly_returns_the_type_0_because_it_lacks_a_return_type_annotation, typeAsString); return; - case 259 /* FunctionDeclaration */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : + case 262 /* FunctionDeclaration */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : if (noImplicitAny && !declaration.name) { - if (wideningKind === 3 /* GeneratorYield */ ) error(declaration, Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString); - else error(declaration, Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + if (wideningKind === 3 /* GeneratorYield */ ) error2(declaration, Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString); + else error2(declaration, Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } diagnostic = !noImplicitAny ? Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage : wideningKind === 3 /* GeneratorYield */ ? Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; - case 197 /* MappedType */ : - if (noImplicitAny) error(declaration, Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + case 200 /* MappedType */ : + if (noImplicitAny) error2(declaration, Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); return; default: diagnostic = noImplicitAny ? Diagnostics.Variable_0_implicitly_has_an_1_type : Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; @@ -57602,16 +58189,15 @@ ${lanes.join("\n")} for (const inference of inferences)if (!inference.isFixed) inference.inferredType = void 0; } function addIntraExpressionInferenceSite(context, node, type) { - var _a2; - ((_a2 = context.intraExpressionInferenceSites) != null ? _a2 : context.intraExpressionInferenceSites = []).push({ + (context.intraExpressionInferenceSites ?? (context.intraExpressionInferenceSites = [])).push({ node: node, type: type }); } function inferFromIntraExpressionSites(context) { if (context.intraExpressionInferenceSites) { - for (const { node: node , type: type } of context.intraExpressionInferenceSites){ - const contextualType = node.kind === 171 /* MethodDeclaration */ ? getContextualTypeForObjectLiteralMethod(node, 2 /* NoConstraints */ ) : getContextualType2(node, 2 /* NoConstraints */ ); + for (const { node: node, type: type } of context.intraExpressionInferenceSites){ + const contextualType = node.kind === 174 /* MethodDeclaration */ ? getContextualTypeForObjectLiteralMethod(node, 2 /* NoConstraints */ ) : getContextualType2(node, 2 /* NoConstraints */ ); if (contextualType) inferTypes(context.inferences, type, contextualType); } context.intraExpressionInferenceSites = void 0; @@ -57651,14 +58237,14 @@ ${lanes.join("\n")} function couldContainTypeVariables(type) { const objectFlags = getObjectFlags(type); if (objectFlags & 524288 /* CouldContainTypeVariablesComputed */ ) return !!(objectFlags & 1048576 /* CouldContainTypeVariables */ ); - const result = !!(type.flags & 465829888 /* Instantiable */ || type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || forEach(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 14384 /* ObjectLiteral */ && type.symbol.declarations || objectFlags & 12583968 /* InstantiationExpressionType */ ) || type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */ ) && !isNonGenericTopLevelType(type) && some(type.types, couldContainTypeVariables)); - if (type.flags & 3899393 /* ObjectFlagsType */ ) type.objectFlags |= 524288 /* CouldContainTypeVariablesComputed */ | (result ? 1048576 /* CouldContainTypeVariables */ : 0); + const result = !!(type.flags & 465829888 /* Instantiable */ || type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || some(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 14384 /* ObjectLiteral */ && type.symbol.declarations || objectFlags & 12583968 /* InstantiationExpressionType */ ) || type.flags & 137363456 /* TemplateLiteral */ && !(type.flags & 1024 /* EnumLiteral */ ) && !isNonGenericTopLevelType(type) && some(type.types, couldContainTypeVariables)); + if (type.flags & 138117121 /* ObjectFlagsType */ ) type.objectFlags |= 524288 /* CouldContainTypeVariablesComputed */ | (result ? 1048576 /* CouldContainTypeVariables */ : 0); return result; } function isNonGenericTopLevelType(type) { if (type.aliasSymbol && !type.aliasTypeArguments) { - const declaration = getDeclarationOfKind(type.aliasSymbol, 262 /* TypeAliasDeclaration */ ); - return !!(declaration && findAncestor(declaration.parent, (n)=>n.kind === 308 /* SourceFile */ ? true : n.kind === 264 /* ModuleDeclaration */ ? false : "quit")); + const declaration = getDeclarationOfKind(type.aliasSymbol, 265 /* TypeAliasDeclaration */ ); + return !!(declaration && findAncestor(declaration.parent, (n)=>n.kind === 312 /* SourceFile */ ? true : n.kind === 267 /* ModuleDeclaration */ ? false : "quit")); } return false; } @@ -57685,26 +58271,27 @@ ${lanes.join("\n")} const indexInfos = type.flags & 4 /* String */ ? [ createIndexInfo(stringType, emptyObjectType, /*isReadonly*/ false) ] : emptyArray; - return createAnonymousType(void 0, members, emptyArray, emptyArray, indexInfos); + return createAnonymousType(/*symbol*/ void 0, members, emptyArray, emptyArray, indexInfos); } function inferTypeForHomomorphicMappedType(source, target, constraint) { - if (inInferTypeForHomomorphicMappedType) return void 0; - const key = source.id + "," + target.id + "," + constraint.id; - if (reverseMappedCache.has(key)) return reverseMappedCache.get(key); - inInferTypeForHomomorphicMappedType = true; + const cacheKey = source.id + "," + target.id + "," + constraint.id; + if (reverseMappedCache.has(cacheKey)) return reverseMappedCache.get(cacheKey); + const recursionKey = source.id + "," + (target.target || target).id; + if (contains(homomorphicMappedTypeInferenceStack, recursionKey)) return void 0; + homomorphicMappedTypeInferenceStack.push(recursionKey); const type = createReverseMappedType(source, target, constraint); - inInferTypeForHomomorphicMappedType = false; - reverseMappedCache.set(key, type); + homomorphicMappedTypeInferenceStack.pop(); + reverseMappedCache.set(cacheKey, type); return type; } function isPartiallyInferableType(type) { - return !(getObjectFlags(type) & 262144 /* NonInferrableType */ ) || isObjectLiteralType2(type) && some(getPropertiesOfType(type), (prop)=>isPartiallyInferableType(getTypeOfSymbol(prop))) || isTupleType(type) && some(getTypeArguments(type), isPartiallyInferableType); + return !(getObjectFlags(type) & 262144 /* NonInferrableType */ ) || isObjectLiteralType2(type) && some(getPropertiesOfType(type), (prop)=>isPartiallyInferableType(getTypeOfSymbol(prop))) || isTupleType(type) && some(getElementTypes(type), isPartiallyInferableType); } function createReverseMappedType(source, target, constraint) { if (!(getIndexInfoOfType(source, stringType) || getPropertiesOfType(source).length !== 0 && isPartiallyInferableType(source))) return void 0; if (isArrayType(source)) return createArrayType(inferReverseMappedType(getTypeArguments(source)[0], target, constraint), isReadonlyArrayType(source)); if (isTupleType(source)) { - const elementTypes = map(getTypeArguments(source), (t)=>inferReverseMappedType(t, target, constraint)); + const elementTypes = map(getElementTypes(source), (t)=>inferReverseMappedType(t, target, constraint)); const elementFlags = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? sameMap(source.target.elementFlags, (f)=>f & 2 /* Optional */ ? 1 /* Required */ : f) : source.target.elementFlags; return createTupleType(elementTypes, elementFlags, source.target.readonly, source.target.labeledElementDeclarations); } @@ -58028,17 +58615,14 @@ ${lanes.join("\n")} const saveInferencePriority = inferencePriority; inferencePriority = 2048 /* MaxValue */ ; const saveExpandingFlags = expandingFlags; - const sourceIdentity = getRecursionIdentity(source); - const targetIdentity = getRecursionIdentity(target); - if (contains(sourceStack, sourceIdentity)) expandingFlags |= 1 /* Source */ ; - if (contains(targetStack, targetIdentity)) expandingFlags |= 2 /* Target */ ; - if (expandingFlags !== 3 /* Both */ ) { - (sourceStack || (sourceStack = [])).push(sourceIdentity); - (targetStack || (targetStack = [])).push(targetIdentity); - action(source, target); - targetStack.pop(); - sourceStack.pop(); - } else inferencePriority = -1 /* Circularity */ ; + (sourceStack ?? (sourceStack = [])).push(source); + (targetStack ?? (targetStack = [])).push(target); + if (isDeeplyNestedType(source, sourceStack, sourceStack.length, 2)) expandingFlags |= 1 /* Source */ ; + if (isDeeplyNestedType(target, targetStack, targetStack.length, 2)) expandingFlags |= 2 /* Target */ ; + if (expandingFlags !== 3 /* Both */ ) action(source, target); + else inferencePriority = -1 /* Circularity */ ; + targetStack.pop(); + sourceStack.pop(); expandingFlags = saveExpandingFlags; visited.set(key, inferencePriority); inferencePriority = Math.min(inferencePriority, saveInferencePriority); @@ -58144,7 +58728,7 @@ ${lanes.join("\n")} return true; } if (constraintType.flags & 262144 /* TypeParameter */ ) { - inferWithPriority(getIndexType(source), constraintType, 32 /* MappedTypeConstraint */ ); + inferWithPriority(getIndexType(source, /*indexFlags*/ !!source.pattern ? 2 /* NoIndexSignatures */ : 0 /* None */ ), constraintType, 32 /* MappedTypeConstraint */ ); const extendedConstraint = getConstraintOfType(constraintType); if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) return true; const propTypes = map(getPropertiesOfType(source), getTypeOfSymbol); @@ -58198,7 +58782,7 @@ ${lanes.join("\n")} } } function inferFromObjectTypes(source, target) { - var _a2, _b; + var _a, _b; if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target))) { inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target)); return; @@ -58241,7 +58825,7 @@ ${lanes.join("\n")} inferFromTypes(sliceTupleType(source, startLength + targetInfo.impliedArity, endLength), elementTypes[startLength + 1]); } } else if (elementFlags[startLength] & 8 /* Variadic */ && elementFlags[startLength + 1] & 4 /* Rest */ ) { - const param = (_a2 = getInferenceInfoForType(elementTypes[startLength])) == null ? void 0 : _a2.typeParameter; + const param = (_a = getInferenceInfoForType(elementTypes[startLength])) == null ? void 0 : _a.typeParameter; const constraint = param && getBaseConstraintOfType(param); if (constraint && isTupleType(constraint) && !constraint.target.hasRestElement) { const impliedArity = constraint.target.fixedLength; @@ -58299,11 +58883,13 @@ ${lanes.join("\n")} for(let i = 0; i < len; i++)inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); } function inferFromSignature(source, target) { - const saveBivariant = bivariant; - const kind = target.declaration ? target.declaration.kind : 0 /* Unknown */ ; - bivariant = bivariant || kind === 171 /* MethodDeclaration */ || kind === 170 /* MethodSignature */ || kind === 173 /* Constructor */ ; - applyToParameterTypes(source, target, inferFromContravariantTypesIfStrictFunctionTypes); - bivariant = saveBivariant; + if (!(source.flags & 64 /* IsNonInferrable */ )) { + const saveBivariant = bivariant; + const kind = target.declaration ? target.declaration.kind : 0 /* Unknown */ ; + bivariant = bivariant || kind === 174 /* MethodDeclaration */ || kind === 173 /* MethodSignature */ || kind === 176 /* Constructor */ ; + applyToParameterTypes(source, target, inferFromContravariantTypesIfStrictFunctionTypes); + bivariant = saveBivariant; + } applyToReturnTypes(source, target, inferFromTypes); } function inferFromIndexTypes(source, target) { @@ -58367,14 +58953,15 @@ ${lanes.join("\n")} const inference = context.inferences[index]; if (!inference.inferredType) { let inferredType; - const signature = context.signature; - if (signature) { - const inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : void 0; - if (inference.contraCandidates) { - const useCovariantType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */ ) && some(inference.contraCandidates, (t)=>isTypeSubtypeOf(inferredCovariantType, t)) && every(context.inferences, (other)=>other !== inference && getConstraintOfTypeParameter(other.typeParameter) !== inference.typeParameter || every(other.candidates, (t)=>isTypeSubtypeOf(t, inferredCovariantType))); - inferredType = useCovariantType ? inferredCovariantType : getContravariantInference(inference); - } else if (inferredCovariantType) inferredType = inferredCovariantType; - else if (context.flags & 1 /* NoDefault */ ) inferredType = silentNeverType; + let fallbackType; + if (context.signature) { + const inferredCovariantType = inference.candidates ? getCovariantInference(inference, context.signature) : void 0; + const inferredContravariantType = inference.contraCandidates ? getContravariantInference(inference) : void 0; + if (inferredCovariantType || inferredContravariantType) { + const preferCovariantType = inferredCovariantType && (!inferredContravariantType || !(inferredCovariantType.flags & 131072 /* Never */ ) && some(inference.contraCandidates, (t)=>isTypeSubtypeOf(inferredCovariantType, t)) && every(context.inferences, (other)=>other !== inference && getConstraintOfTypeParameter(other.typeParameter) !== inference.typeParameter || every(other.candidates, (t)=>isTypeSubtypeOf(t, inferredCovariantType)))); + inferredType = preferCovariantType ? inferredCovariantType : inferredContravariantType; + fallbackType = preferCovariantType ? inferredContravariantType : inferredCovariantType; + } else if (context.flags & 1 /* NoDefault */ ) inferredType = silentNeverType; else { const defaultType = getDefaultFromTypeParameter(inference.typeParameter); if (defaultType) inferredType = instantiateType(defaultType, mergeTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper)); @@ -58384,7 +58971,7 @@ ${lanes.join("\n")} const constraint = getConstraintOfTypeParameter(inference.typeParameter); if (constraint) { const instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper); - if (!inferredType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) inference.inferredType = inferredType = instantiatedConstraint; + if (!inferredType || inferredType === wildcardType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) inference.inferredType = fallbackType && context.compareTypes(fallbackType, getTypeWithThisArgument(instantiatedConstraint, fallbackType)) ? fallbackType : instantiatedConstraint; } } return inference.inferredType; @@ -58436,7 +59023,7 @@ ${lanes.join("\n")} case "await": if (isCallExpression(node.parent)) return Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function; default: - if (node.parent.kind === 300 /* ShorthandPropertyAssignment */ ) return Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer; + if (node.parent.kind === 304 /* ShorthandPropertyAssignment */ ) return Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer; else return Diagnostics.Cannot_find_name_0; } } @@ -58445,75 +59032,72 @@ ${lanes.join("\n")} if (!links.resolvedSymbol) links.resolvedSymbol = !nodeIsMissing(node) && resolveName(node, node.escapedText, 1160127 /* ExportValue */ , getCannotFindNameDiagnosticForName(node), node, !isWriteOnlyAccess(node), /*excludeGlobals*/ false) || unknownSymbol; return links.resolvedSymbol; } - function isInTypeQuery(node) { - return !!findAncestor(node, (n)=>n.kind === 183 /* TypeQuery */ ? true : n.kind === 79 /* Identifier */ || n.kind === 163 /* QualifiedName */ ? false : "quit"); - } function isInAmbientOrTypeNode(node) { - return !!(node.flags & 16777216 /* Ambient */ || findAncestor(node, (n)=>isInterfaceDeclaration(n) || isTypeLiteralNode(n))); + return !!(node.flags & 33554432 /* Ambient */ || findAncestor(node, (n)=>isInterfaceDeclaration(n) || isTypeAliasDeclaration(n) || isTypeLiteralNode(n))); } function getFlowCacheKey(node, declaredType, initialType, flowContainer) { switch(node.kind){ - case 79 /* Identifier */ : + case 80 /* Identifier */ : if (!isThisInTypeQuery(node)) { const symbol = getResolvedSymbol(node); return symbol !== unknownSymbol ? `${flowContainer ? getNodeId(flowContainer) : "-1"}|${getTypeId(declaredType)}|${getTypeId(initialType)}|${getSymbolId(symbol)}` : void 0; } - case 108 /* ThisKeyword */ : + case 110 /* ThisKeyword */ : return `0|${flowContainer ? getNodeId(flowContainer) : "-1"}|${getTypeId(declaredType)}|${getTypeId(initialType)}`; - case 232 /* NonNullExpression */ : - case 214 /* ParenthesizedExpression */ : + case 235 /* NonNullExpression */ : + case 217 /* ParenthesizedExpression */ : return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); - case 163 /* QualifiedName */ : + case 166 /* QualifiedName */ : const left = getFlowCacheKey(node.left, declaredType, initialType, flowContainer); return left && left + "." + node.right.escapedText; - case 208 /* PropertyAccessExpression */ : - case 209 /* ElementAccessExpression */ : + case 211 /* PropertyAccessExpression */ : + case 212 /* ElementAccessExpression */ : const propName = getAccessedPropertyName(node); if (propName !== void 0) { const key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); return key && key + "." + propName; } break; - case 203 /* ObjectBindingPattern */ : - case 204 /* ArrayBindingPattern */ : - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - case 171 /* MethodDeclaration */ : + case 206 /* ObjectBindingPattern */ : + case 207 /* ArrayBindingPattern */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + case 174 /* MethodDeclaration */ : return `${getNodeId(node)}#${getTypeId(declaredType)}`; } return void 0; } function isMatchingReference(source, target) { switch(target.kind){ - case 214 /* ParenthesizedExpression */ : - case 232 /* NonNullExpression */ : + case 217 /* ParenthesizedExpression */ : + case 235 /* NonNullExpression */ : return isMatchingReference(source, target.expression); - case 223 /* BinaryExpression */ : - return isAssignmentExpression(target) && isMatchingReference(source, target.left) || isBinaryExpression(target) && target.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source, target.right); + case 226 /* BinaryExpression */ : + return isAssignmentExpression(target) && isMatchingReference(source, target.left) || isBinaryExpression(target) && target.operatorToken.kind === 28 /* CommaToken */ && isMatchingReference(source, target.right); } switch(source.kind){ - case 233 /* MetaProperty */ : - return target.kind === 233 /* MetaProperty */ && source.keywordToken === target.keywordToken && source.name.escapedText === target.name.escapedText; - case 79 /* Identifier */ : - case 80 /* PrivateIdentifier */ : - return isThisInTypeQuery(source) ? target.kind === 108 /* ThisKeyword */ : target.kind === 79 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || (isVariableDeclaration(target) || isBindingElement(target)) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfDeclaration(target); - case 108 /* ThisKeyword */ : - return target.kind === 108 /* ThisKeyword */ ; - case 106 /* SuperKeyword */ : - return target.kind === 106 /* SuperKeyword */ ; - case 232 /* NonNullExpression */ : - case 214 /* ParenthesizedExpression */ : + case 236 /* MetaProperty */ : + return target.kind === 236 /* MetaProperty */ && source.keywordToken === target.keywordToken && source.name.escapedText === target.name.escapedText; + case 80 /* Identifier */ : + case 81 /* PrivateIdentifier */ : + return isThisInTypeQuery(source) ? target.kind === 110 /* ThisKeyword */ : target.kind === 80 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || (isVariableDeclaration(target) || isBindingElement(target)) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfDeclaration(target); + case 110 /* ThisKeyword */ : + return target.kind === 110 /* ThisKeyword */ ; + case 108 /* SuperKeyword */ : + return target.kind === 108 /* SuperKeyword */ ; + case 235 /* NonNullExpression */ : + case 217 /* ParenthesizedExpression */ : return isMatchingReference(source.expression, target); - case 208 /* PropertyAccessExpression */ : - case 209 /* ElementAccessExpression */ : + case 211 /* PropertyAccessExpression */ : + case 212 /* ElementAccessExpression */ : const sourcePropertyName = getAccessedPropertyName(source); const targetPropertyName = isAccessExpression(target) ? getAccessedPropertyName(target) : void 0; return sourcePropertyName !== void 0 && targetPropertyName !== void 0 && targetPropertyName === sourcePropertyName && isMatchingReference(source.expression, target.expression); - case 163 /* QualifiedName */ : + case 166 /* QualifiedName */ : return isAccessExpression(target) && source.right.escapedText === getAccessedPropertyName(target) && isMatchingReference(source.left, target.expression); - case 223 /* BinaryExpression */ : - return isBinaryExpression(source) && source.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source.right, target); + case 226 /* BinaryExpression */ : + return isBinaryExpression(source) && source.operatorToken.kind === 28 /* CommaToken */ && isMatchingReference(source.right, target); } return false; } @@ -58531,22 +59115,22 @@ ${lanes.join("\n")} return type.flags & 8192 /* UniqueESSymbol */ ? type.escapedName : type.flags & 384 /* StringOrNumberLiteral */ ? escapeLeadingUnderscores("" + type.value) : void 0; } function tryGetElementAccessExpressionName(node) { - if (isStringOrNumericLiteralLike(node.argumentExpression)) return escapeLeadingUnderscores(node.argumentExpression.text); - if (isEntityNameExpression(node.argumentExpression)) { - const symbol = resolveEntityName(node.argumentExpression, 111551 /* Value */ , /*ignoreErrors*/ true); - if (!symbol || !(isConstVariable(symbol) || symbol.flags & 8 /* EnumMember */ )) return void 0; - const declaration = symbol.valueDeclaration; - if (declaration === void 0) return void 0; - const type = tryGetTypeFromEffectiveTypeNode(declaration); - if (type) { - const name = tryGetNameFromType(type); - if (name !== void 0) return name; - } - if (hasOnlyExpressionInitializer(declaration) && isBlockScopedNameDeclaredBeforeUse(declaration, node.argumentExpression)) { - const initializer = getEffectiveInitializer(declaration); - if (initializer) return tryGetNameFromType(getTypeOfExpression(initializer)); - if (isEnumMember(declaration)) return getTextOfPropertyName(declaration.name); - } + return isStringOrNumericLiteralLike(node.argumentExpression) ? escapeLeadingUnderscores(node.argumentExpression.text) : isEntityNameExpression(node.argumentExpression) ? tryGetNameFromEntityNameExpression(node.argumentExpression) : void 0; + } + function tryGetNameFromEntityNameExpression(node) { + const symbol = resolveEntityName(node, 111551 /* Value */ , /*ignoreErrors*/ true); + if (!symbol || !(isConstantVariable(symbol) || symbol.flags & 8 /* EnumMember */ )) return void 0; + const declaration = symbol.valueDeclaration; + if (declaration === void 0) return void 0; + const type = tryGetTypeFromEffectiveTypeNode(declaration); + if (type) { + const name = tryGetNameFromType(type); + if (name !== void 0) return name; + } + if (hasOnlyExpressionInitializer(declaration) && isBlockScopedNameDeclaredBeforeUse(declaration, node)) { + const initializer = getEffectiveInitializer(declaration); + if (initializer) return tryGetNameFromType(getTypeOfExpression(initializer)); + if (isEnumMember(declaration)) return getTextOfPropertyName(declaration.name); } return void 0; } @@ -58621,8 +59205,8 @@ ${lanes.join("\n")} return unionType.keyPropertyName.length ? unionType.keyPropertyName : void 0; } function getConstituentTypeForKeyType(unionType, keyType) { - var _a2; - const result = (_a2 = unionType.constituentMap) == null ? void 0 : _a2.get(getTypeId(getRegularTypeOfLiteralType(keyType))); + var _a; + const result = (_a = unionType.constituentMap) == null ? void 0 : _a.get(getTypeId(getRegularTypeOfLiteralType(keyType))); return result !== unknownType ? result : void 0; } function getMatchingUnionConstituentForType(unionType, type) { @@ -58632,7 +59216,7 @@ ${lanes.join("\n")} } function getMatchingUnionConstituentForObjectLiteral(unionType, node) { const keyPropertyName = getKeyPropertyName(unionType); - const propNode = keyPropertyName && find(node.properties, (p)=>p.symbol && p.kind === 299 /* PropertyAssignment */ && p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer)); + const propNode = keyPropertyName && find(node.properties, (p)=>p.symbol && p.kind === 303 /* PropertyAssignment */ && p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer)); const propType = propNode && getContextFreeTypeOfExpression(propNode.initializer); return propType && getConstituentTypeForKeyType(unionType, propType); } @@ -58643,7 +59227,7 @@ ${lanes.join("\n")} if (expression.arguments) for (const argument of expression.arguments){ if (isOrContainsMatchingReference(reference, argument)) return true; } - if (expression.expression.kind === 208 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, expression.expression.expression)) return true; + if (expression.expression.kind === 211 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, expression.expression.expression)) return true; return false; } function getFlowNodeId(flow) { @@ -58661,11 +59245,10 @@ ${lanes.join("\n")} return false; } function getAssignmentReducedType(declaredType, assignedType) { - var _a2; if (declaredType === assignedType) return declaredType; if (assignedType.flags & 131072 /* Never */ ) return assignedType; const key = `A${getTypeId(declaredType)},${getTypeId(assignedType)}`; - return (_a2 = getCachedType(key)) != null ? _a2 : setCachedType(key, getAssignmentReducedTypeWorker(declaredType, assignedType)); + return getCachedType(key) ?? setCachedType(key, getAssignmentReducedTypeWorker(declaredType, assignedType)); } function getAssignmentReducedTypeWorker(declaredType, assignedType) { const filteredType = filterType(declaredType, (t)=>typeMaybeAssignableTo(assignedType, t)); @@ -58708,7 +59291,7 @@ ${lanes.join("\n")} return 83886079 /* UnknownFacts */ ; } function getIntersectionTypeFacts(type) { - const ignoreObjects = maybeTypeOfKind(type, 134348796 /* Primitive */ ); + const ignoreObjects = maybeTypeOfKind(type, 402784252 /* Primitive */ ); let oredFacts = 0 /* None */ ; let andedFacts = 134217727 /* All */ ; for (const t of type.types)if (!(ignoreObjects && t.flags & 524288 /* Object */ )) { @@ -58756,11 +59339,11 @@ ${lanes.join("\n")} ]) : type; } function getTypeOfDestructuredProperty(type, name) { - var _a2; + var _a; const nameType = getLiteralTypeFromPropertyName(name); if (!isTypeUsableAsPropertyName(nameType)) return errorType; const text = getPropertyNameFromType(nameType); - return getTypeOfPropertyOfType(type, text) || includeUndefinedInIndexSignature((_a2 = getApplicableIndexInfoForName(type, text)) == null ? void 0 : _a2.type) || errorType; + return getTypeOfPropertyOfType(type, text) || includeUndefinedInIndexSignature((_a = getApplicableIndexInfoForName(type, text)) == null ? void 0 : _a.type) || errorType; } function getTypeOfDestructuredArrayElement(type, index) { return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || includeUndefinedInIndexSignature(checkIteratedTypeOrElementType(65 /* Destructuring */ , type, undefinedType, /*errorNode*/ void 0)) || errorType; @@ -58776,11 +59359,11 @@ ${lanes.join("\n")} return createArrayType(checkIteratedTypeOrElementType(65 /* Destructuring */ , type, undefinedType, /*errorNode*/ void 0) || errorType); } function getAssignedTypeOfBinaryExpression(node) { - const isDestructuringDefaultAssignment = node.parent.kind === 206 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || node.parent.kind === 299 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + const isDestructuringDefaultAssignment = node.parent.kind === 209 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || node.parent.kind === 303 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } function isDestructuringAssignmentTarget(parent2) { - return parent2.parent.kind === 223 /* BinaryExpression */ && parent2.parent.left === parent2 || parent2.parent.kind === 247 /* ForOfStatement */ && parent2.parent.initializer === parent2; + return parent2.parent.kind === 226 /* BinaryExpression */ && parent2.parent.left === parent2 || parent2.parent.kind === 250 /* ForOfStatement */ && parent2.parent.initializer === parent2; } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); @@ -58795,23 +59378,23 @@ ${lanes.join("\n")} return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer); } function getAssignedType(node) { - const { parent: parent2 } = node; + const { parent: parent2 } = node; switch(parent2.kind){ - case 246 /* ForInStatement */ : + case 249 /* ForInStatement */ : return stringType; - case 247 /* ForOfStatement */ : + case 250 /* ForOfStatement */ : return checkRightHandSideOfForOf(parent2) || errorType; - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : return getAssignedTypeOfBinaryExpression(parent2); - case 217 /* DeleteExpression */ : + case 220 /* DeleteExpression */ : return undefinedType; - case 206 /* ArrayLiteralExpression */ : + case 209 /* ArrayLiteralExpression */ : return getAssignedTypeOfArrayLiteralElement(parent2, node); - case 227 /* SpreadElement */ : + case 230 /* SpreadElement */ : return getAssignedTypeOfSpreadExpression(parent2); - case 299 /* PropertyAssignment */ : + case 303 /* PropertyAssignment */ : return getAssignedTypeOfPropertyAssignment(parent2); - case 300 /* ShorthandPropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : return getAssignedTypeOfShorthandPropertyAssignment(parent2); } return errorType; @@ -58819,7 +59402,7 @@ ${lanes.join("\n")} function getInitialTypeOfBindingElement(node) { const pattern = node.parent; const parentType = getInitialType(pattern.parent); - const type = pattern.kind === 203 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : getTypeOfDestructuredSpreadExpression(parentType); + const type = pattern.kind === 206 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : getTypeOfDestructuredSpreadExpression(parentType); return getTypeWithDefault(type, node.initializer); } function getTypeOfInitializer(node) { @@ -58828,39 +59411,39 @@ ${lanes.join("\n")} } function getInitialTypeOfVariableDeclaration(node) { if (node.initializer) return getTypeOfInitializer(node.initializer); - if (node.parent.parent.kind === 246 /* ForInStatement */ ) return stringType; - if (node.parent.parent.kind === 247 /* ForOfStatement */ ) return checkRightHandSideOfForOf(node.parent.parent) || errorType; + if (node.parent.parent.kind === 249 /* ForInStatement */ ) return stringType; + if (node.parent.parent.kind === 250 /* ForOfStatement */ ) return checkRightHandSideOfForOf(node.parent.parent) || errorType; return errorType; } function getInitialType(node) { - return node.kind === 257 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); + return node.kind === 260 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } function isEmptyArrayAssignment(node) { - return node.kind === 257 /* VariableDeclaration */ && node.initializer && isEmptyArrayLiteral2(node.initializer) || node.kind !== 205 /* BindingElement */ && node.parent.kind === 223 /* BinaryExpression */ && isEmptyArrayLiteral2(node.parent.right); + return node.kind === 260 /* VariableDeclaration */ && node.initializer && isEmptyArrayLiteral2(node.initializer) || node.kind !== 208 /* BindingElement */ && node.parent.kind === 226 /* BinaryExpression */ && isEmptyArrayLiteral2(node.parent.right); } function getReferenceCandidate(node) { switch(node.kind){ - case 214 /* ParenthesizedExpression */ : + case 217 /* ParenthesizedExpression */ : return getReferenceCandidate(node.expression); - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : switch(node.operatorToken.kind){ - case 63 /* EqualsToken */ : - case 75 /* BarBarEqualsToken */ : - case 76 /* AmpersandAmpersandEqualsToken */ : - case 77 /* QuestionQuestionEqualsToken */ : + case 64 /* EqualsToken */ : + case 76 /* BarBarEqualsToken */ : + case 77 /* AmpersandAmpersandEqualsToken */ : + case 78 /* QuestionQuestionEqualsToken */ : return getReferenceCandidate(node.left); - case 27 /* CommaToken */ : + case 28 /* CommaToken */ : return getReferenceCandidate(node.right); } } return node; } function getReferenceRoot(node) { - const { parent: parent2 } = node; - return parent2.kind === 214 /* ParenthesizedExpression */ || parent2.kind === 223 /* BinaryExpression */ && parent2.operatorToken.kind === 63 /* EqualsToken */ && parent2.left === node || parent2.kind === 223 /* BinaryExpression */ && parent2.operatorToken.kind === 27 /* CommaToken */ && parent2.right === node ? getReferenceRoot(parent2) : node; + const { parent: parent2 } = node; + return parent2.kind === 217 /* ParenthesizedExpression */ || parent2.kind === 226 /* BinaryExpression */ && parent2.operatorToken.kind === 64 /* EqualsToken */ && parent2.left === node || parent2.kind === 226 /* BinaryExpression */ && parent2.operatorToken.kind === 28 /* CommaToken */ && parent2.right === node ? getReferenceRoot(parent2) : node; } function getTypeOfSwitchClause(clause) { - if (clause.kind === 292 /* CaseClause */ ) return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); + if (clause.kind === 296 /* CaseClause */ ) return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); return neverType; } function getSwitchClauseTypes(switchStatement) { @@ -58872,10 +59455,10 @@ ${lanes.join("\n")} return links.switchTypes; } function getSwitchClauseTypeOfWitnesses(switchStatement) { - if (some(switchStatement.caseBlock.clauses, (clause)=>clause.kind === 292 /* CaseClause */ && !isStringLiteralLike(clause.expression))) return void 0; + if (some(switchStatement.caseBlock.clauses, (clause)=>clause.kind === 296 /* CaseClause */ && !isStringLiteralLike(clause.expression))) return void 0; const witnesses = []; for (const clause of switchStatement.caseBlock.clauses){ - const text = clause.kind === 292 /* CaseClause */ ? clause.expression.text : void 0; + const text = clause.kind === 296 /* CaseClause */ ? clause.expression.text : void 0; witnesses.push(text && !contains(witnesses, text) ? text : void 0); } return witnesses; @@ -58884,7 +59467,7 @@ ${lanes.join("\n")} return source.flags & 1048576 /* Union */ ? !forEach(source.types, (t)=>!contains(types, t)) : contains(types, source); } function isTypeSubsetOf(source, target) { - return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target); + return !!(source === target || source.flags & 131072 /* Never */ || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target)); } function isTypeSubsetOfUnion(source, target) { if (source.flags & 1048576 /* Union */ ) { @@ -59012,8 +59595,8 @@ ${lanes.join("\n")} function isEvolvingArrayOperationTarget(node) { const root = getReferenceRoot(node); const parent2 = root.parent; - const isLengthPushOrUnshift = isPropertyAccessExpression(parent2) && (parent2.name.escapedText === "length" || parent2.parent.kind === 210 /* CallExpression */ && isIdentifier(parent2.name) && isPushOrUnshiftIdentifier(parent2.name)); - const isElementAssignment = parent2.kind === 209 /* ElementAccessExpression */ && parent2.expression === root && parent2.parent.kind === 223 /* BinaryExpression */ && parent2.parent.operatorToken.kind === 63 /* EqualsToken */ && parent2.parent.left === parent2 && !isAssignmentTarget(parent2.parent) && isTypeAssignableToKind(getTypeOfExpression(parent2.argumentExpression), 296 /* NumberLike */ ); + const isLengthPushOrUnshift = isPropertyAccessExpression(parent2) && (parent2.name.escapedText === "length" || parent2.parent.kind === 213 /* CallExpression */ && isIdentifier(parent2.name) && isPushOrUnshiftIdentifier(parent2.name)); + const isElementAssignment = parent2.kind === 212 /* ElementAccessExpression */ && parent2.expression === root && parent2.parent.kind === 226 /* BinaryExpression */ && parent2.parent.operatorToken.kind === 64 /* EqualsToken */ && parent2.parent.left === parent2 && !isAssignmentTarget(parent2.parent) && isTypeAssignableToKind(getTypeOfExpression(parent2.argumentExpression), 296 /* NumberLike */ ); return isLengthPushOrUnshift || isElementAssignment; } function isDeclarationWithExplicitTypeAnnotation(node) { @@ -59030,7 +59613,7 @@ ${lanes.join("\n")} const declaration = symbol.valueDeclaration; if (declaration) { if (isDeclarationWithExplicitTypeAnnotation(declaration)) return getTypeOfSymbol(symbol); - if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === 247 /* ForOfStatement */ ) { + if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === 250 /* ForOfStatement */ ) { const statement = declaration.parent.parent; const expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ void 0); if (expressionType) { @@ -59043,15 +59626,15 @@ ${lanes.join("\n")} } } function getTypeOfDottedName(node, diagnostic) { - if (!(node.flags & 33554432 /* InWithStatement */ )) switch(node.kind){ - case 79 /* Identifier */ : + if (!(node.flags & 67108864 /* InWithStatement */ )) switch(node.kind){ + case 80 /* Identifier */ : const symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node)); return getExplicitTypeOfSymbol(symbol, diagnostic); - case 108 /* ThisKeyword */ : + case 110 /* ThisKeyword */ : return getExplicitThisType(node); - case 106 /* SuperKeyword */ : + case 108 /* SuperKeyword */ : return checkSuperExpression(node); - case 208 /* PropertyAccessExpression */ : + case 211 /* PropertyAccessExpression */ : { const type = getTypeOfDottedName(node.expression, diagnostic); if (type) { @@ -59065,7 +59648,7 @@ ${lanes.join("\n")} } return void 0; } - case 214 /* ParenthesizedExpression */ : + case 217 /* ParenthesizedExpression */ : return getTypeOfDottedName(node.expression, diagnostic); } } @@ -59074,8 +59657,8 @@ ${lanes.join("\n")} let signature = links.effectsSignature; if (signature === void 0) { let funcType; - if (node.parent.kind === 241 /* ExpressionStatement */ ) funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ void 0); - else if (node.expression.kind !== 106 /* SuperKeyword */ ) { + if (node.parent.kind === 244 /* ExpressionStatement */ ) funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ void 0); + else if (node.expression.kind !== 108 /* SuperKeyword */ ) { if (isOptionalChain(node)) funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression); else funcType = checkNonNullExpression(node.expression); } @@ -59107,7 +59690,7 @@ ${lanes.join("\n")} } function isFalseExpression(expr) { const node = skipParentheses(expr, /*excludeJSDocTypeAssertions*/ true); - return node.kind === 95 /* FalseKeyword */ || node.kind === 223 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right)); + return node.kind === 97 /* FalseKeyword */ || node.kind === 226 /* BinaryExpression */ && (node.operatorToken.kind === 56 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || node.operatorToken.kind === 57 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right)); } function isReachableFlowNodeWorker(flow, noCacheCheck) { while(true){ @@ -59165,7 +59748,7 @@ ${lanes.join("\n")} } if (flags & 496 /* SwitchClause */ ) flow = flow.antecedent; else if (flags & 512 /* Call */ ) { - if (flow.node.expression.kind === 106 /* SuperKeyword */ ) return true; + if (flow.node.expression.kind === 108 /* SuperKeyword */ ) return true; flow = flow.antecedent; } else if (flags & 4 /* BranchLabel */ ) return every(flow.antecedents, (f)=>isPostSuperFlowNode(f, /*noCacheCheck*/ false)); else if (flags & 8 /* LoopLabel */ ) flow = flow.antecedents[0]; @@ -59181,19 +59764,21 @@ ${lanes.join("\n")} } function isConstantReference(node) { switch(node.kind){ - case 79 /* Identifier */ : + case 110 /* ThisKeyword */ : + return true; + case 80 /* Identifier */ : if (!isThisInTypeQuery(node)) { const symbol = getResolvedSymbol(node); - return isConstVariable(symbol) || isParameterOrCatchClauseVariable(symbol) && !isSymbolAssigned(symbol); + return isConstantVariable(symbol) || isParameterOrCatchClauseVariable(symbol) && !isSymbolAssigned(symbol); } break; - case 208 /* PropertyAccessExpression */ : - case 209 /* ElementAccessExpression */ : + case 211 /* PropertyAccessExpression */ : + case 212 /* ElementAccessExpression */ : return isConstantReference(node.expression) && isReadonlySymbol(getNodeLinks(node).resolvedSymbol || unknownSymbol); } return false; } - function getFlowTypeOfReference(reference, declaredType, initialType = declaredType, flowContainer, flowNode = ((_a2)=>(_a2 = tryCast(reference, canHaveFlowNode)) == null ? void 0 : _a2.flowNode)()) { + function getFlowTypeOfReference(reference, declaredType, initialType = declaredType, flowContainer, flowNode = ((_a)=>(_a = tryCast(reference, canHaveFlowNode)) == null ? void 0 : _a.flowNode)()) { let key; let isKeySet = false; let flowDepth = 0; @@ -59204,7 +59789,7 @@ ${lanes.join("\n")} const evolvedType = getTypeFromFlowType(getTypeAtFlowNode(flowNode)); sharedFlowCount = sharedFlowStart; const resultType = getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); - if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 232 /* NonNullExpression */ && !(resultType.flags & 131072 /* Never */ ) && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */ ).flags & 131072 /* Never */ ) return declaredType; + if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 235 /* NonNullExpression */ && !(resultType.flags & 131072 /* Never */ ) && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */ ).flags & 131072 /* Never */ ) return declaredType; return resultType === nonNullUnknownType ? unknownType : resultType; function getOrSetCacheKey() { if (isKeySet) return key; @@ -59212,9 +59797,9 @@ ${lanes.join("\n")} return key = getFlowCacheKey(reference, declaredType, initialType, flowContainer); } function getTypeAtFlowNode(flow) { - var _a3; + var _a2; if (flowDepth === 2e3) { - (_a3 = tracing) == null || _a3.instant(tracing.Phase.CheckTypes, "getTypeAtFlowNode_DepthLimit", { + (_a2 = tracing) == null || _a2.instant(tracing.Phase.CheckTypes, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); flowAnalysisDisabled = true; @@ -59267,7 +59852,7 @@ ${lanes.join("\n")} target.antecedents = saveAntecedents; } else if (flags & 2 /* Start */ ) { const container = flow.node; - if (container && container !== flowContainer && reference.kind !== 208 /* PropertyAccessExpression */ && reference.kind !== 209 /* ElementAccessExpression */ && reference.kind !== 108 /* ThisKeyword */ ) { + if (container && container !== flowContainer && reference.kind !== 211 /* PropertyAccessExpression */ && reference.kind !== 212 /* ElementAccessExpression */ && !(reference.kind === 110 /* ThisKeyword */ && container.kind !== 219 /* ArrowFunction */ )) { flow = container.flowNode; continue; } @@ -59284,7 +59869,7 @@ ${lanes.join("\n")} } function getInitialOrAssignedType(flow) { const node = flow.node; - return getNarrowableTypeForReference(node.kind === 257 /* VariableDeclaration */ || node.kind === 205 /* BindingElement */ ? getInitialType(node) : getAssignedType(node), reference); + return getNarrowableTypeForReference(node.kind === 260 /* VariableDeclaration */ || node.kind === 208 /* BindingElement */ ? getInitialType(node) : getAssignedType(node), reference); } function getTypeAtFlowAssignment(flow) { const node = flow.node; @@ -59304,21 +59889,21 @@ ${lanes.join("\n")} } if (containsMatchingReference(reference, node)) { if (!isReachableFlowNode(flow)) return unreachableNeverType; - if (isVariableDeclaration(node) && (isInJSFile(node) || isVarConst(node))) { + if (isVariableDeclaration(node) && (isInJSFile(node) || isVarConstLike(node))) { const init = getDeclaredExpandoInitializer(node); - if (init && (init.kind === 215 /* FunctionExpression */ || init.kind === 216 /* ArrowFunction */ )) return getTypeAtFlowNode(flow.antecedent); + if (init && (init.kind === 218 /* FunctionExpression */ || init.kind === 219 /* ArrowFunction */ )) return getTypeAtFlowNode(flow.antecedent); } return declaredType; } - if (isVariableDeclaration(node) && node.parent.parent.kind === 246 /* ForInStatement */ && (isMatchingReference(reference, node.parent.parent.expression) || optionalChainContainsReference(node.parent.parent.expression, reference))) return getNonNullableTypeIfNeeded(finalizeEvolvingArrayType(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)))); + if (isVariableDeclaration(node) && node.parent.parent.kind === 249 /* ForInStatement */ && (isMatchingReference(reference, node.parent.parent.expression) || optionalChainContainsReference(node.parent.parent.expression, reference))) return getNonNullableTypeIfNeeded(finalizeEvolvingArrayType(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)))); return void 0; } function narrowTypeByAssertion(type, expr) { const node = skipParentheses(expr, /*excludeJSDocTypeAssertions*/ true); - if (node.kind === 95 /* FalseKeyword */ ) return unreachableNeverType; - if (node.kind === 223 /* BinaryExpression */ ) { - if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ ) return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); - if (node.operatorToken.kind === 56 /* BarBarToken */ ) return getUnionType([ + if (node.kind === 97 /* FalseKeyword */ ) return unreachableNeverType; + if (node.kind === 226 /* BinaryExpression */ ) { + if (node.operatorToken.kind === 56 /* AmpersandAmpersandToken */ ) return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); + if (node.operatorToken.kind === 57 /* BarBarToken */ ) return getUnionType([ narrowTypeByAssertion(type, node.left), narrowTypeByAssertion(type, node.right) ]); @@ -59342,13 +59927,13 @@ ${lanes.join("\n")} function getTypeAtFlowArrayMutation(flow) { if (declaredType === autoType || declaredType === autoArrayType) { const node = flow.node; - const expr = node.kind === 210 /* CallExpression */ ? node.expression.expression : node.left.expression; + const expr = node.kind === 213 /* CallExpression */ ? node.expression.expression : node.left.expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { const flowType = getTypeAtFlowNode(flow.antecedent); const type = getTypeFromFlowType(flowType); if (getObjectFlags(type) & 256 /* EvolvingArray */ ) { let evolvedType2 = type; - if (node.kind === 210 /* CallExpression */ ) for (const arg of node.arguments)evolvedType2 = addEvolvingArrayElementType(evolvedType2, arg); + if (node.kind === 213 /* CallExpression */ ) for (const arg of node.arguments)evolvedType2 = addEvolvingArrayElementType(evolvedType2, arg); else { const indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); if (isTypeAssignableToKind(indexType, 296 /* NumberLike */ )) evolvedType2 = addEvolvingArrayElementType(evolvedType2, node.right); @@ -59375,11 +59960,11 @@ ${lanes.join("\n")} const flowType = getTypeAtFlowNode(flow.antecedent); let type = getTypeFromFlowType(flowType); if (isMatchingReference(reference, expr)) type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); - else if (expr.kind === 218 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) type = narrowTypeBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + else if (expr.kind === 221 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) type = narrowTypeBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); else { if (strictNullChecks) { if (optionalChainContainsReference(expr, reference)) type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, (t)=>!(t.flags & 163840 /* Never */ )); - else if (expr.kind === 218 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, (t)=>!(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined")); + else if (expr.kind === 221 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, (t)=>!(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined")); } const access = getDiscriminantPropertyAccess(expr, type); if (access) type = narrowTypeBySwitchOnDiscriminantProperty(type, access, flow.switchStatement, flow.clauseStart, flow.clauseEnd); @@ -59400,7 +59985,7 @@ ${lanes.join("\n")} const type = getTypeFromFlowType(flowType); if (type === declaredType && declaredType === initialType) return type; pushIfUnique(antecedentTypes, type); - if (!isTypeSubsetOf(type, declaredType)) subtypeReduction = true; + if (!isTypeSubsetOf(type, initialType)) subtypeReduction = true; if (isIncomplete(flowType)) seenIncomplete = true; } if (bypassFlow) { @@ -59409,7 +59994,7 @@ ${lanes.join("\n")} if (!(type.flags & 131072 /* Never */ ) && !contains(antecedentTypes, type) && !isExhaustiveSwitchStatement(bypassFlow.switchStatement)) { if (type === declaredType && declaredType === initialType) return type; antecedentTypes.push(type); - if (!isTypeSubsetOf(type, declaredType)) subtypeReduction = true; + if (!isTypeSubsetOf(type, initialType)) subtypeReduction = true; if (isIncomplete(flowType)) seenIncomplete = true; } } @@ -59446,7 +60031,7 @@ ${lanes.join("\n")} } const type = getTypeFromFlowType(flowType); pushIfUnique(antecedentTypes, type); - if (!isTypeSubsetOf(type, declaredType)) subtypeReduction = true; + if (!isTypeSubsetOf(type, initialType)) subtypeReduction = true; if (type === declaredType) break; } const result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */ ); @@ -59471,7 +60056,7 @@ ${lanes.join("\n")} if (isMatchingReference(reference, expr.expression)) return expr; } else if (isIdentifier(expr)) { const symbol = getResolvedSymbol(expr); - if (isConstVariable(symbol)) { + if (isConstantVariable(symbol)) { const declaration = symbol.valueDeclaration; if (isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && isAccessExpression(declaration.initializer) && isMatchingReference(reference, declaration.initializer.expression)) return declaration.initializer; if (isBindingElement(declaration) && !declaration.initializer) { @@ -59508,11 +60093,11 @@ ${lanes.join("\n")} }); } function narrowTypeByDiscriminantProperty(type, access, operator, value1, assumeTrue) { - if ((operator === 36 /* EqualsEqualsEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */ ) && type.flags & 1048576 /* Union */ ) { + if ((operator === 37 /* EqualsEqualsEqualsToken */ || operator === 38 /* ExclamationEqualsEqualsToken */ ) && type.flags & 1048576 /* Union */ ) { const keyPropertyName = getKeyPropertyName(type); if (keyPropertyName && keyPropertyName === getAccessedPropertyName(access)) { const candidate = getConstituentTypeForKeyType(type, getTypeOfExpression(value1)); - if (candidate) return operator === (assumeTrue ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */ ) ? candidate : isUnitType(getTypeOfPropertyOfType(candidate, keyPropertyName) || unknownType) ? removeType(type, candidate) : type; + if (candidate) return operator === (assumeTrue ? 37 /* EqualsEqualsEqualsToken */ : 38 /* ExclamationEqualsEqualsToken */ ) ? candidate : isUnitType(getTypeOfPropertyOfType(candidate, keyPropertyName) || unknownType) ? removeType(type, candidate) : type; } } return narrowTypeByDiscriminant(type, access, (t)=>narrowTypeByEquality(t, operator, value1, assumeTrue)); @@ -59534,7 +60119,7 @@ ${lanes.join("\n")} } function isTypePresencePossible(type, propName, assumeTrue) { const prop = getPropertyOfType(type, propName); - return prop ? !!(prop.flags & 16777216 /* Optional */ ) || assumeTrue : !!getApplicableIndexInfoForName(type, propName) || !assumeTrue; + return prop ? !!(prop.flags & 16777216 /* Optional */ || getCheckFlags(prop) & 48 /* Partial */ ) || assumeTrue : !!getApplicableIndexInfoForName(type, propName) || !assumeTrue; } function narrowTypeByInKeyword(type, nameType, assumeTrue) { const name = getPropertyNameFromType(nameType); @@ -59554,20 +60139,20 @@ ${lanes.join("\n")} } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch(expr.operatorToken.kind){ - case 63 /* EqualsToken */ : - case 75 /* BarBarEqualsToken */ : - case 76 /* AmpersandAmpersandEqualsToken */ : - case 77 /* QuestionQuestionEqualsToken */ : + case 64 /* EqualsToken */ : + case 76 /* BarBarEqualsToken */ : + case 77 /* AmpersandAmpersandEqualsToken */ : + case 78 /* QuestionQuestionEqualsToken */ : return narrowTypeByTruthiness(narrowType(type, expr.right, assumeTrue), expr.left, assumeTrue); - case 34 /* EqualsEqualsToken */ : - case 35 /* ExclamationEqualsToken */ : - case 36 /* EqualsEqualsEqualsToken */ : - case 37 /* ExclamationEqualsEqualsToken */ : + case 35 /* EqualsEqualsToken */ : + case 36 /* ExclamationEqualsToken */ : + case 37 /* EqualsEqualsEqualsToken */ : + case 38 /* ExclamationEqualsEqualsToken */ : const operator = expr.operatorToken.kind; const left = getReferenceCandidate(expr.left); const right = getReferenceCandidate(expr.right); - if (left.kind === 218 /* TypeOfExpression */ && isStringLiteralLike(right)) return narrowTypeByTypeof(type, left, operator, right, assumeTrue); - if (right.kind === 218 /* TypeOfExpression */ && isStringLiteralLike(left)) return narrowTypeByTypeof(type, right, operator, left, assumeTrue); + if (left.kind === 221 /* TypeOfExpression */ && isStringLiteralLike(right)) return narrowTypeByTypeof(type, left, operator, right, assumeTrue); + if (right.kind === 221 /* TypeOfExpression */ && isStringLiteralLike(left)) return narrowTypeByTypeof(type, right, operator, left, assumeTrue); if (isMatchingReference(reference, left)) return narrowTypeByEquality(type, operator, right, assumeTrue); if (isMatchingReference(reference, right)) return narrowTypeByEquality(type, operator, left, assumeTrue); if (strictNullChecks) { @@ -59581,25 +60166,28 @@ ${lanes.join("\n")} if (isMatchingConstructorReference(left)) return narrowTypeByConstructor(type, operator, right, assumeTrue); if (isMatchingConstructorReference(right)) return narrowTypeByConstructor(type, operator, left, assumeTrue); break; - case 102 /* InstanceOfKeyword */ : + case 104 /* InstanceOfKeyword */ : return narrowTypeByInstanceof(type, expr, assumeTrue); - case 101 /* InKeyword */ : + case 103 /* InKeyword */ : if (isPrivateIdentifier(expr.left)) return narrowTypeByPrivateIdentifierInInExpression(type, expr, assumeTrue); const target = getReferenceCandidate(expr.right); - const leftType = getTypeOfExpression(expr.left); - if (leftType.flags & 8576 /* StringOrNumberLiteralOrUnique */ ) { - if (containsMissingType(type) && isAccessExpression(reference) && isMatchingReference(reference.expression, target) && getAccessedPropertyName(reference) === getPropertyNameFromType(leftType)) return getTypeWithFacts(type, assumeTrue ? 524288 /* NEUndefined */ : 65536 /* EQUndefined */ ); - if (isMatchingReference(reference, target)) return narrowTypeByInKeyword(type, leftType, assumeTrue); + if (containsMissingType(type) && isAccessExpression(reference) && isMatchingReference(reference.expression, target)) { + const leftType = getTypeOfExpression(expr.left); + if (isTypeUsableAsPropertyName(leftType) && getAccessedPropertyName(reference) === getPropertyNameFromType(leftType)) return getTypeWithFacts(type, assumeTrue ? 524288 /* NEUndefined */ : 65536 /* EQUndefined */ ); + } + if (isMatchingReference(reference, target)) { + const leftType = getTypeOfExpression(expr.left); + if (isTypeUsableAsPropertyName(leftType)) return narrowTypeByInKeyword(type, leftType, assumeTrue); } break; - case 27 /* CommaToken */ : + case 28 /* CommaToken */ : return narrowType(type, expr.right, assumeTrue); - case 55 /* AmpersandAmpersandToken */ : + case 56 /* AmpersandAmpersandToken */ : return assumeTrue ? narrowType(narrowType(type, expr.left, /*assumeTrue*/ true), expr.right, /*assumeTrue*/ true) : getUnionType([ narrowType(type, expr.left, /*assumeTrue*/ false), narrowType(type, expr.right, /*assumeTrue*/ false) ]); - case 56 /* BarBarToken */ : + case 57 /* BarBarToken */ : return assumeTrue ? getUnionType([ narrowType(type, expr.left, /*assumeTrue*/ true), narrowType(type, expr.right, /*assumeTrue*/ true) @@ -59618,17 +60206,17 @@ ${lanes.join("\n")} return getNarrowedType(type, targetType, assumeTrue, /*checkDerived*/ true); } function narrowTypeByOptionalChainContainment(type, operator, value1, assumeTrue) { - const equalsOperator = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */ ; - const nullableFlags = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */ ? 98304 /* Nullable */ : 32768 /* Undefined */ ; + const equalsOperator = operator === 35 /* EqualsEqualsToken */ || operator === 37 /* EqualsEqualsEqualsToken */ ; + const nullableFlags = operator === 35 /* EqualsEqualsToken */ || operator === 36 /* ExclamationEqualsToken */ ? 98304 /* Nullable */ : 32768 /* Undefined */ ; const valueType = getTypeOfExpression(value1); const removeNullable = equalsOperator !== assumeTrue && everyType(valueType, (t)=>!!(t.flags & nullableFlags)) || equalsOperator === assumeTrue && everyType(valueType, (t)=>!(t.flags & (3 /* AnyOrUnknown */ | nullableFlags))); return removeNullable ? getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */ ) : type; } function narrowTypeByEquality(type, operator, value1, assumeTrue) { if (type.flags & 1 /* Any */ ) return type; - if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */ ) assumeTrue = !assumeTrue; + if (operator === 36 /* ExclamationEqualsToken */ || operator === 38 /* ExclamationEqualsEqualsToken */ ) assumeTrue = !assumeTrue; const valueType = getTypeOfExpression(value1); - const doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */ ; + const doubleEquals = operator === 35 /* EqualsEqualsToken */ || operator === 36 /* ExclamationEqualsToken */ ; if (valueType.flags & 98304 /* Nullable */ ) { if (!strictNullChecks) return type; const facts = doubleEquals ? assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ : valueType.flags & 65536 /* Null */ ? assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ : assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */ ; @@ -59636,7 +60224,7 @@ ${lanes.join("\n")} } if (assumeTrue) { if (!doubleEquals && (type.flags & 2 /* Unknown */ || someType(type, isEmptyAnonymousObjectType))) { - if (valueType.flags & 201457660 /* NonPrimitive */ || isEmptyAnonymousObjectType(valueType)) return valueType; + if (valueType.flags & 469893116 /* NonPrimitive */ || isEmptyAnonymousObjectType(valueType)) return valueType; if (valueType.flags & 524288 /* Object */ ) return nonPrimitiveType; } const filteredType = filterType(type, (t)=>areTypesComparable(t, valueType) || doubleEquals && isCoercibleUnderDoubleEquals(t, valueType)); @@ -59646,7 +60234,7 @@ ${lanes.join("\n")} return type; } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { - if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */ ) assumeTrue = !assumeTrue; + if (operator === 36 /* ExclamationEqualsToken */ || operator === 38 /* ExclamationEqualsEqualsToken */ ) assumeTrue = !assumeTrue; const target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) type = getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */ ); @@ -59672,7 +60260,7 @@ ${lanes.join("\n")} let groundClauseTypes; for(let i = 0; i < clauseTypes.length; i += 1){ const t = clauseTypes[i]; - if (t.flags & 201457660 /* NonPrimitive */ ) { + if (t.flags & 469893116 /* NonPrimitive */ ) { if (groundClauseTypes !== void 0) groundClauseTypes.push(t); } else if (t.flags & 524288 /* Object */ ) { if (groundClauseTypes === void 0) groundClauseTypes = clauseTypes.slice(0, i); @@ -59732,7 +60320,7 @@ ${lanes.join("\n")} function narrowTypeBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { const witnesses = getSwitchClauseTypeOfWitnesses(switchStatement); if (!witnesses) return type; - const defaultIndex = findIndex(switchStatement.caseBlock.clauses, (clause)=>clause.kind === 293 /* DefaultClause */ ); + const defaultIndex = findIndex(switchStatement.caseBlock.clauses, (clause)=>clause.kind === 297 /* DefaultClause */ ); const hasDefaultClause = clauseStart === clauseEnd || defaultIndex >= clauseStart && defaultIndex < clauseEnd; if (hasDefaultClause) { const notEqualFacts = getNotEqualFactsFromTypeofSwitch(clauseStart, clauseEnd, witnesses); @@ -59745,7 +60333,7 @@ ${lanes.join("\n")} return (isPropertyAccessExpression(expr) && idText(expr.name) === "constructor" || isElementAccessExpression(expr) && isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") && isMatchingReference(reference, expr.expression); } function narrowTypeByConstructor(type, operator, identifier, assumeTrue) { - if (assumeTrue ? operator !== 34 /* EqualsEqualsToken */ && operator !== 36 /* EqualsEqualsEqualsToken */ : operator !== 35 /* ExclamationEqualsToken */ && operator !== 37 /* ExclamationEqualsEqualsToken */ ) return type; + if (assumeTrue ? operator !== 35 /* EqualsEqualsToken */ && operator !== 37 /* EqualsEqualsEqualsToken */ : operator !== 36 /* ExclamationEqualsToken */ && operator !== 38 /* ExclamationEqualsEqualsToken */ ) return type; const identifierType = getTypeOfExpression(identifier); if (!isFunctionType(identifierType) && !isConstructorType(identifierType)) return type; const prototypeProperty = getPropertyOfType(identifierType, "prototype"); @@ -59780,9 +60368,8 @@ ${lanes.join("\n")} return emptyObjectType; } function getNarrowedType(type, candidate, assumeTrue, checkDerived) { - var _a3; const key2 = type.flags & 1048576 /* Union */ ? `N${getTypeId(type)},${getTypeId(candidate)},${(assumeTrue ? 1 : 0) | (checkDerived ? 2 : 0)}` : void 0; - return (_a3 = getCachedType(key2)) != null ? _a3 : setCachedType(key2, getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived)); + return getCachedType(key2) ?? setCachedType(key2, getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived)); } function getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived) { if (!assumeTrue) { @@ -59835,12 +60422,12 @@ ${lanes.join("\n")} return type; } function narrowType(type, expr, assumeTrue) { - if (isExpressionOfOptionalChainRoot(expr) || isBinaryExpression(expr.parent) && (expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ || expr.parent.operatorToken.kind === 77 /* QuestionQuestionEqualsToken */ ) && expr.parent.left === expr) return narrowTypeByOptionality(type, expr, assumeTrue); + if (isExpressionOfOptionalChainRoot(expr) || isBinaryExpression(expr.parent) && (expr.parent.operatorToken.kind === 61 /* QuestionQuestionToken */ || expr.parent.operatorToken.kind === 78 /* QuestionQuestionEqualsToken */ ) && expr.parent.left === expr) return narrowTypeByOptionality(type, expr, assumeTrue); switch(expr.kind){ - case 79 /* Identifier */ : + case 80 /* Identifier */ : if (!isMatchingReference(reference, expr) && inlineLevel < 5) { const symbol = getResolvedSymbol(expr); - if (isConstVariable(symbol)) { + if (isConstantVariable(symbol)) { const declaration = symbol.valueDeclaration; if (declaration && isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && isConstantReference(reference)) { inlineLevel++; @@ -59850,20 +60437,20 @@ ${lanes.join("\n")} } } } - case 108 /* ThisKeyword */ : - case 106 /* SuperKeyword */ : - case 208 /* PropertyAccessExpression */ : - case 209 /* ElementAccessExpression */ : + case 110 /* ThisKeyword */ : + case 108 /* SuperKeyword */ : + case 211 /* PropertyAccessExpression */ : + case 212 /* ElementAccessExpression */ : return narrowTypeByTruthiness(type, expr, assumeTrue); - case 210 /* CallExpression */ : + case 213 /* CallExpression */ : return narrowTypeByCallExpression(type, expr, assumeTrue); - case 214 /* ParenthesizedExpression */ : - case 232 /* NonNullExpression */ : + case 217 /* ParenthesizedExpression */ : + case 235 /* NonNullExpression */ : return narrowType(type, expr.expression, assumeTrue); - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 221 /* PrefixUnaryExpression */ : - if (expr.operator === 53 /* ExclamationToken */ ) return narrowType(type, expr.operand, !assumeTrue); + case 224 /* PrefixUnaryExpression */ : + if (expr.operator === 54 /* ExclamationToken */ ) return narrowType(type, expr.operand, !assumeTrue); break; } return type; @@ -59877,10 +60464,10 @@ ${lanes.join("\n")} } function getTypeOfSymbolAtLocation(symbol, location) { symbol = getExportSymbolOfValueSymbolIfExported(symbol); - if (location.kind === 79 /* Identifier */ || location.kind === 80 /* PrivateIdentifier */ ) { + if (location.kind === 80 /* Identifier */ || location.kind === 81 /* PrivateIdentifier */ ) { if (isRightSideOfQualifiedNameOrPropertyAccess(location)) location = location.parent; if (isExpressionNode(location) && (!isAssignmentTarget(location) || isWriteAccess(location))) { - const type = getTypeOfExpression(location); + const type = removeOptionalTypeMarker(getTypeOfExpression(location)); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) return type; } } @@ -59888,31 +60475,31 @@ ${lanes.join("\n")} return getNonMissingTypeOfSymbol(symbol); } function getControlFlowContainer(node) { - return findAncestor(node.parent, (node2)=>isFunctionLike(node2) && !getImmediatelyInvokedFunctionExpression(node2) || node2.kind === 265 /* ModuleBlock */ || node2.kind === 308 /* SourceFile */ || node2.kind === 169 /* PropertyDeclaration */ ); + return findAncestor(node.parent, (node2)=>isFunctionLike(node2) && !getImmediatelyInvokedFunctionExpression(node2) || node2.kind === 268 /* ModuleBlock */ || node2.kind === 312 /* SourceFile */ || node2.kind === 172 /* PropertyDeclaration */ ); } function isSymbolAssigned(symbol) { if (!symbol.valueDeclaration) return false; const parent2 = getRootDeclaration(symbol.valueDeclaration).parent; const links = getNodeLinks(parent2); - if (!(links.flags & 524288 /* AssignmentsMarked */ )) { - links.flags |= 524288 /* AssignmentsMarked */ ; + if (!(links.flags & 131072 /* AssignmentsMarked */ )) { + links.flags |= 131072 /* AssignmentsMarked */ ; if (!hasParentWithAssignmentsMarked(parent2)) markNodeAssignments(parent2); } return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!findAncestor(node.parent, (node2)=>(isFunctionLike(node2) || isCatchClause(node2)) && !!(getNodeLinks(node2).flags & 524288 /* AssignmentsMarked */ )); + return !!findAncestor(node.parent, (node2)=>(isFunctionLike(node2) || isCatchClause(node2)) && !!(getNodeLinks(node2).flags & 131072 /* AssignmentsMarked */ )); } function markNodeAssignments(node) { - if (node.kind === 79 /* Identifier */ ) { + if (node.kind === 80 /* Identifier */ ) { if (isAssignmentTarget(node)) { const symbol = getResolvedSymbol(node); if (isParameterOrCatchClauseVariable(symbol)) symbol.isAssigned = true; } } else forEachChild(node, markNodeAssignments); } - function isConstVariable(symbol) { - return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ ) !== 0; + function isConstantVariable(symbol) { + return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 6 /* Constant */ ) !== 0; } function parameterInitializerContainsUndefined(declaration) { const links = getNodeLinks(declaration); @@ -59931,12 +60518,12 @@ ${lanes.join("\n")} return links.parameterInitializerContainsUndefined; } function removeOptionalityFromDeclaredType(declaredType, declaration) { - const removeUndefined = strictNullChecks && declaration.kind === 166 /* Parameter */ && declaration.initializer && getTypeFacts(declaredType) & 16777216 /* IsUndefined */ && !parameterInitializerContainsUndefined(declaration); + const removeUndefined = strictNullChecks && declaration.kind === 169 /* Parameter */ && declaration.initializer && getTypeFacts(declaredType) & 16777216 /* IsUndefined */ && !parameterInitializerContainsUndefined(declaration); return removeUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */ ) : declaredType; } function isConstraintPosition(type, node) { const parent2 = node.parent; - return parent2.kind === 208 /* PropertyAccessExpression */ || parent2.kind === 163 /* QualifiedName */ || parent2.kind === 210 /* CallExpression */ && parent2.expression === node || parent2.kind === 209 /* ElementAccessExpression */ && parent2.expression === node && !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression(parent2.argumentExpression))); + return parent2.kind === 211 /* PropertyAccessExpression */ || parent2.kind === 166 /* QualifiedName */ || parent2.kind === 213 /* CallExpression */ && parent2.expression === node || parent2.kind === 212 /* ElementAccessExpression */ && parent2.expression === node && !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression(parent2.argumentExpression))); } function isGenericTypeWithUnionConstraint(type) { return type.flags & 2097152 /* Intersection */ ? some(type.types, isGenericTypeWithUnionConstraint) : !!(type.flags & 465829888 /* Instantiable */ && getBaseConstraintOrType(type).flags & 1146880 /* Union */ ); @@ -59962,30 +60549,30 @@ ${lanes.join("\n")} }); } function markAliasReferenced(symbol, location) { - if (compilerOptions.verbatimModuleSyntax) return; - if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */ ) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* Value */ )) { + if (!canCollectSymbolAliasAccessabilityData) return; + if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */ ) && !isInTypeQuery(location)) { const target = resolveAlias(symbol); - if (getAllSymbolFlags(target) & 1160127 /* ExportValue */ ) { + if (getSymbolFlags(symbol, /*excludeTypeOnlyMeanings*/ true) & 1160127 /* ExportValue */ ) { if (getIsolatedModules(compilerOptions) || shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(getExportSymbolOfValueSymbolIfExported(target))) markAliasSymbolAsReferenced(symbol); else markConstEnumAliasAsReferenced(symbol); } } } function getNarrowedTypeOfSymbol(symbol, location) { - var _a2; + var _a; const type = getTypeOfSymbol(symbol); const declaration = symbol.valueDeclaration; if (declaration) { if (isBindingElement(declaration) && !declaration.initializer && !declaration.dotDotDotToken && declaration.parent.elements.length >= 2) { const parent2 = declaration.parent.parent; - if (parent2.kind === 257 /* VariableDeclaration */ && getCombinedNodeFlags(declaration) & 2 /* Const */ || parent2.kind === 166 /* Parameter */ ) { + if (parent2.kind === 260 /* VariableDeclaration */ && getCombinedNodeFlagsCached(declaration) & 6 /* Constant */ || parent2.kind === 169 /* Parameter */ ) { const links = getNodeLinks(parent2); - if (!(links.flags & 16777216 /* InCheckIdentifier */ )) { - links.flags |= 16777216 /* InCheckIdentifier */ ; + if (!(links.flags & 4194304 /* InCheckIdentifier */ )) { + links.flags |= 4194304 /* InCheckIdentifier */ ; const parentType = getTypeForBindingElementParent(parent2, 0 /* Normal */ ); const parentTypeConstraint = parentType && mapType(parentType, getBaseConstraintOrType); - links.flags &= -16777217 /* InCheckIdentifier */ ; - if (parentTypeConstraint && parentTypeConstraint.flags & 1048576 /* Union */ && !(parent2.kind === 166 /* Parameter */ && isSymbolAssigned(symbol))) { + links.flags &= -4194305 /* InCheckIdentifier */ ; + if (parentTypeConstraint && parentTypeConstraint.flags & 1048576 /* Union */ && !(parent2.kind === 169 /* Parameter */ && isSymbolAssigned(symbol))) { const pattern = declaration.parent; const narrowedType = getFlowTypeOfReference(pattern, parentTypeConstraint, parentTypeConstraint, /*flowContainer*/ void 0, location.flowNode); if (narrowedType.flags & 131072 /* Never */ ) return neverType; @@ -59999,7 +60586,7 @@ ${lanes.join("\n")} if (func.parameters.length >= 2 && isContextSensitiveFunctionOrObjectLiteralMethod(func)) { const contextualSignature = getContextualSignature(func); if (contextualSignature && contextualSignature.parameters.length === 1 && signatureHasRestParameter(contextualSignature)) { - const restType = getReducedApparentType(instantiateType(getTypeOfSymbol(contextualSignature.parameters[0]), (_a2 = getInferenceContext(func)) == null ? void 0 : _a2.nonFixingMapper)); + const restType = getReducedApparentType(instantiateType(getTypeOfSymbol(contextualSignature.parameters[0]), (_a = getInferenceContext(func)) == null ? void 0 : _a.nonFixingMapper)); if (restType.flags & 1048576 /* Union */ && everyType(restType, isTupleType) && !isSymbolAssigned(symbol)) { const narrowedType = getFlowTypeOfReference(func, restType, restType, /*flowContainer*/ void 0, location.flowNode); const index = func.parameters.indexOf(declaration) - (getThisParameter(func) ? 1 : 0); @@ -60017,44 +60604,30 @@ ${lanes.join("\n")} if (symbol === unknownSymbol) return errorType; if (symbol === argumentsSymbol) { if (isInPropertyInitializerOrClassStaticBlock(node)) { - error(node, Diagnostics.arguments_cannot_be_referenced_in_property_initializers); + error2(node, Diagnostics.arguments_cannot_be_referenced_in_property_initializers); return errorType; } const container = getContainingFunction(node); if (languageVersion < 2 /* ES2015 */ ) { - if (container.kind === 216 /* ArrowFunction */ ) error(node, Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); - else if (hasSyntacticModifier(container, 512 /* Async */ )) error(node, Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); + if (container.kind === 219 /* ArrowFunction */ ) error2(node, Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); + else if (hasSyntacticModifier(container, 512 /* Async */ )) error2(node, Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); } getNodeLinks(container).flags |= 512 /* CaptureArguments */ ; return getTypeOfSymbol(symbol); } if (shouldMarkIdentifierAliasReferenced(node)) markAliasReferenced(symbol, node); const localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); - const targetSymbol = checkDeprecatedAliasedSymbol(localOrExportSymbol, node); + const targetSymbol = resolveAliasWithDeprecationCheck(localOrExportSymbol, node); if (isDeprecatedSymbol(targetSymbol) && isUncalledFunctionReference(node, targetSymbol) && targetSymbol.declarations) addDeprecatedSuggestion(node, targetSymbol.declarations, node.escapedText); let declaration = localOrExportSymbol.valueDeclaration; if (declaration && localOrExportSymbol.flags & 32 /* Class */ ) { - if (declaration.kind === 260 /* ClassDeclaration */ && nodeIsDecorated(legacyDecorators, declaration)) { - let container = getContainingClass(node); - while(container !== void 0){ - if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 1048576 /* ClassWithConstructorReference */ ; - getNodeLinks(node).flags |= 2097152 /* ConstructorReferenceInClass */ ; - break; - } - container = getContainingClass(container); - } - } else if (declaration.kind === 228 /* ClassExpression */ ) { + if (isClassLike(declaration) && declaration.name !== node) { let container = getThisContainer(node, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false); - while(container.kind !== 308 /* SourceFile */ ){ - if (container.parent === declaration) { - if (isPropertyDeclaration(container) && isStatic(container) || isClassStaticBlockDeclaration(container)) { - getNodeLinks(declaration).flags |= 1048576 /* ClassWithConstructorReference */ ; - getNodeLinks(node).flags |= 2097152 /* ConstructorReferenceInClass */ ; - } - break; - } - container = getThisContainer(container, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false); + while(container.kind !== 312 /* SourceFile */ && container.parent !== declaration)container = getThisContainer(container, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false); + if (container.kind !== 312 /* SourceFile */ ) { + getNodeLinks(declaration).flags |= 262144 /* ContainsConstructorReference */ ; + getNodeLinks(container).flags |= 262144 /* ContainsConstructorReference */ ; + getNodeLinks(node).flags |= 536870912 /* ConstructorReference */ ; } } } @@ -60064,12 +60637,12 @@ ${lanes.join("\n")} if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */ ) && !(isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */ )) { const assignmentError = localOrExportSymbol.flags & 384 /* Enum */ ? Diagnostics.Cannot_assign_to_0_because_it_is_an_enum : localOrExportSymbol.flags & 32 /* Class */ ? Diagnostics.Cannot_assign_to_0_because_it_is_a_class : localOrExportSymbol.flags & 1536 /* Module */ ? Diagnostics.Cannot_assign_to_0_because_it_is_a_namespace : localOrExportSymbol.flags & 16 /* Function */ ? Diagnostics.Cannot_assign_to_0_because_it_is_a_function : localOrExportSymbol.flags & 2097152 /* Alias */ ? Diagnostics.Cannot_assign_to_0_because_it_is_an_import : Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable; - error(node, assignmentError, symbolToString(symbol)); + error2(node, assignmentError, symbolToString(symbol)); return errorType; } if (isReadonlySymbol(localOrExportSymbol)) { - if (localOrExportSymbol.flags & 3 /* Variable */ ) error(node, Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol)); - else error(node, Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol)); + if (localOrExportSymbol.flags & 3 /* Variable */ ) error2(node, Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol)); + else error2(node, Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol)); return errorType; } } @@ -60080,26 +60653,28 @@ ${lanes.join("\n")} else return type; if (!declaration) return type; type = getNarrowableTypeForReference(type, node, checkMode); - const isParameter2 = getRootDeclaration(declaration).kind === 166 /* Parameter */ ; + const isParameter2 = getRootDeclaration(declaration).kind === 169 /* Parameter */ ; const declarationContainer = getControlFlowContainer(declaration); let flowContainer = getControlFlowContainer(node); const isOuterVariable = flowContainer !== declarationContainer; const isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); const isModuleExports = symbol.flags & 134217728 /* ModuleExports */ ; - while(flowContainer !== declarationContainer && (flowContainer.kind === 215 /* FunctionExpression */ || flowContainer.kind === 216 /* ArrowFunction */ || isObjectLiteralOrClassExpressionMethodOrAccessor(flowContainer)) && (isConstVariable(localOrExportSymbol) && type !== autoArrayType || isParameter2 && !isSymbolAssigned(localOrExportSymbol)))flowContainer = getControlFlowContainer(flowContainer); - const assumeInitialized = isParameter2 || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 16387 /* Void */ ) !== 0 || isInTypeQuery(node) || isInAmbientOrTypeNode(node) || node.parent.kind === 278 /* ExportSpecifier */ ) || node.parent.kind === 232 /* NonNullExpression */ || declaration.kind === 257 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 16777216 /* Ambient */ ; - const initialType = assumeInitialized ? isParameter2 ? removeOptionalityFromDeclaredType(type, declaration) : type : type === autoType || type === autoArrayType ? undefinedType : getOptionalType(type); - const flowType = getFlowTypeOfReference(node, type, initialType, flowContainer); + const typeIsAutomatic = type === autoType || type === autoArrayType; + const isAutomaticTypeInNonNull = typeIsAutomatic && node.parent.kind === 235 /* NonNullExpression */ ; + while(flowContainer !== declarationContainer && (flowContainer.kind === 218 /* FunctionExpression */ || flowContainer.kind === 219 /* ArrowFunction */ || isObjectLiteralOrClassExpressionMethodOrAccessor(flowContainer)) && (isConstantVariable(localOrExportSymbol) && type !== autoArrayType || isParameter2 && !isSymbolAssigned(localOrExportSymbol)))flowContainer = getControlFlowContainer(flowContainer); + const assumeInitialized = isParameter2 || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 16387 /* Void */ ) !== 0 || isInTypeQuery(node) || isInAmbientOrTypeNode(node) || node.parent.kind === 281 /* ExportSpecifier */ ) || node.parent.kind === 235 /* NonNullExpression */ || declaration.kind === 260 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 33554432 /* Ambient */ ; + const initialType = isAutomaticTypeInNonNull ? undefinedType : assumeInitialized ? isParameter2 ? removeOptionalityFromDeclaredType(type, declaration) : type : typeIsAutomatic ? undefinedType : getOptionalType(type); + const flowType = isAutomaticTypeInNonNull ? getNonNullableType(getFlowTypeOfReference(node, type, initialType, flowContainer)) : getFlowTypeOfReference(node, type, initialType, flowContainer); if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(getNameOfDeclaration(declaration), Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); - error(node, Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + error2(getNameOfDeclaration(declaration), Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error2(node, Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); } } else if (!assumeInitialized && !containsUndefinedType(type) && containsUndefinedType(flowType)) { - error(node, Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + error2(node, Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); return type; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; @@ -60111,12 +60686,12 @@ ${lanes.join("\n")} } } function shouldMarkIdentifierAliasReferenced(node) { - var _a2; + var _a; const parent2 = node.parent; if (parent2) { if (isPropertyAccessExpression(parent2) && parent2.expression === node) return false; if (isExportSpecifier(parent2) && parent2.isTypeOnly) return false; - const greatGrandparent = (_a2 = parent2.parent) == null ? void 0 : _a2.parent; + const greatGrandparent = (_a = parent2.parent) == null ? void 0 : _a.parent; if (greatGrandparent && isExportDeclaration(greatGrandparent) && greatGrandparent.isTypeOnly) return false; } return true; @@ -60131,7 +60706,7 @@ ${lanes.join("\n")} return findAncestor(node, (n)=>!n || nodeStartsNewLexicalEnvironment(n) ? "quit" : isIterationStatement(n, /*lookInLabeledStatements*/ false)); } function checkNestedBlockScopedBinding(node, symbol) { - if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & 34 /* Class */ ) === 0 || !symbol.valueDeclaration || isSourceFile(symbol.valueDeclaration) || symbol.valueDeclaration.parent.kind === 295 /* CatchClause */ ) return; + if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & 34 /* Class */ ) === 0 || !symbol.valueDeclaration || isSourceFile(symbol.valueDeclaration) || symbol.valueDeclaration.parent.kind === 299 /* CatchClause */ ) return; const container = getEnclosingBlockScopeContainer(symbol.valueDeclaration); const isCaptured = isInsideFunctionOrInstancePropertyInitializer(node, container); const enclosingIterationStatement = getEnclosingIterationStatement(container); @@ -60139,7 +60714,7 @@ ${lanes.join("\n")} if (isCaptured) { let capturesBlockScopeBindingInLoopBody = true; if (isForStatement(container)) { - const varDeclList = getAncestor(symbol.valueDeclaration, 258 /* VariableDeclarationList */ ); + const varDeclList = getAncestor(symbol.valueDeclaration, 261 /* VariableDeclarationList */ ); if (varDeclList && varDeclList.parent === container) { const part = getPartOfForStatementContainingNode(node.parent, container); if (part) { @@ -60154,8 +60729,8 @@ ${lanes.join("\n")} if (capturesBlockScopeBindingInLoopBody) getNodeLinks(enclosingIterationStatement).flags |= 4096 /* LoopWithCapturedBlockScopedBinding */ ; } if (isForStatement(container)) { - const varDeclList = getAncestor(symbol.valueDeclaration, 258 /* VariableDeclarationList */ ); - if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* NeedsLoopOutParameter */ ; + const varDeclList = getAncestor(symbol.valueDeclaration, 261 /* VariableDeclarationList */ ); + if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) getNodeLinks(symbol.valueDeclaration).flags |= 65536 /* NeedsLoopOutParameter */ ; } getNodeLinks(symbol.valueDeclaration).flags |= 32768 /* BlockScopedBindingInLoop */ ; } @@ -60167,19 +60742,19 @@ ${lanes.join("\n")} } function isAssignedInBodyOfForStatement(node, container) { let current = node; - while(current.parent.kind === 214 /* ParenthesizedExpression */ )current = current.parent; + while(current.parent.kind === 217 /* ParenthesizedExpression */ )current = current.parent; let isAssigned = false; if (isAssignmentTarget(current)) isAssigned = true; - else if (current.parent.kind === 221 /* PrefixUnaryExpression */ || current.parent.kind === 222 /* PostfixUnaryExpression */ ) { + else if (current.parent.kind === 224 /* PrefixUnaryExpression */ || current.parent.kind === 225 /* PostfixUnaryExpression */ ) { const expr = current.parent; - isAssigned = expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */ ; + isAssigned = expr.operator === 46 /* PlusPlusToken */ || expr.operator === 47 /* MinusMinusToken */ ; } if (!isAssigned) return false; return !!findAncestor(current, (n)=>n === container ? "quit" : n === container.statement); } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2 /* LexicalThis */ ; - if (container.kind === 169 /* PropertyDeclaration */ || container.kind === 173 /* Constructor */ ) { + if (container.kind === 172 /* PropertyDeclaration */ || container.kind === 176 /* Constructor */ ) { const classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* CaptureThis */ ; } else getNodeLinks(container).flags |= 4 /* CaptureThis */ ; @@ -60197,24 +60772,24 @@ ${lanes.join("\n")} const containingClassDecl = container.parent; const baseTypeNode = getClassExtendsHeritageElement(containingClassDecl); if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { - if (canHaveFlowNode(node) && node.flowNode && !isPostSuperFlowNode(node.flowNode, /*noCacheCheck*/ false)) error(node, diagnosticMessage); + if (canHaveFlowNode(node) && node.flowNode && !isPostSuperFlowNode(node.flowNode, /*noCacheCheck*/ false)) error2(node, diagnosticMessage); } } function checkThisInStaticClassFieldInitializerInDecoratedClass(thisExpression, container) { - if (isPropertyDeclaration(container) && hasStaticModifier(container) && legacyDecorators && container.initializer && textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && hasDecorators(container.parent)) error(thisExpression, Diagnostics.Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class); + if (isPropertyDeclaration(container) && hasStaticModifier(container) && legacyDecorators && container.initializer && textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && hasDecorators(container.parent)) error2(thisExpression, Diagnostics.Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class); } function checkThisExpression(node) { const isNodeInTypeQuery = isInTypeQuery(node); - let container = getThisContainer(node, /* includeArrowFunctions */ true, /*includeClassComputedPropertyName*/ true); + let container = getThisContainer(node, /*includeArrowFunctions*/ true, /*includeClassComputedPropertyName*/ true); let capturedByArrowFunction = false; let thisInComputedPropertyName = false; - if (container.kind === 173 /* Constructor */ ) checkThisBeforeSuper(node, container, Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); + if (container.kind === 176 /* Constructor */ ) checkThisBeforeSuper(node, container, Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); while(true){ - if (container.kind === 216 /* ArrowFunction */ ) { - container = getThisContainer(container, /* includeArrowFunctions */ false, !thisInComputedPropertyName); + if (container.kind === 219 /* ArrowFunction */ ) { + container = getThisContainer(container, /*includeArrowFunctions*/ false, !thisInComputedPropertyName); capturedByArrowFunction = true; } - if (container.kind === 164 /* ComputedPropertyName */ ) { + if (container.kind === 167 /* ComputedPropertyName */ ) { container = getThisContainer(container, !capturedByArrowFunction, /*includeClassComputedPropertyName*/ false); thisInComputedPropertyName = true; continue; @@ -60222,25 +60797,25 @@ ${lanes.join("\n")} break; } checkThisInStaticClassFieldInitializerInDecoratedClass(node, container); - if (thisInComputedPropertyName) error(node, Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); + if (thisInComputedPropertyName) error2(node, Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); else switch(container.kind){ - case 264 /* ModuleDeclaration */ : - error(node, Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); + case 267 /* ModuleDeclaration */ : + error2(node, Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); break; - case 263 /* EnumDeclaration */ : - error(node, Diagnostics.this_cannot_be_referenced_in_current_location); + case 266 /* EnumDeclaration */ : + error2(node, Diagnostics.this_cannot_be_referenced_in_current_location); break; - case 173 /* Constructor */ : - if (isInConstructorArgumentInitializer(node, container)) error(node, Diagnostics.this_cannot_be_referenced_in_constructor_arguments); + case 176 /* Constructor */ : + if (isInConstructorArgumentInitializer(node, container)) error2(node, Diagnostics.this_cannot_be_referenced_in_constructor_arguments); break; } if (!isNodeInTypeQuery && capturedByArrowFunction && languageVersion < 2 /* ES2015 */ ) captureLexicalThis(node, container); const type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container); if (noImplicitThis) { const globalThisType2 = getTypeOfSymbol(globalThisSymbol); - if (type === globalThisType2 && capturedByArrowFunction) error(node, Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this); + if (type === globalThisType2 && capturedByArrowFunction) error2(node, Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this); else if (!type) { - const diag2 = error(node, Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + const diag2 = error2(node, Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); if (!isSourceFile(container)) { const outsideThis = tryGetThisTypeAt(container); if (outsideThis && outsideThis !== globalThisType2) addRelatedInfo(diag2, createDiagnosticForNode(container, Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container)); @@ -60288,32 +60863,29 @@ ${lanes.join("\n")} } } function getClassNameFromPrototypeMethod(container) { - if (container.kind === 215 /* FunctionExpression */ && isBinaryExpression(container.parent) && getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */ ) return container.parent.left.expression.expression; - else if (container.kind === 171 /* MethodDeclaration */ && container.parent.kind === 207 /* ObjectLiteralExpression */ && isBinaryExpression(container.parent.parent) && getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */ ) return container.parent.parent.left.expression; - else if (container.kind === 215 /* FunctionExpression */ && container.parent.kind === 299 /* PropertyAssignment */ && container.parent.parent.kind === 207 /* ObjectLiteralExpression */ && isBinaryExpression(container.parent.parent.parent) && getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */ ) return container.parent.parent.parent.left.expression; - else if (container.kind === 215 /* FunctionExpression */ && isPropertyAssignment(container.parent) && isIdentifier(container.parent.name) && (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && isObjectLiteralExpression(container.parent.parent) && isCallExpression(container.parent.parent.parent) && container.parent.parent.parent.arguments[2] === container.parent.parent && getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */ ) return container.parent.parent.parent.arguments[0].expression; + if (container.kind === 218 /* FunctionExpression */ && isBinaryExpression(container.parent) && getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */ ) return container.parent.left.expression.expression; + else if (container.kind === 174 /* MethodDeclaration */ && container.parent.kind === 210 /* ObjectLiteralExpression */ && isBinaryExpression(container.parent.parent) && getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */ ) return container.parent.parent.left.expression; + else if (container.kind === 218 /* FunctionExpression */ && container.parent.kind === 303 /* PropertyAssignment */ && container.parent.parent.kind === 210 /* ObjectLiteralExpression */ && isBinaryExpression(container.parent.parent.parent) && getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */ ) return container.parent.parent.parent.left.expression; + else if (container.kind === 218 /* FunctionExpression */ && isPropertyAssignment(container.parent) && isIdentifier(container.parent.name) && (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && isObjectLiteralExpression(container.parent.parent) && isCallExpression(container.parent.parent.parent) && container.parent.parent.parent.arguments[2] === container.parent.parent && getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */ ) return container.parent.parent.parent.arguments[0].expression; else if (isMethodDeclaration(container) && isIdentifier(container.name) && (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") && isObjectLiteralExpression(container.parent) && isCallExpression(container.parent.parent) && container.parent.parent.arguments[2] === container.parent && getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */ ) return container.parent.parent.arguments[0].expression; } function getTypeForThisExpressionFromJSDoc(node) { - const jsdocType = getJSDocType(node); - if (jsdocType && jsdocType.kind === 320 /* JSDocFunctionType */ ) { - const jsDocFunctionType = jsdocType; - if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */ ) return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); - } const thisTag = getJSDocThisTag(node); if (thisTag && thisTag.typeExpression) return getTypeFromTypeNode(thisTag.typeExpression); + const signature = getSignatureOfTypeTag(node); + if (signature) return getThisTypeOfSignature(signature); } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!findAncestor(node, (n)=>isFunctionLikeDeclaration(n) ? "quit" : n.kind === 166 /* Parameter */ && n.parent === constructorDecl); + return !!findAncestor(node, (n)=>isFunctionLikeDeclaration(n) ? "quit" : n.kind === 169 /* Parameter */ && n.parent === constructorDecl); } function checkSuperExpression(node) { - const isCallExpression2 = node.parent.kind === 210 /* CallExpression */ && node.parent.expression === node; + const isCallExpression2 = node.parent.kind === 213 /* CallExpression */ && node.parent.expression === node; const immediateContainer = getSuperContainer(node, /*stopOnFunctions*/ true); let container = immediateContainer; let needToCaptureLexicalThis = false; let inAsyncFunction = false; if (!isCallExpression2) { - while(container && container.kind === 216 /* ArrowFunction */ ){ + while(container && container.kind === 219 /* ArrowFunction */ ){ if (hasSyntacticModifier(container, 512 /* Async */ )) inAsyncFunction = true; container = getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */ ; @@ -60322,56 +60894,56 @@ ${lanes.join("\n")} } let nodeCheckFlag = 0; if (!container || !isLegalUsageOfSuperExpression(container)) { - const current = findAncestor(node, (n)=>n === container ? "quit" : n.kind === 164 /* ComputedPropertyName */ ); - if (current && current.kind === 164 /* ComputedPropertyName */ ) error(node, Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); - else if (isCallExpression2) error(node, Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); - else if (!container || !container.parent || !(isClassLike(container.parent) || container.parent.kind === 207 /* ObjectLiteralExpression */ )) error(node, Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); - else error(node, Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); + const current = findAncestor(node, (n)=>n === container ? "quit" : n.kind === 167 /* ComputedPropertyName */ ); + if (current && current.kind === 167 /* ComputedPropertyName */ ) error2(node, Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); + else if (isCallExpression2) error2(node, Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); + else if (!container || !container.parent || !(isClassLike(container.parent) || container.parent.kind === 210 /* ObjectLiteralExpression */ )) error2(node, Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + else error2(node, Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); return errorType; } - if (!isCallExpression2 && immediateContainer.kind === 173 /* Constructor */ ) checkThisBeforeSuper(node, container, Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + if (!isCallExpression2 && immediateContainer.kind === 176 /* Constructor */ ) checkThisBeforeSuper(node, container, Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); if (isStatic(container) || isCallExpression2) { nodeCheckFlag = 32 /* SuperStatic */ ; if (!isCallExpression2 && languageVersion >= 2 /* ES2015 */ && languageVersion <= 8 /* ES2021 */ && (isPropertyDeclaration(container) || isClassStaticBlockDeclaration(container))) forEachEnclosingBlockScopeContainer(node.parent, (current)=>{ - if (!isSourceFile(current) || isExternalOrCommonJsModule(current)) getNodeLinks(current).flags |= 8388608 /* ContainsSuperPropertyInStaticInitializer */ ; + if (!isSourceFile(current) || isExternalOrCommonJsModule(current)) getNodeLinks(current).flags |= 2097152 /* ContainsSuperPropertyInStaticInitializer */ ; }); } else nodeCheckFlag = 16 /* SuperInstance */ ; getNodeLinks(node).flags |= nodeCheckFlag; - if (container.kind === 171 /* MethodDeclaration */ && inAsyncFunction) { + if (container.kind === 174 /* MethodDeclaration */ && inAsyncFunction) { if (isSuperProperty(node.parent) && isAssignmentTarget(node.parent)) getNodeLinks(container).flags |= 256 /* MethodWithSuperPropertyAssignmentInAsync */ ; else getNodeLinks(container).flags |= 128 /* MethodWithSuperPropertyAccessInAsync */ ; } if (needToCaptureLexicalThis) captureLexicalThis(node.parent, container); - if (container.parent.kind === 207 /* ObjectLiteralExpression */ ) { + if (container.parent.kind === 210 /* ObjectLiteralExpression */ ) { if (languageVersion < 2 /* ES2015 */ ) { - error(node, Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + error2(node, Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return errorType; } else return anyType; } const classLikeDeclaration = container.parent; if (!getClassExtendsHeritageElement(classLikeDeclaration)) { - error(node, Diagnostics.super_can_only_be_referenced_in_a_derived_class); + error2(node, Diagnostics.super_can_only_be_referenced_in_a_derived_class); return errorType; } const classType = getDeclaredTypeOfSymbol(getSymbolOfDeclaration(classLikeDeclaration)); const baseClassType = classType && getBaseTypes(classType)[0]; if (!baseClassType) return errorType; - if (container.kind === 173 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { - error(node, Diagnostics.super_cannot_be_referenced_in_constructor_arguments); + if (container.kind === 176 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + error2(node, Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return errorType; } return nodeCheckFlag === 32 /* SuperStatic */ ? getBaseConstructorTypeOfClass(classType) : getTypeWithThisArgument(baseClassType, classType.thisType); function isLegalUsageOfSuperExpression(container2) { - if (isCallExpression2) return container2.kind === 173 /* Constructor */ ; - else if (isClassLike(container2.parent) || container2.parent.kind === 207 /* ObjectLiteralExpression */ ) { - if (isStatic(container2)) return container2.kind === 171 /* MethodDeclaration */ || container2.kind === 170 /* MethodSignature */ || container2.kind === 174 /* GetAccessor */ || container2.kind === 175 /* SetAccessor */ || container2.kind === 169 /* PropertyDeclaration */ || container2.kind === 172 /* ClassStaticBlockDeclaration */ ; - else return container2.kind === 171 /* MethodDeclaration */ || container2.kind === 170 /* MethodSignature */ || container2.kind === 174 /* GetAccessor */ || container2.kind === 175 /* SetAccessor */ || container2.kind === 169 /* PropertyDeclaration */ || container2.kind === 168 /* PropertySignature */ || container2.kind === 173 /* Constructor */ ; + if (isCallExpression2) return container2.kind === 176 /* Constructor */ ; + else if (isClassLike(container2.parent) || container2.parent.kind === 210 /* ObjectLiteralExpression */ ) { + if (isStatic(container2)) return container2.kind === 174 /* MethodDeclaration */ || container2.kind === 173 /* MethodSignature */ || container2.kind === 177 /* GetAccessor */ || container2.kind === 178 /* SetAccessor */ || container2.kind === 172 /* PropertyDeclaration */ || container2.kind === 175 /* ClassStaticBlockDeclaration */ ; + else return container2.kind === 174 /* MethodDeclaration */ || container2.kind === 173 /* MethodSignature */ || container2.kind === 177 /* GetAccessor */ || container2.kind === 178 /* SetAccessor */ || container2.kind === 172 /* PropertyDeclaration */ || container2.kind === 171 /* PropertySignature */ || container2.kind === 176 /* Constructor */ ; } return false; } } function getContainingObjectLiteral(func) { - return (func.kind === 171 /* MethodDeclaration */ || func.kind === 174 /* GetAccessor */ || func.kind === 175 /* SetAccessor */ ) && func.parent.kind === 207 /* ObjectLiteralExpression */ ? func.parent : func.kind === 215 /* FunctionExpression */ && func.parent.kind === 299 /* PropertyAssignment */ ? func.parent.parent : void 0; + return (func.kind === 174 /* MethodDeclaration */ || func.kind === 177 /* GetAccessor */ || func.kind === 178 /* SetAccessor */ ) && func.parent.kind === 210 /* ObjectLiteralExpression */ ? func.parent : func.kind === 218 /* FunctionExpression */ && func.parent.kind === 303 /* PropertyAssignment */ ? func.parent.parent : void 0; } function getThisTypeArgument(type) { return getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? getTypeArguments(type)[0] : void 0; @@ -60381,8 +60953,19 @@ ${lanes.join("\n")} return t.flags & 2097152 /* Intersection */ ? forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); }); } + function getThisTypeOfObjectLiteralFromContextualType(containingLiteral, contextualType) { + let literal = containingLiteral; + let type = contextualType; + while(type){ + const thisType = getThisTypeFromContextualType(type); + if (thisType) return thisType; + if (literal.parent.kind !== 303 /* PropertyAssignment */ ) break; + literal = literal.parent.parent; + type = getApparentTypeOfContextualType(literal, /*contextFlags*/ void 0); + } + } function getContextualThisParameterType(func) { - if (func.kind === 216 /* ArrowFunction */ ) return void 0; + if (func.kind === 219 /* ArrowFunction */ ) return void 0; if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { const contextualSignature = getContextualSignature(func); if (contextualSignature) { @@ -60395,22 +60978,15 @@ ${lanes.join("\n")} const containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { const contextualType = getApparentTypeOfContextualType(containingLiteral, /*contextFlags*/ void 0); - let literal = containingLiteral; - let type = contextualType; - while(type){ - const thisType = getThisTypeFromContextualType(type); - if (thisType) return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral))); - if (literal.parent.kind !== 299 /* PropertyAssignment */ ) break; - literal = literal.parent.parent; - type = getApparentTypeOfContextualType(literal, /*contextFlags*/ void 0); - } + const thisType = getThisTypeOfObjectLiteralFromContextualType(containingLiteral, contextualType); + if (thisType) return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral))); return getWidenedType(contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral)); } const parent2 = walkUpParenthesizedExpressions(func.parent); - if (parent2.kind === 223 /* BinaryExpression */ && parent2.operatorToken.kind === 63 /* EqualsToken */ ) { + if (parent2.kind === 226 /* BinaryExpression */ && parent2.operatorToken.kind === 64 /* EqualsToken */ ) { const target = parent2.left; if (isAccessExpression(target)) { - const { expression: expression } = target; + const { expression: expression } = target; if (inJs && isIdentifier(expression)) { const sourceFile = getSourceFileOfNode(parent2); if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) return void 0; @@ -60446,20 +61022,20 @@ ${lanes.join("\n")} const typeNode = getEffectiveTypeAnnotationNode(declaration) || (isInJSFile(declaration) ? tryGetJSDocSatisfiesTypeNode(declaration) : void 0); if (typeNode) return getTypeFromTypeNode(typeNode); switch(declaration.kind){ - case 166 /* Parameter */ : + case 169 /* Parameter */ : return getContextuallyTypedParameterType(declaration); - case 205 /* BindingElement */ : + case 208 /* BindingElement */ : return getContextualTypeForBindingElement(declaration, contextFlags); - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : if (isStatic(declaration)) return getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags); } } function getContextualTypeForBindingElement(declaration, contextFlags) { const parent2 = declaration.parent.parent; const name = declaration.propertyName || declaration.name; - const parentType = getContextualTypeForVariableLikeDeclaration(parent2, contextFlags) || parent2.kind !== 205 /* BindingElement */ && parent2.initializer && checkDeclarationInitializer(parent2, declaration.dotDotDotToken ? 64 /* RestBindingElement */ : 0 /* Normal */ ); + const parentType = getContextualTypeForVariableLikeDeclaration(parent2, contextFlags) || parent2.kind !== 208 /* BindingElement */ && parent2.initializer && checkDeclarationInitializer(parent2, declaration.dotDotDotToken ? 64 /* RestBindingElement */ : 0 /* Normal */ ); if (!parentType || isBindingPattern(name) || isComputedNonLiteralName(name)) return void 0; - if (parent2.name.kind === 204 /* ArrayBindingPattern */ ) { + if (parent2.name.kind === 207 /* ArrayBindingPattern */ ) { const index = indexOfNode(declaration.parent.elements, declaration); if (index < 0) return void 0; return getContextualTypeForElementExpression(parentType, index); @@ -60574,24 +61150,24 @@ ${lanes.join("\n")} return signature ? getOrCreateTypeFromSignature(signature) : void 0; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 212 /* TaggedTemplateExpression */ ) return getContextualTypeForArgument(template.parent, substitutionExpression); + if (template.parent.kind === 215 /* TaggedTemplateExpression */ ) return getContextualTypeForArgument(template.parent, substitutionExpression); return void 0; } function getContextualTypeForBinaryOperand(node, contextFlags) { const binaryExpression = node.parent; - const { left: left , operatorToken: operatorToken , right: right } = binaryExpression; + const { left: left, operatorToken: operatorToken, right: right } = binaryExpression; switch(operatorToken.kind){ - case 63 /* EqualsToken */ : - case 76 /* AmpersandAmpersandEqualsToken */ : - case 75 /* BarBarEqualsToken */ : - case 77 /* QuestionQuestionEqualsToken */ : + case 64 /* EqualsToken */ : + case 77 /* AmpersandAmpersandEqualsToken */ : + case 76 /* BarBarEqualsToken */ : + case 78 /* QuestionQuestionEqualsToken */ : return node === right ? getContextualTypeForAssignmentDeclaration(binaryExpression) : void 0; - case 56 /* BarBarToken */ : - case 60 /* QuestionQuestionToken */ : + case 57 /* BarBarToken */ : + case 61 /* QuestionQuestionToken */ : const type = getContextualType2(binaryExpression, contextFlags); return node === right && (type && type.pattern || !type && !isDefaultedExpandoInitializer(binaryExpression)) ? getTypeOfExpression(left) : type; - case 55 /* AmpersandAmpersandToken */ : - case 27 /* CommaToken */ : + case 56 /* AmpersandAmpersandToken */ : + case 28 /* CommaToken */ : return node === right ? getContextualType2(binaryExpression, contextFlags) : void 0; default: return void 0; @@ -60617,7 +61193,7 @@ ${lanes.join("\n")} } } function getContextualTypeForAssignmentDeclaration(binaryExpression) { - var _a2, _b; + var _a, _b; const kind = getAssignmentDeclarationKind(binaryExpression); switch(kind){ case 0 /* None */ : @@ -60641,7 +61217,7 @@ ${lanes.join("\n")} if (overallAnnotation) return getTypeFromTypeNode(overallAnnotation); else if (isIdentifier(lhs.expression)) { const id = lhs.expression; - const parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */ , void 0, id.escapedText, /*isUse*/ true); + const parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */ , /*nameNotFoundMessage*/ void 0, id.escapedText, /*isUse*/ true); if (parentSymbol) { const annotated2 = parentSymbol.valueDeclaration && getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); if (annotated2) { @@ -60651,14 +61227,14 @@ ${lanes.join("\n")} return void 0; } } - return isInJSFile(decl2) ? void 0 : getTypeOfExpression(binaryExpression.left); + return isInJSFile(decl2) || decl2 === binaryExpression.left ? void 0 : getTypeOfExpression(binaryExpression.left); } case 1 /* ExportsProperty */ : case 6 /* Prototype */ : case 3 /* PrototypeProperty */ : case 2 /* ModuleExports */ : let valueDeclaration; - if (kind !== 2 /* ModuleExports */ ) valueDeclaration = canHaveSymbol(binaryExpression.left) ? (_a2 = binaryExpression.left.symbol) == null ? void 0 : _a2.valueDeclaration : void 0; + if (kind !== 2 /* ModuleExports */ ) valueDeclaration = canHaveSymbol(binaryExpression.left) ? (_a = binaryExpression.left.symbol) == null ? void 0 : _a.valueDeclaration : void 0; valueDeclaration || (valueDeclaration = (_b = binaryExpression.symbol) == null ? void 0 : _b.valueDeclaration); const annotated = valueDeclaration && getEffectiveTypeAnnotationNode(valueDeclaration); return annotated ? getTypeFromTypeNode(annotated) : void 0; @@ -60674,7 +61250,7 @@ ${lanes.join("\n")} if (kind === 4 /* ThisProperty */ ) return true; if (!isInJSFile(declaration) || kind !== 5 /* Property */ || !isIdentifier(declaration.left.expression)) return false; const name = declaration.left.expression.escapedText; - const symbol = resolveName(declaration.left, name, 111551 /* Value */ , void 0, void 0, /*isUse*/ true, /*excludeGlobals*/ true); + const symbol = resolveName(declaration.left, name, 111551 /* Value */ , /*nameNotFoundMessage*/ void 0, /*nameArg*/ void 0, /*isUse*/ true, /*excludeGlobals*/ true); return isThisInitializedDeclaration(symbol == null ? void 0 : symbol.valueDeclaration); } function getContextualTypeForThisPropertyAssignment(binaryExpression) { @@ -60697,7 +61273,7 @@ ${lanes.join("\n")} } function getTypeOfPropertyOfContextualType(type, name, nameType) { return mapType(type, (t)=>{ - var _a2; + var _a; if (isGenericMappedType(t) && !t.declaration.nameType) { const constraint = getConstraintTypeFromMappedType(t); const constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint; @@ -60710,14 +61286,14 @@ ${lanes.join("\n")} const restType = getElementTypeOfSliceOfTupleType(t, t.target.fixedLength, /*endSkipCount*/ 0, /*writing*/ false, /*noReductions*/ true); if (restType) return restType; } - return (_a2 = findApplicableIndexInfo(getIndexInfosOfStructuredType(t), nameType || getStringLiteralType(unescapeLeadingUnderscores(name)))) == null ? void 0 : _a2.type; + return (_a = findApplicableIndexInfo(getIndexInfosOfStructuredType(t), nameType || getStringLiteralType(unescapeLeadingUnderscores(name)))) == null ? void 0 : _a.type; } return void 0; }, /*noReductions*/ true); } function getContextualTypeForObjectLiteralMethod(node, contextFlags) { Debug.assert(isObjectLiteralMethod(node)); - if (node.flags & 33554432 /* InWithStatement */ ) return void 0; + if (node.flags & 67108864 /* InWithStatement */ ) return void 0; return getContextualTypeForObjectLiteralElement(node, contextFlags); } function getContextualTypeForObjectLiteralElement(element, contextFlags) { @@ -60730,25 +61306,53 @@ ${lanes.join("\n")} const symbol = getSymbolOfDeclaration(element); return getTypeOfPropertyOfContextualType(type, symbol.escapedName, getSymbolLinks(symbol).nameType); } + if (hasDynamicName(element)) { + const name = getNameOfDeclaration(element); + if (name && isComputedPropertyName(name)) { + const exprType = checkExpression(name.expression); + const propType = isTypeUsableAsPropertyName(exprType) && getTypeOfPropertyOfContextualType(type, getPropertyNameFromType(exprType)); + if (propType) return propType; + } + } if (element.name) { const nameType = getLiteralTypeFromPropertyName(element.name); return mapType(type, (t)=>{ - var _a2; - return (_a2 = findApplicableIndexInfo(getIndexInfosOfStructuredType(t), nameType)) == null ? void 0 : _a2.type; + var _a; + return (_a = findApplicableIndexInfo(getIndexInfosOfStructuredType(t), nameType)) == null ? void 0 : _a.type; }, /*noReductions*/ true); } } return void 0; } - function getContextualTypeForElementExpression(arrayContextualType, index) { - return arrayContextualType && (index >= 0 && getTypeOfPropertyOfContextualType(arrayContextualType, "" + index) || mapType(arrayContextualType, (t)=>isTupleType(t) ? getElementTypeOfSliceOfTupleType(t, 0, /*endSkipCount*/ 0, /*writing*/ false, /*noReductions*/ true) : getIteratedTypeOrElementType(1 /* Element */ , t, undefinedType, /*errorNode*/ void 0, /*checkAssignability*/ false), /*noReductions*/ true)); + function getSpreadIndices(elements) { + let first2, last2; + for(let i = 0; i < elements.length; i++)if (isSpreadElement(elements[i])) { + first2 ?? (first2 = i); + last2 = i; + } + return { + first: first2, + last: last2 + }; + } + function getContextualTypeForElementExpression(type, index, length2, firstSpreadIndex, lastSpreadIndex) { + return type && mapType(type, (t)=>{ + if (isTupleType(t)) { + if ((firstSpreadIndex === void 0 || index < firstSpreadIndex) && index < t.target.fixedLength) return getTypeArguments(t)[index]; + const offset = length2 !== void 0 && (lastSpreadIndex === void 0 || index > lastSpreadIndex) ? length2 - index : 0; + const fixedEndLength = offset > 0 && t.target.hasRestElement ? getEndElementCount(t.target, 3 /* Fixed */ ) : 0; + if (offset > 0 && offset <= fixedEndLength) return getTypeArguments(t)[getTypeReferenceArity(t) - offset]; + return getElementTypeOfSliceOfTupleType(t, firstSpreadIndex === void 0 ? t.target.fixedLength : Math.min(t.target.fixedLength, firstSpreadIndex), length2 === void 0 || lastSpreadIndex === void 0 ? fixedEndLength : Math.min(fixedEndLength, length2 - lastSpreadIndex), /*writing*/ false, /*noReductions*/ true); + } + return (!firstSpreadIndex || index < firstSpreadIndex) && getTypeOfPropertyOfContextualType(t, "" + index) || getIteratedTypeOrElementType(1 /* Element */ , t, undefinedType, /*errorNode*/ void 0, /*checkAssignability*/ false); + }, /*noReductions*/ true); } function getContextualTypeForConditionalOperand(node, contextFlags) { const conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType2(conditional, contextFlags) : void 0; } function getContextualTypeForChildJsxExpression(node, child, contextFlags) { - const attributesType = getApparentTypeOfContextualType(node.openingElement.tagName, contextFlags); + const attributesType = getApparentTypeOfContextualType(node.openingElement.attributes, contextFlags); const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) return void 0; const realChildren = getSemanticJsxChildren(node.children); @@ -60767,58 +61371,67 @@ ${lanes.join("\n")} if (isJsxAttribute(attribute)) { const attributesType = getApparentTypeOfContextualType(attribute.parent, contextFlags); if (!attributesType || isTypeAny(attributesType)) return void 0; - return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); + return getTypeOfPropertyOfContextualType(attributesType, getEscapedTextOfJsxAttributeName(attribute.name)); } else return getContextualType2(attribute.parent, contextFlags); } function isPossiblyDiscriminantValue(node) { switch(node.kind){ - case 10 /* StringLiteral */ : - case 8 /* NumericLiteral */ : - case 9 /* BigIntLiteral */ : - case 14 /* NoSubstitutionTemplateLiteral */ : - case 110 /* TrueKeyword */ : - case 95 /* FalseKeyword */ : - case 104 /* NullKeyword */ : - case 79 /* Identifier */ : - case 155 /* UndefinedKeyword */ : + case 11 /* StringLiteral */ : + case 9 /* NumericLiteral */ : + case 10 /* BigIntLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + case 228 /* TemplateExpression */ : + case 112 /* TrueKeyword */ : + case 97 /* FalseKeyword */ : + case 106 /* NullKeyword */ : + case 80 /* Identifier */ : + case 157 /* UndefinedKeyword */ : return true; - case 208 /* PropertyAccessExpression */ : - case 214 /* ParenthesizedExpression */ : + case 211 /* PropertyAccessExpression */ : + case 217 /* ParenthesizedExpression */ : return isPossiblyDiscriminantValue(node.expression); - case 291 /* JsxExpression */ : + case 294 /* JsxExpression */ : return !node.expression || isPossiblyDiscriminantValue(node.expression); } return false; } function discriminateContextualTypeByObjectMembers(node, contextualType) { - return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, concatenate(map(filter(node.properties, (p)=>!!p.symbol && p.kind === 299 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName)), (prop)=>[ + return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, concatenate(map(filter(node.properties, (p)=>!!p.symbol && p.kind === 303 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName)), (prop)=>[ ()=>getContextFreeTypeOfExpression(prop.initializer), prop.symbol.escapedName ]), map(filter(getPropertiesOfType(contextualType), (s)=>{ - var _a2; - return !!(s.flags & 16777216 /* Optional */ ) && !!((_a2 = node == null ? void 0 : node.symbol) == null ? void 0 : _a2.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); + var _a; + return !!(s.flags & 16777216 /* Optional */ ) && !!((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), (s)=>[ ()=>undefinedType, s.escapedName - ])), isTypeAssignableTo, contextualType); + ])), isTypeAssignableTo); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { - return discriminateTypeByDiscriminableItems(contextualType, concatenate(map(filter(node.properties, (p)=>!!p.symbol && p.kind === 288 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer))), (prop)=>[ + const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + return discriminateTypeByDiscriminableItems(contextualType, concatenate(map(filter(node.properties, (p)=>!!p.symbol && p.kind === 291 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer))), (prop)=>[ !prop.initializer ? ()=>trueType : ()=>getContextFreeTypeOfExpression(prop.initializer), prop.symbol.escapedName ]), map(filter(getPropertiesOfType(contextualType), (s)=>{ - var _a2; - return !!(s.flags & 16777216 /* Optional */ ) && !!((_a2 = node == null ? void 0 : node.symbol) == null ? void 0 : _a2.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); + var _a; + if (!(s.flags & 16777216 /* Optional */ ) || !((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.members)) return false; + const element = node.parent.parent; + if (s.escapedName === jsxChildrenPropertyName && isJsxElement(element) && getSemanticJsxChildren(element.children).length) return false; + return !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), (s)=>[ ()=>undefinedType, s.escapedName - ])), isTypeAssignableTo, contextualType); + ])), isTypeAssignableTo); } function getApparentTypeOfContextualType(node, contextFlags) { const contextualType = isObjectLiteralMethod(node) ? getContextualTypeForObjectLiteralMethod(node, contextFlags) : getContextualType2(node, contextFlags); const instantiatedType = instantiateContextualType(contextualType, node, contextFlags); if (instantiatedType && !(contextFlags && contextFlags & 2 /* NoConstraints */ && instantiatedType.flags & 8650752 /* TypeVariable */ )) { - const apparentType = mapType(instantiatedType, getApparentType, /*noReductions*/ true); + const apparentType = mapType(instantiatedType, // When obtaining apparent type of *contextual* type we don't want to get apparent type of mapped types. + // That would evaluate mapped types with array or tuple type constraints too eagerly + // and thus it would prevent `getTypeOfPropertyOfContextualType` from obtaining per-position contextual type for elements of array literal expressions. + // Apparent type of other mapped types is already the mapped type itself so we can just avoid calling `getApparentType` here for all mapped types. + (t)=>getObjectFlags(t) & 32 /* Mapped */ ? t : getApparentType(t), /*noReductions*/ true); return apparentType.flags & 1048576 /* Union */ && isObjectLiteralExpression(node) ? discriminateContextualTypeByObjectMembers(node, apparentType) : apparentType.flags & 1048576 /* Union */ && isJsxAttributes(node) ? discriminateContextualTypeByJSXAttributes(node, apparentType) : apparentType; } } @@ -60840,73 +61453,73 @@ ${lanes.join("\n")} return type; } function getContextualType2(node, contextFlags) { - var _a2, _b; - if (node.flags & 33554432 /* InWithStatement */ ) return void 0; + var _a; + if (node.flags & 67108864 /* InWithStatement */ ) return void 0; const index = findContextualNode(node, /*includeCaches*/ !contextFlags); if (index >= 0) return contextualTypes[index]; - const { parent: parent2 } = node; + const { parent: parent2 } = node; switch(parent2.kind){ - case 257 /* VariableDeclaration */ : - case 166 /* Parameter */ : - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : - case 205 /* BindingElement */ : + case 260 /* VariableDeclaration */ : + case 169 /* Parameter */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : + case 208 /* BindingElement */ : return getContextualTypeForInitializerExpression(node, contextFlags); - case 216 /* ArrowFunction */ : - case 250 /* ReturnStatement */ : + case 219 /* ArrowFunction */ : + case 253 /* ReturnStatement */ : return getContextualTypeForReturnExpression(node, contextFlags); - case 226 /* YieldExpression */ : + case 229 /* YieldExpression */ : return getContextualTypeForYieldOperand(parent2, contextFlags); - case 220 /* AwaitExpression */ : + case 223 /* AwaitExpression */ : return getContextualTypeForAwaitOperand(parent2, contextFlags); - case 210 /* CallExpression */ : - case 211 /* NewExpression */ : + case 213 /* CallExpression */ : + case 214 /* NewExpression */ : return getContextualTypeForArgument(parent2, node); - case 167 /* Decorator */ : + case 170 /* Decorator */ : return getContextualTypeForDecorator(parent2); - case 213 /* TypeAssertionExpression */ : - case 231 /* AsExpression */ : + case 216 /* TypeAssertionExpression */ : + case 234 /* AsExpression */ : return isConstTypeReference(parent2.type) ? getContextualType2(parent2, contextFlags) : getTypeFromTypeNode(parent2.type); - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : return getContextualTypeForBinaryOperand(node, contextFlags); - case 299 /* PropertyAssignment */ : - case 300 /* ShorthandPropertyAssignment */ : + case 303 /* PropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : return getContextualTypeForObjectLiteralElement(parent2, contextFlags); - case 301 /* SpreadAssignment */ : + case 305 /* SpreadAssignment */ : return getContextualType2(parent2.parent, contextFlags); - case 206 /* ArrayLiteralExpression */ : + case 209 /* ArrayLiteralExpression */ : { const arrayLiteral = parent2; const type = getApparentTypeOfContextualType(arrayLiteral, contextFlags); - const spreadIndex = (_b = (_a2 = getNodeLinks(arrayLiteral)).firstSpreadIndex) != null ? _b : _a2.firstSpreadIndex = findIndex(arrayLiteral.elements, isSpreadElement); const elementIndex = indexOfNode(arrayLiteral.elements, node); - return getContextualTypeForElementExpression(type, spreadIndex < 0 || elementIndex < spreadIndex ? elementIndex : -1); + const spreadIndices = (_a = getNodeLinks(arrayLiteral)).spreadIndices ?? (_a.spreadIndices = getSpreadIndices(arrayLiteral.elements)); + return getContextualTypeForElementExpression(type, elementIndex, arrayLiteral.elements.length, spreadIndices.first, spreadIndices.last); } - case 224 /* ConditionalExpression */ : + case 227 /* ConditionalExpression */ : return getContextualTypeForConditionalOperand(node, contextFlags); - case 236 /* TemplateSpan */ : - Debug.assert(parent2.parent.kind === 225 /* TemplateExpression */ ); + case 239 /* TemplateSpan */ : + Debug.assert(parent2.parent.kind === 228 /* TemplateExpression */ ); return getContextualTypeForSubstitutionExpression(parent2.parent, node); - case 214 /* ParenthesizedExpression */ : + case 217 /* ParenthesizedExpression */ : if (isInJSFile(parent2)) { if (isJSDocSatisfiesExpression(parent2)) return getTypeFromTypeNode(getJSDocSatisfiesExpressionType(parent2)); const typeTag = getJSDocTypeTag(parent2); if (typeTag && !isConstTypeReference(typeTag.typeExpression.type)) return getTypeFromTypeNode(typeTag.typeExpression.type); } return getContextualType2(parent2, contextFlags); - case 232 /* NonNullExpression */ : + case 235 /* NonNullExpression */ : return getContextualType2(parent2, contextFlags); - case 235 /* SatisfiesExpression */ : + case 238 /* SatisfiesExpression */ : return getTypeFromTypeNode(parent2.type); - case 274 /* ExportAssignment */ : + case 277 /* ExportAssignment */ : return tryGetTypeFromEffectiveTypeNode(parent2); - case 291 /* JsxExpression */ : + case 294 /* JsxExpression */ : return getContextualTypeForJsxExpression(parent2, contextFlags); - case 288 /* JsxAttribute */ : - case 290 /* JsxSpreadAttribute */ : + case 291 /* JsxAttribute */ : + case 293 /* JsxSpreadAttribute */ : return getContextualTypeForJsxAttribute(parent2, contextFlags); - case 283 /* JsxOpeningElement */ : - case 282 /* JsxSelfClosingElement */ : + case 286 /* JsxOpeningElement */ : + case 285 /* JsxSelfClosingElement */ : return getContextualJsxElementAttributesType(parent2, contextFlags); } return void 0; @@ -60975,7 +61588,7 @@ ${lanes.join("\n")} return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); } function getStaticTypeOfReferencedJsxConstructor(context) { - if (isJsxIntrinsicIdentifier(context.tagName)) { + if (isJsxIntrinsicTagName(context.tagName)) { const result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context); const fakeSignature = createSignatureForJSXIntrinsic(context, result); return getOrCreateTypeFromSignature(fakeSignature); @@ -60992,25 +61605,9 @@ ${lanes.join("\n")} function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { const managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { - const declaredManagedType = getDeclaredTypeOfSymbol(managedSym); const ctorType = getStaticTypeOfReferencedJsxConstructor(context); - if (managedSym.flags & 524288 /* TypeAlias */ ) { - const params = getSymbolLinks(managedSym).typeParameters; - if (length(params) >= 2) { - const args = fillMissingTypeArguments([ - ctorType, - attributesType - ], params, 2, isInJSFile(context)); - return getTypeAliasInstantiation(managedSym, args); - } - } - if (length(declaredManagedType.typeParameters) >= 2) { - const args = fillMissingTypeArguments([ - ctorType, - attributesType - ], declaredManagedType.typeParameters, 2, isInJSFile(context)); - return createTypeReference(declaredManagedType, args); - } + const result = instantiateAliasOrInterfaceWithDefaults(managedSym, isInJSFile(context), ctorType, attributesType); + if (result) return result; } return attributesType; } @@ -61019,7 +61616,7 @@ ${lanes.join("\n")} const forcedLookupLocation = getJsxElementPropertiesName(ns); let attributesType = forcedLookupLocation === void 0 ? getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType) : forcedLookupLocation === "" ? getReturnTypeOfSignature(sig) : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation); if (!attributesType) { - if (!!forcedLookupLocation && !!length(context.attributes.properties)) error(context, Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, unescapeLeadingUnderscores(forcedLookupLocation)); + if (!!forcedLookupLocation && !!length(context.attributes.properties)) error2(context, Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, unescapeLeadingUnderscores(forcedLookupLocation)); return unknownType; } attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType); @@ -61098,7 +61695,7 @@ ${lanes.join("\n")} const params = combineIntersectionParameters(left, right, paramMapper); const thisParam = combineIntersectionThisParam(left.thisParameter, right.thisParameter, paramMapper); const minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); - const result = createSignature(declaration, typeParams, thisParam, params, /*resolvedReturnType*/ void 0, /*resolvedTypePredicate*/ void 0, minArgCount, (left.flags | right.flags) & 39 /* PropagatingFlags */ ); + const result = createSignature(declaration, typeParams, thisParam, params, /*resolvedReturnType*/ void 0, /*resolvedTypePredicate*/ void 0, minArgCount, (left.flags | right.flags) & 167 /* PropagatingFlags */ ); result.compositeKind = 2097152 /* Intersection */ ; result.compositeSignatures = concatenate(left.compositeKind === 2097152 /* Intersection */ && left.compositeSignatures || [ left @@ -61126,7 +61723,7 @@ ${lanes.join("\n")} return isFunctionExpressionOrArrowFunction(node) || isObjectLiteralMethod(node) ? getContextualSignature(node) : void 0; } function getContextualSignature(node) { - Debug.assert(node.kind !== 171 /* MethodDeclaration */ || isObjectLiteralMethod(node)); + Debug.assert(node.kind !== 174 /* MethodDeclaration */ || isObjectLiteralMethod(node)); const typeTagSignature = getSignatureOfTypeTag(node); if (typeTagSignature) return typeTagSignature; const type = getApparentTypeOfContextualType(node, 1 /* Signature */ ); @@ -61155,7 +61752,11 @@ ${lanes.join("\n")} return node.isSpread ? getIndexedAccessType(node.type, numberType) : node.type; } function hasDefaultValue(node) { - return node.kind === 205 /* BindingElement */ && !!node.initializer || node.kind === 223 /* BinaryExpression */ && node.operatorToken.kind === 63 /* EqualsToken */ ; + return node.kind === 208 /* BindingElement */ && !!node.initializer || node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 64 /* EqualsToken */ ; + } + function isSpreadIntoCallOrNew(node) { + const parent2 = walkUpParenthesizedExpressions(node.parent); + return isSpreadElement(parent2) && isCallOrNewExpression(parent2.parent); } function checkArrayLiteral(node, checkMode, forceTuple) { const elements = node.elements; @@ -61166,11 +61767,11 @@ ${lanes.join("\n")} const inDestructuringPattern = isAssignmentTarget(node); const inConstContext = isConstContext(node); const contextualType = getApparentTypeOfContextualType(node, /*contextFlags*/ void 0); - const inTupleContext = !!contextualType && someType(contextualType, isTupleLikeType); + const inTupleContext = isSpreadIntoCallOrNew(node) || !!contextualType && someType(contextualType, isTupleLikeType); let hasOmittedExpression = false; for(let i = 0; i < elementCount; i++){ const e = elements[i]; - if (e.kind === 227 /* SpreadElement */ ) { + if (e.kind === 230 /* SpreadElement */ ) { if (languageVersion < 2 /* ES2015 */ ) checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 1024 /* SpreadArray */ ); const spreadType = checkExpression(e.expression, checkMode, forceTuple); if (isArrayLikeType(spreadType)) { @@ -61184,7 +61785,7 @@ ${lanes.join("\n")} elementTypes.push(checkIteratedTypeOrElementType(33 /* Spread */ , spreadType, undefinedType, e.expression)); elementFlags.push(4 /* Rest */ ); } - } else if (exactOptionalPropertyTypes && e.kind === 229 /* OmittedExpression */ ) { + } else if (exactOptionalPropertyTypes && e.kind === 232 /* OmittedExpression */ ) { hasOmittedExpression = true; elementTypes.push(undefinedOrMissingType); elementFlags.push(2 /* Optional */ ); @@ -61215,12 +61816,12 @@ ${lanes.join("\n")} } function isNumericName(name) { switch(name.kind){ - case 164 /* ComputedPropertyName */ : + case 167 /* ComputedPropertyName */ : return isNumericComputedName(name); - case 79 /* Identifier */ : + case 80 /* Identifier */ : return isNumericLiteralName(name.escapedText); - case 8 /* NumericLiteral */ : - case 10 /* StringLiteral */ : + case 9 /* NumericLiteral */ : + case 11 /* StringLiteral */ : return isNumericLiteralName(name.text); default: return false; @@ -61232,7 +61833,7 @@ ${lanes.join("\n")} function checkComputedPropertyName(node) { const links = getNodeLinks(node.expression); if (!links.resolvedType) { - if ((isTypeLiteralNode(node.parent.parent) || isClassLike(node.parent.parent) || isInterfaceDeclaration(node.parent.parent)) && isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 101 /* InKeyword */ && node.parent.kind !== 174 /* GetAccessor */ && node.parent.kind !== 175 /* SetAccessor */ ) return links.resolvedType = errorType; + if ((isTypeLiteralNode(node.parent.parent) || isClassLike(node.parent.parent) || isInterfaceDeclaration(node.parent.parent)) && isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 103 /* InKeyword */ && node.parent.kind !== 177 /* GetAccessor */ && node.parent.kind !== 178 /* SetAccessor */ ) return links.resolvedType = errorType; links.resolvedType = checkExpression(node.expression); if (isPropertyDeclaration(node.parent) && !hasStaticModifier(node.parent) && isClassExpression(node.parent.parent)) { const container = getEnclosingBlockScopeContainer(node.parent.parent); @@ -61243,18 +61844,18 @@ ${lanes.join("\n")} getNodeLinks(node.parent.parent).flags |= 32768 /* BlockScopedBindingInLoop */ ; } } - if (links.resolvedType.flags & 98304 /* Nullable */ || !isTypeAssignableToKind(links.resolvedType, 402665900 /* ESSymbolLike */ ) && !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) error(node, Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); + if (links.resolvedType.flags & 98304 /* Nullable */ || !isTypeAssignableToKind(links.resolvedType, 402665900 /* ESSymbolLike */ ) && !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) error2(node, Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } return links.resolvedType; } function isSymbolWithNumericName(symbol) { - var _a2; - const firstDecl = (_a2 = symbol.declarations) == null ? void 0 : _a2[0]; + var _a; + const firstDecl = (_a = symbol.declarations) == null ? void 0 : _a[0]; return isNumericLiteralName(symbol.escapedName) || firstDecl && isNamedDeclaration(firstDecl) && isNumericName(firstDecl.name); } function isSymbolWithSymbolName(symbol) { - var _a2; - const firstDecl = (_a2 = symbol.declarations) == null ? void 0 : _a2[0]; + var _a; + const firstDecl = (_a = symbol.declarations) == null ? void 0 : _a[0]; return isKnownSymbol(symbol) || firstDecl && isNamedDeclaration(firstDecl) && isComputedPropertyName(firstDecl.name) && isTypeAssignableToKind(checkComputedPropertyName(firstDecl.name), 4096 /* ESSymbol */ ); } function getObjectLiteralIndexInfo(node, offset, properties, keyType) { @@ -61276,8 +61877,8 @@ ${lanes.join("\n")} } return links.immediateTarget; } - function checkObjectLiteral(node, checkMode) { - var _a2; + function checkObjectLiteral(node, checkMode = 0 /* Normal */ ) { + var _a; const inDestructuringPattern = isAssignmentTarget(node); checkGrammarObjectLiteralExpression(node, inDestructuringPattern); const allPropertiesTable = strictNullChecks ? createSymbolTable() : void 0; @@ -61286,11 +61887,11 @@ ${lanes.join("\n")} let spread = emptyObjectType; pushCachedContextualType(node); const contextualType = getApparentTypeOfContextualType(node, /*contextFlags*/ void 0); - const contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 203 /* ObjectBindingPattern */ || contextualType.pattern.kind === 207 /* ObjectLiteralExpression */ ); + const contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 206 /* ObjectBindingPattern */ || contextualType.pattern.kind === 210 /* ObjectLiteralExpression */ ); const inConstContext = isConstContext(node); const checkFlags = inConstContext ? 8 /* Readonly */ : 0; const isInJavascript = isInJSFile(node) && !isInJsonFile(node); - const enumTag = getJSDocEnumTag(node); + const enumTag = isInJavascript ? getJSDocEnumTag(node) : void 0; const isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; let objectFlags = freshObjectLiteralFlag; let patternWithComputedProperties = false; @@ -61301,12 +61902,12 @@ ${lanes.join("\n")} let offset = 0; for (const memberDecl of node.properties){ let member = getSymbolOfDeclaration(memberDecl); - const computedNameType = memberDecl.name && memberDecl.name.kind === 164 /* ComputedPropertyName */ ? checkComputedPropertyName(memberDecl.name) : void 0; - if (memberDecl.kind === 299 /* PropertyAssignment */ || memberDecl.kind === 300 /* ShorthandPropertyAssignment */ || isObjectLiteralMethod(memberDecl)) { - let type = memberDecl.kind === 299 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : // avoid resolving the left side of the ShorthandPropertyAssignment outside of the destructuring + const computedNameType = memberDecl.name && memberDecl.name.kind === 167 /* ComputedPropertyName */ ? checkComputedPropertyName(memberDecl.name) : void 0; + if (memberDecl.kind === 303 /* PropertyAssignment */ || memberDecl.kind === 304 /* ShorthandPropertyAssignment */ || isObjectLiteralMethod(memberDecl)) { + let type = memberDecl.kind === 303 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : // avoid resolving the left side of the ShorthandPropertyAssignment outside of the destructuring // for error recovery purposes. For example, if a user wrote `{ a = 100 }` instead of `{ a: 100 }`. // we don't want to say "could not find 'a'". - memberDecl.kind === 300 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); + memberDecl.kind === 304 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); if (isInJavascript) { const jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { @@ -61319,12 +61920,12 @@ ${lanes.join("\n")} const prop = nameType ? createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */ ) : createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags); if (nameType) prop.links.nameType = nameType; if (inDestructuringPattern) { - const isOptional = memberDecl.kind === 299 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer) || memberDecl.kind === 300 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer; + const isOptional = memberDecl.kind === 303 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer) || memberDecl.kind === 304 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer; if (isOptional) prop.flags |= 16777216 /* Optional */ ; } else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */ )) { const impliedProp = getPropertyOfType(contextualType, member.escapedName); if (impliedProp) prop.flags |= impliedProp.flags & 16777216 /* Optional */ ; - else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, stringType)) error(memberDecl.name, Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); + else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, stringType)) error2(memberDecl.name, Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); } prop.declarations = member.declarations; prop.parent = member.parent; @@ -61333,13 +61934,13 @@ ${lanes.join("\n")} prop.links.target = member; member = prop; allPropertiesTable == null || allPropertiesTable.set(prop.escapedName, prop); - if (contextualType && checkMode && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */ ) && (memberDecl.kind === 299 /* PropertyAssignment */ || memberDecl.kind === 171 /* MethodDeclaration */ ) && isContextSensitive(memberDecl)) { + if (contextualType && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */ ) && (memberDecl.kind === 303 /* PropertyAssignment */ || memberDecl.kind === 174 /* MethodDeclaration */ ) && isContextSensitive(memberDecl)) { const inferenceContext = getInferenceContext(node); Debug.assert(inferenceContext); - const inferenceNode = memberDecl.kind === 299 /* PropertyAssignment */ ? memberDecl.initializer : memberDecl; + const inferenceNode = memberDecl.kind === 303 /* PropertyAssignment */ ? memberDecl.initializer : memberDecl; addIntraExpressionInferenceSite(inferenceContext, inferenceNode, type); } - } else if (memberDecl.kind === 301 /* SpreadAssignment */ ) { + } else if (memberDecl.kind === 305 /* SpreadAssignment */ ) { if (languageVersion < 2 /* ES2015 */ ) checkExternalEmitHelpers(memberDecl, 2 /* Assign */ ); if (propertiesArray.length > 0) { spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext); @@ -61349,7 +61950,7 @@ ${lanes.join("\n")} hasComputedNumberProperty = false; hasComputedSymbolProperty = false; } - const type = getReducedType(checkExpression(memberDecl.expression)); + const type = getReducedType(checkExpression(memberDecl.expression, checkMode & 2 /* Inferential */ )); if (isValidSpreadType(type)) { const mergedType = tryMergeUnionOfObjectTypeAndEmptyObject(type, inConstContext); if (allPropertiesTable) checkSpreadPropOverrides(mergedType, allPropertiesTable, memberDecl); @@ -61357,12 +61958,12 @@ ${lanes.join("\n")} if (isErrorType(spread)) continue; spread = getSpreadType(spread, mergedType, node.symbol, objectFlags, inConstContext); } else { - error(memberDecl, Diagnostics.Spread_types_may_only_be_created_from_object_types); + error2(memberDecl, Diagnostics.Spread_types_may_only_be_created_from_object_types); spread = errorType; } continue; } else { - Debug.assert(memberDecl.kind === 174 /* GetAccessor */ || memberDecl.kind === 175 /* SetAccessor */ ); + Debug.assert(memberDecl.kind === 177 /* GetAccessor */ || memberDecl.kind === 178 /* SetAccessor */ ); checkNodeDeferred(memberDecl); } if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */ )) { @@ -61377,11 +61978,11 @@ ${lanes.join("\n")} } popContextualType(); if (contextualTypeHasPattern) { - const rootPatternParent = findAncestor(contextualType.pattern.parent, (n)=>n.kind === 257 /* VariableDeclaration */ || n.kind === 223 /* BinaryExpression */ || n.kind === 166 /* Parameter */ ); - const spreadOrOutsideRootObject = findAncestor(node, (n)=>n === rootPatternParent || n.kind === 301 /* SpreadAssignment */ ); - if (spreadOrOutsideRootObject.kind !== 301 /* SpreadAssignment */ ) { + const rootPatternParent = findAncestor(contextualType.pattern.parent, (n)=>n.kind === 260 /* VariableDeclaration */ || n.kind === 226 /* BinaryExpression */ || n.kind === 169 /* Parameter */ ); + const spreadOrOutsideRootObject = findAncestor(node, (n)=>n === rootPatternParent || n.kind === 305 /* SpreadAssignment */ ); + if (spreadOrOutsideRootObject.kind !== 305 /* SpreadAssignment */ ) { for (const prop of getPropertiesOfType(contextualType))if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) { - if (!(prop.flags & 16777216 /* Optional */ )) error(prop.valueDeclaration || ((_a2 = tryCast(prop, isTransientSymbol)) == null ? void 0 : _a2.links.bindingElement), Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + if (!(prop.flags & 16777216 /* Optional */ )) error2(prop.valueDeclaration || ((_a = tryCast(prop, isTransientSymbol)) == null ? void 0 : _a.links.bindingElement), Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); propertiesTable.set(prop.escapedName, prop); propertiesArray.push(prop); } @@ -61425,7 +62026,7 @@ ${lanes.join("\n")} } function checkJsxElementDeferred(node) { checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); - if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) getIntrinsicTagSymbol(node.closingElement); + if (isJsxIntrinsicTagName(node.closingElement.tagName)) getIntrinsicTagSymbol(node.closingElement); else checkExpression(node.closingElement.tagName); checkJsxChildren(node); } @@ -61436,22 +62037,22 @@ ${lanes.join("\n")} function checkJsxFragment(node) { checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); const nodeSourceFile = getSourceFileOfNode(node); - if (getJSXTransformEnabled(compilerOptions) && (compilerOptions.jsxFactory || nodeSourceFile.pragmas.has("jsx")) && !compilerOptions.jsxFragmentFactory && !nodeSourceFile.pragmas.has("jsxfrag")) error(node, compilerOptions.jsxFactory ? Diagnostics.The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_compiler_option : Diagnostics.An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments); + if (getJSXTransformEnabled(compilerOptions) && (compilerOptions.jsxFactory || nodeSourceFile.pragmas.has("jsx")) && !compilerOptions.jsxFragmentFactory && !nodeSourceFile.pragmas.has("jsxfrag")) error2(node, compilerOptions.jsxFactory ? Diagnostics.The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_compiler_option : Diagnostics.An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments); checkJsxChildren(node); return getJsxElementTypeAt(node) || anyType; } function isHyphenatedJsxName(name) { return stringContains(name, "-"); } - function isJsxIntrinsicIdentifier(tagName) { - return tagName.kind === 79 /* Identifier */ && isIntrinsicJsxName(tagName.escapedText); + function isJsxIntrinsicTagName(tagName) { + return isIdentifier(tagName) && isIntrinsicJsxName(tagName.escapedText) || isJsxNamespacedName(tagName); } function checkJsxAttribute(node, checkMode) { return node.initializer ? checkExpressionForMutableLocation(node.initializer, checkMode) : trueType; } - function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode = 0 /* Normal */ ) { const attributes = openingLikeElement.attributes; - const attributesType = getContextualType2(attributes, 0 /* None */ ); + const contextualType = getContextualType2(attributes, 0 /* None */ ); const allAttributesTable = strictNullChecks ? createSymbolTable() : void 0; let attributesTable = createSymbolTable(); let spread = emptyJsxObjectType; @@ -61473,24 +62074,30 @@ ${lanes.join("\n")} attributeSymbol.links.target = member; attributesTable.set(attributeSymbol.escapedName, attributeSymbol); allAttributesTable == null || allAttributesTable.set(attributeSymbol.escapedName, attributeSymbol); - if (attributeDecl.name.escapedText === jsxChildrenPropertyName) explicitlySpecifyChildrenAttribute = true; - if (attributesType) { - const prop = getPropertyOfType(attributesType, member.escapedName); - if (prop && prop.declarations && isDeprecatedSymbol(prop)) addDeprecatedSuggestion(attributeDecl.name, prop.declarations, attributeDecl.name.escapedText); + if (getEscapedTextOfJsxAttributeName(attributeDecl.name) === jsxChildrenPropertyName) explicitlySpecifyChildrenAttribute = true; + if (contextualType) { + const prop = getPropertyOfType(contextualType, member.escapedName); + if (prop && prop.declarations && isDeprecatedSymbol(prop) && isIdentifier(attributeDecl.name)) addDeprecatedSuggestion(attributeDecl.name, prop.declarations, attributeDecl.name.escapedText); + } + if (contextualType && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */ ) && isContextSensitive(attributeDecl)) { + const inferenceContext = getInferenceContext(attributes); + Debug.assert(inferenceContext); + const inferenceNode = attributeDecl.initializer.expression; + addIntraExpressionInferenceSite(inferenceContext, inferenceNode, exprType); } } else { - Debug.assert(attributeDecl.kind === 290 /* JsxSpreadAttribute */ ); + Debug.assert(attributeDecl.kind === 293 /* JsxSpreadAttribute */ ); if (attributesTable.size > 0) { spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false); attributesTable = createSymbolTable(); } - const exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode)); + const exprType = getReducedType(checkExpression(attributeDecl.expression, checkMode & 2 /* Inferential */ )); if (isTypeAny(exprType)) hasSpreadAnyType = true; if (isValidSpreadType(exprType)) { spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false); if (allAttributesTable) checkSpreadPropOverrides(exprType, allAttributesTable, attributeDecl); } else { - error(attributeDecl.expression, Diagnostics.Spread_types_may_only_be_created_from_object_types); + error2(attributeDecl.expression, Diagnostics.Spread_types_may_only_be_created_from_object_types); typeToIntersect = typeToIntersect ? getIntersectionType([ typeToIntersect, exprType @@ -61501,13 +62108,13 @@ ${lanes.join("\n")} if (!hasSpreadAnyType) { if (attributesTable.size > 0) spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false); } - const parent2 = openingLikeElement.parent.kind === 281 /* JsxElement */ ? openingLikeElement.parent : void 0; + const parent2 = openingLikeElement.parent.kind === 284 /* JsxElement */ ? openingLikeElement.parent : void 0; if (parent2 && parent2.openingElement === openingLikeElement && parent2.children.length > 0) { const childrenTypes = checkJsxChildren(parent2, checkMode); if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (explicitlySpecifyChildrenAttribute) error(attributes, Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, unescapeLeadingUnderscores(jsxChildrenPropertyName)); - const contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes, /*contextFlags*/ void 0); - const childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); + if (explicitlySpecifyChildrenAttribute) error2(attributes, Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, unescapeLeadingUnderscores(jsxChildrenPropertyName)); + const contextualType2 = getApparentTypeOfContextualType(openingLikeElement.attributes, /*contextFlags*/ void 0); + const childrenContextualType = contextualType2 && getTypeOfPropertyOfContextualType(contextualType2, jsxChildrenPropertyName); const childrenPropSymbol = createSymbol(4 /* Property */ , jsxChildrenPropertyName); childrenPropSymbol.links.type = childrenTypes.length === 1 ? childrenTypes[0] : childrenContextualType && someType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) : createArrayType(getUnionType(childrenTypes)); childrenPropSymbol.valueDeclaration = factory.createPropertySignature(/*modifiers*/ void 0, unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ void 0, /*type*/ void 0); @@ -61534,9 +62141,9 @@ ${lanes.join("\n")} function checkJsxChildren(node, checkMode) { const childrenTypes = []; for (const child of node.children){ - if (child.kind === 11 /* JsxText */ ) { + if (child.kind === 12 /* JsxText */ ) { if (!child.containsOnlyTriviaWhiteSpaces) childrenTypes.push(stringType); - } else if (child.kind === 291 /* JsxExpression */ && !child.expression) continue; + } else if (child.kind === 294 /* JsxExpression */ && !child.expression) continue; else childrenTypes.push(checkExpressionForMutableLocation(child, checkMode)); } return childrenTypes; @@ -61545,7 +62152,7 @@ ${lanes.join("\n")} for (const right of getPropertiesOfType(type))if (!(right.flags & 16777216 /* Optional */ )) { const left = props.get(right.escapedName); if (left) { - const diagnostic = error(left.valueDeclaration, Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, unescapeLeadingUnderscores(left.escapedName)); + const diagnostic = error2(left.valueDeclaration, Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, unescapeLeadingUnderscores(left.escapedName)); addRelatedInfo(diagnostic, createDiagnosticForNode(spread, Diagnostics.This_spread_always_overwrites_this_property)); } } @@ -61564,8 +62171,8 @@ ${lanes.join("\n")} if (!links.resolvedSymbol) { const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node); if (!isErrorType(intrinsicElementsType)) { - if (!isIdentifier(node.tagName)) return Debug.fail(); - const intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText); + if (!isIdentifier(node.tagName) && !isJsxNamespacedName(node.tagName)) return Debug.fail(); + const intrinsicProp = getPropertyOfType(intrinsicElementsType, isJsxNamespacedName(node.tagName) ? getEscapedTextOfJsxNamespacedName(node.tagName) : node.tagName.escapedText); if (intrinsicProp) { links.jsxFlags |= 1 /* IntrinsicNamedElement */ ; return links.resolvedSymbol = intrinsicProp; @@ -61575,10 +62182,10 @@ ${lanes.join("\n")} links.jsxFlags |= 2 /* IntrinsicIndexedElement */ ; return links.resolvedSymbol = intrinsicElementsType.symbol; } - error(node, Diagnostics.Property_0_does_not_exist_on_type_1, idText(node.tagName), "JSX." + JsxNames.IntrinsicElements); + error2(node, Diagnostics.Property_0_does_not_exist_on_type_1, intrinsicTagNameToString(node.tagName), "JSX." + JsxNames.IntrinsicElements); return links.resolvedSymbol = unknownSymbol; } else { - if (noImplicitAny) error(node, Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, unescapeLeadingUnderscores(JsxNames.IntrinsicElements)); + if (noImplicitAny) error2(node, Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, unescapeLeadingUnderscores(JsxNames.IntrinsicElements)); return links.resolvedSymbol = unknownSymbol; } } @@ -61605,7 +62212,7 @@ ${lanes.join("\n")} let resolvedNamespace = getJsxNamespaceContainerForImplicitImport(location); if (!resolvedNamespace || resolvedNamespace === unknownSymbol) { const namespaceName = getJsxNamespace(location); - resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */ , /*diagnosticMessage*/ void 0, namespaceName, /*isUse*/ false); + resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */ , /*nameNotFoundMessage*/ void 0, namespaceName, /*isUse*/ false); } if (resolvedNamespace) { const candidate = resolveSymbol(getSymbol2(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */ )); @@ -61616,7 +62223,7 @@ ${lanes.join("\n")} } if (links) links.jsxNamespace = false; } - const s = resolveSymbol(getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */ , /*diagnosticMessage*/ void 0)); + const s = resolveSymbol(getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */ , /*diagnostic*/ void 0)); if (s === unknownSymbol) return void 0; return s; } @@ -61627,13 +62234,16 @@ ${lanes.join("\n")} if (propertiesOfJsxElementAttribPropInterface) { if (propertiesOfJsxElementAttribPropInterface.length === 0) return ""; else if (propertiesOfJsxElementAttribPropInterface.length === 1) return propertiesOfJsxElementAttribPropInterface[0].escapedName; - else if (propertiesOfJsxElementAttribPropInterface.length > 1 && jsxElementAttribPropInterfaceSym.declarations) error(jsxElementAttribPropInterfaceSym.declarations[0], Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, unescapeLeadingUnderscores(nameOfAttribPropContainer)); + else if (propertiesOfJsxElementAttribPropInterface.length > 1 && jsxElementAttribPropInterfaceSym.declarations) error2(jsxElementAttribPropInterfaceSym.declarations[0], Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, unescapeLeadingUnderscores(nameOfAttribPropContainer)); } return void 0; } function getJsxLibraryManagedAttributes(jsxNamespace) { return jsxNamespace && getSymbol2(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 788968 /* Type */ ); } + function getJsxElementTypeSymbol(jsxNamespace) { + return jsxNamespace && getSymbol2(jsxNamespace.exports, JsxNames.ElementType, 788968 /* Type */ ); + } function getJsxElementPropertiesName(jsxNamespace) { return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace); } @@ -61647,7 +62257,7 @@ ${lanes.join("\n")} else if (elementType.flags & 128 /* StringLiteral */ ) { const intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller); if (!intrinsicType) { - error(caller, Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements); + error2(caller, Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements); return emptyArray; } else { const fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType); @@ -61693,11 +62303,11 @@ ${lanes.join("\n")} } function generateInitialErrorChain() { const componentName = getTextOfNode(openingLikeElement.tagName); - return chainDiagnosticMessages(/* details */ void 0, Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName); + return chainDiagnosticMessages(/*details*/ void 0, Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName); } } function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { - Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); + Debug.assert(isJsxIntrinsicTagName(node.tagName)); const links = getNodeLinks(node); if (!links.resolvedJsxElementAttributesType) { const symbol = getIntrinsicTagSymbol(node); @@ -61722,14 +62332,38 @@ ${lanes.join("\n")} nullType ]); } + function getJsxElementTypeTypeAt(location) { + const ns = getJsxNamespaceAt(location); + if (!ns) return void 0; + const sym = getJsxElementTypeSymbol(ns); + if (!sym) return void 0; + const type = instantiateAliasOrInterfaceWithDefaults(sym, isInJSFile(location)); + if (!type || isErrorType(type)) return void 0; + return type; + } + function instantiateAliasOrInterfaceWithDefaults(managedSym, inJs, ...typeArguments) { + const declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + if (managedSym.flags & 524288 /* TypeAlias */ ) { + const params = getSymbolLinks(managedSym).typeParameters; + if (length(params) >= typeArguments.length) { + const args = fillMissingTypeArguments(typeArguments, params, typeArguments.length, inJs); + return length(args) === 0 ? declaredManagedType : getTypeAliasInstantiation(managedSym, args); + } + } + if (length(declaredManagedType.typeParameters) >= typeArguments.length) { + const args = fillMissingTypeArguments(typeArguments, declaredManagedType.typeParameters, typeArguments.length, inJs); + return createTypeReference(declaredManagedType, args); + } + return void 0; + } function getJsxIntrinsicTagNamesAt(location) { const intrinsics = getJsxType(JsxNames.IntrinsicElements, location); return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; } function checkJsxPreconditions(errorNode) { - if ((compilerOptions.jsx || 0 /* None */ ) === 0 /* None */ ) error(errorNode, Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); + if ((compilerOptions.jsx || 0 /* None */ ) === 0 /* None */ ) error2(errorNode, Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); if (getJsxElementTypeAt(errorNode) === void 0) { - if (noImplicitAny) error(errorNode, Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); + if (noImplicitAny) error2(errorNode, Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); } } function checkJsxOpeningLikeElementOrOpeningFragment(node) { @@ -61744,7 +62378,7 @@ ${lanes.join("\n")} if (!(isJsxOpeningFragment(node) && jsxFactoryNamespace === "null")) jsxFactorySym = resolveName(jsxFactoryLocation, jsxFactoryNamespace, 111551 /* Value */ , jsxFactoryRefErr, jsxFactoryNamespace, /*isUse*/ true); if (jsxFactorySym) { jsxFactorySym.isReferenced = 67108863 /* All */ ; - if (!compilerOptions.verbatimModuleSyntax && jsxFactorySym.flags & 2097152 /* Alias */ && !getTypeOnlyAliasDeclaration(jsxFactorySym)) markAliasSymbolAsReferenced(jsxFactorySym); + if (canCollectSymbolAliasAccessabilityData && jsxFactorySym.flags & 2097152 /* Alias */ && !getTypeOnlyAliasDeclaration(jsxFactorySym)) markAliasSymbolAsReferenced(jsxFactorySym); } if (isJsxOpeningFragment(node)) { const file = getSourceFileOfNode(node); @@ -61756,7 +62390,15 @@ ${lanes.join("\n")} const jsxOpeningLikeNode = node; const sig = getResolvedSignature(jsxOpeningLikeNode); checkDeprecatedSignature(sig, node); - checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode); + const elementTypeConstraint = getJsxElementTypeTypeAt(jsxOpeningLikeNode); + if (elementTypeConstraint !== void 0) { + const tagName = jsxOpeningLikeNode.tagName; + const tagType = isJsxIntrinsicTagName(tagName) ? getStringLiteralType(intrinsicTagNameToString(tagName)) : checkExpression(tagName); + checkTypeRelatedTo(tagType, elementTypeConstraint, assignableRelation, tagName, Diagnostics.Its_type_0_is_not_a_valid_JSX_element_type, ()=>{ + const componentName = getTextOfNode(tagName); + return chainDiagnosticMessages(/*details*/ void 0, Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName); + }); + } else checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode); } } function isKnownProperty(targetType, name, isComparingJsxAttributes) { @@ -61774,12 +62416,12 @@ ${lanes.join("\n")} checkGrammarJsxExpression(node); if (node.expression) { const type = checkExpression(node.expression, checkMode); - if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) error(node, Diagnostics.JSX_spread_child_must_be_an_array_type); + if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) error2(node, Diagnostics.JSX_spread_child_must_be_an_array_type); return type; } else return errorType; } function getDeclarationNodeFlagsFromSymbol(s) { - return s.valueDeclaration ? getCombinedNodeFlags(s.valueDeclaration) : 0; + return s.valueDeclaration ? getCombinedNodeFlagsCached(s.valueDeclaration) : 0; } function isPrototypeProperty(symbol) { if (symbol.flags & 8192 /* Method */ || getCheckFlags(symbol) & 4 /* SyntheticMethod */ ) return true; @@ -61789,7 +62431,7 @@ ${lanes.join("\n")} } } function checkPropertyAccessibility(node, isSuper, writing, type, prop, reportError = true) { - const errorNode = !reportError ? void 0 : node.kind === 163 /* QualifiedName */ ? node.right : node.kind === 202 /* ImportType */ ? node : node.kind === 205 /* BindingElement */ && node.propertyName ? node.propertyName : node.name; + const errorNode = !reportError ? void 0 : node.kind === 166 /* QualifiedName */ ? node.right : node.kind === 205 /* ImportType */ ? node : node.kind === 208 /* BindingElement */ && node.propertyName ? node.propertyName : node.name; return checkPropertyAccessibilityAtLocation(node, isSuper, writing, type, prop, errorNode); } function checkPropertyAccessibilityAtLocation(location, isSuper, writing, containingType, prop, errorNode) { @@ -61797,19 +62439,19 @@ ${lanes.join("\n")} if (isSuper) { if (languageVersion < 2 /* ES2015 */ ) { if (symbolHasNonMethodDeclaration(prop)) { - if (errorNode) error(errorNode, Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + if (errorNode) error2(errorNode, Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); return false; } } if (flags & 256 /* Abstract */ ) { - if (errorNode) error(errorNode, Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + if (errorNode) error2(errorNode, Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); return false; } } if (flags & 256 /* Abstract */ && symbolHasNonMethodDeclaration(prop) && (isThisProperty(location) || isThisInitializedObjectBindingExpression(location) || isObjectBindingPattern(location.parent) && isThisInitializedDeclaration(location.parent.parent))) { const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(location)) { - if (errorNode) error(errorNode, Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); + if (errorNode) error2(errorNode, Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); return false; } } @@ -61817,7 +62459,7 @@ ${lanes.join("\n")} if (flags & 8 /* Private */ ) { const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (!isNodeWithinClass(location, declaringClassDeclaration)) { - if (errorNode) error(errorNode, Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + if (errorNode) error2(errorNode, Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); return false; } return true; @@ -61831,14 +62473,14 @@ ${lanes.join("\n")} enclosingClass = getEnclosingClassFromThisParameter(location); enclosingClass = enclosingClass && isClassDerivedFromDeclaringClasses(enclosingClass, prop, writing); if (flags & 32 /* Static */ || !enclosingClass) { - if (errorNode) error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || containingType)); + if (errorNode) error2(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || containingType)); return false; } } if (flags & 32 /* Static */ ) return true; if (containingType.flags & 262144 /* TypeParameter */ ) containingType = containingType.isThisType ? getConstraintOfTypeParameter(containingType) : getBaseConstraintOfType(containingType); if (!containingType || !hasBaseType(containingType, enclosingClass)) { - if (errorNode) error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2, symbolToString(prop), typeToString(enclosingClass), typeToString(containingType)); + if (errorNode) error2(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2, symbolToString(prop), typeToString(enclosingClass), typeToString(containingType)); return false; } return true; @@ -61851,7 +62493,7 @@ ${lanes.join("\n")} return void 0; } function getThisParameterFromNodeContext(node) { - const thisContainer = getThisContainer(node, /* includeArrowFunctions */ false, /*includeClassComputedPropertyName*/ false); + const thisContainer = getThisContainer(node, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false); return thisContainer && isFunctionLike(thisContainer) ? getThisParameter(thisContainer) : void 0; } function symbolHasNonMethodDeclaration(symbol) { @@ -61868,31 +62510,31 @@ ${lanes.join("\n")} } function reportObjectPossiblyNullOrUndefinedError(node, facts) { const nodeText2 = isEntityNameExpression(node) ? entityNameToString(node) : void 0; - if (node.kind === 104 /* NullKeyword */ ) { - error(node, Diagnostics.The_value_0_cannot_be_used_here, "null"); + if (node.kind === 106 /* NullKeyword */ ) { + error2(node, Diagnostics.The_value_0_cannot_be_used_here, "null"); return; } if (nodeText2 !== void 0 && nodeText2.length < 100) { if (isIdentifier(node) && nodeText2 === "undefined") { - error(node, Diagnostics.The_value_0_cannot_be_used_here, "undefined"); + error2(node, Diagnostics.The_value_0_cannot_be_used_here, "undefined"); return; } - error(node, facts & 16777216 /* IsUndefined */ ? facts & 33554432 /* IsNull */ ? Diagnostics._0_is_possibly_null_or_undefined : Diagnostics._0_is_possibly_undefined : Diagnostics._0_is_possibly_null, nodeText2); - } else error(node, facts & 16777216 /* IsUndefined */ ? facts & 33554432 /* IsNull */ ? Diagnostics.Object_is_possibly_null_or_undefined : Diagnostics.Object_is_possibly_undefined : Diagnostics.Object_is_possibly_null); + error2(node, facts & 16777216 /* IsUndefined */ ? facts & 33554432 /* IsNull */ ? Diagnostics._0_is_possibly_null_or_undefined : Diagnostics._0_is_possibly_undefined : Diagnostics._0_is_possibly_null, nodeText2); + } else error2(node, facts & 16777216 /* IsUndefined */ ? facts & 33554432 /* IsNull */ ? Diagnostics.Object_is_possibly_null_or_undefined : Diagnostics.Object_is_possibly_undefined : Diagnostics.Object_is_possibly_null); } function reportCannotInvokePossiblyNullOrUndefinedError(node, facts) { - error(node, facts & 16777216 /* IsUndefined */ ? facts & 33554432 /* IsNull */ ? Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : Diagnostics.Cannot_invoke_an_object_which_is_possibly_null); + error2(node, facts & 16777216 /* IsUndefined */ ? facts & 33554432 /* IsNull */ ? Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : Diagnostics.Cannot_invoke_an_object_which_is_possibly_null); } function checkNonNullTypeWithReporter(type, node, reportError) { if (strictNullChecks && type.flags & 2 /* Unknown */ ) { if (isEntityNameExpression(node)) { const nodeText2 = entityNameToString(node); if (nodeText2.length < 100) { - error(node, Diagnostics._0_is_of_type_unknown, nodeText2); + error2(node, Diagnostics._0_is_of_type_unknown, nodeText2); return errorType; } } - error(node, Diagnostics.Object_is_of_type_unknown); + error2(node, Diagnostics.Object_is_of_type_unknown); return errorType; } const facts = getTypeFacts(type); @@ -61912,20 +62554,20 @@ ${lanes.join("\n")} if (isEntityNameExpression(node)) { const nodeText2 = entityNameToString(node); if (isIdentifier(node) && nodeText2 === "undefined") { - error(node, Diagnostics.The_value_0_cannot_be_used_here, nodeText2); + error2(node, Diagnostics.The_value_0_cannot_be_used_here, nodeText2); return nonNullType; } if (nodeText2.length < 100) { - error(node, Diagnostics._0_is_possibly_undefined, nodeText2); + error2(node, Diagnostics._0_is_possibly_undefined, nodeText2); return nonNullType; } } - error(node, Diagnostics.Object_is_possibly_undefined); + error2(node, Diagnostics.Object_is_possibly_undefined); } return nonNullType; } - function checkPropertyAccessExpression(node, checkMode) { - return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node, checkMode) : checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name, checkMode); + function checkPropertyAccessExpression(node, checkMode, writeOnly) { + return node.flags & 64 /* OptionalChain */ ? checkPropertyAccessChain(node, checkMode) : checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name, checkMode, writeOnly); } function checkPropertyAccessChain(node, checkMode) { const leftType = checkExpression(node.expression); @@ -61937,12 +62579,12 @@ ${lanes.join("\n")} return checkPropertyAccessExpressionOrQualifiedName(node, node.left, leftType, node.right, checkMode); } function isMethodAccessForCall(node) { - while(node.parent.kind === 214 /* ParenthesizedExpression */ )node = node.parent; + while(node.parent.kind === 217 /* ParenthesizedExpression */ )node = node.parent; return isCallOrNewExpression(node.parent) && node.parent.expression === node; } function lookupSymbolForPrivateIdentifierDeclaration(propName, location) { - for(let containingClass = getContainingClass(location); !!containingClass; containingClass = getContainingClass(containingClass)){ - const { symbol: symbol } = containingClass; + for(let containingClass = getContainingClassExcludingClassDecorators(location); !!containingClass; containingClass = getContainingClass(containingClass)){ + const { symbol: symbol } = containingClass; const name = getSymbolNameForPrivateIdentifier(symbol, propName); const prop = symbol.members && symbol.members.get(name) || symbol.exports && symbol.exports.get(name); if (prop) return prop; @@ -61952,7 +62594,7 @@ ${lanes.join("\n")} if (!getContainingClass(privId)) return grammarErrorOnNode(privId, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); if (!isForInStatement(privId.parent)) { if (!isExpressionNode(privId)) return grammarErrorOnNode(privId, 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); - const isInOperation = isBinaryExpression(privId.parent) && privId.parent.operatorToken.kind === 101 /* InKeyword */ ; + const isInOperation = isBinaryExpression(privId.parent) && privId.parent.operatorToken.kind === 103 /* InKeyword */ ; if (!getSymbolForPrivateIdentifierExpression(privId) && !isInOperation) return grammarErrorOnNode(privId, Diagnostics.Cannot_find_name_0, idText(privId)); } return false; @@ -61960,7 +62602,7 @@ ${lanes.join("\n")} function checkPrivateIdentifierExpression(privId) { checkGrammarPrivateIdentifierExpression(privId); const symbol = getSymbolForPrivateIdentifierExpression(privId); - if (symbol) markPropertyAsReferenced(symbol, /* nodeForCheckWriteOnly: */ void 0, /* isThisAccess: */ false); + if (symbol) markPropertyAsReferenced(symbol, /*nodeForCheckWriteOnly*/ void 0, /*isSelfTypeAccess*/ false); return anyType; } function getSymbolForPrivateIdentifierExpression(privId) { @@ -61991,12 +62633,12 @@ ${lanes.join("\n")} const lexicalClass = getContainingClass(lexicalValueDecl); Debug.assert(!!lexicalClass); if (findAncestor(lexicalClass, (n)=>typeClass === n)) { - const diagnostic = error(right, Diagnostics.The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_private_identifier_with_the_same_spelling, diagName, typeToString(leftType)); + const diagnostic = error2(right, Diagnostics.The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_private_identifier_with_the_same_spelling, diagName, typeToString(leftType)); addRelatedInfo(diagnostic, createDiagnosticForNode(lexicalValueDecl, Diagnostics.The_shadowing_declaration_of_0_is_defined_here, diagName), createDiagnosticForNode(typeValueDecl, Diagnostics.The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here, diagName)); return true; } } - error(right, Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier, diagName, diagnosticName(typeClass.name || anon)); + error2(right, Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier, diagName, diagnosticName(typeClass.name || anon)); return true; } return false; @@ -62004,7 +62646,7 @@ ${lanes.join("\n")} function isThisPropertyAccessInConstructor(node, prop) { return (isConstructorDeclaredProperty(prop) || isThisProperty(node) && isAutoTypedProperty(prop)) && getThisContainer(node, /*includeArrowFunctions*/ true, /*includeClassComputedPropertyName*/ false) === getDeclaringConstructor(prop); } - function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right, checkMode) { + function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right, checkMode, writeOnly) { const parentSymbol = getNodeLinks(left).resolvedSymbol; const assignmentKind = getAssignmentTargetKind(node); const apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType); @@ -62019,25 +62661,28 @@ ${lanes.join("\n")} if (assignmentKind && lexicallyScopedSymbol && lexicallyScopedSymbol.valueDeclaration && isMethodDeclaration(lexicallyScopedSymbol.valueDeclaration)) grammarErrorOnNode(right, Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable, idText(right)); if (isAnyLike) { if (lexicallyScopedSymbol) return isErrorType(apparentType) ? errorType : apparentType; - if (!getContainingClass(right)) { + if (getContainingClassExcludingClassDecorators(right) === void 0) { grammarErrorOnNode(right, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); return anyType; } } - prop = lexicallyScopedSymbol ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedSymbol) : void 0; - if (!prop && checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) return errorType; - else { - const isSetonlyAccessor = prop && prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */ ); - if (isSetonlyAccessor && assignmentKind !== 1 /* Definite */ ) error(node, Diagnostics.Private_accessor_was_defined_without_a_getter); + prop = lexicallyScopedSymbol && getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedSymbol); + if (prop === void 0) { + if (checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) return errorType; + const containingClass = getContainingClassExcludingClassDecorators(right); + if (containingClass && isPlainJsFile(getSourceFileOfNode(containingClass), compilerOptions.checkJs)) grammarErrorOnNode(right, Diagnostics.Private_field_0_must_be_declared_in_an_enclosing_class, idText(right)); + } else { + const isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */ ); + if (isSetonlyAccessor && assignmentKind !== 1 /* Definite */ ) error2(node, Diagnostics.Private_accessor_was_defined_without_a_getter); } } else { if (isAnyLike) { if (isIdentifier(left) && parentSymbol) markAliasReferenced(parentSymbol, node); return isErrorType(apparentType) ? errorType : apparentType; } - prop = getPropertyOfType(apparentType, right.escapedText, /*skipObjectFunctionPropertyAugment*/ false, /*includeTypeOnlyMembers*/ node.kind === 163 /* QualifiedName */ ); + prop = getPropertyOfType(apparentType, right.escapedText, /*skipObjectFunctionPropertyAugment*/ false, /*includeTypeOnlyMembers*/ node.kind === 166 /* QualifiedName */ ); } - if (isIdentifier(left) && parentSymbol && (getIsolatedModules(compilerOptions) || !(prop && (isConstEnumOrConstEnumOnlyModule(prop) || prop.flags & 8 /* EnumMember */ && node.parent.kind === 302 /* EnumMember */ )) || shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(node))) markAliasReferenced(parentSymbol, node); + if (isIdentifier(left) && parentSymbol && (getIsolatedModules(compilerOptions) || !(prop && (isConstEnumOrConstEnumOnlyModule(prop) || prop.flags & 8 /* EnumMember */ && node.parent.kind === 306 /* EnumMember */ )) || shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(node))) markAliasReferenced(parentSymbol, node); let propType; if (!prop) { const indexInfo = !isPrivateIdentifier(right) && (assignmentKind === 0 /* None */ || !isGenericObjectType(leftType) || isThisTypeParameter(leftType)) ? getApplicableIndexInfoForName(apparentType, right.escapedText) : void 0; @@ -62045,34 +62690,34 @@ ${lanes.join("\n")} const isUncheckedJS = isUncheckedJSSuggestion(node, leftType.symbol, /*excludeClasses*/ true); if (!isUncheckedJS && isJSLiteralType(leftType)) return anyType; if (leftType.symbol === globalThisSymbol) { - if (globalThisSymbol.exports.has(right.escapedText) && globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */ ) error(right, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(right.escapedText), typeToString(leftType)); - else if (noImplicitAny) error(right, Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType)); + if (globalThisSymbol.exports.has(right.escapedText) && globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */ ) error2(right, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(right.escapedText), typeToString(leftType)); + else if (noImplicitAny) error2(right, Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType)); return anyType; } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) reportNonexistentProperty(right, isThisTypeParameter(leftType) ? apparentType : leftType, isUncheckedJS); return errorType; } - if (indexInfo.isReadonly && (isAssignmentTarget(node) || isDeleteTarget(node))) error(node, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); + if (indexInfo.isReadonly && (isAssignmentTarget(node) || isDeleteTarget(node))) error2(node, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); propType = compilerOptions.noUncheckedIndexedAccess && !isAssignmentTarget(node) ? getUnionType([ indexInfo.type, missingType ]) : indexInfo.type; - if (compilerOptions.noPropertyAccessFromIndexSignature && isPropertyAccessExpression(node)) error(right, Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0, unescapeLeadingUnderscores(right.escapedText)); - if (indexInfo.declaration && getCombinedNodeFlags(indexInfo.declaration) & 268435456 /* Deprecated */ ) addDeprecatedSuggestion(right, [ + if (compilerOptions.noPropertyAccessFromIndexSignature && isPropertyAccessExpression(node)) error2(right, Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0, unescapeLeadingUnderscores(right.escapedText)); + if (indexInfo.declaration && isDeprecatedDeclaration2(indexInfo.declaration)) addDeprecatedSuggestion(right, [ indexInfo.declaration ], right.escapedText); } else { - if (isDeprecatedSymbol(prop) && isUncalledFunctionReference(node, prop) && prop.declarations) addDeprecatedSuggestion(right, prop.declarations, right.escapedText); + const targetPropSymbol = resolveAliasWithDeprecationCheck(prop, right); + if (isDeprecatedSymbol(targetPropSymbol) && isUncalledFunctionReference(node, targetPropSymbol) && targetPropSymbol.declarations) addDeprecatedSuggestion(right, targetPropSymbol.declarations, right.escapedText); checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, isSelfTypeAccess(left, parentSymbol)); getNodeLinks(node).resolvedSymbol = prop; - const writing = isWriteAccess(node); - checkPropertyAccessibility(node, left.kind === 106 /* SuperKeyword */ , writing, apparentType, prop); + checkPropertyAccessibility(node, left.kind === 108 /* SuperKeyword */ , isWriteAccess(node), apparentType, prop); if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) { - error(right, Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, idText(right)); + error2(right, Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, idText(right)); return errorType; } - propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : writing ? getWriteTypeOfSymbol(prop) : getTypeOfSymbol(prop); + propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : writeOnly || isWriteOnlyAccess(node) ? getWriteTypeOfSymbol(prop) : getTypeOfSymbol(prop); } return getFlowTypeOfAccessExpression(node, prop, propType, right, checkMode); } @@ -62081,7 +62726,7 @@ ${lanes.join("\n")} if (file) { if (compilerOptions.checkJs === void 0 && file.checkJsDirective === void 0 && (file.scriptKind === 1 /* JS */ || file.scriptKind === 2 /* JSX */ )) { const declarationFile = forEach(suggestion == null ? void 0 : suggestion.declarations, getSourceFileOfNode); - return !(file !== declarationFile && !!declarationFile && isGlobalSourceFile(declarationFile)) && !(excludeClasses && suggestion && suggestion.flags & 32 /* Class */ ) && !(!!node && excludeClasses && isPropertyAccessExpression(node) && node.expression.kind === 108 /* ThisKeyword */ ); + return !(file !== declarationFile && !!declarationFile && isGlobalSourceFile(declarationFile)) && !(excludeClasses && suggestion && suggestion.flags & 32 /* Class */ ) && !(!!node && excludeClasses && isPropertyAccessExpression(node) && node.expression.kind === 110 /* ThisKeyword */ ); } } return false; @@ -62093,53 +62738,53 @@ ${lanes.join("\n")} if (propType === autoType) return getFlowTypeOfProperty(node, prop); propType = getNarrowableTypeForReference(propType, node, checkMode); let assumeUninitialized = false; - if (strictNullChecks && strictPropertyInitialization && isAccessExpression(node) && node.expression.kind === 108 /* ThisKeyword */ ) { + if (strictNullChecks && strictPropertyInitialization && isAccessExpression(node) && node.expression.kind === 110 /* ThisKeyword */ ) { const declaration = prop && prop.valueDeclaration; if (declaration && isPropertyWithoutInitializer(declaration)) { if (!isStatic(declaration)) { const flowContainer = getControlFlowContainer(node); - if (flowContainer.kind === 173 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 16777216 /* Ambient */ )) assumeUninitialized = true; + if (flowContainer.kind === 176 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 33554432 /* Ambient */ )) assumeUninitialized = true; } } } else if (strictNullChecks && prop && prop.valueDeclaration && isPropertyAccessExpression(prop.valueDeclaration) && getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) assumeUninitialized = true; const flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !containsUndefinedType(propType) && containsUndefinedType(flowType)) { - error(errorNode, Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); + error2(errorNode, Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); return propType; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } function checkPropertyNotUsedBeforeDeclaration(prop, node, right) { - const { valueDeclaration: valueDeclaration } = prop; + const { valueDeclaration: valueDeclaration } = prop; if (!valueDeclaration || getSourceFileOfNode(node).isDeclarationFile) return; let diagnosticMessage; const declarationName = idText(right); - if (isInPropertyInitializerOrClassStaticBlock(node) && !isOptionalPropertyDeclaration(valueDeclaration) && !(isAccessExpression(node) && isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !(isMethodDeclaration(valueDeclaration) && getCombinedModifierFlags(valueDeclaration) & 32 /* Static */ ) && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) diagnosticMessage = error(right, Diagnostics.Property_0_is_used_before_its_initialization, declarationName); - else if (valueDeclaration.kind === 260 /* ClassDeclaration */ && node.parent.kind !== 180 /* TypeReference */ && !(valueDeclaration.flags & 16777216 /* Ambient */ ) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) diagnosticMessage = error(right, Diagnostics.Class_0_used_before_its_declaration, declarationName); + if (isInPropertyInitializerOrClassStaticBlock(node) && !isOptionalPropertyDeclaration(valueDeclaration) && !(isAccessExpression(node) && isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !(isMethodDeclaration(valueDeclaration) && getCombinedModifierFlagsCached(valueDeclaration) & 32 /* Static */ ) && (useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) diagnosticMessage = error2(right, Diagnostics.Property_0_is_used_before_its_initialization, declarationName); + else if (valueDeclaration.kind === 263 /* ClassDeclaration */ && node.parent.kind !== 183 /* TypeReference */ && !(valueDeclaration.flags & 33554432 /* Ambient */ ) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) diagnosticMessage = error2(right, Diagnostics.Class_0_used_before_its_declaration, declarationName); if (diagnosticMessage) addRelatedInfo(diagnosticMessage, createDiagnosticForNode(valueDeclaration, Diagnostics._0_is_declared_here, declarationName)); } function isInPropertyInitializerOrClassStaticBlock(node) { return !!findAncestor(node, (node2)=>{ switch(node2.kind){ - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : return true; - case 299 /* PropertyAssignment */ : - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 301 /* SpreadAssignment */ : - case 164 /* ComputedPropertyName */ : - case 236 /* TemplateSpan */ : - case 291 /* JsxExpression */ : - case 288 /* JsxAttribute */ : - case 289 /* JsxAttributes */ : - case 290 /* JsxSpreadAttribute */ : - case 283 /* JsxOpeningElement */ : - case 230 /* ExpressionWithTypeArguments */ : - case 294 /* HeritageClause */ : + case 303 /* PropertyAssignment */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 305 /* SpreadAssignment */ : + case 167 /* ComputedPropertyName */ : + case 239 /* TemplateSpan */ : + case 294 /* JsxExpression */ : + case 291 /* JsxAttribute */ : + case 292 /* JsxAttributes */ : + case 293 /* JsxSpreadAttribute */ : + case 286 /* JsxOpeningElement */ : + case 233 /* ExpressionWithTypeArguments */ : + case 298 /* HeritageClause */ : return false; - case 216 /* ArrowFunction */ : - case 241 /* ExpressionStatement */ : + case 219 /* ArrowFunction */ : + case 244 /* ExpressionStatement */ : return isBlock(node2.parent) && isClassStaticBlockDeclaration(node2.parent.parent) ? true : "quit"; default: return isExpressionNode(node2) ? false : "quit"; @@ -62164,7 +62809,7 @@ ${lanes.join("\n")} function reportNonexistentProperty(propNode, containingType, isUncheckedJS) { let errorInfo; let relatedInfo; - if (!isPrivateIdentifier(propNode) && containingType.flags & 1048576 /* Union */ && !(containingType.flags & 134348796 /* Primitive */ )) { + if (!isPrivateIdentifier(propNode) && containingType.flags & 1048576 /* Union */ && !(containingType.flags & 402784252 /* Primitive */ )) { for (const subtype of containingType.types)if (!getPropertyOfType(subtype, propNode.escapedText) && !getApplicableIndexInfoForName(subtype, propNode.escapedText)) { errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(propNode), typeToString(subtype)); break; @@ -62241,7 +62886,7 @@ ${lanes.join("\n")} const strName = isString(name) ? name : idText(name); const properties = getPropertiesOfType(containingType); const jsxSpecific = strName === "for" ? find(properties, (x)=>symbolName(x) === "htmlFor") : strName === "class" ? find(properties, (x)=>symbolName(x) === "className") : void 0; - return jsxSpecific != null ? jsxSpecific : getSpellingSuggestionForName(strName, properties, 111551 /* Value */ ); + return jsxSpecific ?? getSpellingSuggestionForName(strName, properties, 111551 /* Value */ ); } function getSuggestionForNonexistentProperty(name, containingType) { const suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -62327,25 +62972,25 @@ ${lanes.join("\n")} (getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */ ; } function isSelfTypeAccess(name, parent2) { - return name.kind === 108 /* ThisKeyword */ || !!parent2 && isEntityNameExpression(name) && parent2 === getResolvedSymbol(getFirstIdentifier(name)); + return name.kind === 110 /* ThisKeyword */ || !!parent2 && isEntityNameExpression(name) && parent2 === getResolvedSymbol(getFirstIdentifier(name)); } function isValidPropertyAccess(node, propertyName) { switch(node.kind){ - case 208 /* PropertyAccessExpression */ : - return isValidPropertyAccessWithType(node, node.expression.kind === 106 /* SuperKeyword */ , propertyName, getWidenedType(checkExpression(node.expression))); - case 163 /* QualifiedName */ : + case 211 /* PropertyAccessExpression */ : + return isValidPropertyAccessWithType(node, node.expression.kind === 108 /* SuperKeyword */ , propertyName, getWidenedType(checkExpression(node.expression))); + case 166 /* QualifiedName */ : return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left))); - case 202 /* ImportType */ : + case 205 /* ImportType */ : return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node)); } } function isValidPropertyAccessForCompletions(node, type, property) { - return isPropertyAccessible(node, node.kind === 208 /* PropertyAccessExpression */ && node.expression.kind === 106 /* SuperKeyword */ , /* isWrite */ false, type, property); + return isPropertyAccessible(node, node.kind === 211 /* PropertyAccessExpression */ && node.expression.kind === 108 /* SuperKeyword */ , /*isWrite*/ false, type, property); } function isValidPropertyAccessWithType(node, isSuper, propertyName, type) { if (isTypeAny(type)) return true; const prop = getPropertyOfType(type, propertyName); - return !!prop && isPropertyAccessible(node, isSuper, /* isWrite */ false, type, prop); + return !!prop && isPropertyAccessible(node, isSuper, /*isWrite*/ false, type, prop); } function isPropertyAccessible(node, isSuper, isWrite, containingType, property) { if (isTypeAny(containingType)) return true; @@ -62357,10 +63002,10 @@ ${lanes.join("\n")} } function getForInVariableSymbol(node) { const initializer = node.initializer; - if (initializer.kind === 258 /* VariableDeclarationList */ ) { + if (initializer.kind === 261 /* VariableDeclarationList */ ) { const variable = initializer.declarations[0]; if (variable && !isBindingPattern(variable.name)) return getSymbolOfDeclaration(variable); - } else if (initializer.kind === 79 /* Identifier */ ) return getResolvedSymbol(initializer); + } else if (initializer.kind === 80 /* Identifier */ ) return getResolvedSymbol(initializer); return void 0; } function hasNumericPropertyNames(type) { @@ -62368,13 +63013,13 @@ ${lanes.join("\n")} } function isForInVariableForNumericPropertyNames(expr) { const e = skipParentheses(expr); - if (e.kind === 79 /* Identifier */ ) { + if (e.kind === 80 /* Identifier */ ) { const symbol = getResolvedSymbol(e); if (symbol.flags & 3 /* Variable */ ) { let child = expr; let node = expr.parent; while(node){ - if (node.kind === 246 /* ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) return true; + if (node.kind === 249 /* ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) return true; child = node; node = node.parent; } @@ -62383,7 +63028,7 @@ ${lanes.join("\n")} return false; } function checkIndexedAccess(node, checkMode) { - return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node, checkMode) : checkElementAccessExpression(node, checkNonNullExpression(node.expression), checkMode); + return node.flags & 64 /* OptionalChain */ ? checkElementAccessChain(node, checkMode) : checkElementAccessExpression(node, checkNonNullExpression(node.expression), checkMode); } function checkElementAccessChain(node, checkMode) { const exprType = checkExpression(node.expression); @@ -62396,7 +63041,7 @@ ${lanes.join("\n")} const indexType = checkExpression(indexExpression); if (isErrorType(objectType) || objectType === silentNeverType) return objectType; if (isConstEnumObjectType(objectType) && !isStringLiteralLike(indexExpression)) { - error(indexExpression, Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); + error2(indexExpression, Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } const effectiveIndexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType; @@ -62409,9 +63054,9 @@ ${lanes.join("\n")} } function resolveUntypedCall(node) { if (callLikeExpressionMayHaveTypeArguments(node)) forEach(node.typeArguments, checkSourceElement); - if (node.kind === 212 /* TaggedTemplateExpression */ ) checkExpression(node.template); + if (node.kind === 215 /* TaggedTemplateExpression */ ) checkExpression(node.template); else if (isJsxOpeningLikeElement(node)) checkExpression(node.attributes); - else if (node.kind !== 167 /* Decorator */ ) forEach(node.arguments, (argument)=>{ + else if (node.kind !== 170 /* Decorator */ ) forEach(node.arguments, (argument)=>{ checkExpression(argument); }); return anySignature; @@ -62451,7 +63096,7 @@ ${lanes.join("\n")} } } function isSpreadArgument(arg) { - return !!arg && (arg.kind === 227 /* SpreadElement */ || arg.kind === 234 /* SyntheticExpression */ && arg.isSpread); + return !!arg && (arg.kind === 230 /* SpreadElement */ || arg.kind === 237 /* SyntheticExpression */ && arg.isSpread); } function getSpreadArgumentIndex(args) { return findIndex(args, isSpreadArgument); @@ -62467,17 +63112,17 @@ ${lanes.join("\n")} let callIsIncomplete = false; let effectiveParameterCount = getParameterCount(signature); let effectiveMinimumArguments = getMinArgumentCount(signature); - if (node.kind === 212 /* TaggedTemplateExpression */ ) { + if (node.kind === 215 /* TaggedTemplateExpression */ ) { argCount = args.length; - if (node.template.kind === 225 /* TemplateExpression */ ) { + if (node.template.kind === 228 /* TemplateExpression */ ) { const lastSpan = last(node.template.templateSpans); callIsIncomplete = nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; } else { const templateLiteral = node.template; - Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */ ); + Debug.assert(templateLiteral.kind === 15 /* NoSubstitutionTemplateLiteral */ ); callIsIncomplete = !!templateLiteral.isUnterminated; } - } else if (node.kind === 167 /* Decorator */ ) argCount = getDecoratorArgumentCount(node, signature); + } else if (node.kind === 170 /* Decorator */ ) argCount = getDecoratorArgumentCount(node, signature); else if (isJsxOpeningLikeElement(node)) { callIsIncomplete = node.attributes.end === node.end; if (callIsIncomplete) return true; @@ -62485,7 +63130,7 @@ ${lanes.join("\n")} effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); } else if (!node.arguments) { - Debug.assert(node.kind === 211 /* NewExpression */ ); + Debug.assert(node.kind === 214 /* NewExpression */ ); return getMinArgumentCount(signature) === 0; } else { argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; @@ -62548,7 +63193,7 @@ ${lanes.join("\n")} } function inferTypeArguments(node, signature, args, checkMode, context) { if (isJsxOpeningLikeElement(node)) return inferJsxTypeArguments(node, signature, checkMode, context); - if (node.kind !== 167 /* Decorator */ ) { + if (node.kind !== 170 /* Decorator */ ) { const skipBindingPatterns = every(signature.typeParameters, (p)=>!!getDefaultFromTypeParameter(p)); const contextualType = getContextualType2(node, skipBindingPatterns ? 8 /* SkipBindingPatterns */ : 0 /* None */ ); if (contextualType) { @@ -62583,7 +63228,7 @@ ${lanes.join("\n")} } for(let i = 0; i < argCount; i++){ const arg = args[i]; - if (arg.kind !== 229 /* OmittedExpression */ && !(checkMode & 32 /* IsForStringLiteralArgumentCompletions */ && hasSkipDirectInferenceFlag(arg))) { + if (arg.kind !== 232 /* OmittedExpression */ ) { const paramType = getTypeAtPosition(signature, i); if (couldContainTypeVariables(paramType)) { const argType = checkExpressionWithContextualType(arg, paramType, context, checkMode); @@ -62598,40 +63243,44 @@ ${lanes.join("\n")} return getInferredTypes(context); } function getMutableArrayOrTupleType(type) { - return type.flags & 1048576 /* Union */ ? mapType(type, getMutableArrayOrTupleType) : type.flags & 1 /* Any */ || isMutableArrayOrTuple(getBaseConstraintOfType(type) || type) ? type : isTupleType(type) ? createTupleType(getTypeArguments(type), type.target.elementFlags, /*readonly*/ false, type.target.labeledElementDeclarations) : createTupleType([ + return type.flags & 1048576 /* Union */ ? mapType(type, getMutableArrayOrTupleType) : type.flags & 1 /* Any */ || isMutableArrayOrTuple(getBaseConstraintOfType(type) || type) ? type : isTupleType(type) ? createTupleType(getElementTypes(type), type.target.elementFlags, /*readonly*/ false, type.target.labeledElementDeclarations) : createTupleType([ type ], [ 8 /* Variadic */ ]); } function getSpreadArgumentType(args, index, argCount, restType, context, checkMode) { + const inConstContext = isConstTypeVariable(restType); if (index >= argCount - 1) { const arg = args[argCount - 1]; - if (isSpreadArgument(arg)) return getMutableArrayOrTupleType(arg.kind === 234 /* SyntheticExpression */ ? arg.type : checkExpressionWithContextualType(arg.expression, restType, context, checkMode)); + if (isSpreadArgument(arg)) { + const spreadType = arg.kind === 237 /* SyntheticExpression */ ? arg.type : checkExpressionWithContextualType(arg.expression, restType, context, checkMode); + if (isArrayLikeType(spreadType)) return getMutableArrayOrTupleType(spreadType); + return createArrayType(checkIteratedTypeOrElementType(33 /* Spread */ , spreadType, undefinedType, arg.kind === 230 /* SpreadElement */ ? arg.expression : arg), inConstContext); + } } const types = []; const flags = []; const names = []; - const inConstContext = isConstTypeVariable(restType); for(let i = index; i < argCount; i++){ const arg = args[i]; if (isSpreadArgument(arg)) { - const spreadType = arg.kind === 234 /* SyntheticExpression */ ? arg.type : checkExpression(arg.expression); + const spreadType = arg.kind === 237 /* SyntheticExpression */ ? arg.type : checkExpression(arg.expression); if (isArrayLikeType(spreadType)) { types.push(spreadType); flags.push(8 /* Variadic */ ); } else { - types.push(checkIteratedTypeOrElementType(33 /* Spread */ , spreadType, undefinedType, arg.kind === 227 /* SpreadElement */ ? arg.expression : arg)); + types.push(checkIteratedTypeOrElementType(33 /* Spread */ , spreadType, undefinedType, arg.kind === 230 /* SpreadElement */ ? arg.expression : arg)); flags.push(4 /* Rest */ ); } } else { - const contextualType = getIndexedAccessType(restType, getNumberLiteralType(i - index), 256 /* Contextual */ ); + const contextualType = isTupleType(restType) ? getContextualTypeForElementExpression(restType, i - index, argCount - index) || unknownType : getIndexedAccessType(restType, getNumberLiteralType(i - index), 256 /* Contextual */ ); const argType = checkExpressionWithContextualType(arg, contextualType, context, checkMode); const hasPrimitiveContextualType = inConstContext || maybeTypeOfKind(contextualType, 406978556 /* StringMapping */ ); types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); flags.push(1 /* Required */ ); } - if (arg.kind === 234 /* SyntheticExpression */ && arg.tupleNameSource) names.push(arg.tupleNameSource); + if (arg.kind === 237 /* SyntheticExpression */ && arg.tupleNameSource) names.push(arg.tupleNameSource); } return createTupleType(types, flags, inConstContext, length(names) === length(types) ? names : void 0); } @@ -62654,7 +63303,7 @@ ${lanes.join("\n")} return typeArgumentTypes; } function getJsxReferenceKind(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) return 2 /* Mixed */ ; + if (isJsxIntrinsicTagName(node.tagName)) return 2 /* Mixed */ ; const tagType = getApparentType(checkExpression(node.tagName)); if (length(getSignaturesOfType(tagType, 1 /* Construct */ ))) return 0 /* Component */ ; if (length(getSignaturesOfType(tagType, 0 /* Call */ ))) return 1 /* Function */ ; @@ -62663,11 +63312,12 @@ ${lanes.join("\n")} function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors2, containingMessageChain, errorOutputContainer) { const paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); const attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ void 0, checkMode); - return checkTagNameDoesNotExpectTooManyArguments() && checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors2 ? node.tagName : void 0, node.attributes, /*headMessage*/ void 0, containingMessageChain, errorOutputContainer); + const checkAttributesType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(attributesType) : attributesType; + return checkTagNameDoesNotExpectTooManyArguments() && checkTypeRelatedToAndOptionallyElaborate(checkAttributesType, paramType, relation, reportErrors2 ? node.tagName : void 0, node.attributes, /*headMessage*/ void 0, containingMessageChain, errorOutputContainer); function checkTagNameDoesNotExpectTooManyArguments() { - var _a2; + var _a; if (getJsxNamespaceContainerForImplicitImport(node)) return true; - const tagType = isJsxOpeningElement(node) || isJsxSelfClosingElement(node) && !isJsxIntrinsicIdentifier(node.tagName) ? checkExpression(node.tagName) : void 0; + const tagType = (isJsxOpeningElement(node) || isJsxSelfClosingElement(node)) && !(isJsxIntrinsicTagName(node.tagName) || isJsxNamespacedName(node.tagName)) ? checkExpression(node.tagName) : void 0; if (!tagType) return true; const tagCallSignatures = getSignaturesOfType(tagType, 0 /* Call */ ); if (!length(tagCallSignatures)) return true; @@ -62700,7 +63350,7 @@ ${lanes.join("\n")} if (absoluteMinArgCount <= maxParamCount) return true; if (reportErrors2) { const diag2 = createDiagnosticForNode(node.tagName, Diagnostics.Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3, entityNameToString(node.tagName), absoluteMinArgCount, entityNameToString(factory2), maxParamCount); - const tagNameDeclaration = (_a2 = getSymbolAtLocation(node.tagName)) == null ? void 0 : _a2.valueDeclaration; + const tagNameDeclaration = (_a = getSymbolAtLocation(node.tagName)) == null ? void 0 : _a.valueDeclaration; if (tagNameDeclaration) addRelatedInfo(diag2, createDiagnosticForNode(tagNameDeclaration, Diagnostics._0_is_declared_here, entityNameToString(node.tagName))); if (errorOutputContainer && errorOutputContainer.skipLogging) (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag2); if (!errorOutputContainer.skipLogging) diagnostics.add(diag2); @@ -62736,7 +63386,7 @@ ${lanes.join("\n")} const argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for(let i = 0; i < argCount; i++){ const arg = args[i]; - if (arg.kind !== 229 /* OmittedExpression */ ) { + if (arg.kind !== 232 /* OmittedExpression */ ) { const paramType = getTypeAtPosition(signature, i); const argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ void 0, checkMode); const checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType; @@ -62767,7 +63417,7 @@ ${lanes.join("\n")} } } function getThisArgumentOfCall(node) { - const expression = node.kind === 210 /* CallExpression */ ? node.expression : node.kind === 212 /* TaggedTemplateExpression */ ? node.tag : void 0; + const expression = node.kind === 213 /* CallExpression */ ? node.expression : node.kind === 215 /* TaggedTemplateExpression */ ? node.tag : node.kind === 170 /* Decorator */ && !legacyDecorators ? node.expression : void 0; if (expression) { const callee = skipOuterExpressions(expression); if (isAccessExpression(callee)) return callee.expression; @@ -62780,17 +63430,17 @@ ${lanes.join("\n")} return result; } function getEffectiveCallArguments(node) { - if (node.kind === 212 /* TaggedTemplateExpression */ ) { + if (node.kind === 215 /* TaggedTemplateExpression */ ) { const template = node.template; const args2 = [ createSyntheticExpression(template, getGlobalTemplateStringsArrayType()) ]; - if (template.kind === 225 /* TemplateExpression */ ) forEach(template.templateSpans, (span)=>{ + if (template.kind === 228 /* TemplateExpression */ ) forEach(template.templateSpans, (span)=>{ args2.push(span.expression); }); return args2; } - if (node.kind === 167 /* Decorator */ ) return getEffectiveDecoratorArguments(node); + if (node.kind === 170 /* Decorator */ ) return getEffectiveDecoratorArguments(node); if (isJsxOpeningLikeElement(node)) return node.attributes.properties.length > 0 || isJsxOpeningElement(node) && node.parent.children.length > 0 ? [ node.attributes ] : emptyArray; @@ -62800,11 +63450,11 @@ ${lanes.join("\n")} const effectiveArgs = args.slice(0, spreadIndex); for(let i = spreadIndex; i < args.length; i++){ const arg = args[i]; - const spreadType = arg.kind === 227 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); - if (spreadType && isTupleType(spreadType)) forEach(getTypeArguments(spreadType), (t, i2)=>{ - var _a2; + const spreadType = arg.kind === 230 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); + if (spreadType && isTupleType(spreadType)) forEach(getElementTypes(spreadType), (t, i2)=>{ + var _a; const flags = spreadType.target.elementFlags[i2]; - const syntheticArg = createSyntheticExpression(arg, flags & 4 /* Rest */ ? createArrayType(t) : t, !!(flags & 12 /* Variable */ ), (_a2 = spreadType.target.labeledElementDeclarations) == null ? void 0 : _a2[i2]); + const syntheticArg = createSyntheticExpression(arg, flags & 4 /* Rest */ ? createArrayType(t) : t, !!(flags & 12 /* Variable */ ), (_a = spreadType.target.labeledElementDeclarations) == null ? void 0 : _a[i2]); effectiveArgs.push(syntheticArg); }); else effectiveArgs.push(arg); @@ -62831,16 +63481,16 @@ ${lanes.join("\n")} } function getLegacyDecoratorArgumentCount(node, signature) { switch(node.parent.kind){ - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : return 1; - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : return hasAccessorModifier(node.parent) ? 3 : 2; - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; - case 166 /* Parameter */ : + case 169 /* Parameter */ : return 3; default: return Debug.fail(); @@ -62865,19 +63515,19 @@ ${lanes.join("\n")} sourceFile: sourceFile }; } - function getDiagnosticForCallNode(node, message, arg0, arg1, arg2, arg3) { + function getDiagnosticForCallNode(node, message, ...args) { if (isCallExpression(node)) { - const { sourceFile: sourceFile , start: start , length: length2 } = getDiagnosticSpanForCallNode(node); - if ("message" in message) return createFileDiagnostic(sourceFile, start, length2, message, arg0, arg1, arg2, arg3); + const { sourceFile: sourceFile, start: start, length: length2 } = getDiagnosticSpanForCallNode(node); + if ("message" in message) return createFileDiagnostic(sourceFile, start, length2, message, ...args); return createDiagnosticForFileFromMessageChain(sourceFile, message); } else { - if ("message" in message) return createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3); + if ("message" in message) return createDiagnosticForNode(node, message, ...args); return createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(node), node, message); } } function isPromiseResolveArityError(node) { if (!isCallExpression(node) || !isIdentifier(node.expression)) return false; - const symbol = resolveName(node.expression, node.expression.escapedText, 111551 /* Value */ , void 0, void 0, false); + const symbol = resolveName(node.expression, node.expression.escapedText, 111551 /* Value */ , /*nameNotFoundMessage*/ void 0, /*nameArg*/ void 0, /*isUse*/ false); const decl = symbol == null ? void 0 : symbol.valueDeclaration; if (!decl || !isParameter(decl) || !isFunctionExpressionOrArrowFunction(decl.parent) || !isNewExpression(decl.parent.parent) || !isIdentifier(decl.parent.parent.expression)) return false; const globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); @@ -62886,7 +63536,7 @@ ${lanes.join("\n")} return constructorSymbol === globalPromiseSymbol; } function getArgumentArityError(node, signatures, args, headMessage) { - var _a2; + var _a; const spreadIndex = getSpreadArgumentIndex(args); if (spreadIndex > -1) return createDiagnosticForNode(args[spreadIndex], Diagnostics.A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter); let min2 = Number.POSITIVE_INFINITY; @@ -62909,7 +63559,7 @@ ${lanes.join("\n")} const parameterRange = hasRestParameter2 ? min2 : min2 < max ? min2 + "-" + max : min2; const isVoidPromiseError = !hasRestParameter2 && parameterRange === 1 && args.length === 0 && isPromiseResolveArityError(node); if (isVoidPromiseError && isInJSFile(node)) return getDiagnosticForCallNode(node, Diagnostics.Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_without_arguments); - const error2 = isDecorator(node) ? hasRestParameter2 ? Diagnostics.The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_at_least_0 : Diagnostics.The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_0 : hasRestParameter2 ? Diagnostics.Expected_at_least_0_arguments_but_got_1 : isVoidPromiseError ? Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise : Diagnostics.Expected_0_arguments_but_got_1; + const error3 = isDecorator(node) ? hasRestParameter2 ? Diagnostics.The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_at_least_0 : Diagnostics.The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_0 : hasRestParameter2 ? Diagnostics.Expected_at_least_0_arguments_but_got_1 : isVoidPromiseError ? Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise : Diagnostics.Expected_0_arguments_but_got_1; if (min2 < args.length && args.length < max) { if (headMessage) { let chain = chainDiagnosticMessages(/*details*/ void 0, Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, args.length, maxBelow, minAbove); @@ -62920,13 +63570,22 @@ ${lanes.join("\n")} } else if (args.length < min2) { let diagnostic; if (headMessage) { - let chain = chainDiagnosticMessages(/*details*/ void 0, error2, parameterRange, args.length); + let chain = chainDiagnosticMessages(/*details*/ void 0, error3, parameterRange, args.length); chain = chainDiagnosticMessages(chain, headMessage); diagnostic = getDiagnosticForCallNode(node, chain); - } else diagnostic = getDiagnosticForCallNode(node, error2, parameterRange, args.length); - const parameter = (_a2 = closestSignature == null ? void 0 : closestSignature.declaration) == null ? void 0 : _a2.parameters[closestSignature.thisParameter ? args.length + 1 : args.length]; + } else diagnostic = getDiagnosticForCallNode(node, error3, parameterRange, args.length); + const parameter = (_a = closestSignature == null ? void 0 : closestSignature.declaration) == null ? void 0 : _a.parameters[closestSignature.thisParameter ? args.length + 1 : args.length]; if (parameter) { - const parameterError = createDiagnosticForNode(parameter, isBindingPattern(parameter.name) ? Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : isRestParameter(parameter) ? Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided : Diagnostics.An_argument_for_0_was_not_provided, !parameter.name ? args.length : !isBindingPattern(parameter.name) ? idText(getFirstIdentifier(parameter.name)) : void 0); + const messageAndArgs = isBindingPattern(parameter.name) ? [ + Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided + ] : isRestParameter(parameter) ? [ + Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided, + idText(getFirstIdentifier(parameter.name)) + ] : [ + Diagnostics.An_argument_for_0_was_not_provided, + !parameter.name ? args.length : idText(getFirstIdentifier(parameter.name)) + ]; + const parameterError = createDiagnosticForNode(parameter, ...messageAndArgs); return addRelatedInfo(diagnostic, parameterError); } return diagnostic; @@ -62937,11 +63596,11 @@ ${lanes.join("\n")} if (end === pos) end++; setTextRangePosEnd(errorSpan, pos, end); if (headMessage) { - let chain = chainDiagnosticMessages(/*details*/ void 0, error2, parameterRange, args.length); + let chain = chainDiagnosticMessages(/*details*/ void 0, error3, parameterRange, args.length); chain = chainDiagnosticMessages(chain, headMessage); return createDiagnosticForNodeArrayFromMessageChain(getSourceFileOfNode(node), errorSpan, chain); } - return createDiagnosticForNodeArray(getSourceFileOfNode(node), errorSpan, error2, parameterRange, args.length); + return createDiagnosticForNodeArray(getSourceFileOfNode(node), errorSpan, error3, parameterRange, args.length); } } function getTypeArgumentArityError(node, signatures, typeArguments, headMessage) { @@ -62981,30 +63640,26 @@ ${lanes.join("\n")} return createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, headMessage) { - const isTaggedTemplate = node.kind === 212 /* TaggedTemplateExpression */ ; - const isDecorator2 = node.kind === 167 /* Decorator */ ; + const isTaggedTemplate = node.kind === 215 /* TaggedTemplateExpression */ ; + const isDecorator2 = node.kind === 170 /* Decorator */ ; const isJsxOpeningOrSelfClosingElement = isJsxOpeningLikeElement(node); const reportErrors2 = !isInferencePartiallyBlocked && !candidatesOutArray; let typeArguments; if (!isDecorator2 && !isSuperCall(node)) { typeArguments = node.typeArguments; - if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 106 /* SuperKeyword */ ) forEach(typeArguments, checkSourceElement); + if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 108 /* SuperKeyword */ ) forEach(typeArguments, checkSourceElement); } const candidates = candidatesOutArray || []; reorderCandidates(signatures, candidates, callChainFlags); - if (!candidates.length) { - if (reportErrors2) diagnostics.add(getDiagnosticForCallNode(node, Diagnostics.Call_target_does_not_contain_any_signatures)); - return resolveErrorCall(node); - } + Debug.assert(candidates.length, "Revert #54442 and add a testcase with whatever triggered this"); const args = getEffectiveCallArguments(node); const isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; let argCheckMode = !isDecorator2 && !isSingleNonGenericCandidate && some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */ ; - argCheckMode |= checkMode & 32 /* IsForStringLiteralArgumentCompletions */ ; let candidatesForArgumentError; let candidateForArgumentArityError; let candidateForTypeArgumentError; let result; - const signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */ ) && node.kind === 210 /* CallExpression */ && node.arguments.hasTrailingComma; + const signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */ ) && node.kind === 213 /* CallExpression */ && node.arguments.hasTrailingComma; if (candidates.length > 1) result = chooseOverload(candidates, subtypeRelation, isSingleNonGenericCandidate, signatureHelpTrailingComma); if (!result) result = chooseOverload(candidates, assignableRelation, isSingleNonGenericCandidate, signatureHelpTrailingComma); if (result) return result; @@ -63055,7 +63710,7 @@ ${lanes.join("\n")} ]; let diag2; if (every(diags, (d)=>d.start === diags[0].start && d.length === diags[0].length && d.file === diags[0].file)) { - const { file: file , start: start , length: length2 } = diags[0]; + const { file: file, start: start, length: length2 } = diags[0]; diag2 = { file: file, start: start, @@ -63081,11 +63736,11 @@ ${lanes.join("\n")} } return result; function addImplementationSuccessElaboration(failed, diagnostic) { - var _a2, _b; + var _a, _b; const oldCandidatesForArgumentError = candidatesForArgumentError; const oldCandidateForArgumentArityError = candidateForArgumentArityError; const oldCandidateForTypeArgumentError = candidateForTypeArgumentError; - const failedSignatureDeclarations = ((_b = (_a2 = failed.declaration) == null ? void 0 : _a2.symbol) == null ? void 0 : _b.declarations) || emptyArray; + const failedSignatureDeclarations = ((_b = (_a = failed.declaration) == null ? void 0 : _a.symbol) == null ? void 0 : _b.declarations) || emptyArray; const isOverload = failedSignatureDeclarations.length > 1; const implDecl = isOverload ? find(failedSignatureDeclarations, (d)=>isFunctionLikeDeclaration(d) && nodeIsPresent(d.body)) : void 0; if (implDecl) { @@ -63143,7 +63798,7 @@ ${lanes.join("\n")} continue; } if (argCheckMode) { - argCheckMode = checkMode & 32 /* IsForStringLiteralArgumentCompletions */ ; + argCheckMode = 0 /* Normal */ ; if (inferenceContext) { const typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext); checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, isInJSFile(candidate.declaration), inferenceContext.inferredTypeParameters); @@ -63172,7 +63827,7 @@ ${lanes.join("\n")} const thisParameters = mapDefined(candidates, (c)=>c.thisParameter); let thisParameter; if (thisParameters.length) thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter)); - const { min: minArgumentCount , max: maxNonRestParam } = minAndMax(candidates, getNumNonRestParameters); + const { min: minArgumentCount, max: maxNonRestParam } = minAndMax(candidates, getNumNonRestParameters); const parameters = []; for(let i = 0; i < maxNonRestParam; i++){ const symbols = mapDefined(candidates, (s)=>signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : last(s.parameters) : i < s.parameters.length ? s.parameters[i] : void 0); @@ -63180,7 +63835,7 @@ ${lanes.join("\n")} parameters.push(createCombinedSymbolFromTypes(symbols, mapDefined(candidates, (candidate)=>tryGetTypeAtPosition(candidate, i)))); } const restParameterSymbols = mapDefined(candidates, (c)=>signatureHasRestParameter(c) ? last(c.parameters) : void 0); - let flags = 0 /* None */ ; + let flags = 128 /* IsSignatureCandidateForOverloadFailure */ ; if (restParameterSymbols.length !== 0) { const type = createArrayType(getUnionType(mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */ )); parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); @@ -63188,7 +63843,7 @@ ${lanes.join("\n")} } if (candidates.some(signatureHasLiteralTypes)) flags |= 2 /* HasLiteralTypes */ ; return createSignature(candidates[0].declaration, /*typeParameters*/ void 0, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. - thisParameter, parameters, /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), /*typePredicate*/ void 0, minArgumentCount, flags); + thisParameter, parameters, /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), /*resolvedTypePredicate*/ void 0, minArgumentCount, flags); } function getNumNonRestParameters(signature) { const numParams = signature.parameters.length; @@ -63203,7 +63858,7 @@ ${lanes.join("\n")} function pickLongestCandidateSignature(node, candidates, args, checkMode) { const bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === void 0 ? args.length : apparentArgumentCount); const candidate = candidates[bestIndex]; - const { typeParameters: typeParameters } = candidate; + const { typeParameters: typeParameters } = candidate; if (!typeParameters) return candidate; const typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : void 0; const instantiated = typeArgumentNodes ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isInJSFile(node))) : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args, checkMode); @@ -63236,7 +63891,7 @@ ${lanes.join("\n")} return maxParamsIndex; } function resolveCallExpression(node, candidatesOutArray, checkMode) { - if (node.expression.kind === 106 /* SuperKeyword */ ) { + if (node.expression.kind === 108 /* SuperKeyword */ ) { const superType = checkSuperExpression(node.expression); if (isTypeAny(superType)) { for (const arg of node.arguments)checkExpression(arg); @@ -63265,16 +63920,16 @@ ${lanes.join("\n")} const callSignatures = getSignaturesOfType(apparentType, 0 /* Call */ ); const numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */ ).length; if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { - if (!isErrorType(funcType) && node.typeArguments) error(node, Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + if (!isErrorType(funcType) && node.typeArguments) error2(node, Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); return resolveUntypedCall(node); } if (!callSignatures.length) { - if (numConstructSignatures) error(node, Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + if (numConstructSignatures) error2(node, Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); else { let relatedInformation; if (node.arguments.length === 1) { const text = getSourceFileOfNode(node).text; - if (isLineBreak(text.charCodeAt(skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) relatedInformation = createDiagnosticForNode(node.expression, Diagnostics.Are_you_missing_a_semicolon); + if (isLineBreak(text.charCodeAt(skipTrivia(text, node.expression.end, /*stopAfterLineBreak*/ true) - 1))) relatedInformation = createDiagnosticForNode(node.expression, Diagnostics.Are_you_missing_a_semicolon); } invocationError(node.expression, apparentType, 0 /* Call */ , relatedInformation); } @@ -63285,7 +63940,7 @@ ${lanes.join("\n")} return resolvingSignature; } if (callSignatures.some((sig)=>isInJSFile(sig.declaration) && !!getJSDocClassTag(sig.declaration))) { - error(node, Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + error2(node, Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray, checkMode, callChainFlags); @@ -63299,26 +63954,26 @@ ${lanes.join("\n")} function resolveNewExpression(node, candidatesOutArray, checkMode) { if (node.arguments && languageVersion < 1 /* ES5 */ ) { const spreadIndex = getSpreadArgumentIndex(node.arguments); - if (spreadIndex >= 0) error(node.arguments[spreadIndex], Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); + if (spreadIndex >= 0) error2(node.arguments[spreadIndex], Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); } let expressionType = checkNonNullExpression(node.expression); if (expressionType === silentNeverType) return silentNeverSignature; expressionType = getApparentType(expressionType); if (isErrorType(expressionType)) return resolveErrorCall(node); if (isTypeAny(expressionType)) { - if (node.typeArguments) error(node, Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + if (node.typeArguments) error2(node, Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); return resolveUntypedCall(node); } const constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */ ); if (constructSignatures.length) { if (!isConstructorAccessible(node, constructSignatures[0])) return resolveErrorCall(node); if (someSignature(constructSignatures, (signature)=>!!(signature.flags & 4 /* Abstract */ ))) { - error(node, Diagnostics.Cannot_create_an_instance_of_an_abstract_class); + error2(node, Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } const valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && hasSyntacticModifier(valueDecl, 256 /* Abstract */ )) { - error(node, Diagnostics.Cannot_create_an_instance_of_an_abstract_class); + error2(node, Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0 /* None */ ); @@ -63327,8 +63982,8 @@ ${lanes.join("\n")} if (callSignatures.length) { const signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */ ); if (!noImplicitAny) { - if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) error(node, Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - if (getThisTypeOfSignature(signature) === voidType) error(node, Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) error2(node, Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + if (getThisTypeOfSignature(signature) === voidType) error2(node, Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); } return signature; } @@ -63365,7 +64020,7 @@ ${lanes.join("\n")} if (!signature || !signature.declaration) return true; const declaration = signature.declaration; const modifiers = getSelectedEffectiveModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */ ); - if (!modifiers || declaration.kind !== 173 /* Constructor */ ) return true; + if (!modifiers || declaration.kind !== 176 /* Constructor */ ) return true; const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); const declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); if (!isNodeWithinClass(node, declaringClassDeclaration)) { @@ -63374,8 +64029,8 @@ ${lanes.join("\n")} const containingType = getTypeOfNode(containingClass); if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) return true; } - if (modifiers & 8 /* Private */ ) error(node, Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); - if (modifiers & 16 /* Protected */ ) error(node, Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + if (modifiers & 8 /* Private */ ) error2(node, Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + if (modifiers & 16 /* Protected */ ) error2(node, Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); return false; } return true; @@ -63401,12 +64056,12 @@ ${lanes.join("\n")} if (hasSignatures) break; } } - if (!hasSignatures) errorInfo = chainDiagnosticMessages(/* detials */ void 0, isCall ? Diagnostics.No_constituent_of_type_0_is_callable : Diagnostics.No_constituent_of_type_0_is_constructable, typeToString(apparentType)); + if (!hasSignatures) errorInfo = chainDiagnosticMessages(/*details*/ void 0, isCall ? Diagnostics.No_constituent_of_type_0_is_callable : Diagnostics.No_constituent_of_type_0_is_constructable, typeToString(apparentType)); if (!errorInfo) errorInfo = chainDiagnosticMessages(errorInfo, isCall ? Diagnostics.Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other : Diagnostics.Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other, typeToString(apparentType)); } else errorInfo = chainDiagnosticMessages(errorInfo, isCall ? Diagnostics.Type_0_has_no_call_signatures : Diagnostics.Type_0_has_no_construct_signatures, typeToString(apparentType)); let headMessage = isCall ? Diagnostics.This_expression_is_not_callable : Diagnostics.This_expression_is_not_constructable; if (isCallExpression(errorTarget.parent) && errorTarget.parent.arguments.length === 0) { - const { resolvedSymbol: resolvedSymbol } = getNodeLinks(errorTarget); + const { resolvedSymbol: resolvedSymbol } = getNodeLinks(errorTarget); if (resolvedSymbol && resolvedSymbol.flags & 32768 /* GetAccessor */ ) headMessage = Diagnostics.This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without; } return { @@ -63415,11 +64070,11 @@ ${lanes.join("\n")} }; } function invocationError(errorTarget, apparentType, kind, relatedInformation) { - const { messageChain: messageChain , relatedMessage: relatedInfo } = invocationErrorDetails(errorTarget, apparentType, kind); + const { messageChain: messageChain, relatedMessage: relatedInfo } = invocationErrorDetails(errorTarget, apparentType, kind); const diagnostic = createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(errorTarget), errorTarget, messageChain); if (relatedInfo) addRelatedInfo(diagnostic, createDiagnosticForNode(errorTarget, relatedInfo)); if (isCallExpression(errorTarget.parent)) { - const { start: start , length: length2 } = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true); + const { start: start, length: length2 } = getDiagnosticSpanForCallNode(errorTarget.parent, /*doNotIncludeArguments*/ true); diagnostic.start = start; diagnostic.length = length2; } @@ -63455,16 +64110,16 @@ ${lanes.join("\n")} } function getDiagnosticHeadMessageForDecoratorResolution(node) { switch(node.parent.kind){ - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : return Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 166 /* Parameter */ : + case 169 /* Parameter */ : return Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : return Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : return Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; default: return Debug.fail(); @@ -63479,7 +64134,7 @@ ${lanes.join("\n")} if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) return resolveUntypedCall(node); if (isPotentiallyUncalledDecorator(node, callSignatures) && !isParenthesizedExpression(node.expression)) { const nodeStr = getTextOfNode(node.expression, /*includeTrivia*/ false); - error(node, Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr); + error2(node, Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr); return resolveErrorCall(node); } const headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); @@ -63500,16 +64155,16 @@ ${lanes.join("\n")} const typeSymbol = exports && getSymbol2(exports, JsxNames.Element, 788968 /* Type */ ); const returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* Type */ , node); const declaration = factory.createFunctionTypeNode(/*typeParameters*/ void 0, [ - factory.createParameterDeclaration(/*modifiers*/ void 0, /*dotdotdot*/ void 0, "props", /*questionMark*/ void 0, nodeBuilder.typeToTypeNode(result, node)) - ], returnNode ? factory.createTypeReferenceNode(returnNode, /*typeArguments*/ void 0) : factory.createKeywordTypeNode(131 /* AnyKeyword */ )); + factory.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, "props", /*questionToken*/ void 0, nodeBuilder.typeToTypeNode(result, node)) + ], returnNode ? factory.createTypeReferenceNode(returnNode, /*typeArguments*/ void 0) : factory.createKeywordTypeNode(133 /* AnyKeyword */ )); const parameterSymbol = createSymbol(1 /* FunctionScopedVariable */ , "props"); parameterSymbol.links.type = result; return createSignature(declaration, /*typeParameters*/ void 0, /*thisParameter*/ void 0, [ parameterSymbol - ], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, /*returnTypePredicate*/ void 0, 1, 0 /* None */ ); + ], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, /*resolvedTypePredicate*/ void 0, 1, 0 /* None */ ); } function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) { - if (isJsxIntrinsicIdentifier(node.tagName)) { + if (isJsxIntrinsicTagName(node.tagName)) { const result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); const fakeSignature = createSignatureForJSXIntrinsic(node, result); checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*inferenceContext*/ void 0, 0 /* Normal */ ), result, node.tagName, node.attributes); @@ -63525,7 +64180,7 @@ ${lanes.join("\n")} const signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node); if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) return resolveUntypedCall(node); if (signatures.length === 0) { - error(node.tagName, Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, getTextOfNode(node.tagName)); + error2(node.tagName, Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, getTextOfNode(node.tagName)); return resolveErrorCall(node); } return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */ ); @@ -63535,43 +64190,46 @@ ${lanes.join("\n")} } function resolveSignature(node, candidatesOutArray, checkMode) { switch(node.kind){ - case 210 /* CallExpression */ : + case 213 /* CallExpression */ : return resolveCallExpression(node, candidatesOutArray, checkMode); - case 211 /* NewExpression */ : + case 214 /* NewExpression */ : return resolveNewExpression(node, candidatesOutArray, checkMode); - case 212 /* TaggedTemplateExpression */ : + case 215 /* TaggedTemplateExpression */ : return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode); - case 167 /* Decorator */ : + case 170 /* Decorator */ : return resolveDecorator(node, candidatesOutArray, checkMode); - case 283 /* JsxOpeningElement */ : - case 282 /* JsxSelfClosingElement */ : + case 286 /* JsxOpeningElement */ : + case 285 /* JsxSelfClosingElement */ : return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode); } - throw Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); + Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } function getResolvedSignature(node, candidatesOutArray, checkMode) { const links = getNodeLinks(node); const cached = links.resolvedSignature; if (cached && cached !== resolvingSignature && !candidatesOutArray) return cached; links.resolvedSignature = resolvingSignature; - const result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */ ); - if (result !== resolvingSignature) links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; + let result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */ ); + if (result !== resolvingSignature) { + if (links.resolvedSignature !== resolvingSignature) result = links.resolvedSignature; + links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; + } return result; } function isJSConstructor(node) { - var _a2; + var _a; if (!node || !isInJSFile(node)) return false; const func = isFunctionDeclaration(node) || isFunctionExpression(node) ? node : (isVariableDeclaration(node) || isPropertyAssignment(node)) && node.initializer && isFunctionExpression(node.initializer) ? node.initializer : void 0; if (func) { if (getJSDocClassTag(node)) return true; if (isPropertyAssignment(walkUpParenthesizedExpressions(func.parent))) return false; const symbol = getSymbolOfDeclaration(func); - return !!((_a2 = symbol == null ? void 0 : symbol.members) == null ? void 0 : _a2.size); + return !!((_a = symbol == null ? void 0 : symbol.members) == null ? void 0 : _a.size); } return false; } function mergeJSSymbols(target, source) { - var _a2, _b; + var _a, _b; if (source) { const links = getSymbolLinks(source); if (!links.inferredClassSymbol || !links.inferredClassSymbol.has(getSymbolId(target))) { @@ -63579,7 +64237,7 @@ ${lanes.join("\n")} inferred.exports = inferred.exports || createSymbolTable(); inferred.members = inferred.members || createSymbolTable(); inferred.flags |= source.flags & 32 /* Class */ ; - if ((_a2 = source.exports) == null ? void 0 : _a2.size) mergeSymbolTable(inferred.exports, source.exports); + if ((_a = source.exports) == null ? void 0 : _a.size) mergeSymbolTable(inferred.exports, source.exports); if ((_b = source.members) == null ? void 0 : _b.size) mergeSymbolTable(inferred.members, source.members); (links.inferredClassSymbol || (links.inferredClassSymbol = /* @__PURE__ */ new Map())).set(getSymbolId(inferred), inferred); return inferred; @@ -63588,9 +64246,9 @@ ${lanes.join("\n")} } } function getAssignedClassSymbol(decl) { - var _a2; + var _a; const assignmentSymbol = decl && getSymbolOfExpando(decl, /*allowDeclaration*/ true); - const prototype = (_a2 = assignmentSymbol == null ? void 0 : assignmentSymbol.exports) == null ? void 0 : _a2.get("prototype"); + const prototype = (_a = assignmentSymbol == null ? void 0 : assignmentSymbol.exports) == null ? void 0 : _a.get("prototype"); const init = (prototype == null ? void 0 : prototype.valueDeclaration) && getAssignedJSPrototype(prototype.valueDeclaration); return init ? getSymbolOfDeclaration(init) : void 0; } @@ -63599,20 +64257,20 @@ ${lanes.join("\n")} let name; let decl; if (isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJSFile(node) && !(isVarConst(node.parent) && isFunctionLikeDeclaration(node))) return void 0; + if (!isInJSFile(node) && !(isVarConstLike(node.parent) && isFunctionLikeDeclaration(node))) return void 0; name = node.parent.name; decl = node.parent; } else if (isBinaryExpression(node.parent)) { const parentNode = node.parent; const parentNodeOperator = node.parent.operatorToken.kind; - if (parentNodeOperator === 63 /* EqualsToken */ && (allowDeclaration || parentNode.right === node)) { + if (parentNodeOperator === 64 /* EqualsToken */ && (allowDeclaration || parentNode.right === node)) { name = parentNode.left; decl = name; - } else if (parentNodeOperator === 56 /* BarBarToken */ || parentNodeOperator === 60 /* QuestionQuestionToken */ ) { + } else if (parentNodeOperator === 57 /* BarBarToken */ || parentNodeOperator === 61 /* QuestionQuestionToken */ ) { if (isVariableDeclaration(parentNode.parent) && parentNode.parent.initializer === parentNode) { name = parentNode.parent.name; decl = parentNode.parent; - } else if (isBinaryExpression(parentNode.parent) && parentNode.parent.operatorToken.kind === 63 /* EqualsToken */ && (allowDeclaration || parentNode.parent.right === parentNode)) { + } else if (isBinaryExpression(parentNode.parent) && parentNode.parent.operatorToken.kind === 64 /* EqualsToken */ && (allowDeclaration || parentNode.parent.right === parentNode)) { name = parentNode.parent.left; decl = name; } @@ -63628,33 +64286,33 @@ ${lanes.join("\n")} function getAssignedJSPrototype(node) { if (!node.parent) return false; let parent2 = node.parent; - while(parent2 && parent2.kind === 208 /* PropertyAccessExpression */ )parent2 = parent2.parent; - if (parent2 && isBinaryExpression(parent2) && isPrototypeAccess(parent2.left) && parent2.operatorToken.kind === 63 /* EqualsToken */ ) { + while(parent2 && parent2.kind === 211 /* PropertyAccessExpression */ )parent2 = parent2.parent; + if (parent2 && isBinaryExpression(parent2) && isPrototypeAccess(parent2.left) && parent2.operatorToken.kind === 64 /* EqualsToken */ ) { const right = getInitializerOfBinaryExpression(parent2); return isObjectLiteralExpression(right) && right; } } function checkCallExpression(node, checkMode) { - var _a2, _b, _c; + var _a, _b, _c; checkGrammarTypeArguments(node, node.typeArguments); const signature = getResolvedSignature(node, /*candidatesOutArray*/ void 0, checkMode); if (signature === resolvingSignature) return silentNeverType; checkDeprecatedSignature(signature, node); - if (node.expression.kind === 106 /* SuperKeyword */ ) return voidType; - if (node.kind === 211 /* NewExpression */ ) { + if (node.expression.kind === 108 /* SuperKeyword */ ) return voidType; + if (node.kind === 214 /* NewExpression */ ) { const declaration = signature.declaration; - if (declaration && declaration.kind !== 173 /* Constructor */ && declaration.kind !== 177 /* ConstructSignature */ && declaration.kind !== 182 /* ConstructorType */ && !(isJSDocSignature(declaration) && ((_b = (_a2 = getJSDocRoot(declaration)) == null ? void 0 : _a2.parent) == null ? void 0 : _b.kind) === 173 /* Constructor */ ) && !isJSDocConstructSignature(declaration) && !isJSConstructor(declaration)) { - if (noImplicitAny) error(node, Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); + if (declaration && declaration.kind !== 176 /* Constructor */ && declaration.kind !== 180 /* ConstructSignature */ && declaration.kind !== 185 /* ConstructorType */ && !(isJSDocSignature(declaration) && ((_b = (_a = getJSDocRoot(declaration)) == null ? void 0 : _a.parent) == null ? void 0 : _b.kind) === 176 /* Constructor */ ) && !isJSDocConstructSignature(declaration) && !isJSConstructor(declaration)) { + if (noImplicitAny) error2(node, Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); return anyType; } } if (isInJSFile(node) && shouldResolveJsRequire(compilerOptions) && isCommonJsRequire(node)) return resolveExternalModuleTypeByLiteral(node.arguments[0]); const returnType = getReturnTypeOfSignature(signature); if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) return getESSymbolLikeTypeForNode(walkUpParenthesizedExpressions(node.parent)); - if (node.kind === 210 /* CallExpression */ && !node.questionDotToken && node.parent.kind === 241 /* ExpressionStatement */ && returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) { - if (!isDottedName(node.expression)) error(node.expression, Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name); + if (node.kind === 213 /* CallExpression */ && !node.questionDotToken && node.parent.kind === 244 /* ExpressionStatement */ && returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) { + if (!isDottedName(node.expression)) error2(node.expression, Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name); else if (!getEffectsSignature(node)) { - const diagnostic = error(node.expression, Diagnostics.Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation); + const diagnostic = error2(node.expression, Diagnostics.Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation); getTypeOfDottedName(node.expression, diagnostic); } } @@ -63672,7 +64330,8 @@ ${lanes.join("\n")} return returnType; } function checkDeprecatedSignature(signature, node) { - if (signature.declaration && signature.declaration.flags & 268435456 /* Deprecated */ ) { + if (signature.flags & 128 /* IsSignatureCandidateForOverloadFailure */ ) return; + if (signature.declaration && signature.declaration.flags & 536870912 /* Deprecated */ ) { const suggestionNode = getDeprecatedSuggestionNode(node); const name = tryGetPropertyAccessOrIdentifierToString(getInvokedExpression(node)); addDeprecatedSuggestionWithSignature(suggestionNode, signature.declaration, name, signatureToString(signature)); @@ -63681,20 +64340,20 @@ ${lanes.join("\n")} function getDeprecatedSuggestionNode(node) { node = skipParentheses(node); switch(node.kind){ - case 210 /* CallExpression */ : - case 167 /* Decorator */ : - case 211 /* NewExpression */ : + case 213 /* CallExpression */ : + case 170 /* Decorator */ : + case 214 /* NewExpression */ : return getDeprecatedSuggestionNode(node.expression); - case 212 /* TaggedTemplateExpression */ : + case 215 /* TaggedTemplateExpression */ : return getDeprecatedSuggestionNode(node.tag); - case 283 /* JsxOpeningElement */ : - case 282 /* JsxSelfClosingElement */ : + case 286 /* JsxOpeningElement */ : + case 285 /* JsxSelfClosingElement */ : return getDeprecatedSuggestionNode(node.tagName); - case 209 /* ElementAccessExpression */ : + case 212 /* ElementAccessExpression */ : return node.argumentExpression; - case 208 /* PropertyAccessExpression */ : + case 211 /* PropertyAccessExpression */ : return node.name; - case 180 /* TypeReference */ : + case 183 /* TypeReference */ : const typeReference = node; return isQualifiedName(typeReference.typeName) ? typeReference.typeName.right : typeReference; default: @@ -63717,14 +64376,14 @@ ${lanes.join("\n")} const specifierType = checkExpressionCached(specifier); const optionsType = node.arguments.length > 1 ? checkExpressionCached(node.arguments[1]) : void 0; for(let i = 2; i < node.arguments.length; ++i)checkExpressionCached(node.arguments[i]); - if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) error(specifier, Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); + if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) error2(specifier, Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); if (optionsType) { const importCallOptionsType = getGlobalImportCallOptionsType(/*reportErrors*/ true); if (importCallOptionsType !== emptyObjectType) checkTypeAssignableTo(optionsType, getNullableType(importCallOptionsType, 32768 /* Undefined */ ), node.arguments[1]); } const moduleSymbol = resolveExternalModuleName(node, specifier); if (moduleSymbol) { - const esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true, /*suppressUsageError*/ false); + const esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontResolveAlias*/ true, /*suppressInteropError*/ false); if (esModuleSymbol) return createPromiseReturnType(node, getTypeWithSyntheticDefaultOnly(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier) || getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier)); } return createPromiseReturnType(node, anyType); @@ -63751,11 +64410,11 @@ ${lanes.join("\n")} return void 0; } function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol, moduleSpecifier) { - var _a2; + var _a; if (allowSyntheticDefaultImports && type && !isErrorType(type)) { const synthType = type; if (!synthType.syntheticType) { - const file = (_a2 = originalSymbol.declarations) == null ? void 0 : _a2.find(isSourceFile); + const file = (_a = originalSymbol.declarations) == null ? void 0 : _a.find(isSourceFile); const hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false, moduleSpecifier); if (hasSyntheticDefault) { const anonymousSymbol = createSymbol(2048 /* TypeLiteral */ , "__type" /* Type */ ); @@ -63769,15 +64428,15 @@ ${lanes.join("\n")} return type; } function isCommonJsRequire(node) { - if (!isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) return false; + if (!isRequireCall(node, /*requireStringLiteralLikeArgument*/ true)) return false; if (!isIdentifier(node.expression)) return Debug.fail(); const resolvedRequire = resolveName(node.expression, node.expression.escapedText, 111551 /* Value */ , /*nameNotFoundMessage*/ void 0, /*nameArg*/ void 0, /*isUse*/ true); if (resolvedRequire === requireSymbol) return true; if (resolvedRequire.flags & 2097152 /* Alias */ ) return false; - const targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ ? 259 /* FunctionDeclaration */ : resolvedRequire.flags & 3 /* Variable */ ? 257 /* VariableDeclaration */ : 0 /* Unknown */ ; + const targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ ? 262 /* FunctionDeclaration */ : resolvedRequire.flags & 3 /* Variable */ ? 260 /* VariableDeclaration */ : 0 /* Unknown */ ; if (targetDeclarationKind !== 0 /* Unknown */ ) { const decl = getDeclarationOfKind(resolvedRequire, targetDeclarationKind); - return !!decl && !!(decl.flags & 16777216 /* Ambient */ ); + return !!decl && !!(decl.flags & 33554432 /* Ambient */ ); } return false; } @@ -63788,56 +64447,85 @@ ${lanes.join("\n")} checkDeprecatedSignature(signature, node); return getReturnTypeOfSignature(signature); } - function checkAssertion(node) { - if (node.kind === 213 /* TypeAssertionExpression */ ) { + function checkAssertion(node, checkMode) { + if (node.kind === 216 /* TypeAssertionExpression */ ) { const file = getSourceFileOfNode(node); if (file && fileExtensionIsOneOf(file.fileName, [ ".cts" /* Cts */ , ".mts" /* Mts */ ])) grammarErrorOnNode(node, Diagnostics.This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead); } - return checkAssertionWorker(node, node.type, node.expression); + return checkAssertionWorker(node, checkMode); } function isValidConstAssertionArgument(node) { switch(node.kind){ - case 10 /* StringLiteral */ : - case 14 /* NoSubstitutionTemplateLiteral */ : - case 8 /* NumericLiteral */ : - case 9 /* BigIntLiteral */ : - case 110 /* TrueKeyword */ : - case 95 /* FalseKeyword */ : - case 206 /* ArrayLiteralExpression */ : - case 207 /* ObjectLiteralExpression */ : - case 225 /* TemplateExpression */ : + case 11 /* StringLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + case 9 /* NumericLiteral */ : + case 10 /* BigIntLiteral */ : + case 112 /* TrueKeyword */ : + case 97 /* FalseKeyword */ : + case 209 /* ArrayLiteralExpression */ : + case 210 /* ObjectLiteralExpression */ : + case 228 /* TemplateExpression */ : return true; - case 214 /* ParenthesizedExpression */ : + case 217 /* ParenthesizedExpression */ : return isValidConstAssertionArgument(node.expression); - case 221 /* PrefixUnaryExpression */ : + case 224 /* PrefixUnaryExpression */ : const op = node.operator; const arg = node.operand; - return op === 40 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */ ) || op === 39 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */ ; - case 208 /* PropertyAccessExpression */ : - case 209 /* ElementAccessExpression */ : + return op === 41 /* MinusToken */ && (arg.kind === 9 /* NumericLiteral */ || arg.kind === 10 /* BigIntLiteral */ ) || op === 40 /* PlusToken */ && arg.kind === 9 /* NumericLiteral */ ; + case 211 /* PropertyAccessExpression */ : + case 212 /* ElementAccessExpression */ : const expr = skipParentheses(node.expression); const symbol = isEntityNameExpression(expr) ? resolveEntityName(expr, 111551 /* Value */ , /*ignoreErrors*/ true) : void 0; return !!(symbol && symbol.flags & 384 /* Enum */ ); } return false; } - function checkAssertionWorker(errNode, type, expression, checkMode) { - let exprType = checkExpression(expression, checkMode); + function checkAssertionWorker(node, checkMode) { + const { type: type, expression: expression } = getAssertionTypeAndExpression(node); + const exprType = checkExpression(expression, checkMode); if (isConstTypeReference(type)) { - if (!isValidConstAssertionArgument(expression)) error(expression, Diagnostics.A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals); + if (!isValidConstAssertionArgument(expression)) error2(expression, Diagnostics.A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals); return getRegularTypeOfLiteralType(exprType); } + const links = getNodeLinks(node); + links.assertionExpressionType = exprType; checkSourceElement(type); - exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType)); + checkNodeDeferred(node); + return getTypeFromTypeNode(type); + } + function getAssertionTypeAndExpression(node) { + let type; + let expression; + switch(node.kind){ + case 234 /* AsExpression */ : + case 216 /* TypeAssertionExpression */ : + type = node.type; + expression = node.expression; + break; + case 217 /* ParenthesizedExpression */ : + type = getJSDocTypeAssertionType(node); + expression = node.expression; + break; + } + return { + type: type, + expression: expression + }; + } + function checkAssertionDeferred(node) { + const { type: type } = getAssertionTypeAndExpression(node); + const errNode = isParenthesizedExpression(node) ? type : node; + const links = getNodeLinks(node); + Debug.assertIsDefined(links.assertionExpressionType); + const exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(links.assertionExpressionType)); const targetType = getTypeFromTypeNode(type); if (!isErrorType(targetType)) addLazyDiagnostic(()=>{ const widenedType = getWidenedType(exprType); if (!isTypeComparableTo(targetType, widenedType)) checkTypeComparableTo(exprType, targetType, errNode, Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first); }); - return targetType; } function checkNonNullChain(node) { const leftType = checkExpression(node.expression); @@ -63845,12 +64533,16 @@ ${lanes.join("\n")} return propagateOptionalTypeMarker(getNonNullableType(nonOptionalType), node, nonOptionalType !== leftType); } function checkNonNullAssertion(node) { - return node.flags & 32 /* OptionalChain */ ? checkNonNullChain(node) : getNonNullableType(checkExpression(node.expression)); + return node.flags & 64 /* OptionalChain */ ? checkNonNullChain(node) : getNonNullableType(checkExpression(node.expression)); } function checkExpressionWithTypeArguments(node) { checkGrammarExpressionWithTypeArguments(node); forEach(node.typeArguments, checkSourceElement); - const exprType = node.kind === 230 /* ExpressionWithTypeArguments */ ? checkExpression(node.expression) : isThisIdentifier(node.exprName) ? checkThisExpression(node.exprName) : checkExpression(node.exprName); + if (node.kind === 233 /* ExpressionWithTypeArguments */ ) { + const parent2 = walkUpParenthesizedExpressions(node.parent); + if (parent2.kind === 226 /* BinaryExpression */ && parent2.operatorToken.kind === 104 /* InstanceOfKeyword */ && isNodeDescendantOf(node, parent2.right)) error2(node, Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_not_be_an_instantiation_expression); + } + const exprType = node.kind === 233 /* ExpressionWithTypeArguments */ ? checkExpression(node.expression) : isThisIdentifier(node.exprName) ? checkThisExpression(node.exprName) : checkExpression(node.exprName); return getInstantiationExpressionType(exprType, node); } function getInstantiationExpressionType(exprType, node) { @@ -63867,7 +64559,7 @@ ${lanes.join("\n")} let hasApplicableSignature = false; const result2 = getInstantiatedTypePart(type); hasSomeApplicableSignature || (hasSomeApplicableSignature = hasApplicableSignature); - if (hasSignatures && !hasApplicableSignature) nonApplicableType != null ? nonApplicableType : nonApplicableType = type; + if (hasSignatures && !hasApplicableSignature) nonApplicableType ?? (nonApplicableType = type); return result2; function getInstantiatedTypePart(type2) { if (type2.flags & 524288 /* Object */ ) { @@ -63877,7 +64569,7 @@ ${lanes.join("\n")} hasSignatures || (hasSignatures = resolved.callSignatures.length !== 0 || resolved.constructSignatures.length !== 0); hasApplicableSignature || (hasApplicableSignature = callSignatures.length !== 0 || constructSignatures.length !== 0); if (callSignatures !== resolved.callSignatures || constructSignatures !== resolved.constructSignatures) { - const result3 = createAnonymousType(void 0, resolved.members, callSignatures, constructSignatures, resolved.indexInfos); + const result3 = createAnonymousType(/*symbol*/ void 0, resolved.members, callSignatures, constructSignatures, resolved.indexInfos); result3.objectFlags |= 8388608 /* InstantiationExpressionType */ ; result3.node = node; return result3; @@ -63909,20 +64601,21 @@ ${lanes.join("\n")} const exprType = checkExpression(expression, checkMode); const targetType = getTypeFromTypeNode(target); if (isErrorType(targetType)) return targetType; - checkTypeAssignableToAndOptionallyElaborate(exprType, targetType, target, expression, Diagnostics.Type_0_does_not_satisfy_the_expected_type_1); + const errorNode = findAncestor(target.parent, (n)=>n.kind === 238 /* SatisfiesExpression */ || n.kind === 357 /* JSDocSatisfiesTag */ ); + checkTypeAssignableToAndOptionallyElaborate(exprType, targetType, errorNode, expression, Diagnostics.Type_0_does_not_satisfy_the_expected_type_1); return exprType; } function checkMetaProperty(node) { checkGrammarMetaProperty(node); - if (node.keywordToken === 103 /* NewKeyword */ ) return checkNewTargetMetaProperty(node); - if (node.keywordToken === 100 /* ImportKeyword */ ) return checkImportMetaProperty(node); + if (node.keywordToken === 105 /* NewKeyword */ ) return checkNewTargetMetaProperty(node); + if (node.keywordToken === 102 /* ImportKeyword */ ) return checkImportMetaProperty(node); return Debug.assertNever(node.keywordToken); } function checkMetaPropertyKeyword(node) { switch(node.keywordToken){ - case 100 /* ImportKeyword */ : + case 102 /* ImportKeyword */ : return getGlobalImportMetaExpressionType(); - case 103 /* NewKeyword */ : + case 105 /* NewKeyword */ : const type = checkNewTargetMetaProperty(node); return isErrorType(type) ? errorType : createNewTargetExpressionType(type); default: @@ -63932,9 +64625,9 @@ ${lanes.join("\n")} function checkNewTargetMetaProperty(node) { const container = getNewTargetContainer(node); if (!container) { - error(node, Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); + error2(node, Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); return errorType; - } else if (container.kind === 173 /* Constructor */ ) { + } else if (container.kind === 176 /* Constructor */ ) { const symbol = getSymbolOfDeclaration(container.parent); return getTypeOfSymbol(symbol); } else { @@ -63944,10 +64637,10 @@ ${lanes.join("\n")} } function checkImportMetaProperty(node) { if (moduleKind === 100 /* Node16 */ || moduleKind === 199 /* NodeNext */ ) { - if (getSourceFileOfNode(node).impliedNodeFormat !== 99 /* ESNext */ ) error(node, Diagnostics.The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output); - } else if (moduleKind < 6 /* ES2020 */ && moduleKind !== 4 /* System */ ) error(node, Diagnostics.The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system_node16_or_nodenext); + if (getSourceFileOfNode(node).impliedNodeFormat !== 99 /* ESNext */ ) error2(node, Diagnostics.The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output); + } else if (moduleKind < 6 /* ES2020 */ && moduleKind !== 4 /* System */ ) error2(node, Diagnostics.The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system_node16_or_nodenext); const file = getSourceFileOfNode(node); - Debug.assert(!!(file.flags & 4194304 /* PossiblyContainsImportMeta */ ), "Containing file is missing import meta node flag."); + Debug.assert(!!(file.flags & 8388608 /* PossiblyContainsImportMeta */ ), "Containing file is missing import meta node flag."); return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType; } function getTypeOfParameter(symbol) { @@ -63958,7 +64651,8 @@ ${lanes.join("\n")} } return type; } - function getTupleElementLabel(d) { + function getTupleElementLabel(d, index, restParameterName = "arg") { + if (!d) return `${restParameterName}_${index}`; Debug.assert(isIdentifier(d.name)); return d.name.escapedText; } @@ -63970,45 +64664,54 @@ ${lanes.join("\n")} if (isTupleType(restType)) { const associatedNames = restType.target.labeledElementDeclarations; const index = pos - paramCount; - return associatedNames && getTupleElementLabel(associatedNames[index]) || restParameter.escapedName + "_" + index; + return getTupleElementLabel(associatedNames == null ? void 0 : associatedNames[index], index, restParameter.escapedName); } return restParameter.escapedName; } - function getParameterIdentifierNameAtPosition(signature, pos) { - var _a2; - if (((_a2 = signature.declaration) == null ? void 0 : _a2.kind) === 320 /* JSDocFunctionType */ ) return void 0; + function getParameterIdentifierInfoAtPosition(signature, pos) { + var _a; + if (((_a = signature.declaration) == null ? void 0 : _a.kind) === 324 /* JSDocFunctionType */ ) return void 0; const paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { const param = signature.parameters[pos]; - return isParameterDeclarationWithIdentifierName(param) ? [ - param.escapedName, - false - ] : void 0; + const paramIdent = getParameterDeclarationIdentifier(param); + return paramIdent ? { + parameter: paramIdent, + parameterName: param.escapedName, + isRestParameter: false + } : void 0; } const restParameter = signature.parameters[paramCount] || unknownSymbol; - if (!isParameterDeclarationWithIdentifierName(restParameter)) return void 0; + const restIdent = getParameterDeclarationIdentifier(restParameter); + if (!restIdent) return void 0; const restType = getTypeOfSymbol(restParameter); if (isTupleType(restType)) { const associatedNames = restType.target.labeledElementDeclarations; const index = pos - paramCount; const associatedName = associatedNames == null ? void 0 : associatedNames[index]; const isRestTupleElement = !!(associatedName == null ? void 0 : associatedName.dotDotDotToken); - return associatedName ? [ - getTupleElementLabel(associatedName), - isRestTupleElement - ] : void 0; + if (associatedName) { + Debug.assert(isIdentifier(associatedName.name)); + return { + parameter: associatedName.name, + parameterName: associatedName.name.escapedText, + isRestParameter: isRestTupleElement + }; + } + return void 0; } - if (pos === paramCount) return [ - restParameter.escapedName, - true - ]; + if (pos === paramCount) return { + parameter: restIdent, + parameterName: restParameter.escapedName, + isRestParameter: true + }; return void 0; } - function isParameterDeclarationWithIdentifierName(symbol) { - return symbol.valueDeclaration && isParameter(symbol.valueDeclaration) && isIdentifier(symbol.valueDeclaration.name); + function getParameterDeclarationIdentifier(symbol) { + return symbol.valueDeclaration && isParameter(symbol.valueDeclaration) && isIdentifier(symbol.valueDeclaration.name) && symbol.valueDeclaration.name; } function isValidDeclarationForTupleLabel(d) { - return d.kind === 199 /* NamedTupleMember */ || isParameter(d) && d.name && isIdentifier(d.name); + return d.kind === 202 /* NamedTupleMember */ || isParameter(d) && d.name && isIdentifier(d.name); } function getNameableDeclarationAtPosition(signature, pos) { const paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); @@ -64111,7 +64814,7 @@ ${lanes.join("\n")} } function getNonArrayRestType(signature) { const restType = getEffectiveRestType(signature); - return restType && !isArrayType(restType) && !isTypeAny(restType) && (getReducedType(restType).flags & 131072 /* Never */ ) === 0 ? restType : void 0; + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : void 0; } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); @@ -64166,7 +64869,7 @@ ${lanes.join("\n")} if (!links.type) { const declaration = parameter.valueDeclaration; links.type = type || (declaration ? getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true) : getTypeOfSymbol(parameter)); - if (declaration && declaration.name.kind !== 79 /* Identifier */ ) { + if (declaration && declaration.name.kind !== 80 /* Identifier */ ) { if (links.type === unknownType) links.type = getTypeFromBindingPattern(declaration.name); assignBindingElementTypes(declaration.name, links.type); } @@ -64175,7 +64878,7 @@ ${lanes.join("\n")} function assignBindingElementTypes(pattern, parentType) { for (const element of pattern.elements)if (!isOmittedExpression(element)) { const type = getBindingElementTypeFromParentType(element, parentType); - if (element.name.kind === 79 /* Identifier */ ) getSymbolLinks(getSymbolOfDeclaration(element)).type = type; + if (element.name.kind === 80 /* Identifier */ ) getSymbolLinks(getSymbolOfDeclaration(element)).type = type; else assignBindingElementTypes(element.name, type); } } @@ -64239,13 +64942,13 @@ ${lanes.join("\n")} ]); } function createClassAccessorDecoratorTargetType(thisType, valueType) { - return tryCreateTypeReference(getGlobalClassAccessorDecoratorTargetType(/*reportError*/ true), [ + return tryCreateTypeReference(getGlobalClassAccessorDecoratorTargetType(/*reportErrors*/ true), [ thisType, valueType ]); } function createClassAccessorDecoratorResultType(thisType, valueType) { - return tryCreateTypeReference(getGlobalClassAccessorDecoratorResultType(/*reportError*/ true), [ + return tryCreateTypeReference(getGlobalClassAccessorDecoratorResultType(/*reportErrors*/ true), [ thisType, valueType ]); @@ -64270,13 +64973,13 @@ ${lanes.join("\n")} ], returnType); } function getESDecoratorCallSignature(decorator) { - const { parent: parent2 } = decorator; + const { parent: parent2 } = decorator; const links = getNodeLinks(parent2); if (!links.decoratorSignature) { links.decoratorSignature = anySignature; switch(parent2.kind){ - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : { const node = parent2; const targetType = getTypeOfSymbol(getSymbolOfDeclaration(node)); @@ -64284,9 +64987,9 @@ ${lanes.join("\n")} links.decoratorSignature = createESDecoratorCallSignature(targetType, contextType, targetType); break; } - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : { const node = parent2; if (!isClassLike(node.parent)) break; @@ -64298,7 +65001,7 @@ ${lanes.join("\n")} links.decoratorSignature = createESDecoratorCallSignature(targetType, contextType, returnType); break; } - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : { const node = parent2; if (!isClassLike(node.parent)) break; @@ -64315,13 +65018,13 @@ ${lanes.join("\n")} return links.decoratorSignature === anySignature ? void 0 : links.decoratorSignature; } function getLegacyDecoratorCallSignature(decorator) { - const { parent: parent2 } = decorator; + const { parent: parent2 } = decorator; const links = getNodeLinks(parent2); if (!links.decoratorSignature) { links.decoratorSignature = anySignature; switch(parent2.kind){ - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : { const node = parent2; const targetType = getTypeOfSymbol(getSymbolOfDeclaration(node)); @@ -64334,7 +65037,7 @@ ${lanes.join("\n")} ])); break; } - case 166 /* Parameter */ : + case 169 /* Parameter */ : { const node = parent2; if (!isConstructorDeclaration(node.parent) && !(isMethodDeclaration(node.parent) || isSetAccessorDeclaration(node.parent) && isClassLike(node.parent.parent))) break; @@ -64354,10 +65057,10 @@ ${lanes.join("\n")} ], voidType); break; } - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 169 /* PropertyDeclaration */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 172 /* PropertyDeclaration */ : { const node = parent2; if (!isClassLike(node.parent)) break; @@ -64417,9 +65120,9 @@ ${lanes.join("\n")} function createPromiseReturnType(func, promisedType) { const promiseType = createPromiseType(promisedType); if (promiseType === unknownType) { - error(func, isImportCall(func) ? Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); + error2(func, isImportCall(func) ? Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); return errorType; - } else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) error(func, isImportCall(func) ? Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) error2(func, isImportCall(func) ? Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); return promiseType; } function createNewTargetExpressionType(targetType) { @@ -64442,20 +65145,25 @@ ${lanes.join("\n")} let yieldType; let nextType; let fallbackReturnType = voidType; - if (func.body.kind !== 238 /* Block */ ) { + if (func.body.kind !== 241 /* Block */ ) { returnType = checkExpressionCached(func.body, checkMode && checkMode & -9 /* SkipGenericFunctions */ ); if (isAsync) returnType = unwrapAwaitedType(checkAwaitedType(returnType, /*withAlias*/ false, /*errorNode*/ func, Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member)); } else if (isGenerator) { const returnTypes = checkAndAggregateReturnExpressionTypes(func, checkMode); if (!returnTypes) fallbackReturnType = neverType; else if (returnTypes.length > 0) returnType = getUnionType(returnTypes, 2 /* Subtype */ ); - const { yieldTypes: yieldTypes , nextTypes: nextTypes } = checkAndAggregateYieldOperandTypes(func, checkMode); + const { yieldTypes: yieldTypes, nextTypes: nextTypes } = checkAndAggregateYieldOperandTypes(func, checkMode); yieldType = some(yieldTypes) ? getUnionType(yieldTypes, 2 /* Subtype */ ) : void 0; nextType = some(nextTypes) ? getIntersectionType(nextTypes) : void 0; } else { const types = checkAndAggregateReturnExpressionTypes(func, checkMode); if (!types) return functionFlags & 2 /* Async */ ? createPromiseReturnType(func, neverType) : neverType; - if (types.length === 0) return functionFlags & 2 /* Async */ ? createPromiseReturnType(func, voidType) : voidType; + if (types.length === 0) { + const contextualReturnType = getContextualReturnType(func, /*contextFlags*/ void 0); + const returnType2 = contextualReturnType && (unwrapReturnType(contextualReturnType, functionFlags) || voidType).flags & 32768 /* Undefined */ ? undefinedType : voidType; + return functionFlags & 2 /* Async */ ? createPromiseReturnType(func, returnType2) : // Async function + returnType2; + } returnType = getUnionType(types, 2 /* Subtype */ ); } if (returnType || yieldType || nextType) { @@ -64547,7 +65255,7 @@ ${lanes.join("\n")} return links.isExhaustive; } function computeExhaustiveSwitchStatement(node) { - if (node.expression.kind === 218 /* TypeOfExpression */ ) { + if (node.expression.kind === 221 /* TypeOfExpression */ ) { const witnesses = getSwitchClauseTypeOfWitnesses(node); if (!witnesses) return false; const operandConstraint = getBaseConstraintOrType(checkExpressionCached(node.expression.expression)); @@ -64572,6 +65280,10 @@ ${lanes.join("\n")} forEachReturnStatement(func.body, (returnStatement)=>{ const expr = returnStatement.expression; if (expr) { + if (expr.kind === 213 /* CallExpression */ && expr.expression.kind === 80 /* Identifier */ && checkExpressionCached(expr.expression).symbol === func.symbol) { + hasReturnOfTypeNever = true; + return; + } let type = checkExpressionCached(expr, checkMode && checkMode & -9 /* SkipGenericFunctions */ ); if (functionFlags & 2 /* Async */ ) type = unwrapAwaitedType(checkAwaitedType(type, /*withAlias*/ false, func, Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member)); if (type.flags & 131072 /* Never */ ) hasReturnOfTypeNever = true; @@ -64584,11 +65296,11 @@ ${lanes.join("\n")} } function mayReturnNever(func) { switch(func.kind){ - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : return true; - case 171 /* MethodDeclaration */ : - return func.parent.kind === 207 /* ObjectLiteralExpression */ ; + case 174 /* MethodDeclaration */ : + return func.parent.kind === 210 /* ObjectLiteralExpression */ ; default: return false; } @@ -64599,25 +65311,25 @@ ${lanes.join("\n")} function checkAllCodePathsInNonVoidFunctionReturnOrThrowDiagnostics() { const functionFlags = getFunctionFlags(func); const type = returnType && unwrapReturnType(returnType, functionFlags); - if (type && maybeTypeOfKind(type, 16385 /* Void */ )) return; - if (func.kind === 170 /* MethodSignature */ || nodeIsMissing(func.body) || func.body.kind !== 238 /* Block */ || !functionHasImplicitReturn(func)) return; - const hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */ ; + if (type && (maybeTypeOfKind(type, 16384 /* Void */ ) || type.flags & 32769 /* Undefined */ )) return; + if (func.kind === 173 /* MethodSignature */ || nodeIsMissing(func.body) || func.body.kind !== 241 /* Block */ || !functionHasImplicitReturn(func)) return; + const hasExplicitReturn = func.flags & 1024 /* HasExplicitReturn */ ; const errorNode = getEffectiveReturnTypeNode(func) || func; - if (type && type.flags & 131072 /* Never */ ) error(errorNode, Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); - else if (type && !hasExplicitReturn) error(errorNode, Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); - else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) error(errorNode, Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + if (type && type.flags & 131072 /* Never */ ) error2(errorNode, Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + else if (type && !hasExplicitReturn) error2(errorNode, Diagnostics.A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value); + else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) error2(errorNode, Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); else if (compilerOptions.noImplicitReturns) { if (!type) { if (!hasExplicitReturn) return; const inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); - if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) return; + if (isUnwrappedReturnTypeUndefinedVoidOrAny(func, inferredReturnType)) return; } - error(errorNode, Diagnostics.Not_all_code_paths_return_a_value); + error2(errorNode, Diagnostics.Not_all_code_paths_return_a_value); } } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - Debug.assert(node.kind !== 171 /* MethodDeclaration */ || isObjectLiteralMethod(node)); + Debug.assert(node.kind !== 174 /* MethodDeclaration */ || isObjectLiteralMethod(node)); checkNodeDeferred(node); if (isFunctionExpression(node)) checkCollisionsForDeclarationName(node, node.name); if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) { @@ -64627,7 +65339,7 @@ ${lanes.join("\n")} const links = getNodeLinks(node); if (links.contextFreeType) return links.contextFreeType; const returnType = getReturnTypeFromBody(node, checkMode); - const returnOnlySignature = createSignature(void 0, void 0, void 0, emptyArray, returnType, /*resolvedTypePredicate*/ void 0, 0, 0 /* None */ ); + const returnOnlySignature = createSignature(/*declaration*/ void 0, /*typeParameters*/ void 0, /*thisParameter*/ void 0, emptyArray, returnType, /*resolvedTypePredicate*/ void 0, 0, 64 /* IsNonInferrable */ ); const returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [ returnOnlySignature ], emptyArray, emptyArray); @@ -64638,7 +65350,7 @@ ${lanes.join("\n")} return anyFunctionType; } const hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 215 /* FunctionExpression */ ) checkGrammarForGenerator(node); + if (!hasGrammarError && node.kind === 218 /* FunctionExpression */ ) checkGrammarForGenerator(node); contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode); return getTypeOfSymbol(getSymbolOfDeclaration(node)); } @@ -64662,6 +65374,9 @@ ${lanes.join("\n")} instantiatedContextualSignature || (instantiatedContextualSignature = inferenceContext ? instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature); assignContextualParameterTypes(signature, instantiatedContextualSignature); } else assignNonContextualParameterTypes(signature); + } else if (contextualSignature && !node.typeParameters && contextualSignature.parameters.length > node.parameters.length) { + const inferenceContext = getInferenceContext(node); + if (checkMode && checkMode & 2 /* Inferential */ ) inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext); } if (contextualSignature && !getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) { const returnType = getReturnTypeFromBody(node, checkMode); @@ -64672,13 +65387,13 @@ ${lanes.join("\n")} } } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - Debug.assert(node.kind !== 171 /* MethodDeclaration */ || isObjectLiteralMethod(node)); + Debug.assert(node.kind !== 174 /* MethodDeclaration */ || isObjectLiteralMethod(node)); const functionFlags = getFunctionFlags(node); const returnType = getReturnTypeFromAnnotation(node); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); if (node.body) { if (!getEffectiveReturnTypeNode(node)) getReturnTypeOfSignature(getSignatureFromDeclaration(node)); - if (node.body.kind === 238 /* Block */ ) checkSourceElement(node.body); + if (node.body.kind === 241 /* Block */ ) checkSourceElement(node.body); else { const exprType = checkExpression(node.body); const returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags); @@ -64719,20 +65434,20 @@ ${lanes.join("\n")} return !setProp; } function isReadonlySymbol(symbol) { - return !!(getCheckFlags(symbol) & 8 /* Readonly */ || symbol.flags & 4 /* Property */ && getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ || symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */ ) || symbol.flags & 8 /* EnumMember */ || some(symbol.declarations, isReadonlyAssignmentDeclaration)); + return !!(getCheckFlags(symbol) & 8 /* Readonly */ || symbol.flags & 4 /* Property */ && getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 6 /* Constant */ || symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */ ) || symbol.flags & 8 /* EnumMember */ || some(symbol.declarations, isReadonlyAssignmentDeclaration)); } function isAssignmentToReadonlyEntity(expr, symbol, assignmentKind) { - var _a2, _b; + var _a, _b; if (assignmentKind === 0 /* None */ ) return false; if (isReadonlySymbol(symbol)) { - if (symbol.flags & 4 /* Property */ && isAccessExpression(expr) && expr.expression.kind === 108 /* ThisKeyword */ ) { + if (symbol.flags & 4 /* Property */ && isAccessExpression(expr) && expr.expression.kind === 110 /* ThisKeyword */ ) { const ctor = getContainingFunction(expr); - if (!(ctor && (ctor.kind === 173 /* Constructor */ || isJSConstructor(ctor)))) return true; + if (!(ctor && (ctor.kind === 176 /* Constructor */ || isJSConstructor(ctor)))) return true; if (symbol.valueDeclaration) { const isAssignmentDeclaration2 = isBinaryExpression(symbol.valueDeclaration); const isLocalPropertyDeclaration = ctor.parent === symbol.valueDeclaration.parent; const isLocalParameterProperty = ctor === symbol.valueDeclaration.parent; - const isLocalThisPropertyAssignment = isAssignmentDeclaration2 && ((_a2 = symbol.parent) == null ? void 0 : _a2.valueDeclaration) === ctor.parent; + const isLocalThisPropertyAssignment = isAssignmentDeclaration2 && ((_a = symbol.parent) == null ? void 0 : _a.valueDeclaration) === ctor.parent; const isLocalThisPropertyAssignmentConstructorFunction = isAssignmentDeclaration2 && ((_b = symbol.parent) == null ? void 0 : _b.valueDeclaration) === ctor; const isWriteableSymbol = isLocalPropertyDeclaration || isLocalParameterProperty || isLocalThisPropertyAssignment || isLocalThisPropertyAssignmentConstructorFunction; return !isWriteableSymbol; @@ -64742,11 +65457,11 @@ ${lanes.join("\n")} } if (isAccessExpression(expr)) { const node = skipParentheses(expr.expression); - if (node.kind === 79 /* Identifier */ ) { + if (node.kind === 80 /* Identifier */ ) { const symbol2 = getNodeLinks(node).resolvedSymbol; if (symbol2.flags & 2097152 /* Alias */ ) { const declaration = getDeclarationOfAliasSymbol(symbol2); - return !!declaration && declaration.kind === 271 /* NamespaceImport */ ; + return !!declaration && declaration.kind === 274 /* NamespaceImport */ ; } } } @@ -64754,12 +65469,12 @@ ${lanes.join("\n")} } function checkReferenceExpression(expr, invalidReferenceMessage, invalidOptionalChainMessage) { const node = skipOuterExpressions(expr, 7 /* Parentheses */ ); - if (node.kind !== 79 /* Identifier */ && !isAccessExpression(node)) { - error(expr, invalidReferenceMessage); + if (node.kind !== 80 /* Identifier */ && !isAccessExpression(node)) { + error2(expr, invalidReferenceMessage); return false; } - if (node.flags & 32 /* OptionalChain */ ) { - error(expr, invalidOptionalChainMessage); + if (node.flags & 64 /* OptionalChain */ ) { + error2(expr, invalidOptionalChainMessage); return false; } return true; @@ -64768,21 +65483,21 @@ ${lanes.join("\n")} checkExpression(node.expression); const expr = skipParentheses(node.expression); if (!isAccessExpression(expr)) { - error(expr, Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); + error2(expr, Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); return booleanType; } - if (isPropertyAccessExpression(expr) && isPrivateIdentifier(expr.name)) error(expr, Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_private_identifier); + if (isPropertyAccessExpression(expr) && isPrivateIdentifier(expr.name)) error2(expr, Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_private_identifier); const links = getNodeLinks(expr); const symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); if (symbol) { - if (isReadonlySymbol(symbol)) error(expr, Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + if (isReadonlySymbol(symbol)) error2(expr, Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); checkDeleteExpressionMustBeOptional(expr, symbol); } return booleanType; } function checkDeleteExpressionMustBeOptional(expr, symbol) { const type = getTypeOfSymbol(symbol); - if (strictNullChecks && !(type.flags & 131075 /* Never */ ) && !(exactOptionalPropertyTypes ? symbol.flags & 16777216 /* Optional */ : getTypeFacts(type) & 16777216 /* IsUndefined */ )) error(expr, Diagnostics.The_operand_of_a_delete_operator_must_be_optional); + if (strictNullChecks && !(type.flags & 131075 /* Never */ ) && !(exactOptionalPropertyTypes ? symbol.flags & 16777216 /* Optional */ : getTypeFacts(type) & 16777216 /* IsUndefined */ )) error2(expr, Diagnostics.The_operand_of_a_delete_operator_must_be_optional); } function checkTypeOfExpression(node) { checkExpression(node.expression); @@ -64792,25 +65507,32 @@ ${lanes.join("\n")} checkExpression(node.expression); return undefinedWideningType; } - function checkAwaitExpressionGrammar(node) { + function checkAwaitGrammar(node) { + let hasError = false; const container = getContainingFunctionOrClassStaticBlock(node); - if (container && isClassStaticBlockDeclaration(container)) error(node, Diagnostics.Await_expression_cannot_be_used_inside_a_class_static_block); - else if (!(node.flags & 32768 /* AwaitContext */ )) { + if (container && isClassStaticBlockDeclaration(container)) { + const message = isAwaitExpression(node) ? Diagnostics.await_expression_cannot_be_used_inside_a_class_static_block : Diagnostics.await_using_statements_cannot_be_used_inside_a_class_static_block; + error2(node, message); + hasError = true; + } else if (!(node.flags & 65536 /* AwaitContext */ )) { if (isInTopLevelContext(node)) { const sourceFile = getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { let span; if (!isEffectiveExternalModule(sourceFile, compilerOptions)) { - span != null ? span : span = getSpanOfTokenAtPosition(sourceFile, node.pos); - const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module); + span ?? (span = getSpanOfTokenAtPosition(sourceFile, node.pos)); + const message = isAwaitExpression(node) ? Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module : Diagnostics.await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module; + const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, message); diagnostics.add(diagnostic); + hasError = true; } switch(moduleKind){ case 100 /* Node16 */ : case 199 /* NodeNext */ : if (sourceFile.impliedNodeFormat === 1 /* CommonJS */ ) { - span != null ? span : span = getSpanOfTokenAtPosition(sourceFile, node.pos); + span ?? (span = getSpanOfTokenAtPosition(sourceFile, node.pos)); diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level)); + hasError = true; break; } case 7 /* ES2022 */ : @@ -64818,8 +65540,10 @@ ${lanes.join("\n")} case 4 /* System */ : if (languageVersion >= 4 /* ES2017 */ ) break; default: - span != null ? span : span = getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher)); + span ?? (span = getSpanOfTokenAtPosition(sourceFile, node.pos)); + const message = isAwaitExpression(node) ? Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher : Diagnostics.Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher; + diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, message)); + hasError = true; break; } } @@ -64827,19 +65551,25 @@ ${lanes.join("\n")} const sourceFile = getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { const span = getSpanOfTokenAtPosition(sourceFile, node.pos); - const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); - if (container && container.kind !== 173 /* Constructor */ && (getFunctionFlags(container) & 2 /* Async */ ) === 0) { + const message = isAwaitExpression(node) ? Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules : Diagnostics.await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules; + const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, message); + if (container && container.kind !== 176 /* Constructor */ && (getFunctionFlags(container) & 2 /* Async */ ) === 0) { const relatedInfo = createDiagnosticForNode(container, Diagnostics.Did_you_mean_to_mark_this_function_as_async); addRelatedInfo(diagnostic, relatedInfo); } diagnostics.add(diagnostic); + hasError = true; } } } - if (isInParameterInitializerBeforeContainingFunction(node)) error(node, Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); + if (isAwaitExpression(node) && isInParameterInitializerBeforeContainingFunction(node)) { + error2(node, Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); + hasError = true; + } + return hasError; } function checkAwaitExpression(node) { - addLazyDiagnostic(()=>checkAwaitExpressionGrammar(node)); + addLazyDiagnostic(()=>checkAwaitGrammar(node)); const operandType = checkExpression(node.expression); const awaitedType = checkAwaitedType(operandType, /*withAlias*/ true, node, Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); if (awaitedType === operandType && !isErrorType(awaitedType) && !(operandType.flags & 3 /* AnyOrUnknown */ )) addErrorOrSuggestion(/*isError*/ false, createDiagnosticForNode(node, Diagnostics.await_has_no_effect_on_the_type_of_this_expression)); @@ -64849,37 +65579,37 @@ ${lanes.join("\n")} const operandType = checkExpression(node.operand); if (operandType === silentNeverType) return silentNeverType; switch(node.operand.kind){ - case 8 /* NumericLiteral */ : + case 9 /* NumericLiteral */ : switch(node.operator){ - case 40 /* MinusToken */ : + case 41 /* MinusToken */ : return getFreshTypeOfLiteralType(getNumberLiteralType(-node.operand.text)); - case 39 /* PlusToken */ : + case 40 /* PlusToken */ : return getFreshTypeOfLiteralType(getNumberLiteralType(+node.operand.text)); } break; - case 9 /* BigIntLiteral */ : - if (node.operator === 40 /* MinusToken */ ) return getFreshTypeOfLiteralType(getBigIntLiteralType({ + case 10 /* BigIntLiteral */ : + if (node.operator === 41 /* MinusToken */ ) return getFreshTypeOfLiteralType(getBigIntLiteralType({ negative: true, base10Value: parsePseudoBigInt(node.operand.text) })); } switch(node.operator){ - case 39 /* PlusToken */ : - case 40 /* MinusToken */ : - case 54 /* TildeToken */ : + case 40 /* PlusToken */ : + case 41 /* MinusToken */ : + case 55 /* TildeToken */ : checkNonNullType(operandType, node.operand); - if (maybeTypeOfKindConsideringBaseConstraint(operandType, 12288 /* ESSymbolLike */ )) error(node.operand, Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, tokenToString(node.operator)); - if (node.operator === 39 /* PlusToken */ ) { - if (maybeTypeOfKindConsideringBaseConstraint(operandType, 2112 /* BigIntLike */ )) error(node.operand, Diagnostics.Operator_0_cannot_be_applied_to_type_1, tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType))); + if (maybeTypeOfKindConsideringBaseConstraint(operandType, 12288 /* ESSymbolLike */ )) error2(node.operand, Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, tokenToString(node.operator)); + if (node.operator === 40 /* PlusToken */ ) { + if (maybeTypeOfKindConsideringBaseConstraint(operandType, 2112 /* BigIntLike */ )) error2(node.operand, Diagnostics.Operator_0_cannot_be_applied_to_type_1, tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType))); return numberType; } return getUnaryResultType(operandType); - case 53 /* ExclamationToken */ : - checkTruthinessExpression(node.operand); + case 54 /* ExclamationToken */ : + checkTruthinessOfType(operandType, node.operand); const facts = getTypeFacts(operandType) & 12582912 /* Falsy */ ; return facts === 4194304 /* Truthy */ ? falseType : facts === 8388608 /* Falsy */ ? trueType : booleanType; - case 45 /* PlusPlusToken */ : - case 46 /* MinusMinusToken */ : + case 46 /* PlusPlusToken */ : + case 47 /* MinusMinusToken */ : const ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); if (ok) checkReferenceExpression(node.operand, Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access, Diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access); return getUnaryResultType(operandType); @@ -64928,8 +65658,8 @@ ${lanes.join("\n")} } function checkInstanceOfExpression(left, right, leftType, rightType) { if (leftType === silentNeverType || rightType === silentNeverType) return silentNeverType; - if (!isTypeAny(leftType) && allTypesAssignableToKind(leftType, 134348796 /* Primitive */ )) error(left, Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); - if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) error(right, Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); + if (!isTypeAny(leftType) && allTypesAssignableToKind(leftType, 402784252 /* Primitive */ )) error2(left, Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) error2(right, Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); return booleanType; } function hasEmptyObjectIntersection(type) { @@ -64945,7 +65675,7 @@ ${lanes.join("\n")} } } else checkTypeAssignableTo(checkNonNullType(leftType, left), stringNumberSymbolType, left); if (checkTypeAssignableTo(checkNonNullType(rightType, right), nonPrimitiveType, right)) { - if (hasEmptyObjectIntersection(rightType)) error(right, Diagnostics.Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operator, typeToString(rightType)); + if (hasEmptyObjectIntersection(rightType)) error2(right, Diagnostics.Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operator, typeToString(rightType)); } return booleanType; } @@ -64958,7 +65688,7 @@ ${lanes.join("\n")} function checkObjectLiteralDestructuringPropertyAssignment(node, objectLiteralType, propertyIndex, allProperties, rightIsThis = false) { const properties = node.properties; const property = properties[propertyIndex]; - if (property.kind === 299 /* PropertyAssignment */ || property.kind === 300 /* ShorthandPropertyAssignment */ ) { + if (property.kind === 303 /* PropertyAssignment */ || property.kind === 304 /* ShorthandPropertyAssignment */ ) { const name = property.name; const exprType = getLiteralTypeFromPropertyName(name); if (isTypeUsableAsPropertyName(exprType)) { @@ -64971,9 +65701,9 @@ ${lanes.join("\n")} } const elementType = getIndexedAccessType(objectLiteralType, exprType, 32 /* ExpressionPosition */ , name); const type = getFlowTypeOfDestructuring(property, elementType); - return checkDestructuringAssignment(property.kind === 300 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); - } else if (property.kind === 301 /* SpreadAssignment */ ) { - if (propertyIndex < properties.length - 1) error(property, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + return checkDestructuringAssignment(property.kind === 304 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); + } else if (property.kind === 305 /* SpreadAssignment */ ) { + if (propertyIndex < properties.length - 1) error2(property, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); else { if (languageVersion < 99 /* ESNext */ ) checkExternalEmitHelpers(property, 4 /* Rest */ ); const nonRestNames = []; @@ -64984,7 +65714,7 @@ ${lanes.join("\n")} checkGrammarForDisallowedTrailingComma(allProperties, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); return checkDestructuringAssignment(property.expression, type); } - } else error(property, Diagnostics.Property_assignment_expected); + } else error2(property, Diagnostics.Property_assignment_expected); } function checkArrayLiteralAssignment(node, sourceType, checkMode) { const elements = node.elements; @@ -64993,7 +65723,7 @@ ${lanes.join("\n")} let inBoundsType = compilerOptions.noUncheckedIndexedAccess ? void 0 : possiblyOutOfBoundsType; for(let i = 0; i < elements.length; i++){ let type = possiblyOutOfBoundsType; - if (node.elements[i].kind === 227 /* SpreadElement */ ) type = inBoundsType = inBoundsType != null ? inBoundsType : checkIteratedTypeOrElementType(65 /* Destructuring */ , sourceType, undefinedType, node) || errorType; + if (node.elements[i].kind === 230 /* SpreadElement */ ) type = inBoundsType = inBoundsType ?? (checkIteratedTypeOrElementType(65 /* Destructuring */ , sourceType, undefinedType, node) || errorType); checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, type, checkMode); } return sourceType; @@ -65001,8 +65731,8 @@ ${lanes.join("\n")} function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { const elements = node.elements; const element = elements[elementIndex]; - if (element.kind !== 229 /* OmittedExpression */ ) { - if (element.kind !== 227 /* SpreadElement */ ) { + if (element.kind !== 232 /* OmittedExpression */ ) { + if (element.kind !== 230 /* SpreadElement */ ) { const indexType = getNumberLiteralType(elementIndex); if (isArrayLikeType(sourceType)) { const accessFlags = 32 /* ExpressionPosition */ | (hasDefaultValue(element) ? 16 /* NoTupleBoundsCheck */ : 0); @@ -65013,10 +65743,10 @@ ${lanes.join("\n")} } return checkDestructuringAssignment(element, elementType, checkMode); } - if (elementIndex < elements.length - 1) error(element, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + if (elementIndex < elements.length - 1) error2(element, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); else { const restExpression = element.expression; - if (restExpression.kind === 223 /* BinaryExpression */ && restExpression.operatorToken.kind === 63 /* EqualsToken */ ) error(restExpression.operatorToken, Diagnostics.A_rest_element_cannot_have_an_initializer); + if (restExpression.kind === 226 /* BinaryExpression */ && restExpression.operatorToken.kind === 64 /* EqualsToken */ ) error2(restExpression.operatorToken, Diagnostics.A_rest_element_cannot_have_an_initializer); else { checkGrammarForDisallowedTrailingComma(node.elements, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); const type = everyType(sourceType, isTupleType) ? mapType(sourceType, (t)=>sliceTupleType(t, elementIndex)) : createArrayType(elementType); @@ -65028,7 +65758,7 @@ ${lanes.join("\n")} } function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { let target; - if (exprOrAssignment.kind === 300 /* ShorthandPropertyAssignment */ ) { + if (exprOrAssignment.kind === 304 /* ShorthandPropertyAssignment */ ) { const prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { if (strictNullChecks && !(getTypeFacts(checkExpression(prop.objectAssignmentInitializer)) & 16777216 /* IsUndefined */ )) sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */ ); @@ -65036,66 +65766,66 @@ ${lanes.join("\n")} } target = exprOrAssignment.name; } else target = exprOrAssignment; - if (target.kind === 223 /* BinaryExpression */ && target.operatorToken.kind === 63 /* EqualsToken */ ) { + if (target.kind === 226 /* BinaryExpression */ && target.operatorToken.kind === 64 /* EqualsToken */ ) { checkBinaryExpression(target, checkMode); target = target.left; if (strictNullChecks) sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */ ); } - if (target.kind === 207 /* ObjectLiteralExpression */ ) return checkObjectLiteralAssignment(target, sourceType, rightIsThis); - if (target.kind === 206 /* ArrayLiteralExpression */ ) return checkArrayLiteralAssignment(target, sourceType, checkMode); + if (target.kind === 210 /* ObjectLiteralExpression */ ) return checkObjectLiteralAssignment(target, sourceType, rightIsThis); + if (target.kind === 209 /* ArrayLiteralExpression */ ) return checkArrayLiteralAssignment(target, sourceType, checkMode); return checkReferenceAssignment(target, sourceType, checkMode); } function checkReferenceAssignment(target, sourceType, checkMode) { const targetType = checkExpression(target, checkMode); - const error2 = target.parent.kind === 301 /* SpreadAssignment */ ? Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; - const optionalError = target.parent.kind === 301 /* SpreadAssignment */ ? Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access : Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access; - if (checkReferenceExpression(target, error2, optionalError)) checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target); + const error3 = target.parent.kind === 305 /* SpreadAssignment */ ? Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; + const optionalError = target.parent.kind === 305 /* SpreadAssignment */ ? Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access : Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access; + if (checkReferenceExpression(target, error3, optionalError)) checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target); if (isPrivateIdentifierPropertyAccessExpression(target)) checkExternalEmitHelpers(target.parent, 1048576 /* ClassPrivateFieldSet */ ); return sourceType; } function isSideEffectFree(node) { node = skipParentheses(node); switch(node.kind){ - case 79 /* Identifier */ : - case 10 /* StringLiteral */ : - case 13 /* RegularExpressionLiteral */ : - case 212 /* TaggedTemplateExpression */ : - case 225 /* TemplateExpression */ : - case 14 /* NoSubstitutionTemplateLiteral */ : - case 8 /* NumericLiteral */ : - case 9 /* BigIntLiteral */ : - case 110 /* TrueKeyword */ : - case 95 /* FalseKeyword */ : - case 104 /* NullKeyword */ : - case 155 /* UndefinedKeyword */ : - case 215 /* FunctionExpression */ : - case 228 /* ClassExpression */ : - case 216 /* ArrowFunction */ : - case 206 /* ArrayLiteralExpression */ : - case 207 /* ObjectLiteralExpression */ : - case 218 /* TypeOfExpression */ : - case 232 /* NonNullExpression */ : - case 282 /* JsxSelfClosingElement */ : - case 281 /* JsxElement */ : + case 80 /* Identifier */ : + case 11 /* StringLiteral */ : + case 14 /* RegularExpressionLiteral */ : + case 215 /* TaggedTemplateExpression */ : + case 228 /* TemplateExpression */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + case 9 /* NumericLiteral */ : + case 10 /* BigIntLiteral */ : + case 112 /* TrueKeyword */ : + case 97 /* FalseKeyword */ : + case 106 /* NullKeyword */ : + case 157 /* UndefinedKeyword */ : + case 218 /* FunctionExpression */ : + case 231 /* ClassExpression */ : + case 219 /* ArrowFunction */ : + case 209 /* ArrayLiteralExpression */ : + case 210 /* ObjectLiteralExpression */ : + case 221 /* TypeOfExpression */ : + case 235 /* NonNullExpression */ : + case 285 /* JsxSelfClosingElement */ : + case 284 /* JsxElement */ : return true; - case 224 /* ConditionalExpression */ : + case 227 /* ConditionalExpression */ : return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : if (isAssignmentOperator(node.operatorToken.kind)) return false; return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 221 /* PrefixUnaryExpression */ : - case 222 /* PostfixUnaryExpression */ : + case 224 /* PrefixUnaryExpression */ : + case 225 /* PostfixUnaryExpression */ : switch(node.operator){ - case 53 /* ExclamationToken */ : - case 39 /* PlusToken */ : - case 40 /* MinusToken */ : - case 54 /* TildeToken */ : + case 54 /* ExclamationToken */ : + case 40 /* PlusToken */ : + case 41 /* MinusToken */ : + case 55 /* TildeToken */ : return true; } return false; - case 219 /* VoidExpression */ : - case 213 /* TypeAssertionExpression */ : - case 231 /* AsExpression */ : + case 222 /* VoidExpression */ : + case 216 /* TypeAssertionExpression */ : + case 234 /* AsExpression */ : default: return false; } @@ -65132,9 +65862,9 @@ ${lanes.join("\n")} } checkGrammarNullishCoalesceWithLogicalExpression(node); const operator = node.operatorToken.kind; - if (operator === 63 /* EqualsToken */ && (node.left.kind === 207 /* ObjectLiteralExpression */ || node.left.kind === 206 /* ArrayLiteralExpression */ )) { + if (operator === 64 /* EqualsToken */ && (node.left.kind === 210 /* ObjectLiteralExpression */ || node.left.kind === 209 /* ArrayLiteralExpression */ )) { state.skip = true; - setLastResult(state, checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 108 /* ThisKeyword */ )); + setLastResult(state, checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 110 /* ThisKeyword */ )); return state; } return state; @@ -65151,8 +65881,8 @@ ${lanes.join("\n")} const operator = operatorToken.kind; if (isLogicalOrCoalescingBinaryOperator(operator)) { let parent2 = node.parent; - while(parent2.kind === 214 /* ParenthesizedExpression */ || isLogicalOrCoalescingBinaryExpression(parent2))parent2 = parent2.parent; - if (operator === 55 /* AmpersandAmpersandToken */ || isIfStatement(parent2)) checkTestingKnownTruthyCallableOrAwaitableType(node.left, leftType, isIfStatement(parent2) ? parent2.thenStatement : void 0); + while(parent2.kind === 217 /* ParenthesizedExpression */ || isLogicalOrCoalescingBinaryExpression(parent2))parent2 = parent2.parent; + if (operator === 56 /* AmpersandAmpersandToken */ || isIfStatement(parent2)) checkTestingKnownTruthyCallableOrAwaitableType(node.left, leftType, isIfStatement(parent2) ? parent2.thenStatement : void 0); checkTruthinessOfType(leftType, node.left); } } @@ -65168,7 +65898,7 @@ ${lanes.join("\n")} Debug.assertIsDefined(leftType); const rightType = getLastResult(state); Debug.assertIsDefined(rightType); - result = checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node); + result = checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, state.checkMode, node); } state.skip = false; setLeftType(state, /*type*/ void 0); @@ -65198,52 +65928,52 @@ ${lanes.join("\n")} } } function checkGrammarNullishCoalesceWithLogicalExpression(node) { - const { left: left , operatorToken: operatorToken , right: right } = node; - if (operatorToken.kind === 60 /* QuestionQuestionToken */ ) { - if (isBinaryExpression(left) && (left.operatorToken.kind === 56 /* BarBarToken */ || left.operatorToken.kind === 55 /* AmpersandAmpersandToken */ )) grammarErrorOnNode(left, Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, tokenToString(left.operatorToken.kind), tokenToString(operatorToken.kind)); - if (isBinaryExpression(right) && (right.operatorToken.kind === 56 /* BarBarToken */ || right.operatorToken.kind === 55 /* AmpersandAmpersandToken */ )) grammarErrorOnNode(right, Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, tokenToString(right.operatorToken.kind), tokenToString(operatorToken.kind)); + const { left: left, operatorToken: operatorToken, right: right } = node; + if (operatorToken.kind === 61 /* QuestionQuestionToken */ ) { + if (isBinaryExpression(left) && (left.operatorToken.kind === 57 /* BarBarToken */ || left.operatorToken.kind === 56 /* AmpersandAmpersandToken */ )) grammarErrorOnNode(left, Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, tokenToString(left.operatorToken.kind), tokenToString(operatorToken.kind)); + if (isBinaryExpression(right) && (right.operatorToken.kind === 57 /* BarBarToken */ || right.operatorToken.kind === 56 /* AmpersandAmpersandToken */ )) grammarErrorOnNode(right, Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, tokenToString(right.operatorToken.kind), tokenToString(operatorToken.kind)); } } function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { const operator = operatorToken.kind; - if (operator === 63 /* EqualsToken */ && (left.kind === 207 /* ObjectLiteralExpression */ || left.kind === 206 /* ArrayLiteralExpression */ )) return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 108 /* ThisKeyword */ ); + if (operator === 64 /* EqualsToken */ && (left.kind === 210 /* ObjectLiteralExpression */ || left.kind === 209 /* ArrayLiteralExpression */ )) return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 110 /* ThisKeyword */ ); let leftType; if (isLogicalOrCoalescingBinaryOperator(operator)) leftType = checkTruthinessExpression(left, checkMode); else leftType = checkExpression(left, checkMode); const rightType = checkExpression(right, checkMode); - return checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode); + return checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, checkMode, errorNode); } - function checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode) { + function checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, checkMode, errorNode) { const operator = operatorToken.kind; switch(operator){ - case 41 /* AsteriskToken */ : - case 42 /* AsteriskAsteriskToken */ : - case 66 /* AsteriskEqualsToken */ : - case 67 /* AsteriskAsteriskEqualsToken */ : - case 43 /* SlashToken */ : - case 68 /* SlashEqualsToken */ : - case 44 /* PercentToken */ : - case 69 /* PercentEqualsToken */ : - case 40 /* MinusToken */ : - case 65 /* MinusEqualsToken */ : - case 47 /* LessThanLessThanToken */ : - case 70 /* LessThanLessThanEqualsToken */ : - case 48 /* GreaterThanGreaterThanToken */ : - case 71 /* GreaterThanGreaterThanEqualsToken */ : - case 49 /* GreaterThanGreaterThanGreaterThanToken */ : - case 72 /* GreaterThanGreaterThanGreaterThanEqualsToken */ : - case 51 /* BarToken */ : - case 74 /* BarEqualsToken */ : - case 52 /* CaretToken */ : - case 78 /* CaretEqualsToken */ : - case 50 /* AmpersandToken */ : - case 73 /* AmpersandEqualsToken */ : + case 42 /* AsteriskToken */ : + case 43 /* AsteriskAsteriskToken */ : + case 67 /* AsteriskEqualsToken */ : + case 68 /* AsteriskAsteriskEqualsToken */ : + case 44 /* SlashToken */ : + case 69 /* SlashEqualsToken */ : + case 45 /* PercentToken */ : + case 70 /* PercentEqualsToken */ : + case 41 /* MinusToken */ : + case 66 /* MinusEqualsToken */ : + case 48 /* LessThanLessThanToken */ : + case 71 /* LessThanLessThanEqualsToken */ : + case 49 /* GreaterThanGreaterThanToken */ : + case 72 /* GreaterThanGreaterThanEqualsToken */ : + case 50 /* GreaterThanGreaterThanGreaterThanToken */ : + case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */ : + case 52 /* BarToken */ : + case 75 /* BarEqualsToken */ : + case 53 /* CaretToken */ : + case 79 /* CaretEqualsToken */ : + case 51 /* AmpersandToken */ : + case 74 /* AmpersandEqualsToken */ : if (leftType === silentNeverType || rightType === silentNeverType) return silentNeverType; leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); let suggestedOperator; if (leftType.flags & 528 /* BooleanLike */ && rightType.flags & 528 /* BooleanLike */ && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== void 0) { - error(errorNode || operatorToken, Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, tokenToString(operatorToken.kind), tokenToString(suggestedOperator)); + error2(errorNode || operatorToken, Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, tokenToString(operatorToken.kind), tokenToString(suggestedOperator)); return numberType; } else { const leftOk = checkArithmeticOperandType(left, leftType, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type, /*isAwaitValid*/ true); @@ -65253,13 +65983,13 @@ ${lanes.join("\n")} !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */ ) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */ ))) resultType2 = numberType; else if (bothAreBigIntLike(leftType, rightType)) { switch(operator){ - case 49 /* GreaterThanGreaterThanGreaterThanToken */ : - case 72 /* GreaterThanGreaterThanGreaterThanEqualsToken */ : + case 50 /* GreaterThanGreaterThanGreaterThanToken */ : + case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */ : reportOperatorError(); break; - case 42 /* AsteriskAsteriskToken */ : - case 67 /* AsteriskAsteriskEqualsToken */ : - if (languageVersion < 3 /* ES2016 */ ) error(errorNode, Diagnostics.Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later); + case 43 /* AsteriskAsteriskToken */ : + case 68 /* AsteriskAsteriskEqualsToken */ : + if (languageVersion < 3 /* ES2016 */ ) error2(errorNode, Diagnostics.Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later); } resultType2 = bigintType; } else { @@ -65269,8 +65999,8 @@ ${lanes.join("\n")} if (leftOk && rightOk) checkAssignmentOperator(resultType2); return resultType2; } - case 39 /* PlusToken */ : - case 64 /* PlusEqualsToken */ : + case 40 /* PlusToken */ : + case 65 /* PlusEqualsToken */ : if (leftType === silentNeverType || rightType === silentNeverType) return silentNeverType; if (!isTypeAssignableToKind(leftType, 402653316 /* StringLike */ ) && !isTypeAssignableToKind(rightType, 402653316 /* StringLike */ )) { leftType = checkNonNullType(leftType, left); @@ -65287,12 +66017,12 @@ ${lanes.join("\n")} reportOperatorError((left2, right2)=>isTypeAssignableToKind(left2, closeEnoughKind) && isTypeAssignableToKind(right2, closeEnoughKind)); return anyType; } - if (operator === 64 /* PlusEqualsToken */ ) checkAssignmentOperator(resultType); + if (operator === 65 /* PlusEqualsToken */ ) checkAssignmentOperator(resultType); return resultType; - case 29 /* LessThanToken */ : - case 31 /* GreaterThanToken */ : - case 32 /* LessThanEqualsToken */ : - case 33 /* GreaterThanEqualsToken */ : + case 30 /* LessThanToken */ : + case 32 /* GreaterThanToken */ : + case 33 /* LessThanEqualsToken */ : + case 34 /* GreaterThanEqualsToken */ : if (checkForDisallowedESSymbolOperand(operator)) { leftType = getBaseTypeOfLiteralTypeForComparison(checkNonNullType(leftType, left)); rightType = getBaseTypeOfLiteralTypeForComparison(checkNonNullType(rightType, right)); @@ -65304,52 +66034,55 @@ ${lanes.join("\n")} }); } return booleanType; - case 34 /* EqualsEqualsToken */ : - case 35 /* ExclamationEqualsToken */ : - case 36 /* EqualsEqualsEqualsToken */ : - case 37 /* ExclamationEqualsEqualsToken */ : - if (isLiteralExpressionOfObject(left) || isLiteralExpressionOfObject(right)) { - const eqType = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */ ; - error(errorNode, Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value, eqType ? "false" : "true"); - } - checkNaNEquality(errorNode, operator, left, right); - reportOperatorErrorUnless((left2, right2)=>isTypeEqualityComparableTo(left2, right2) || isTypeEqualityComparableTo(right2, left2)); + case 35 /* EqualsEqualsToken */ : + case 36 /* ExclamationEqualsToken */ : + case 37 /* EqualsEqualsEqualsToken */ : + case 38 /* ExclamationEqualsEqualsToken */ : + if (!(checkMode && checkMode & 128 /* TypeOnly */ )) { + if ((isLiteralExpressionOfObject(left) || isLiteralExpressionOfObject(right)) && // only report for === and !== in JS, not == or != + (!isInJSFile(left) || operator === 37 /* EqualsEqualsEqualsToken */ || operator === 38 /* ExclamationEqualsEqualsToken */ )) { + const eqType = operator === 35 /* EqualsEqualsToken */ || operator === 37 /* EqualsEqualsEqualsToken */ ; + error2(errorNode, Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value, eqType ? "false" : "true"); + } + checkNaNEquality(errorNode, operator, left, right); + reportOperatorErrorUnless((left2, right2)=>isTypeEqualityComparableTo(left2, right2) || isTypeEqualityComparableTo(right2, left2)); + } return booleanType; - case 102 /* InstanceOfKeyword */ : + case 104 /* InstanceOfKeyword */ : return checkInstanceOfExpression(left, right, leftType, rightType); - case 101 /* InKeyword */ : + case 103 /* InKeyword */ : return checkInExpression(left, right, leftType, rightType); - case 55 /* AmpersandAmpersandToken */ : - case 76 /* AmpersandAmpersandEqualsToken */ : + case 56 /* AmpersandAmpersandToken */ : + case 77 /* AmpersandAmpersandEqualsToken */ : { const resultType2 = getTypeFacts(leftType) & 4194304 /* Truthy */ ? getUnionType([ extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType ]) : leftType; - if (operator === 76 /* AmpersandAmpersandEqualsToken */ ) checkAssignmentOperator(rightType); + if (operator === 77 /* AmpersandAmpersandEqualsToken */ ) checkAssignmentOperator(rightType); return resultType2; } - case 56 /* BarBarToken */ : - case 75 /* BarBarEqualsToken */ : + case 57 /* BarBarToken */ : + case 76 /* BarBarEqualsToken */ : { const resultType2 = getTypeFacts(leftType) & 8388608 /* Falsy */ ? getUnionType([ getNonNullableType(removeDefinitelyFalsyTypes(leftType)), rightType ], 2 /* Subtype */ ) : leftType; - if (operator === 75 /* BarBarEqualsToken */ ) checkAssignmentOperator(rightType); + if (operator === 76 /* BarBarEqualsToken */ ) checkAssignmentOperator(rightType); return resultType2; } - case 60 /* QuestionQuestionToken */ : - case 77 /* QuestionQuestionEqualsToken */ : + case 61 /* QuestionQuestionToken */ : + case 78 /* QuestionQuestionEqualsToken */ : { const resultType2 = getTypeFacts(leftType) & 262144 /* EQUndefinedOrNull */ ? getUnionType([ getNonNullableType(leftType), rightType ], 2 /* Subtype */ ) : leftType; - if (operator === 77 /* QuestionQuestionEqualsToken */ ) checkAssignmentOperator(rightType); + if (operator === 78 /* QuestionQuestionEqualsToken */ ) checkAssignmentOperator(rightType); return resultType2; } - case 63 /* EqualsToken */ : + case 64 /* EqualsToken */ : const declKind = isBinaryExpression(left.parent) ? getAssignmentDeclarationKind(left.parent) : 0 /* None */ ; checkAssignmentDeclaration(declKind, rightType); if (isAssignmentDeclaration2(declKind)) { @@ -65359,7 +66092,7 @@ ${lanes.join("\n")} checkAssignmentOperator(rightType); return rightType; } - case 27 /* CommaToken */ : + case 28 /* CommaToken */ : if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isIndirectCall(left.parent)) { const sf = getSourceFileOfNode(left); const sourceText = sf.text; @@ -65368,7 +66101,7 @@ ${lanes.join("\n")} if (diag2.code !== Diagnostics.JSX_expressions_must_have_one_parent_element.code) return false; return textSpanContainsPosition(diag2, start); }); - if (!isInDiag2657) error(left, Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); + if (!isInDiag2657) error2(left, Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); } return rightType; default: @@ -65382,7 +66115,7 @@ ${lanes.join("\n")} const propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */ ) { const name = prop.escapedName; - const symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */ , void 0, name, /*isUse*/ false); + const symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */ , /*nameNotFoundMessage*/ void 0, name, /*isUse*/ false); if ((symbol == null ? void 0 : symbol.declarations) && symbol.declarations.some(isJSDocTypedefTag)) { addDuplicateDeclarationErrorsForSymbols(symbol, Diagnostics.Duplicate_identifier_0, unescapeLeadingUnderscores(name), prop); addDuplicateDeclarationErrorsForSymbols(prop, Diagnostics.Duplicate_identifier_0, unescapeLeadingUnderscores(name), symbol); @@ -65391,28 +66124,28 @@ ${lanes.join("\n")} } } function isIndirectCall(node) { - return node.parent.kind === 214 /* ParenthesizedExpression */ && isNumericLiteral(node.left) && node.left.text === "0" && (isCallExpression(node.parent.parent) && node.parent.parent.expression === node.parent || node.parent.parent.kind === 212 /* TaggedTemplateExpression */ ) && // special-case for "eval" because it's the only non-access case where an indirect call actually affects behavior. + return node.parent.kind === 217 /* ParenthesizedExpression */ && isNumericLiteral(node.left) && node.left.text === "0" && (isCallExpression(node.parent.parent) && node.parent.parent.expression === node.parent || node.parent.parent.kind === 215 /* TaggedTemplateExpression */ ) && // special-case for "eval" because it's the only non-access case where an indirect call actually affects behavior. (isAccessExpression(node.right) || isIdentifier(node.right) && node.right.escapedText === "eval"); } function checkForDisallowedESSymbolOperand(operator2) { const offendingSymbolOperand = maybeTypeOfKindConsideringBaseConstraint(leftType, 12288 /* ESSymbolLike */ ) ? left : maybeTypeOfKindConsideringBaseConstraint(rightType, 12288 /* ESSymbolLike */ ) ? right : void 0; if (offendingSymbolOperand) { - error(offendingSymbolOperand, Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, tokenToString(operator2)); + error2(offendingSymbolOperand, Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, tokenToString(operator2)); return false; } return true; } function getSuggestedBooleanOperator(operator2) { switch(operator2){ - case 51 /* BarToken */ : - case 74 /* BarEqualsToken */ : - return 56 /* BarBarToken */ ; - case 52 /* CaretToken */ : - case 78 /* CaretEqualsToken */ : - return 37 /* ExclamationEqualsEqualsToken */ ; - case 50 /* AmpersandToken */ : - case 73 /* AmpersandEqualsToken */ : - return 55 /* AmpersandAmpersandToken */ ; + case 52 /* BarToken */ : + case 75 /* BarEqualsToken */ : + return 57 /* BarBarToken */ ; + case 53 /* CaretToken */ : + case 79 /* CaretEqualsToken */ : + return 38 /* ExclamationEqualsEqualsToken */ ; + case 51 /* AmpersandToken */ : + case 74 /* AmpersandEqualsToken */ : + return 56 /* AmpersandAmpersandToken */ ; default: return void 0; } @@ -65420,18 +66153,20 @@ ${lanes.join("\n")} function checkAssignmentOperator(valueType) { if (isAssignmentOperator(operator)) addLazyDiagnostic(checkAssignmentOperatorWorker); function checkAssignmentOperatorWorker() { + let assigneeType = leftType; + if (isCompoundAssignment(operatorToken.kind) && left.kind === 211 /* PropertyAccessExpression */ ) assigneeType = checkPropertyAccessExpression(left, /*checkMode*/ void 0, /*writeOnly*/ true); if (checkReferenceExpression(left, Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access, Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access)) { let headMessage; if (exactOptionalPropertyTypes && isPropertyAccessExpression(left) && maybeTypeOfKind(valueType, 32768 /* Undefined */ )) { const target = getTypeOfPropertyOfType(getTypeOfExpression(left.expression), left.name.escapedText); if (isExactOptionalPropertyMismatch(valueType, target)) headMessage = Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_type_of_the_target; } - checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right, headMessage); + checkTypeAssignableToAndOptionallyElaborate(valueType, assigneeType, left, right, headMessage); } } } function isAssignmentDeclaration2(kind) { - var _a2; + var _a; switch(kind){ case 2 /* ModuleExports */ : return true; @@ -65442,7 +66177,7 @@ ${lanes.join("\n")} case 4 /* ThisProperty */ : const symbol = getSymbolOfNode(left); const init = getAssignedExpandoInitializer(right); - return !!init && isObjectLiteralExpression(init) && !!((_a2 = symbol == null ? void 0 : symbol.exports) == null ? void 0 : _a2.size); + return !!init && isObjectLiteralExpression(init) && !!((_a = symbol == null ? void 0 : symbol.exports) == null ? void 0 : _a.size); default: return false; } @@ -65470,10 +66205,10 @@ ${lanes.join("\n")} } function tryGiveBetterPrimaryError(errNode, maybeMissingAwait, leftStr, rightStr) { switch(operatorToken.kind){ - case 36 /* EqualsEqualsEqualsToken */ : - case 34 /* EqualsEqualsToken */ : - case 37 /* ExclamationEqualsEqualsToken */ : - case 35 /* ExclamationEqualsToken */ : + case 37 /* EqualsEqualsEqualsToken */ : + case 35 /* EqualsEqualsToken */ : + case 38 /* ExclamationEqualsEqualsToken */ : + case 36 /* ExclamationEqualsToken */ : return errorAndMaybeSuggestAwait(errNode, maybeMissingAwait, Diagnostics.This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap, leftStr, rightStr); default: return void 0; @@ -65483,9 +66218,9 @@ ${lanes.join("\n")} const isLeftNaN = isGlobalNaN(skipParentheses(left2)); const isRightNaN = isGlobalNaN(skipParentheses(right2)); if (isLeftNaN || isRightNaN) { - const err = error(errorNode2, Diagnostics.This_condition_will_always_return_0, tokenToString(operator2 === 36 /* EqualsEqualsEqualsToken */ || operator2 === 34 /* EqualsEqualsToken */ ? 95 /* FalseKeyword */ : 110 /* TrueKeyword */ )); + const err = error2(errorNode2, Diagnostics.This_condition_will_always_return_0, tokenToString(operator2 === 37 /* EqualsEqualsEqualsToken */ || operator2 === 35 /* EqualsEqualsToken */ ? 97 /* FalseKeyword */ : 112 /* TrueKeyword */ )); if (isLeftNaN && isRightNaN) return; - const operatorString = operator2 === 37 /* ExclamationEqualsEqualsToken */ || operator2 === 35 /* ExclamationEqualsToken */ ? tokenToString(53 /* ExclamationToken */ ) : ""; + const operatorString = operator2 === 38 /* ExclamationEqualsEqualsToken */ || operator2 === 36 /* ExclamationEqualsToken */ ? tokenToString(54 /* ExclamationToken */ ) : ""; const location = isLeftNaN ? right2 : left2; const expression = skipParentheses(location); addRelatedInfo(err, createDiagnosticForNode(location, Diagnostics.Did_you_mean_0, `${operatorString}Number.isNaN(${isEntityNameExpression(expression) ? entityNameToString(expression) : "..."})`)); @@ -65542,18 +66277,18 @@ ${lanes.join("\n")} addLazyDiagnostic(()=>{ if (noImplicitAny && !expressionResultIsUnused(node)) { const contextualType = getContextualType2(node, /*contextFlags*/ void 0); - if (!contextualType || isTypeAny(contextualType)) error(node, Diagnostics.yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_type_annotation); + if (!contextualType || isTypeAny(contextualType)) error2(node, Diagnostics.yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_type_annotation); } }); } return type; function checkYieldExpressionGrammar() { - if (!(node.flags & 8192 /* YieldContext */ )) grammarErrorOnFirstToken(node, Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); - if (isInParameterInitializerBeforeContainingFunction(node)) error(node, Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); + if (!(node.flags & 16384 /* YieldContext */ )) grammarErrorOnFirstToken(node, Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); + if (isInParameterInitializerBeforeContainingFunction(node)) error2(node, Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); } } function checkConditionalExpression(node, checkMode) { - const type = checkTruthinessExpression(node.condition); + const type = checkTruthinessExpression(node.condition, checkMode); checkTestingKnownTruthyCallableOrAwaitableType(node.condition, type, node.whenTrue); const type1 = checkExpression(node.whenTrue, checkMode); const type2 = checkExpression(node.whenFalse, checkMode); @@ -65573,11 +66308,13 @@ ${lanes.join("\n")} const types = []; for (const span of node.templateSpans){ const type = checkExpression(span.expression); - if (maybeTypeOfKindConsideringBaseConstraint(type, 12288 /* ESSymbolLike */ )) error(span.expression, Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String); + if (maybeTypeOfKindConsideringBaseConstraint(type, 12288 /* ESSymbolLike */ )) error2(span.expression, Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String); texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } - return isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType2(node, /*contextFlags*/ void 0) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType; + if (isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType2(node, /*contextFlags*/ void 0) || unknownType, isTemplateLiteralContextualType)) return getTemplateLiteralType(texts, types); + const evaluated = node.parent.kind !== 215 /* TaggedTemplateExpression */ && evaluateTemplateExpression(node); + return evaluated ? getFreshTypeOfLiteralType(getStringLiteralType(evaluated)) : stringType; } function isTemplateLiteralContextualType(type) { return !!(type.flags & 134217856 /* TemplateLiteral */ || type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 402653316 /* StringLike */ )); @@ -65613,7 +66350,7 @@ ${lanes.join("\n")} } function isTypeAssertion(node) { node = skipParentheses(node, /*excludeJSDocTypeAssertions*/ true); - return node.kind === 213 /* TypeAssertionExpression */ || node.kind === 231 /* AsExpression */ || isJSDocTypeAssertion(node); + return node.kind === 216 /* TypeAssertionExpression */ || node.kind === 234 /* AsExpression */ || isJSDocTypeAssertion(node); } function checkDeclarationInitializer(declaration, checkMode, contextualType) { const initializer = getEffectiveInitializer(declaration); @@ -65622,15 +66359,15 @@ ${lanes.join("\n")} if (typeNode) return checkSatisfiesExpressionWorker(initializer, typeNode, checkMode); } const type = getQuickTypeOfExpression(initializer) || (contextualType ? checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ void 0, checkMode || 0 /* Normal */ ) : checkExpressionCached(initializer, checkMode)); - return isParameter(declaration) && declaration.name.kind === 204 /* ArrayBindingPattern */ && isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ? padTupleType(type, declaration.name) : type; + return isParameter(declaration) && declaration.name.kind === 207 /* ArrayBindingPattern */ && isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ? padTupleType(type, declaration.name) : type; } function padTupleType(type, pattern) { const patternElements = pattern.elements; - const elementTypes = getTypeArguments(type).slice(); + const elementTypes = getElementTypes(type).slice(); const elementFlags = type.target.elementFlags.slice(); for(let i = getTypeReferenceArity(type); i < patternElements.length; i++){ const e = patternElements[i]; - if (i < patternElements.length - 1 || !(e.kind === 205 /* BindingElement */ && e.dotDotDotToken)) { + if (i < patternElements.length - 1 || !(e.kind === 208 /* BindingElement */ && e.dotDotDotToken)) { elementTypes.push(!isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(e, /*includePatternInType*/ false, /*reportErrors*/ false) : anyType); elementFlags.push(2 /* Optional */ ); if (!isOmittedExpression(e) && !hasDefaultValue(e)) reportImplicitAny(e, anyType); @@ -65639,7 +66376,7 @@ ${lanes.join("\n")} return createTupleType(elementTypes, elementFlags, type.target.readonly); } function widenTypeInferredFromInitializer(declaration, type) { - const widened = getCombinedNodeFlags(declaration) & 2 /* Const */ || isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type); + const widened = getCombinedNodeFlagsCached(declaration) & 6 /* Constant */ || isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type); if (isInJSFile(declaration)) { if (isEmptyLiteralType(widened)) { reportImplicitAny(declaration, anyType); @@ -65667,23 +66404,19 @@ ${lanes.join("\n")} } function isConstContext(node) { const parent2 = node.parent; - return isAssertionExpression(parent2) && isConstTypeReference(parent2.type) || isJSDocTypeAssertion(parent2) && isConstTypeReference(getJSDocTypeAssertionType(parent2)) || isValidConstAssertionArgument(node) && isConstTypeParameterContext(node) || (isParenthesizedExpression(parent2) || isArrayLiteralExpression(parent2) || isSpreadElement(parent2)) && isConstContext(parent2) || (isPropertyAssignment(parent2) || isShorthandPropertyAssignment(parent2) || isTemplateSpan(parent2)) && isConstContext(parent2.parent); - } - function isConstTypeParameterContext(node) { - const contextualType = getContextualType2(node, 0 /* None */ ); - return !!contextualType && someType(contextualType, isConstTypeVariable); + return isAssertionExpression(parent2) && isConstTypeReference(parent2.type) || isJSDocTypeAssertion(parent2) && isConstTypeReference(getJSDocTypeAssertionType(parent2)) || isValidConstAssertionArgument(node) && isConstTypeVariable(getContextualType2(node, 0 /* None */ )) || (isParenthesizedExpression(parent2) || isArrayLiteralExpression(parent2) || isSpreadElement(parent2)) && isConstContext(parent2) || (isPropertyAssignment(parent2) || isShorthandPropertyAssignment(parent2) || isTemplateSpan(parent2)) && isConstContext(parent2.parent); } function checkExpressionForMutableLocation(node, checkMode, forceTuple) { const type = checkExpression(node, checkMode, forceTuple); return isConstContext(node) || isCommonJsExportedExpression(node) ? getRegularTypeOfLiteralType(type) : isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(getContextualType2(node, /*contextFlags*/ void 0), node, /*contextFlags*/ void 0)); } function checkPropertyAssignment(node, checkMode) { - if (node.name.kind === 164 /* ComputedPropertyName */ ) checkComputedPropertyName(node.name); + if (node.name.kind === 167 /* ComputedPropertyName */ ) checkComputedPropertyName(node.name); return checkExpressionForMutableLocation(node.initializer, checkMode); } function checkObjectLiteralMethod(node, checkMode) { checkGrammarMethod(node); - if (node.name.kind === 164 /* ComputedPropertyName */ ) checkComputedPropertyName(node.name); + if (node.name.kind === 167 /* ComputedPropertyName */ ) checkComputedPropertyName(node.name); const uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } @@ -65797,16 +66530,16 @@ ${lanes.join("\n")} function getTypeOfExpression(node) { const quickType = getQuickTypeOfExpression(node); if (quickType) return quickType; - if (node.flags & 134217728 /* TypeCached */ && flowTypeCache) { + if (node.flags & 268435456 /* TypeCached */ && flowTypeCache) { const cachedType = flowTypeCache[getNodeId(node)]; if (cachedType) return cachedType; } const startInvocationCount = flowInvocationCount; - const type = checkExpression(node); + const type = checkExpression(node, 128 /* TypeOnly */ ); if (flowInvocationCount !== startInvocationCount) { const cache = flowTypeCache || (flowTypeCache = []); cache[getNodeId(node)] = type; - setNodeFlags(node, node.flags | 134217728 /* TypeCached */ ); + setNodeFlags(node, node.flags | 268435456 /* TypeCached */ ); } return type; } @@ -65821,7 +66554,7 @@ ${lanes.join("\n")} const type = getQuickTypeOfExpression(expr.expression); return type ? getAwaitedType(type) : void 0; } - if (isCallExpression(expr) && expr.expression.kind !== 106 /* SuperKeyword */ && !isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) return isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) : getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression)); + if (isCallExpression(expr) && expr.expression.kind !== 108 /* SuperKeyword */ && !isRequireCall(expr, /*requireStringLiteralLikeArgument*/ true) && !isSymbolOrSymbolForCall(expr)) return isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) : getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression)); else if (isAssertionExpression(expr) && !isConstTypeReference(expr.type)) return getTypeFromTypeNode(expr.type); else if (isLiteralExpression(node) || isBooleanLiteral(node)) return checkExpression(node); return void 0; @@ -65835,8 +66568,8 @@ ${lanes.join("\n")} return type; } function checkExpression(node, checkMode, forceTuple) { - var _a2, _b; - (_a2 = tracing) == null || _a2.push(tracing.Phase.Check, "checkExpression", { + var _a, _b; + (_a = tracing) == null || _a.push(tracing.Phase.Check, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end, @@ -65853,132 +66586,129 @@ ${lanes.join("\n")} return type; } function checkConstEnumAccess(node, type) { - const ok = node.parent.kind === 208 /* PropertyAccessExpression */ && node.parent.expression === node || node.parent.kind === 209 /* ElementAccessExpression */ && node.parent.expression === node || (node.kind === 79 /* Identifier */ || node.kind === 163 /* QualifiedName */ ) && isInRightSideOfImportOrExportAssignment(node) || node.parent.kind === 183 /* TypeQuery */ && node.parent.exprName === node || node.parent.kind === 278 /* ExportSpecifier */ ; - if (!ok) error(node, Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); + const ok = node.parent.kind === 211 /* PropertyAccessExpression */ && node.parent.expression === node || node.parent.kind === 212 /* ElementAccessExpression */ && node.parent.expression === node || (node.kind === 80 /* Identifier */ || node.kind === 166 /* QualifiedName */ ) && isInRightSideOfImportOrExportAssignment(node) || node.parent.kind === 186 /* TypeQuery */ && node.parent.exprName === node || node.parent.kind === 281 /* ExportSpecifier */ ; + if (!ok) error2(node, Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); if (getIsolatedModules(compilerOptions)) { Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */ )); const constEnumDeclaration = type.symbol.valueDeclaration; - if (constEnumDeclaration.flags & 16777216 /* Ambient */ ) error(node, Diagnostics.Cannot_access_ambient_const_enums_when_0_is_enabled, isolatedModulesLikeFlagName); + if (constEnumDeclaration.flags & 33554432 /* Ambient */ && !isValidTypeOnlyAliasUseSite(node)) error2(node, Diagnostics.Cannot_access_ambient_const_enums_when_0_is_enabled, isolatedModulesLikeFlagName); } } function checkParenthesizedExpression(node, checkMode) { if (hasJSDocNodes(node)) { if (isJSDocSatisfiesExpression(node)) return checkSatisfiesExpressionWorker(node.expression, getJSDocSatisfiesExpressionType(node), checkMode); - if (isJSDocTypeAssertion(node)) { - const type = getJSDocTypeAssertionType(node); - return checkAssertionWorker(type, type, node.expression, checkMode); - } + if (isJSDocTypeAssertion(node)) return checkAssertionWorker(node, checkMode); } return checkExpression(node.expression, checkMode); } function checkExpressionWorker(node, checkMode, forceTuple) { const kind = node.kind; if (cancellationToken) switch(kind){ - case 228 /* ClassExpression */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : + case 231 /* ClassExpression */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : cancellationToken.throwIfCancellationRequested(); } switch(kind){ - case 79 /* Identifier */ : + case 80 /* Identifier */ : return checkIdentifier(node, checkMode); - case 80 /* PrivateIdentifier */ : + case 81 /* PrivateIdentifier */ : return checkPrivateIdentifierExpression(node); - case 108 /* ThisKeyword */ : + case 110 /* ThisKeyword */ : return checkThisExpression(node); - case 106 /* SuperKeyword */ : + case 108 /* SuperKeyword */ : return checkSuperExpression(node); - case 104 /* NullKeyword */ : + case 106 /* NullKeyword */ : return nullWideningType; - case 14 /* NoSubstitutionTemplateLiteral */ : - case 10 /* StringLiteral */ : - return getFreshTypeOfLiteralType(getStringLiteralType(node.text)); - case 8 /* NumericLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + case 11 /* StringLiteral */ : + return hasSkipDirectInferenceFlag(node) ? wildcardType : getFreshTypeOfLiteralType(getStringLiteralType(node.text)); + case 9 /* NumericLiteral */ : checkGrammarNumericLiteral(node); return getFreshTypeOfLiteralType(getNumberLiteralType(+node.text)); - case 9 /* BigIntLiteral */ : + case 10 /* BigIntLiteral */ : checkGrammarBigIntLiteral(node); return getFreshTypeOfLiteralType(getBigIntLiteralType({ negative: false, base10Value: parsePseudoBigInt(node.text) })); - case 110 /* TrueKeyword */ : + case 112 /* TrueKeyword */ : return trueType; - case 95 /* FalseKeyword */ : + case 97 /* FalseKeyword */ : return falseType; - case 225 /* TemplateExpression */ : + case 228 /* TemplateExpression */ : return checkTemplateExpression(node); - case 13 /* RegularExpressionLiteral */ : + case 14 /* RegularExpressionLiteral */ : return globalRegExpType; - case 206 /* ArrayLiteralExpression */ : + case 209 /* ArrayLiteralExpression */ : return checkArrayLiteral(node, checkMode, forceTuple); - case 207 /* ObjectLiteralExpression */ : + case 210 /* ObjectLiteralExpression */ : return checkObjectLiteral(node, checkMode); - case 208 /* PropertyAccessExpression */ : + case 211 /* PropertyAccessExpression */ : return checkPropertyAccessExpression(node, checkMode); - case 163 /* QualifiedName */ : + case 166 /* QualifiedName */ : return checkQualifiedName(node, checkMode); - case 209 /* ElementAccessExpression */ : + case 212 /* ElementAccessExpression */ : return checkIndexedAccess(node, checkMode); - case 210 /* CallExpression */ : - if (node.expression.kind === 100 /* ImportKeyword */ ) return checkImportCallExpression(node); - case 211 /* NewExpression */ : + case 213 /* CallExpression */ : + if (node.expression.kind === 102 /* ImportKeyword */ ) return checkImportCallExpression(node); + case 214 /* NewExpression */ : return checkCallExpression(node, checkMode); - case 212 /* TaggedTemplateExpression */ : + case 215 /* TaggedTemplateExpression */ : return checkTaggedTemplateExpression(node); - case 214 /* ParenthesizedExpression */ : + case 217 /* ParenthesizedExpression */ : return checkParenthesizedExpression(node, checkMode); - case 228 /* ClassExpression */ : + case 231 /* ClassExpression */ : return checkClassExpression(node); - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 218 /* TypeOfExpression */ : + case 221 /* TypeOfExpression */ : return checkTypeOfExpression(node); - case 213 /* TypeAssertionExpression */ : - case 231 /* AsExpression */ : - return checkAssertion(node); - case 232 /* NonNullExpression */ : + case 216 /* TypeAssertionExpression */ : + case 234 /* AsExpression */ : + return checkAssertion(node, checkMode); + case 235 /* NonNullExpression */ : return checkNonNullAssertion(node); - case 230 /* ExpressionWithTypeArguments */ : + case 233 /* ExpressionWithTypeArguments */ : return checkExpressionWithTypeArguments(node); - case 235 /* SatisfiesExpression */ : + case 238 /* SatisfiesExpression */ : return checkSatisfiesExpression(node); - case 233 /* MetaProperty */ : + case 236 /* MetaProperty */ : return checkMetaProperty(node); - case 217 /* DeleteExpression */ : + case 220 /* DeleteExpression */ : return checkDeleteExpression(node); - case 219 /* VoidExpression */ : + case 222 /* VoidExpression */ : return checkVoidExpression(node); - case 220 /* AwaitExpression */ : + case 223 /* AwaitExpression */ : return checkAwaitExpression(node); - case 221 /* PrefixUnaryExpression */ : + case 224 /* PrefixUnaryExpression */ : return checkPrefixUnaryExpression(node); - case 222 /* PostfixUnaryExpression */ : + case 225 /* PostfixUnaryExpression */ : return checkPostfixUnaryExpression(node); - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : return checkBinaryExpression(node, checkMode); - case 224 /* ConditionalExpression */ : + case 227 /* ConditionalExpression */ : return checkConditionalExpression(node, checkMode); - case 227 /* SpreadElement */ : + case 230 /* SpreadElement */ : return checkSpreadExpression(node, checkMode); - case 229 /* OmittedExpression */ : + case 232 /* OmittedExpression */ : return undefinedWideningType; - case 226 /* YieldExpression */ : + case 229 /* YieldExpression */ : return checkYieldExpression(node); - case 234 /* SyntheticExpression */ : + case 237 /* SyntheticExpression */ : return checkSyntheticExpression(node); - case 291 /* JsxExpression */ : + case 294 /* JsxExpression */ : return checkJsxExpression(node, checkMode); - case 281 /* JsxElement */ : + case 284 /* JsxElement */ : return checkJsxElement(node, checkMode); - case 282 /* JsxSelfClosingElement */ : + case 285 /* JsxSelfClosingElement */ : return checkJsxSelfClosingElement(node, checkMode); - case 285 /* JsxFragment */ : + case 288 /* JsxFragment */ : return checkJsxFragment(node); - case 289 /* JsxAttributes */ : + case 292 /* JsxAttributes */ : return checkJsxAttributes(node, checkMode); - case 283 /* JsxOpeningElement */ : + case 286 /* JsxOpeningElement */ : Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return errorType; @@ -65990,7 +66720,7 @@ ${lanes.join("\n")} checkSourceElement(node.default); const typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node)); getBaseConstraintOfType(typeParameter); - if (!hasNonCircularTypeParameterDefault(typeParameter)) error(node.default, Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); + if (!hasNonCircularTypeParameterDefault(typeParameter)) error2(node.default, Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); const constraintType = getConstraintOfTypeParameter(typeParameter); const defaultType = getDefaultFromTypeParameter(typeParameter); if (constraintType && defaultType) checkTypeAssignableTo(defaultType, getTypeWithThisArgument(instantiateType(constraintType, makeUnaryTypeMapper(typeParameter, defaultType)), defaultType), node.default, Diagnostics.Type_0_does_not_satisfy_the_constraint_1); @@ -65998,15 +66728,15 @@ ${lanes.join("\n")} addLazyDiagnostic(()=>checkTypeNameIsReserved(node.name, Diagnostics.Type_parameter_name_cannot_be_0)); } function checkTypeParameterDeferred(node) { - var _a2, _b; + var _a, _b; if (isInterfaceDeclaration(node.parent) || isClassLike(node.parent) || isTypeAliasDeclaration(node.parent)) { const typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node)); const modifiers = getTypeParameterModifiers(typeParameter) & 98304 /* Out */ ; if (modifiers) { const symbol = getSymbolOfDeclaration(node.parent); - if (isTypeAliasDeclaration(node.parent) && !(getObjectFlags(getDeclaredTypeOfSymbol(symbol)) & 48 /* Mapped */ )) error(node, Diagnostics.Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_types); + if (isTypeAliasDeclaration(node.parent) && !(getObjectFlags(getDeclaredTypeOfSymbol(symbol)) & 48 /* Mapped */ )) error2(node, Diagnostics.Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_types); else if (modifiers === 32768 /* In */ || modifiers === 65536 /* Out */ ) { - (_a2 = tracing) == null || _a2.push(tracing.Phase.CheckTypes, "checkTypeParameterDeferred", { + (_a = tracing) == null || _a.push(tracing.Phase.CheckTypes, "checkTypeParameterDeferred", { parent: getTypeId(getDeclaredTypeOfSymbol(symbol)), id: getTypeId(typeParameter) }); @@ -66026,56 +66756,56 @@ ${lanes.join("\n")} checkVariableLikeDeclaration(node); const func = getContainingFunction(node); if (hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */ )) { - if (!(func.kind === 173 /* Constructor */ && nodeIsPresent(func.body))) error(node, Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); - if (func.kind === 173 /* Constructor */ && isIdentifier(node.name) && node.name.escapedText === "constructor") error(node.name, Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name); + if (!(func.kind === 176 /* Constructor */ && nodeIsPresent(func.body))) error2(node, Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); + if (func.kind === 176 /* Constructor */ && isIdentifier(node.name) && node.name.escapedText === "constructor") error2(node.name, Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name); } - if (!node.initializer && isOptionalDeclaration(node) && isBindingPattern(node.name) && func.body) error(node, Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); + if (!node.initializer && isOptionalDeclaration(node) && isBindingPattern(node.name) && func.body) error2(node, Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); if (node.name && isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { - if (func.parameters.indexOf(node) !== 0) error(node, Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); - if (func.kind === 173 /* Constructor */ || func.kind === 177 /* ConstructSignature */ || func.kind === 182 /* ConstructorType */ ) error(node, Diagnostics.A_constructor_cannot_have_a_this_parameter); - if (func.kind === 216 /* ArrowFunction */ ) error(node, Diagnostics.An_arrow_function_cannot_have_a_this_parameter); - if (func.kind === 174 /* GetAccessor */ || func.kind === 175 /* SetAccessor */ ) error(node, Diagnostics.get_and_set_accessors_cannot_declare_this_parameters); + if (func.parameters.indexOf(node) !== 0) error2(node, Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); + if (func.kind === 176 /* Constructor */ || func.kind === 180 /* ConstructSignature */ || func.kind === 185 /* ConstructorType */ ) error2(node, Diagnostics.A_constructor_cannot_have_a_this_parameter); + if (func.kind === 219 /* ArrowFunction */ ) error2(node, Diagnostics.An_arrow_function_cannot_have_a_this_parameter); + if (func.kind === 177 /* GetAccessor */ || func.kind === 178 /* SetAccessor */ ) error2(node, Diagnostics.get_and_set_accessors_cannot_declare_this_parameters); } - if (node.dotDotDotToken && !isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) error(node, Diagnostics.A_rest_parameter_must_be_of_an_array_type); + if (node.dotDotDotToken && !isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) error2(node, Diagnostics.A_rest_parameter_must_be_of_an_array_type); } function checkTypePredicate(node) { const parent2 = getTypePredicateParent(node); if (!parent2) { - error(node, Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + error2(node, Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); return; } const signature = getSignatureFromDeclaration(parent2); const typePredicate = getTypePredicateOfSignature(signature); if (!typePredicate) return; checkSourceElement(node.type); - const { parameterName: parameterName } = node; + const { parameterName: parameterName } = node; if (typePredicate.kind === 0 /* This */ || typePredicate.kind === 2 /* AssertsThis */ ) getTypeFromThisTypeNode(parameterName); else { if (typePredicate.parameterIndex >= 0) { - if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) error(parameterName, Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) error2(parameterName, Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); else if (typePredicate.type) { const leadingError = ()=>chainDiagnosticMessages(/*details*/ void 0, Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type, /*headMessage*/ void 0, leadingError); } } else if (parameterName) { let hasReportedError = false; - for (const { name: name } of parent2.parameters)if (isBindingPattern(name) && checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { + for (const { name: name } of parent2.parameters)if (isBindingPattern(name) && checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } - if (!hasReportedError) error(node.parameterName, Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + if (!hasReportedError) error2(node.parameterName, Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); } } } function getTypePredicateParent(node) { switch(node.parent.kind){ - case 216 /* ArrowFunction */ : - case 176 /* CallSignature */ : - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 181 /* FunctionType */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : + case 219 /* ArrowFunction */ : + case 179 /* CallSignature */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 184 /* FunctionType */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : const parent2 = node.parent; if (node === parent2.type) return parent2; } @@ -66084,17 +66814,17 @@ ${lanes.join("\n")} for (const element of pattern.elements){ if (isOmittedExpression(element)) continue; const name = element.name; - if (name.kind === 79 /* Identifier */ && name.escapedText === predicateVariableName) { - error(predicateVariableNode, Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); + if (name.kind === 80 /* Identifier */ && name.escapedText === predicateVariableName) { + error2(predicateVariableNode, Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; - } else if (name.kind === 204 /* ArrayBindingPattern */ || name.kind === 203 /* ObjectBindingPattern */ ) { + } else if (name.kind === 207 /* ArrayBindingPattern */ || name.kind === 206 /* ObjectBindingPattern */ ) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) return true; } } } function checkSignatureDeclaration(node) { - if (node.kind === 178 /* IndexSignature */ ) checkGrammarIndexSignature(node); - else if (node.kind === 181 /* FunctionType */ || node.kind === 259 /* FunctionDeclaration */ || node.kind === 182 /* ConstructorType */ || node.kind === 176 /* CallSignature */ || node.kind === 173 /* Constructor */ || node.kind === 177 /* ConstructSignature */ ) checkGrammarFunctionLikeDeclaration(node); + if (node.kind === 181 /* IndexSignature */ ) checkGrammarIndexSignature(node); + else if (node.kind === 184 /* FunctionType */ || node.kind === 262 /* FunctionDeclaration */ || node.kind === 185 /* ConstructorType */ || node.kind === 179 /* CallSignature */ || node.kind === 176 /* Constructor */ || node.kind === 180 /* ConstructSignature */ ) checkGrammarFunctionLikeDeclaration(node); const functionFlags = getFunctionFlags(node); if (!(functionFlags & 4 /* Invalid */ )) { if ((functionFlags & 3 /* AsyncGenerator */ ) === 3 /* AsyncGenerator */ && languageVersion < 99 /* ESNext */ ) checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */ ); @@ -66108,37 +66838,48 @@ ${lanes.join("\n")} addLazyDiagnostic(checkSignatureDeclarationDiagnostics); function checkSignatureDeclarationDiagnostics() { checkCollisionWithArgumentsInGeneratedCode(node); - const returnTypeNode = getEffectiveReturnTypeNode(node); + let returnTypeNode = getEffectiveReturnTypeNode(node); + let returnTypeErrorLocation = returnTypeNode; + if (isInJSFile(node)) { + const typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && isTypeReferenceNode(typeTag.typeExpression.type)) { + const signature = getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); + if (signature && signature.declaration) { + returnTypeNode = getEffectiveReturnTypeNode(signature.declaration); + returnTypeErrorLocation = typeTag.typeExpression.type; + } + } + } if (noImplicitAny && !returnTypeNode) switch(node.kind){ - case 177 /* ConstructSignature */ : - error(node, Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + case 180 /* ConstructSignature */ : + error2(node, Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 176 /* CallSignature */ : - error(node, Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + case 179 /* CallSignature */ : + error2(node, Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } - if (returnTypeNode) { + if (returnTypeNode && returnTypeErrorLocation) { const functionFlags2 = getFunctionFlags(node); if ((functionFlags2 & 5 /* Generator */ ) === 1 /* Generator */ ) { const returnType = getTypeFromTypeNode(returnTypeNode); - if (returnType === voidType) error(returnTypeNode, Diagnostics.A_generator_cannot_have_a_void_type_annotation); + if (returnType === voidType) error2(returnTypeErrorLocation, Diagnostics.A_generator_cannot_have_a_void_type_annotation); else { const generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */ , returnType, (functionFlags2 & 2 /* Async */ ) !== 0) || anyType; const generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */ , returnType, (functionFlags2 & 2 /* Async */ ) !== 0) || generatorYieldType; const generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */ , returnType, (functionFlags2 & 2 /* Async */ ) !== 0) || unknownType; const generatorInstantiation = createGeneratorReturnType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags2 & 2 /* Async */ )); - checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeNode); + checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeErrorLocation); } - } else if ((functionFlags2 & 3 /* AsyncGenerator */ ) === 2 /* Async */ ) checkAsyncFunctionReturnType(node, returnTypeNode); + } else if ((functionFlags2 & 3 /* AsyncGenerator */ ) === 2 /* Async */ ) checkAsyncFunctionReturnType(node, returnTypeNode, returnTypeErrorLocation); } - if (node.kind !== 178 /* IndexSignature */ && node.kind !== 320 /* JSDocFunctionType */ ) registerForUnusedIdentifiersCheck(node); + if (node.kind !== 181 /* IndexSignature */ && node.kind !== 324 /* JSDocFunctionType */ ) registerForUnusedIdentifiersCheck(node); } } function checkClassForDuplicateDeclarations(node) { const instanceNames = /* @__PURE__ */ new Map(); const staticNames = /* @__PURE__ */ new Map(); const privateIdentifiers = /* @__PURE__ */ new Map(); - for (const member of node.members)if (member.kind === 173 /* Constructor */ ) { + for (const member of node.members)if (member.kind === 176 /* Constructor */ ) { for (const param of member.parameters)if (isParameterPropertyDeclaration(param, member) && !isBindingPattern(param.name)) addName(instanceNames, param.name, param.name.escapedText, 3 /* GetOrSetAccessor */ ); } else { const isStaticMember = isStatic(member); @@ -66149,16 +66890,16 @@ ${lanes.join("\n")} const names = isPrivate ? privateIdentifiers : isStaticMember ? staticNames : instanceNames; const memberName = name && getPropertyNameForPropertyNameNode(name); if (memberName) switch(member.kind){ - case 174 /* GetAccessor */ : + case 177 /* GetAccessor */ : addName(names, name, memberName, 1 /* GetAccessor */ | privateStaticFlags); break; - case 175 /* SetAccessor */ : + case 178 /* SetAccessor */ : addName(names, name, memberName, 2 /* SetAccessor */ | privateStaticFlags); break; - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : addName(names, name, memberName, 3 /* GetOrSetAccessor */ | privateStaticFlags); break; - case 171 /* MethodDeclaration */ : + case 174 /* MethodDeclaration */ : addName(names, name, memberName, 8 /* Method */ | privateStaticFlags); break; } @@ -66166,13 +66907,13 @@ ${lanes.join("\n")} function addName(names, location, name, meaning) { const prev = names.get(name); if (prev) { - if ((prev & 16 /* PrivateStatic */ ) !== (meaning & 16 /* PrivateStatic */ )) error(location, Diagnostics.Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name, getTextOfNode(location)); + if ((prev & 16 /* PrivateStatic */ ) !== (meaning & 16 /* PrivateStatic */ )) error2(location, Diagnostics.Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name, getTextOfNode(location)); else { const prevIsMethod = !!(prev & 8 /* Method */ ); const isMethod = !!(meaning & 8 /* Method */ ); if (prevIsMethod || isMethod) { - if (prevIsMethod !== isMethod) error(location, Diagnostics.Duplicate_identifier_0, getTextOfNode(location)); - } else if (prev & meaning & -17 /* PrivateStatic */ ) error(location, Diagnostics.Duplicate_identifier_0, getTextOfNode(location)); + if (prevIsMethod !== isMethod) error2(location, Diagnostics.Duplicate_identifier_0, getTextOfNode(location)); + } else if (prev & meaning & -17 /* PrivateStatic */ ) error2(location, Diagnostics.Duplicate_identifier_0, getTextOfNode(location)); else names.set(name, prev | meaning); } } else names.set(name, meaning); @@ -66189,10 +66930,11 @@ ${lanes.join("\n")} case "length": case "caller": case "arguments": + if (useDefineForClassFields) break; case "prototype": const message = Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; const className = getNameOfSymbolAsWritten(getSymbolOfDeclaration(node)); - error(memberNameNode, message, memberName, className); + error2(memberNameNode, message, memberName, className); break; } } @@ -66200,28 +66942,28 @@ ${lanes.join("\n")} } function checkObjectTypeForDuplicateDeclarations(node) { const names = /* @__PURE__ */ new Map(); - for (const member of node.members)if (member.kind === 168 /* PropertySignature */ ) { + for (const member of node.members)if (member.kind === 171 /* PropertySignature */ ) { let memberName; const name = member.name; switch(name.kind){ - case 10 /* StringLiteral */ : - case 8 /* NumericLiteral */ : + case 11 /* StringLiteral */ : + case 9 /* NumericLiteral */ : memberName = name.text; break; - case 79 /* Identifier */ : + case 80 /* Identifier */ : memberName = idText(name); break; default: continue; } if (names.get(memberName)) { - error(getNameOfDeclaration(member.symbol.valueDeclaration), Diagnostics.Duplicate_identifier_0, memberName); - error(member.name, Diagnostics.Duplicate_identifier_0, memberName); + error2(getNameOfDeclaration(member.symbol.valueDeclaration), Diagnostics.Duplicate_identifier_0, memberName); + error2(member.name, Diagnostics.Duplicate_identifier_0, memberName); } else names.set(memberName, true); } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 261 /* InterfaceDeclaration */ ) { + if (node.kind === 264 /* InterfaceDeclaration */ ) { const nodeSymbol = getSymbolOfDeclaration(node); if (nodeSymbol.declarations && nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) return; } @@ -66239,7 +66981,7 @@ ${lanes.join("\n")} }); }); indexSignatureMap.forEach((entry)=>{ - if (entry.declarations.length > 1) for (const declaration of entry.declarations)error(declaration, Diagnostics.Duplicate_index_signature_for_type_0, typeToString(entry.type)); + if (entry.declarations.length > 1) for (const declaration of entry.declarations)error2(declaration, Diagnostics.Duplicate_index_signature_for_type_0, typeToString(entry.type)); }); } } @@ -66247,23 +66989,23 @@ ${lanes.join("\n")} if (!checkGrammarModifiers(node) && !checkGrammarProperty(node)) checkGrammarComputedPropertyName(node.name); checkVariableLikeDeclaration(node); setNodeLinksForPrivateIdentifierScope(node); - if (hasSyntacticModifier(node, 256 /* Abstract */ ) && node.kind === 169 /* PropertyDeclaration */ && node.initializer) error(node, Diagnostics.Property_0_cannot_have_an_initializer_because_it_is_marked_abstract, declarationNameToString(node.name)); + if (hasSyntacticModifier(node, 256 /* Abstract */ ) && node.kind === 172 /* PropertyDeclaration */ && node.initializer) error2(node, Diagnostics.Property_0_cannot_have_an_initializer_because_it_is_marked_abstract, declarationNameToString(node.name)); } function checkPropertySignature(node) { - if (isPrivateIdentifier(node.name)) error(node, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + if (isPrivateIdentifier(node.name)) error2(node, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); return checkPropertyDeclaration(node); } function checkMethodDeclaration(node) { if (!checkGrammarMethod(node)) checkGrammarComputedPropertyName(node.name); - if (isMethodDeclaration(node) && node.asteriskToken && isIdentifier(node.name) && idText(node.name) === "constructor") error(node.name, Diagnostics.Class_constructor_may_not_be_a_generator); + if (isMethodDeclaration(node) && node.asteriskToken && isIdentifier(node.name) && idText(node.name) === "constructor") error2(node.name, Diagnostics.Class_constructor_may_not_be_a_generator); checkFunctionOrMethodDeclaration(node); - if (hasSyntacticModifier(node, 256 /* Abstract */ ) && node.kind === 171 /* MethodDeclaration */ && node.body) error(node, Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, declarationNameToString(node.name)); - if (isPrivateIdentifier(node.name) && !getContainingClass(node)) error(node, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + if (hasSyntacticModifier(node, 256 /* Abstract */ ) && node.kind === 174 /* MethodDeclaration */ && node.body) error2(node, Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, declarationNameToString(node.name)); + if (isPrivateIdentifier(node.name) && !getContainingClass(node)) error2(node, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); setNodeLinksForPrivateIdentifierScope(node); } function setNodeLinksForPrivateIdentifierScope(node) { if (isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */ ) { - for(let lexicalScope = getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = getEnclosingBlockScopeContainer(lexicalScope))getNodeLinks(lexicalScope).flags |= 4194304 /* ContainsClassWithPrivateIdentifiers */ ; + for(let lexicalScope = getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = getEnclosingBlockScopeContainer(lexicalScope))getNodeLinks(lexicalScope).flags |= 1048576 /* ContainsClassWithPrivateIdentifiers */ ; if (isClassExpression(node.parent)) { const enclosingIterationStatement = getEnclosingIterationStatement(node.parent); if (enclosingIterationStatement) { @@ -66289,7 +67031,7 @@ ${lanes.join("\n")} return; function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n) { if (isPrivateIdentifierClassElementDeclaration(n)) return true; - return n.kind === 169 /* PropertyDeclaration */ && !isStatic(n) && !!n.initializer; + return n.kind === 172 /* PropertyDeclaration */ && !isStatic(n) && !!n.initializer; } function checkConstructorDeclarationDiagnostics() { const containingClassDecl = node.parent; @@ -66298,10 +67040,10 @@ ${lanes.join("\n")} const classExtendsNull = classDeclarationExtendsNull(containingClassDecl); const superCall = findFirstSuperCall(node.body); if (superCall) { - if (classExtendsNull) error(superCall, Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); - const superCallShouldBeRootLevel = (getEmitScriptTarget(compilerOptions) !== 99 /* ESNext */ || !useDefineForClassFields) && (some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || some(node.parameters, (p)=>hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */ ))); + if (classExtendsNull) error2(superCall, Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); + const superCallShouldBeRootLevel = !emitStandardClassFields && (some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || some(node.parameters, (p)=>hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */ ))); if (superCallShouldBeRootLevel) { - if (!superCallIsRootLevelInConstructor(superCall, node.body)) error(superCall, Diagnostics.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); + if (!superCallIsRootLevelInConstructor(superCall, node.body)) error2(superCall, Diagnostics.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); else { let superCallStatement; for (const statement of node.body.statements){ @@ -66311,10 +67053,10 @@ ${lanes.join("\n")} } if (nodeImmediatelyReferencesSuperOrThis(statement)) break; } - if (superCallStatement === void 0) error(node, Diagnostics.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); + if (superCallStatement === void 0) error2(node, Diagnostics.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); } } - } else if (!classExtendsNull) error(node, Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); + } else if (!classExtendsNull) error2(node, Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); } } } @@ -66323,12 +67065,12 @@ ${lanes.join("\n")} return isExpressionStatement(superCallParent) && superCallParent.parent === body; } function nodeImmediatelyReferencesSuperOrThis(node) { - if (node.kind === 106 /* SuperKeyword */ || node.kind === 108 /* ThisKeyword */ ) return true; + if (node.kind === 108 /* SuperKeyword */ || node.kind === 110 /* ThisKeyword */ ) return true; if (isThisContainerOrFunctionBlock(node)) return false; return !!forEachChild(node, nodeImmediatelyReferencesSuperOrThis); } function checkAccessorDeclaration(node) { - if (isIdentifier(node.name) && idText(node.name) === "constructor") error(node.name, Diagnostics.Class_constructor_may_not_be_an_accessor); + if (isIdentifier(node.name) && idText(node.name) === "constructor" && isClassLike(node.parent)) error2(node.name, Diagnostics.Class_constructor_may_not_be_an_accessor); addLazyDiagnostic(checkAccessorDeclarationDiagnostics); checkSourceElement(node.body); setNodeLinksForPrivateIdentifierScope(node); @@ -66336,35 +67078,32 @@ ${lanes.join("\n")} if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node)) checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 174 /* GetAccessor */ ) { - if (!(node.flags & 16777216 /* Ambient */ ) && nodeIsPresent(node.body) && node.flags & 256 /* HasImplicitReturn */ ) { - if (!(node.flags & 512 /* HasExplicitReturn */ )) error(node.name, Diagnostics.A_get_accessor_must_return_a_value); + if (node.kind === 177 /* GetAccessor */ ) { + if (!(node.flags & 33554432 /* Ambient */ ) && nodeIsPresent(node.body) && node.flags & 512 /* HasImplicitReturn */ ) { + if (!(node.flags & 1024 /* HasExplicitReturn */ )) error2(node.name, Diagnostics.A_get_accessor_must_return_a_value); } } - if (node.name.kind === 164 /* ComputedPropertyName */ ) checkComputedPropertyName(node.name); + if (node.name.kind === 167 /* ComputedPropertyName */ ) checkComputedPropertyName(node.name); if (hasBindableName(node)) { const symbol = getSymbolOfDeclaration(node); - const getter = getDeclarationOfKind(symbol, 174 /* GetAccessor */ ); - const setter = getDeclarationOfKind(symbol, 175 /* SetAccessor */ ); + const getter = getDeclarationOfKind(symbol, 177 /* GetAccessor */ ); + const setter = getDeclarationOfKind(symbol, 178 /* SetAccessor */ ); if (getter && setter && !(getNodeCheckFlags(getter) & 1 /* TypeChecked */ )) { getNodeLinks(getter).flags |= 1 /* TypeChecked */ ; const getterFlags = getEffectiveModifierFlags(getter); const setterFlags = getEffectiveModifierFlags(setter); if ((getterFlags & 256 /* Abstract */ ) !== (setterFlags & 256 /* Abstract */ )) { - error(getter.name, Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); - error(setter.name, Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + error2(getter.name, Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + error2(setter.name, Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } if (getterFlags & 16 /* Protected */ && !(setterFlags & 24 /* Private */ ) || getterFlags & 8 /* Private */ && !(setterFlags & 8 /* Private */ )) { - error(getter.name, Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); - error(setter.name, Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + error2(getter.name, Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + error2(setter.name, Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); } - const getterType = getAnnotatedAccessorType(getter); - const setterType = getAnnotatedAccessorType(setter); - if (getterType && setterType) checkTypeAssignableTo(getterType, setterType, getter, Diagnostics.The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type); } } const returnType = getTypeOfAccessors(getSymbolOfDeclaration(node)); - if (node.kind === 174 /* GetAccessor */ ) checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); + if (node.kind === 177 /* GetAccessor */ ) checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } function checkMissingDeclaration(node) { @@ -66407,9 +67146,9 @@ ${lanes.join("\n")} } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 180 /* TypeReference */ && !isInJSFile(node) && !isInJSDoc(node) && node.typeArguments && node.typeName.end !== node.typeArguments.pos) { + if (node.kind === 183 /* TypeReference */ && !isInJSFile(node) && !isInJSDoc(node) && node.typeArguments && node.typeName.end !== node.typeArguments.pos) { const sourceFile = getSourceFileOfNode(node); - if (scanTokenAtPosition(sourceFile, node.typeName.end) === 24 /* DotToken */ ) grammarErrorAtPos(node, skipTrivia(sourceFile.text, node.typeName.end), 1, Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + if (scanTokenAtPosition(sourceFile, node.typeName.end) === 25 /* DotToken */ ) grammarErrorAtPos(node, skipTrivia(sourceFile.text, node.typeName.end), 1, Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } forEach(node.typeArguments, checkSourceElement); checkTypeReferenceOrImport(node); @@ -66423,7 +67162,7 @@ ${lanes.join("\n")} }); const symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { - if (some(symbol.declarations, (d)=>isTypeDeclaration(d) && !!(d.flags & 268435456 /* Deprecated */ ))) addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName); + if (some(symbol.declarations, (d)=>isTypeDeclaration(d) && !!(d.flags & 536870912 /* Deprecated */ ))) addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName); } } } @@ -66455,17 +67194,12 @@ ${lanes.join("\n")} const elementTypes = node.elements; let seenOptionalElement = false; let seenRestElement = false; - const hasNamedElement = some(elementTypes, isNamedTupleMember); for (const e of elementTypes){ - if (e.kind !== 199 /* NamedTupleMember */ && hasNamedElement) { - grammarErrorOnNode(e, Diagnostics.Tuple_members_must_all_have_names_or_all_not_have_names); - break; - } const flags = getTupleElementFlags(e); if (flags & 8 /* Variadic */ ) { const type = getTypeFromTypeNode(e.type); if (!isArrayLikeType(type)) { - error(e, Diagnostics.A_rest_element_type_must_be_an_array_type); + error2(e, Diagnostics.A_rest_element_type_must_be_an_array_type); break; } if (isArrayType(type) || isTupleType(type) && type.target.combinedFlags & 4 /* Rest */ ) seenRestElement = true; @@ -66497,8 +67231,8 @@ ${lanes.join("\n")} if (!(type.flags & 8388608 /* IndexedAccess */ )) return type; const objectType = type.objectType; const indexType = type.indexType; - if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) { - if (accessNode.kind === 209 /* ElementAccessExpression */ && isAssignmentTarget(accessNode) && getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */ ) error(accessNode, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + if (isTypeAssignableTo(indexType, getIndexType(objectType, 0 /* None */ ))) { + if (accessNode.kind === 212 /* ElementAccessExpression */ && isAssignmentTarget(accessNode) && getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */ ) error2(accessNode, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); return type; } const apparentObjectType = getApparentType(objectType); @@ -66508,12 +67242,12 @@ ${lanes.join("\n")} if (propertyName) { const propertySymbol = forEachType(apparentObjectType, (t)=>getPropertyOfType(t, propertyName)); if (propertySymbol && getDeclarationModifierFlagsFromSymbol(propertySymbol) & 24 /* NonPublicAccessibilityModifier */ ) { - error(accessNode, Diagnostics.Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter, unescapeLeadingUnderscores(propertyName)); + error2(accessNode, Diagnostics.Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter, unescapeLeadingUnderscores(propertyName)); return errorType; } } } - error(accessNode, Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); + error2(accessNode, Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); return errorType; } function checkIndexedAccessType(node) { @@ -66536,8 +67270,8 @@ ${lanes.join("\n")} } } function checkGrammarMappedType(node) { - var _a2; - if ((_a2 = node.members) == null ? void 0 : _a2.length) return grammarErrorOnNode(node.members[0], Diagnostics.A_mapped_type_may_not_declare_properties_or_methods); + var _a; + if ((_a = node.members) == null ? void 0 : _a.length) return grammarErrorOnNode(node.members[0], Diagnostics.A_mapped_type_may_not_declare_properties_or_methods); } function checkThisType(node) { getTypeFromThisTypeNode(node); @@ -66550,7 +67284,7 @@ ${lanes.join("\n")} forEachChild(node, checkSourceElement); } function checkInferType(node) { - if (!findAncestor(node, (n)=>n.parent && n.parent.kind === 191 /* ConditionalType */ && n.parent.extendsType === n)) grammarErrorOnNode(node, Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); + if (!findAncestor(node, (n)=>n.parent && n.parent.kind === 194 /* ConditionalType */ && n.parent.extendsType === n)) grammarErrorOnNode(node, Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); checkSourceElement(node.typeParameter); const symbol = getSymbolOfDeclaration(node.typeParameter); if (symbol.declarations && symbol.declarations.length > 1) { @@ -66558,14 +67292,14 @@ ${lanes.join("\n")} if (!links.typeParametersChecked) { links.typeParametersChecked = true; const typeParameter = getDeclaredTypeOfTypeParameter(symbol); - const declarations = getDeclarationsOfKind(symbol, 165 /* TypeParameter */ ); + const declarations = getDeclarationsOfKind(symbol, 168 /* TypeParameter */ ); if (!areTypeParametersIdentical(declarations, [ typeParameter ], (decl)=>[ decl ])) { const name = symbolToString(symbol); - for (const declaration of declarations)error(declaration.name, Diagnostics.All_declarations_of_0_must_have_identical_constraints, name); + for (const declaration of declarations)error2(declaration.name, Diagnostics.All_declarations_of_0_must_have_identical_constraints, name); } } } @@ -66592,18 +67326,19 @@ ${lanes.join("\n")} } function checkNamedTupleMember(node) { if (node.dotDotDotToken && node.questionToken) grammarErrorOnNode(node, Diagnostics.A_tuple_member_cannot_be_both_optional_and_rest); - if (node.type.kind === 187 /* OptionalType */ ) grammarErrorOnNode(node.type, Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type); - if (node.type.kind === 188 /* RestType */ ) grammarErrorOnNode(node.type, Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type); + if (node.type.kind === 190 /* OptionalType */ ) grammarErrorOnNode(node.type, Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type); + if (node.type.kind === 191 /* RestType */ ) grammarErrorOnNode(node.type, Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type); checkSourceElement(node.type); getTypeFromTypeNode(node); } function isPrivateWithinAmbient(node) { - return (hasEffectiveModifier(node, 8 /* Private */ ) || isPrivateIdentifierClassElementDeclaration(node)) && !!(node.flags & 16777216 /* Ambient */ ); + return (hasEffectiveModifier(node, 8 /* Private */ ) || isPrivateIdentifierClassElementDeclaration(node)) && !!(node.flags & 33554432 /* Ambient */ ); } function getEffectiveDeclarationFlags(n, flagsToCheck) { - let flags = getCombinedModifierFlags(n); - if (n.parent.kind !== 261 /* InterfaceDeclaration */ && n.parent.kind !== 260 /* ClassDeclaration */ && n.parent.kind !== 228 /* ClassExpression */ && n.flags & 16777216 /* Ambient */ ) { - if (!(flags & 2 /* Ambient */ ) && !(isModuleBlock(n.parent) && isModuleDeclaration(n.parent.parent) && isGlobalScopeAugmentation(n.parent.parent))) flags |= 1 /* Export */ ; + let flags = getCombinedModifierFlagsCached(n); + if (n.parent.kind !== 264 /* InterfaceDeclaration */ && n.parent.kind !== 263 /* ClassDeclaration */ && n.parent.kind !== 231 /* ClassExpression */ && n.flags & 33554432 /* Ambient */ ) { + const container = getEnclosingContainer(n); + if (container && container.flags & 128 /* ExportContext */ && !(flags & 2 /* Ambient */ ) && !(isModuleBlock(n.parent) && isModuleDeclaration(n.parent.parent) && isGlobalScopeAugmentation(n.parent.parent))) flags |= 1 /* Export */ ; flags |= 2 /* Ambient */ ; } return flags & flagsToCheck; @@ -66622,10 +67357,10 @@ ${lanes.join("\n")} const canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck2); forEach(overloads, (o)=>{ const deviation = getEffectiveDeclarationFlags(o, flagsToCheck2) ^ canonicalFlags; - if (deviation & 1 /* Export */ ) error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); - else if (deviation & 2 /* Ambient */ ) error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); - else if (deviation & 24 /* Protected */ ) error(getNameOfDeclaration(o) || o, Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); - else if (deviation & 256 /* Abstract */ ) error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + if (deviation & 1 /* Export */ ) error2(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + else if (deviation & 2 /* Ambient */ ) error2(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + else if (deviation & 24 /* Protected */ ) error2(getNameOfDeclaration(o) || o, Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + else if (deviation & 256 /* Abstract */ ) error2(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); }); } } @@ -66634,7 +67369,7 @@ ${lanes.join("\n")} const canonicalHasQuestionToken = hasQuestionToken(getCanonicalOverload(overloads, implementation)); forEach(overloads, (o)=>{ const deviation = hasQuestionToken(o) !== canonicalHasQuestionToken; - if (deviation) error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_optional_or_required); + if (deviation) error2(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_optional_or_required); }); } } @@ -66662,26 +67397,25 @@ ${lanes.join("\n")} const subsequentName = subsequentNode.name; if (node.name && subsequentName && // both are private identifiers (isPrivateIdentifier(node.name) && isPrivateIdentifier(subsequentName) && node.name.escapedText === subsequentName.escapedText || // Both are computed property names - // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!) - isComputedPropertyName(node.name) && isComputedPropertyName(subsequentName) || // Both are literal property names that are the same. + isComputedPropertyName(node.name) && isComputedPropertyName(subsequentName) && isTypeIdenticalTo(checkComputedPropertyName(node.name), checkComputedPropertyName(subsequentName)) || // Both are literal property names that are the same. isPropertyNameLiteral(node.name) && isPropertyNameLiteral(subsequentName) && getEscapedTextOfIdentifierOrLiteral(node.name) === getEscapedTextOfIdentifierOrLiteral(subsequentName))) { - const reportError = (node.kind === 171 /* MethodDeclaration */ || node.kind === 170 /* MethodSignature */ ) && isStatic(node) !== isStatic(subsequentNode); + const reportError = (node.kind === 174 /* MethodDeclaration */ || node.kind === 173 /* MethodSignature */ ) && isStatic(node) !== isStatic(subsequentNode); if (reportError) { const diagnostic = isStatic(node) ? Diagnostics.Function_overload_must_be_static : Diagnostics.Function_overload_must_not_be_static; - error(errorNode2, diagnostic); + error2(errorNode2, diagnostic); } return; } if (nodeIsPresent(subsequentNode.body)) { - error(errorNode2, Diagnostics.Function_implementation_name_must_be_0, declarationNameToString(node.name)); + error2(errorNode2, Diagnostics.Function_implementation_name_must_be_0, declarationNameToString(node.name)); return; } } } const errorNode = node.name || node; - if (isConstructor) error(errorNode, Diagnostics.Constructor_implementation_is_missing); - else if (hasSyntacticModifier(node, 256 /* Abstract */ )) error(errorNode, Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); - else error(errorNode, Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); + if (isConstructor) error2(errorNode, Diagnostics.Constructor_implementation_is_missing); + else if (hasSyntacticModifier(node, 256 /* Abstract */ )) error2(errorNode, Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); + else error2(errorNode, Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); } let duplicateFunctionDeclaration = false; let multipleConstructorImplementation = false; @@ -66689,11 +67423,11 @@ ${lanes.join("\n")} const functionDeclarations = []; if (declarations) for (const current of declarations){ const node = current; - const inAmbientContext = node.flags & 16777216 /* Ambient */ ; - const inAmbientContextOrInterface = node.parent && (node.parent.kind === 261 /* InterfaceDeclaration */ || node.parent.kind === 184 /* TypeLiteral */ ) || inAmbientContext; + const inAmbientContext = node.flags & 33554432 /* Ambient */ ; + const inAmbientContextOrInterface = node.parent && (node.parent.kind === 264 /* InterfaceDeclaration */ || node.parent.kind === 187 /* TypeLiteral */ ) || inAmbientContext; if (inAmbientContextOrInterface) previousDeclaration = void 0; - if ((node.kind === 260 /* ClassDeclaration */ || node.kind === 228 /* ClassExpression */ ) && !inAmbientContext) hasNonAmbientClass = true; - if (node.kind === 259 /* FunctionDeclaration */ || node.kind === 171 /* MethodDeclaration */ || node.kind === 170 /* MethodSignature */ || node.kind === 173 /* Constructor */ ) { + if ((node.kind === 263 /* ClassDeclaration */ || node.kind === 231 /* ClassExpression */ ) && !inAmbientContext) hasNonAmbientClass = true; + if (node.kind === 262 /* FunctionDeclaration */ || node.kind === 174 /* MethodDeclaration */ || node.kind === 173 /* MethodSignature */ || node.kind === 176 /* Constructor */ ) { functionDeclarations.push(node); const currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; @@ -66718,16 +67452,16 @@ ${lanes.join("\n")} } } if (multipleConstructorImplementation) forEach(functionDeclarations, (declaration)=>{ - error(declaration, Diagnostics.Multiple_constructor_implementations_are_not_allowed); + error2(declaration, Diagnostics.Multiple_constructor_implementations_are_not_allowed); }); if (duplicateFunctionDeclaration) forEach(functionDeclarations, (declaration)=>{ - error(getNameOfDeclaration(declaration) || declaration, Diagnostics.Duplicate_function_implementation); + error2(getNameOfDeclaration(declaration) || declaration, Diagnostics.Duplicate_function_implementation); }); if (hasNonAmbientClass && !isConstructor && symbol.flags & 16 /* Function */ && declarations) { - const relatedDiagnostics = filter(declarations, (d)=>d.kind === 260 /* ClassDeclaration */ ).map((d)=>createDiagnosticForNode(d, Diagnostics.Consider_adding_a_declare_modifier_to_this_class)); + const relatedDiagnostics = filter(declarations, (d)=>d.kind === 263 /* ClassDeclaration */ ).map((d)=>createDiagnosticForNode(d, Diagnostics.Consider_adding_a_declare_modifier_to_this_class)); forEach(declarations, (declaration)=>{ - const diagnostic = declaration.kind === 260 /* ClassDeclaration */ ? Diagnostics.Class_declaration_cannot_implement_overload_list_for_0 : declaration.kind === 259 /* FunctionDeclaration */ ? Diagnostics.Function_with_bodies_can_only_merge_with_classes_that_are_ambient : void 0; - if (diagnostic) addRelatedInfo(error(getNameOfDeclaration(declaration) || declaration, diagnostic, symbolName(symbol)), ...relatedDiagnostics); + const diagnostic = declaration.kind === 263 /* ClassDeclaration */ ? Diagnostics.Class_declaration_cannot_implement_overload_list_for_0 : declaration.kind === 262 /* FunctionDeclaration */ ? Diagnostics.Function_with_bodies_can_only_merge_with_classes_that_are_ambient : void 0; + if (diagnostic) addRelatedInfo(error2(getNameOfDeclaration(declaration) || declaration, diagnostic, symbolName(symbol)), ...relatedDiagnostics); }); } if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && !hasSyntacticModifier(lastSeenNonAmbientDeclaration, 256 /* Abstract */ ) && !lastSeenNonAmbientDeclaration.questionToken) reportImplementationExpectedError(lastSeenNonAmbientDeclaration); @@ -66741,7 +67475,7 @@ ${lanes.join("\n")} const bodySignature = getSignatureFromDeclaration(bodyDeclaration); for (const signature of signatures)if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { const errorNode = signature.declaration && isJSDocSignature(signature.declaration) ? signature.declaration.parent.tagName : signature.declaration; - addRelatedInfo(error(errorNode, Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature), createDiagnosticForNode(bodyDeclaration, Diagnostics.The_implementation_signature_is_declared_here)); + addRelatedInfo(error2(errorNode, Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature), createDiagnosticForNode(bodyDeclaration, Diagnostics.The_implementation_signature_is_declared_here)); break; } } @@ -66774,70 +67508,70 @@ ${lanes.join("\n")} if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) for (const d of symbol.declarations){ const declarationSpaces = getDeclarationSpaces(d); const name = getNameOfDeclaration(d); - if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) error(name, Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, declarationNameToString(name)); - else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) error(name, Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, declarationNameToString(name)); + if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) error2(name, Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, declarationNameToString(name)); + else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) error2(name, Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, declarationNameToString(name)); } function getDeclarationSpaces(decl) { let d = decl; switch(d.kind){ - case 261 /* InterfaceDeclaration */ : - case 262 /* TypeAliasDeclaration */ : - case 349 /* JSDocTypedefTag */ : - case 341 /* JSDocCallbackTag */ : - case 343 /* JSDocEnumTag */ : + case 264 /* InterfaceDeclaration */ : + case 265 /* TypeAliasDeclaration */ : + case 353 /* JSDocTypedefTag */ : + case 345 /* JSDocCallbackTag */ : + case 347 /* JSDocEnumTag */ : return 2 /* ExportType */ ; - case 264 /* ModuleDeclaration */ : + case 267 /* ModuleDeclaration */ : return isAmbientModule(d) || getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 5 /* ExportValue */ : 4 /* ExportNamespace */ ; - case 260 /* ClassDeclaration */ : - case 263 /* EnumDeclaration */ : - case 302 /* EnumMember */ : + case 263 /* ClassDeclaration */ : + case 266 /* EnumDeclaration */ : + case 306 /* EnumMember */ : return 3 /* ExportValue */ ; - case 308 /* SourceFile */ : + case 312 /* SourceFile */ : return 7 /* ExportNamespace */ ; - case 274 /* ExportAssignment */ : - case 223 /* BinaryExpression */ : + case 277 /* ExportAssignment */ : + case 226 /* BinaryExpression */ : const node2 = d; const expression = isExportAssignment(node2) ? node2.expression : node2.right; if (!isEntityNameExpression(expression)) return 1 /* ExportValue */ ; d = expression; - case 268 /* ImportEqualsDeclaration */ : - case 271 /* NamespaceImport */ : - case 270 /* ImportClause */ : + case 271 /* ImportEqualsDeclaration */ : + case 274 /* NamespaceImport */ : + case 273 /* ImportClause */ : let result = 0 /* None */ ; const target = resolveAlias(getSymbolOfDeclaration(d)); forEach(target.declarations, (d2)=>{ result |= getDeclarationSpaces(d2); }); return result; - case 257 /* VariableDeclaration */ : - case 205 /* BindingElement */ : - case 259 /* FunctionDeclaration */ : - case 273 /* ImportSpecifier */ : - case 79 /* Identifier */ : + case 260 /* VariableDeclaration */ : + case 208 /* BindingElement */ : + case 262 /* FunctionDeclaration */ : + case 276 /* ImportSpecifier */ : + case 80 /* Identifier */ : return 1 /* ExportValue */ ; - case 170 /* MethodSignature */ : - case 168 /* PropertySignature */ : + case 173 /* MethodSignature */ : + case 171 /* PropertySignature */ : return 2 /* ExportType */ ; default: return Debug.failBadSyntaxKind(d); } } } - function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage, arg0) { + function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage, ...args) { const promisedType = getPromisedTypeOfPromise(type, errorNode); - return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0); + return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage, ...args); } function getPromisedTypeOfPromise(type, errorNode, thisTypeForErrorOut) { if (isTypeAny(type)) return void 0; const typeAsPromise = type; if (typeAsPromise.promisedTypeOfPromise) return typeAsPromise.promisedTypeOfPromise; if (isReferenceToType2(type, getGlobalPromiseType(/*reportErrors*/ false))) return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0]; - if (allTypesAssignableToKind(getBaseConstraintOrType(type), 134479868 /* Never */ )) return void 0; + if (allTypesAssignableToKind(getBaseConstraintOrType(type), 402915324 /* Never */ )) return void 0; const thenFunction = getTypeOfPropertyOfType(type, "then"); if (isTypeAny(thenFunction)) return void 0; const thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */ ) : emptyArray; if (thenSignatures.length === 0) { - if (errorNode) error(errorNode, Diagnostics.A_promise_must_have_a_then_method); + if (errorNode) error2(errorNode, Diagnostics.A_promise_must_have_a_then_method); return void 0; } let thisTypeForError; @@ -66850,32 +67584,32 @@ ${lanes.join("\n")} if (!candidates) { Debug.assertIsDefined(thisTypeForError); if (thisTypeForErrorOut) thisTypeForErrorOut.value = thisTypeForError; - if (errorNode) error(errorNode, Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForError)); + if (errorNode) error2(errorNode, Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForError)); return void 0; } const onfulfilledParameterType = getTypeWithFacts(getUnionType(map(candidates, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */ ); if (isTypeAny(onfulfilledParameterType)) return void 0; const onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */ ); if (onfulfilledParameterSignatures.length === 0) { - if (errorNode) error(errorNode, Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback); + if (errorNode) error2(errorNode, Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback); return void 0; } return typeAsPromise.promisedTypeOfPromise = getUnionType(map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */ ); } - function checkAwaitedType(type, withAlias, errorNode, diagnosticMessage, arg0) { - const awaitedType = withAlias ? getAwaitedType(type, errorNode, diagnosticMessage, arg0) : getAwaitedTypeNoAlias(type, errorNode, diagnosticMessage, arg0); + function checkAwaitedType(type, withAlias, errorNode, diagnosticMessage, ...args) { + const awaitedType = withAlias ? getAwaitedType(type, errorNode, diagnosticMessage, ...args) : getAwaitedTypeNoAlias(type, errorNode, diagnosticMessage, ...args); return awaitedType || errorType; } function isThenableType(type) { - if (allTypesAssignableToKind(getBaseConstraintOrType(type), 134479868 /* Never */ )) return false; + if (allTypesAssignableToKind(getBaseConstraintOrType(type), 402915324 /* Never */ )) return false; const thenFunction = getTypeOfPropertyOfType(type, "then"); return !!thenFunction && getSignaturesOfType(getTypeWithFacts(thenFunction, 2097152 /* NEUndefinedOrNull */ ), 0 /* Call */ ).length > 0; } function isAwaitedTypeInstantiation(type) { - var _a2; + var _a; if (type.flags & 16777216 /* Conditional */ ) { const awaitedSymbol = getGlobalAwaitedSymbol(/*reportErrors*/ false); - return !!awaitedSymbol && type.aliasSymbol === awaitedSymbol && ((_a2 = type.aliasTypeArguments) == null ? void 0 : _a2.length) === 1; + return !!awaitedSymbol && type.aliasSymbol === awaitedSymbol && ((_a = type.aliasTypeArguments) == null ? void 0 : _a.length) === 1; } return false; } @@ -66905,21 +67639,21 @@ ${lanes.join("\n")} Debug.assert(isAwaitedTypeInstantiation(type) || getPromisedTypeOfPromise(type) === void 0, "type provided should not be a non-generic 'promise'-like."); return type; } - function getAwaitedType(type, errorNode, diagnosticMessage, arg0) { - const awaitedType = getAwaitedTypeNoAlias(type, errorNode, diagnosticMessage, arg0); + function getAwaitedType(type, errorNode, diagnosticMessage, ...args) { + const awaitedType = getAwaitedTypeNoAlias(type, errorNode, diagnosticMessage, ...args); return awaitedType && createAwaitedTypeIfNeeded(awaitedType); } - function getAwaitedTypeNoAlias(type, errorNode, diagnosticMessage, arg0) { + function getAwaitedTypeNoAlias(type, errorNode, diagnosticMessage, ...args) { if (isTypeAny(type)) return type; if (isAwaitedTypeInstantiation(type)) return type; const typeAsAwaitable = type; if (typeAsAwaitable.awaitedTypeOfType) return typeAsAwaitable.awaitedTypeOfType; if (type.flags & 1048576 /* Union */ ) { if (awaitedTypeStack.lastIndexOf(type.id) >= 0) { - if (errorNode) error(errorNode, Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); + if (errorNode) error2(errorNode, Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); return void 0; } - const mapper = errorNode ? (constituentType)=>getAwaitedTypeNoAlias(constituentType, errorNode, diagnosticMessage, arg0) : getAwaitedTypeNoAlias; + const mapper = errorNode ? (constituentType)=>getAwaitedTypeNoAlias(constituentType, errorNode, diagnosticMessage, ...args) : getAwaitedTypeNoAlias; awaitedTypeStack.push(type.id); const mapped = mapType(type, mapper); awaitedTypeStack.pop(); @@ -66932,11 +67666,11 @@ ${lanes.join("\n")} const promisedType = getPromisedTypeOfPromise(type, /*errorNode*/ void 0, thisTypeForErrorOut); if (promisedType) { if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) { - if (errorNode) error(errorNode, Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); + if (errorNode) error2(errorNode, Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); return void 0; } awaitedTypeStack.push(type.id); - const awaitedType = getAwaitedTypeNoAlias(promisedType, errorNode, diagnosticMessage, arg0); + const awaitedType = getAwaitedTypeNoAlias(promisedType, errorNode, diagnosticMessage, ...args); awaitedTypeStack.pop(); if (!awaitedType) return void 0; return typeAsAwaitable.awaitedTypeOfType = awaitedType; @@ -66946,20 +67680,20 @@ ${lanes.join("\n")} Debug.assertIsDefined(diagnosticMessage); let chain; if (thisTypeForErrorOut.value) chain = chainDiagnosticMessages(chain, Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForErrorOut.value)); - chain = chainDiagnosticMessages(chain, diagnosticMessage, arg0); + chain = chainDiagnosticMessages(chain, diagnosticMessage, ...args); diagnostics.add(createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(errorNode), errorNode, chain)); } return void 0; } return typeAsAwaitable.awaitedTypeOfType = type; } - function checkAsyncFunctionReturnType(node, returnTypeNode) { + function checkAsyncFunctionReturnType(node, returnTypeNode, returnTypeErrorLocation) { const returnType = getTypeFromTypeNode(returnTypeNode); if (languageVersion >= 2 /* ES2015 */ ) { if (isErrorType(returnType)) return; const globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); if (globalPromiseType !== emptyGenericType && !isReferenceToType2(returnType, globalPromiseType)) { - error(returnTypeNode, Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, typeToString(getAwaitedTypeNoAlias(returnType) || voidType)); + reportErrorForInvalidReturnType(Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, returnTypeNode, returnTypeErrorLocation, typeToString(getAwaitedTypeNoAlias(returnType) || voidType)); return; } } else { @@ -66967,30 +67701,39 @@ ${lanes.join("\n")} if (isErrorType(returnType)) return; const promiseConstructorName = getEntityNameFromTypeNode(returnTypeNode); if (promiseConstructorName === void 0) { - error(returnTypeNode, Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); + reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, typeToString(returnType)); return; } const promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 111551 /* Value */ , /*ignoreErrors*/ true); const promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (isErrorType(promiseConstructorType)) { - if (promiseConstructorName.kind === 79 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) error(returnTypeNode, Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); - else error(returnTypeNode, Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, entityNameToString(promiseConstructorName)); + if (promiseConstructorName.kind === 80 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) error2(returnTypeErrorLocation, Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + else reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, entityNameToString(promiseConstructorName)); return; } const globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true); if (globalPromiseConstructorLikeType === emptyObjectType) { - error(returnTypeNode, Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, entityNameToString(promiseConstructorName)); + reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, entityNameToString(promiseConstructorName)); return; } - if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) return; + const headMessage = Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value; + const errorInfo = ()=>returnTypeNode === returnTypeErrorLocation ? void 0 : chainDiagnosticMessages(/*details*/ void 0, Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeErrorLocation, headMessage, errorInfo)) return; const rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); const collidingSymbol = getSymbol2(node.locals, rootName.escapedText, 111551 /* Value */ ); if (collidingSymbol) { - error(collidingSymbol.valueDeclaration, Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, idText(rootName), entityNameToString(promiseConstructorName)); + error2(collidingSymbol.valueDeclaration, Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, idText(rootName), entityNameToString(promiseConstructorName)); return; } } checkAwaitedType(returnType, /*withAlias*/ false, node, Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + function reportErrorForInvalidReturnType(message, returnTypeNode2, returnTypeErrorLocation2, typeName) { + if (returnTypeNode2 === returnTypeErrorLocation2) error2(returnTypeErrorLocation2, message, typeName); + else { + const diag2 = error2(returnTypeErrorLocation2, Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + addRelatedInfo(diag2, createDiagnosticForNode(returnTypeNode2, message, typeName)); + } + } } function checkDecorator(node) { const signature = getResolvedSignature(node); @@ -67002,21 +67745,21 @@ ${lanes.join("\n")} let headMessage; const expectedReturnType = decoratorSignature.resolvedReturnType; switch(node.parent.kind){ - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : headMessage = Diagnostics.Decorator_function_return_type_0_is_not_assignable_to_type_1; break; - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : if (!legacyDecorators) { headMessage = Diagnostics.Decorator_function_return_type_0_is_not_assignable_to_type_1; break; } - case 166 /* Parameter */ : + case 169 /* Parameter */ : headMessage = Diagnostics.Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any; break; - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : headMessage = Diagnostics.Decorator_function_return_type_0_is_not_assignable_to_type_1; break; default: @@ -67025,7 +67768,7 @@ ${lanes.join("\n")} checkTypeAssignableTo(returnType, expectedReturnType, node.expression, headMessage); } function createCallSignature(typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount = parameters.length, flags = 0 /* None */ ) { - const decl = factory.createFunctionTypeNode(/*typeParameters*/ void 0, emptyArray, factory.createKeywordTypeNode(131 /* AnyKeyword */ )); + const decl = factory.createFunctionTypeNode(/*typeParameters*/ void 0, emptyArray, factory.createKeywordTypeNode(133 /* AnyKeyword */ )); return createSignature(decl, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, flags); } function createFunctionType(typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, flags) { @@ -67047,12 +67790,12 @@ ${lanes.join("\n")} function markEntityNameOrEntityExpressionAsReference(typeName, forDecoratorMetadata) { if (!typeName) return; const rootName = getFirstIdentifier(typeName); - const meaning = (typeName.kind === 79 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */ ) | 2097152 /* Alias */ ; - const rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ void 0, /*nameArg*/ void 0, /*isReference*/ true); + const meaning = (typeName.kind === 80 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */ ) | 2097152 /* Alias */ ; + const rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ void 0, /*nameArg*/ void 0, /*isUse*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ ) { - if (!compilerOptions.verbatimModuleSyntax && symbolIsValue(rootSymbol) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol)) && !getTypeOnlyAliasDeclaration(rootSymbol)) markAliasSymbolAsReferenced(rootSymbol); + if (canCollectSymbolAliasAccessabilityData && symbolIsValue(rootSymbol) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol)) && !getTypeOnlyAliasDeclaration(rootSymbol)) markAliasSymbolAsReferenced(rootSymbol); else if (forDecoratorMetadata && getIsolatedModules(compilerOptions) && getEmitModuleKind(compilerOptions) >= 5 /* ES2015 */ && !symbolIsValue(rootSymbol) && !some(rootSymbol.declarations, isTypeOnlyImportOrExportDeclaration)) { - const diag2 = error(typeName, Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled); + const diag2 = error2(typeName, Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled); const aliasDeclaration = find(rootSymbol.declarations || emptyArray, isAliasSymbolDeclaration2); if (aliasDeclaration) addRelatedInfo(diag2, createDiagnosticForNode(aliasDeclaration, Diagnostics._0_was_imported_here, idText(rootName))); } @@ -67064,27 +67807,27 @@ ${lanes.join("\n")} } function getEntityNameForDecoratorMetadata(node) { if (node) switch(node.kind){ - case 190 /* IntersectionType */ : - case 189 /* UnionType */ : + case 193 /* IntersectionType */ : + case 192 /* UnionType */ : return getEntityNameForDecoratorMetadataFromTypeList(node.types); - case 191 /* ConditionalType */ : + case 194 /* ConditionalType */ : return getEntityNameForDecoratorMetadataFromTypeList([ node.trueType, node.falseType ]); - case 193 /* ParenthesizedType */ : - case 199 /* NamedTupleMember */ : + case 196 /* ParenthesizedType */ : + case 202 /* NamedTupleMember */ : return getEntityNameForDecoratorMetadata(node.type); - case 180 /* TypeReference */ : + case 183 /* TypeReference */ : return node.typeName; } } function getEntityNameForDecoratorMetadataFromTypeList(types) { let commonEntityName; for (let typeNode of types){ - while(typeNode.kind === 193 /* ParenthesizedType */ || typeNode.kind === 199 /* NamedTupleMember */ )typeNode = typeNode.type; - if (typeNode.kind === 144 /* NeverKeyword */ ) continue; - if (!strictNullChecks && (typeNode.kind === 198 /* LiteralType */ && typeNode.literal.kind === 104 /* NullKeyword */ || typeNode.kind === 155 /* UndefinedKeyword */ )) continue; + while(typeNode.kind === 196 /* ParenthesizedType */ || typeNode.kind === 202 /* NamedTupleMember */ )typeNode = typeNode.type; + if (typeNode.kind === 146 /* NeverKeyword */ ) continue; + if (!strictNullChecks && (typeNode.kind === 201 /* LiteralType */ && typeNode.literal.kind === 106 /* NullKeyword */ || typeNode.kind === 157 /* UndefinedKeyword */ )) continue; const individualEntityName = getEntityNameForDecoratorMetadata(typeNode); if (!individualEntityName) return void 0; if (commonEntityName) { @@ -67103,7 +67846,7 @@ ${lanes.join("\n")} if (!firstDecorator) return; if (legacyDecorators) { checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */ ); - if (node.kind === 166 /* Parameter */ ) checkExternalEmitHelpers(firstDecorator, 32 /* Param */ ); + if (node.kind === 169 /* Parameter */ ) checkExternalEmitHelpers(firstDecorator, 32 /* Param */ ); } else if (languageVersion < 99 /* ESNext */ ) { checkExternalEmitHelpers(firstDecorator, 8 /* ESDecorateAndRunInitializers */ ); if (isClassDeclaration(node)) { @@ -67120,27 +67863,28 @@ ${lanes.join("\n")} if (compilerOptions.emitDecoratorMetadata) { checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */ ); switch(node.kind){ - case 260 /* ClassDeclaration */ : + case 263 /* ClassDeclaration */ : const constructor = getFirstConstructorWithBody(node); if (constructor) for (const parameter of constructor.parameters)markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); break; - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - const otherKind = node.kind === 174 /* GetAccessor */ ? 175 /* SetAccessor */ : 174 /* GetAccessor */ ; + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + const otherKind = node.kind === 177 /* GetAccessor */ ? 178 /* SetAccessor */ : 177 /* GetAccessor */ ; const otherAccessor = getDeclarationOfKind(getSymbolOfDeclaration(node), otherKind); markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); break; - case 171 /* MethodDeclaration */ : + case 174 /* MethodDeclaration */ : for (const parameter of node.parameters)markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(node)); break; - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveTypeAnnotationNode(node)); break; - case 166 /* Parameter */ : + case 169 /* Parameter */ : markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); const containingSignature = node.parent; for (const parameter of containingSignature.parameters)markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(containingSignature)); break; } } @@ -67155,7 +67899,7 @@ ${lanes.join("\n")} } } function checkJSDocTypeAliasTag(node) { - if (!node.typeExpression) error(node.name, Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); + if (!node.typeExpression) error2(node.name, Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); if (node.name) checkTypeNameIsReserved(node.name, Diagnostics.Type_alias_name_cannot_be_0); checkSourceElement(node.typeExpression); checkTypeParameters(getEffectiveTypeParameterDeclarations(node)); @@ -67174,7 +67918,7 @@ ${lanes.join("\n")} const tags = getAllJSDocTags(host2, isJSDocSatisfiesTag); if (length(tags) > 1) for(let i = 1; i < length(tags); i++){ const tagName = tags[i].tagName; - error(tagName, Diagnostics._0_tag_already_specified, idText(tagName)); + error2(tagName, Diagnostics._0_tag_already_specified, idText(tagName)); } } } @@ -67196,59 +67940,59 @@ ${lanes.join("\n")} } function checkJSDocImplementsTag(node) { const classLike = getEffectiveJSDocHost(node); - if (!classLike || !isClassDeclaration(classLike) && !isClassExpression(classLike)) error(classLike, Diagnostics.JSDoc_0_is_not_attached_to_a_class, idText(node.tagName)); + if (!classLike || !isClassDeclaration(classLike) && !isClassExpression(classLike)) error2(classLike, Diagnostics.JSDoc_0_is_not_attached_to_a_class, idText(node.tagName)); } function checkJSDocAugmentsTag(node) { const classLike = getEffectiveJSDocHost(node); if (!classLike || !isClassDeclaration(classLike) && !isClassExpression(classLike)) { - error(classLike, Diagnostics.JSDoc_0_is_not_attached_to_a_class, idText(node.tagName)); + error2(classLike, Diagnostics.JSDoc_0_is_not_attached_to_a_class, idText(node.tagName)); return; } const augmentsTags = getJSDocTags(classLike).filter(isJSDocAugmentsTag); Debug.assert(augmentsTags.length > 0); - if (augmentsTags.length > 1) error(augmentsTags[1], Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag); + if (augmentsTags.length > 1) error2(augmentsTags[1], Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag); const name = getIdentifierFromEntityNameExpression(node.class.expression); const extend2 = getClassExtendsHeritageElement(classLike); if (extend2) { const className = getIdentifierFromEntityNameExpression(extend2.expression); - if (className && name.escapedText !== className.escapedText) error(name, Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, idText(node.tagName), idText(name), idText(className)); + if (className && name.escapedText !== className.escapedText) error2(name, Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, idText(node.tagName), idText(name), idText(className)); } } function checkJSDocAccessibilityModifiers(node) { const host2 = getJSDocHost(node); - if (host2 && isPrivateIdentifierClassElementDeclaration(host2)) error(node, Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier); + if (host2 && isPrivateIdentifierClassElementDeclaration(host2)) error2(node, Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier); } function getIdentifierFromEntityNameExpression(node) { switch(node.kind){ - case 79 /* Identifier */ : + case 80 /* Identifier */ : return node; - case 208 /* PropertyAccessExpression */ : + case 211 /* PropertyAccessExpression */ : return node.name; default: return void 0; } } function checkFunctionOrMethodDeclaration(node) { - var _a2; + var _a; checkDecorators(node); checkSignatureDeclaration(node); const functionFlags = getFunctionFlags(node); - if (node.name && node.name.kind === 164 /* ComputedPropertyName */ ) checkComputedPropertyName(node.name); + if (node.name && node.name.kind === 167 /* ComputedPropertyName */ ) checkComputedPropertyName(node.name); if (hasBindableName(node)) { const symbol = getSymbolOfDeclaration(node); const localSymbol = node.localSymbol || symbol; - const firstDeclaration = (_a2 = localSymbol.declarations) == null ? void 0 : _a2.find(// Get first non javascript function declaration - (declaration)=>declaration.kind === node.kind && !(declaration.flags & 262144 /* JavaScriptFile */ )); + const firstDeclaration = (_a = localSymbol.declarations) == null ? void 0 : _a.find(// Get first non javascript function declaration + (declaration)=>declaration.kind === node.kind && !(declaration.flags & 524288 /* JavaScriptFile */ )); if (node === firstDeclaration) checkFunctionOrConstructorSymbol(localSymbol); if (symbol.parent) checkFunctionOrConstructorSymbol(symbol); } - const body = node.kind === 170 /* MethodSignature */ ? void 0 : node.body; + const body = node.kind === 173 /* MethodSignature */ ? void 0 : node.body; checkSourceElement(body); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node)); addLazyDiagnostic(checkFunctionOrMethodDeclarationDiagnostics); if (isInJSFile(node)) { const typeTag = getJSDocTypeTag(node); - if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) error(typeTag.typeExpression.type, Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); + if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) error2(typeTag.typeExpression.type, Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); } function checkFunctionOrMethodDeclarationDiagnostics() { if (!getEffectiveReturnTypeNode(node)) { @@ -67271,40 +68015,40 @@ ${lanes.join("\n")} } function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) { for (const node of potentiallyUnusedIdentifiers)switch(node.kind){ - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : checkUnusedClassMembers(node, addDiagnostic); checkUnusedTypeParameters(node, addDiagnostic); break; - case 308 /* SourceFile */ : - case 264 /* ModuleDeclaration */ : - case 238 /* Block */ : - case 266 /* CaseBlock */ : - case 245 /* ForStatement */ : - case 246 /* ForInStatement */ : - case 247 /* ForOfStatement */ : + case 312 /* SourceFile */ : + case 267 /* ModuleDeclaration */ : + case 241 /* Block */ : + case 269 /* CaseBlock */ : + case 248 /* ForStatement */ : + case 249 /* ForInStatement */ : + case 250 /* ForOfStatement */ : checkUnusedLocalsAndParameters(node, addDiagnostic); break; - case 173 /* Constructor */ : - case 215 /* FunctionExpression */ : - case 259 /* FunctionDeclaration */ : - case 216 /* ArrowFunction */ : - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 176 /* Constructor */ : + case 218 /* FunctionExpression */ : + case 262 /* FunctionDeclaration */ : + case 219 /* ArrowFunction */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : if (node.body) checkUnusedLocalsAndParameters(node, addDiagnostic); checkUnusedTypeParameters(node, addDiagnostic); break; - case 170 /* MethodSignature */ : - case 176 /* CallSignature */ : - case 177 /* ConstructSignature */ : - case 181 /* FunctionType */ : - case 182 /* ConstructorType */ : - case 262 /* TypeAliasDeclaration */ : - case 261 /* InterfaceDeclaration */ : + case 173 /* MethodSignature */ : + case 179 /* CallSignature */ : + case 180 /* ConstructSignature */ : + case 184 /* FunctionType */ : + case 185 /* ConstructorType */ : + case 265 /* TypeAliasDeclaration */ : + case 264 /* InterfaceDeclaration */ : checkUnusedTypeParameters(node, addDiagnostic); break; - case 192 /* InferType */ : + case 195 /* InferType */ : checkUnusedInferTypeParameter(node, addDiagnostic); break; default: @@ -67321,27 +68065,27 @@ ${lanes.join("\n")} } function checkUnusedClassMembers(node, addDiagnostic) { for (const member of node.members)switch(member.kind){ - case 171 /* MethodDeclaration */ : - case 169 /* PropertyDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - if (member.kind === 175 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */ ) break; + case 174 /* MethodDeclaration */ : + case 172 /* PropertyDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + if (member.kind === 178 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */ ) break; const symbol = getSymbolOfDeclaration(member); - if (!symbol.isReferenced && (hasEffectiveModifier(member, 8 /* Private */ ) || isNamedDeclaration(member) && isPrivateIdentifier(member.name)) && !(member.flags & 16777216 /* Ambient */ )) addDiagnostic(member, 0 /* Local */ , createDiagnosticForNode(member.name, Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); + if (!symbol.isReferenced && (hasEffectiveModifier(member, 8 /* Private */ ) || isNamedDeclaration(member) && isPrivateIdentifier(member.name)) && !(member.flags & 33554432 /* Ambient */ )) addDiagnostic(member, 0 /* Local */ , createDiagnosticForNode(member.name, Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); break; - case 173 /* Constructor */ : + case 176 /* Constructor */ : for (const parameter of member.parameters)if (!parameter.symbol.isReferenced && hasSyntacticModifier(parameter, 8 /* Private */ )) addDiagnostic(parameter, 0 /* Local */ , createDiagnosticForNode(parameter.name, Diagnostics.Property_0_is_declared_but_its_value_is_never_read, symbolName(parameter.symbol))); break; - case 178 /* IndexSignature */ : - case 237 /* SemicolonClassElement */ : - case 172 /* ClassStaticBlockDeclaration */ : + case 181 /* IndexSignature */ : + case 240 /* SemicolonClassElement */ : + case 175 /* ClassStaticBlockDeclaration */ : break; default: Debug.fail("Unexpected class member"); } } function checkUnusedInferTypeParameter(node, addDiagnostic) { - const { typeParameter: typeParameter } = node; + const { typeParameter: typeParameter } = node; if (isTypeParameterUnused(typeParameter)) addDiagnostic(node, 1 /* Parameter */ , createDiagnosticForNode(node, Diagnostics._0_is_declared_but_its_value_is_never_read, idText(typeParameter.name))); } function checkUnusedTypeParameters(node, addDiagnostic) { @@ -67352,15 +68096,19 @@ ${lanes.join("\n")} for (const typeParameter of typeParameters){ if (!isTypeParameterUnused(typeParameter)) continue; const name = idText(typeParameter.name); - const { parent: parent2 } = typeParameter; - if (parent2.kind !== 192 /* InferType */ && parent2.typeParameters.every(isTypeParameterUnused)) { + const { parent: parent2 } = typeParameter; + if (parent2.kind !== 195 /* InferType */ && parent2.typeParameters.every(isTypeParameterUnused)) { if (tryAddToSet(seenParentsWithEveryUnused, parent2)) { const sourceFile = getSourceFileOfNode(parent2); const range = isJSDocTemplateTag(parent2) ? rangeOfNode(parent2) : rangeOfTypeParameters(sourceFile, parent2.typeParameters); const only = parent2.typeParameters.length === 1; - const message = only ? Diagnostics._0_is_declared_but_its_value_is_never_read : Diagnostics.All_type_parameters_are_unused; - const arg0 = only ? name : void 0; - addDiagnostic(typeParameter, 1 /* Parameter */ , createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, message, arg0)); + const messageAndArg = only ? [ + Diagnostics._0_is_declared_but_its_value_is_never_read, + name + ] : [ + Diagnostics.All_type_parameters_are_unused + ]; + addDiagnostic(typeParameter, 1 /* Parameter */ , createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, ...messageAndArg)); } } else addDiagnostic(typeParameter, 1 /* Parameter */ , createDiagnosticForNode(typeParameter, Diagnostics._0_is_declared_but_its_value_is_never_read, name)); } @@ -67401,8 +68149,11 @@ ${lanes.join("\n")} else if (isBindingElement(declaration) && isObjectBindingPattern(declaration.parent)) { const lastElement = last(declaration.parent.elements); if (declaration === lastElement || !last(declaration.parent.elements).dotDotDotToken) addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); - } else if (isVariableDeclaration(declaration)) addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); - else { + } else if (isVariableDeclaration(declaration)) { + const blockScopeKind = getCombinedNodeFlagsCached(declaration) & 7 /* BlockScoped */ ; + const name = getNameOfDeclaration(declaration); + if (blockScopeKind !== 4 /* Using */ && blockScopeKind !== 6 /* AwaitUsing */ || !name || !isIdentifierThatStartsWithUnderscore(name)) addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); + } else { const parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); const name = local.valueDeclaration && getNameOfDeclaration(local.valueDeclaration); if (parameter && name) { @@ -67416,25 +68167,25 @@ ${lanes.join("\n")} }); unusedImports.forEach(([importClause, unuseds])=>{ const importDecl = importClause.parent; - const nDeclarations = (importClause.name ? 1 : 0) + (importClause.namedBindings ? importClause.namedBindings.kind === 271 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length : 0); + const nDeclarations = (importClause.name ? 1 : 0) + (importClause.namedBindings ? importClause.namedBindings.kind === 274 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length : 0); if (nDeclarations === unuseds.length) addDiagnostic(importDecl, 0 /* Local */ , unuseds.length === 1 ? createDiagnosticForNode(importDecl, Diagnostics._0_is_declared_but_its_value_is_never_read, idText(first(unuseds).name)) : createDiagnosticForNode(importDecl, Diagnostics.All_imports_in_import_declaration_are_unused)); else for (const unused of unuseds)errorUnusedLocal(unused, idText(unused.name), addDiagnostic); }); unusedDestructures.forEach(([bindingPattern, bindingElements])=>{ const kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */ ; if (bindingPattern.elements.length === bindingElements.length) { - if (bindingElements.length === 1 && bindingPattern.parent.kind === 257 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 258 /* VariableDeclarationList */ ) addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); + if (bindingElements.length === 1 && bindingPattern.parent.kind === 260 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 261 /* VariableDeclarationList */ ) addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); else addDiagnostic(bindingPattern, kind, bindingElements.length === 1 ? createDiagnosticForNode(bindingPattern, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(bindingElements).name)) : createDiagnosticForNode(bindingPattern, Diagnostics.All_destructured_elements_are_unused)); } else for (const e of bindingElements)addDiagnostic(e, kind, createDiagnosticForNode(e, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name))); }); unusedVariables.forEach(([declarationList, declarations])=>{ - if (declarationList.declarations.length === declarations.length) addDiagnostic(declarationList, 0 /* Local */ , declarations.length === 1 ? createDiagnosticForNode(first(declarations).name, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(declarations).name)) : createDiagnosticForNode(declarationList.parent.kind === 240 /* VariableStatement */ ? declarationList.parent : declarationList, Diagnostics.All_variables_are_unused)); + if (declarationList.declarations.length === declarations.length) addDiagnostic(declarationList, 0 /* Local */ , declarations.length === 1 ? createDiagnosticForNode(first(declarations).name, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(declarations).name)) : createDiagnosticForNode(declarationList.parent.kind === 243 /* VariableStatement */ ? declarationList.parent : declarationList, Diagnostics.All_variables_are_unused)); else for (const decl of declarations)addDiagnostic(decl, 0 /* Local */ , createDiagnosticForNode(decl, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name))); }); } function checkPotentialUncheckedRenamedBindingElementsInTypes() { - var _a2; - for (const node of potentialUnusedRenamedBindingElementsInTypes)if (!((_a2 = getSymbolOfDeclaration(node)) == null ? void 0 : _a2.isReferenced)) { + var _a; + for (const node of potentialUnusedRenamedBindingElementsInTypes)if (!((_a = getSymbolOfDeclaration(node)) == null ? void 0 : _a.isReferenced)) { const wrappingDeclaration = walkUpBindingElementsAndPatterns(node); Debug.assert(isParameterDeclaration(wrappingDeclaration), "Only parameter declaration should be checked here"); const diagnostic = createDiagnosticForNode(node.name, Diagnostics._0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation, declarationNameToString(node.name), declarationNameToString(node.propertyName)); @@ -67444,23 +68195,23 @@ ${lanes.join("\n")} } function bindingNameText(name) { switch(name.kind){ - case 79 /* Identifier */ : + case 80 /* Identifier */ : return idText(name); - case 204 /* ArrayBindingPattern */ : - case 203 /* ObjectBindingPattern */ : + case 207 /* ArrayBindingPattern */ : + case 206 /* ObjectBindingPattern */ : return bindingNameText(cast(first(name.elements), isBindingElement).name); default: return Debug.assertNever(name); } } function isImportedDeclaration(node) { - return node.kind === 270 /* ImportClause */ || node.kind === 273 /* ImportSpecifier */ || node.kind === 271 /* NamespaceImport */ ; + return node.kind === 273 /* ImportClause */ || node.kind === 276 /* ImportSpecifier */ || node.kind === 274 /* NamespaceImport */ ; } function importClauseFromImported(decl) { - return decl.kind === 270 /* ImportClause */ ? decl : decl.kind === 271 /* NamespaceImport */ ? decl.parent : decl.parent.parent; + return decl.kind === 273 /* ImportClause */ ? decl : decl.kind === 274 /* NamespaceImport */ ? decl.parent : decl.parent.parent; } function checkBlock(node) { - if (node.kind === 238 /* Block */ ) checkGrammarStatementInAmbientContext(node); + if (node.kind === 241 /* Block */ ) checkGrammarStatementInAmbientContext(node); if (isFunctionOrModuleBlock(node)) { const saveFlowAnalysisDisabled = flowAnalysisDisabled; forEach(node.statements, checkSourceElement); @@ -67469,15 +68220,15 @@ ${lanes.join("\n")} if (node.locals) registerForUnusedIdentifiersCheck(node); } function checkCollisionWithArgumentsInGeneratedCode(node) { - if (languageVersion >= 2 /* ES2015 */ || !hasRestParameter(node) || node.flags & 16777216 /* Ambient */ || nodeIsMissing(node.body)) return; + if (languageVersion >= 2 /* ES2015 */ || !hasRestParameter(node) || node.flags & 33554432 /* Ambient */ || nodeIsMissing(node.body)) return; forEach(node.parameters, (p)=>{ if (p.name && !isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) errorSkippedOn("noEmit", p, Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters); }); } function needCollisionCheckForIdentifier(node, identifier, name) { if ((identifier == null ? void 0 : identifier.escapedText) !== name) return false; - if (node.kind === 169 /* PropertyDeclaration */ || node.kind === 168 /* PropertySignature */ || node.kind === 171 /* MethodDeclaration */ || node.kind === 170 /* MethodSignature */ || node.kind === 174 /* GetAccessor */ || node.kind === 175 /* SetAccessor */ || node.kind === 299 /* PropertyAssignment */ ) return false; - if (node.flags & 16777216 /* Ambient */ ) return false; + if (node.kind === 172 /* PropertyDeclaration */ || node.kind === 171 /* PropertySignature */ || node.kind === 174 /* MethodDeclaration */ || node.kind === 173 /* MethodSignature */ || node.kind === 177 /* GetAccessor */ || node.kind === 178 /* SetAccessor */ || node.kind === 303 /* PropertyAssignment */ ) return false; + if (node.flags & 33554432 /* Ambient */ ) return false; if (isImportClause(node) || isImportEqualsDeclaration(node) || isImportSpecifier(node)) { if (isTypeOnlyImportOrExportDeclaration(node)) return false; } @@ -67488,9 +68239,9 @@ ${lanes.join("\n")} function checkIfThisIsCapturedInEnclosingScope(node) { findAncestor(node, (current)=>{ if (getNodeCheckFlags(current) & 4 /* CaptureThis */ ) { - const isDeclaration2 = node.kind !== 79 /* Identifier */ ; - if (isDeclaration2) error(getNameOfDeclaration(node), Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); - else error(node, Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); + const isDeclaration2 = node.kind !== 80 /* Identifier */ ; + if (isDeclaration2) error2(getNameOfDeclaration(node), Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + else error2(node, Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); return true; } return false; @@ -67499,9 +68250,9 @@ ${lanes.join("\n")} function checkIfNewTargetIsCapturedInEnclosingScope(node) { findAncestor(node, (current)=>{ if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */ ) { - const isDeclaration2 = node.kind !== 79 /* Identifier */ ; - if (isDeclaration2) error(getNameOfDeclaration(node), Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); - else error(node, Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); + const isDeclaration2 = node.kind !== 80 /* Identifier */ ; + if (isDeclaration2) error2(getNameOfDeclaration(node), Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + else error2(node, Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); return true; } return false; @@ -67512,20 +68263,20 @@ ${lanes.join("\n")} if (!name || !needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) return; if (isModuleDeclaration(node) && getModuleInstanceState(node) !== 1 /* Instantiated */ ) return; const parent2 = getDeclarationContainer(node); - if (parent2.kind === 308 /* SourceFile */ && isExternalOrCommonJsModule(parent2)) errorSkippedOn("noEmit", name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, declarationNameToString(name), declarationNameToString(name)); + if (parent2.kind === 312 /* SourceFile */ && isExternalOrCommonJsModule(parent2)) errorSkippedOn("noEmit", name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, declarationNameToString(name), declarationNameToString(name)); } function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { if (!name || languageVersion >= 4 /* ES2017 */ || !needCollisionCheckForIdentifier(node, name, "Promise")) return; if (isModuleDeclaration(node) && getModuleInstanceState(node) !== 1 /* Instantiated */ ) return; const parent2 = getDeclarationContainer(node); - if (parent2.kind === 308 /* SourceFile */ && isExternalOrCommonJsModule(parent2) && parent2.flags & 2048 /* HasAsyncFunctions */ ) errorSkippedOn("noEmit", name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, declarationNameToString(name), declarationNameToString(name)); + if (parent2.kind === 312 /* SourceFile */ && isExternalOrCommonJsModule(parent2) && parent2.flags & 4096 /* HasAsyncFunctions */ ) errorSkippedOn("noEmit", name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, declarationNameToString(name), declarationNameToString(name)); } function recordPotentialCollisionWithWeakMapSetInGeneratedCode(node, name) { if (languageVersion <= 8 /* ES2021 */ && (needCollisionCheckForIdentifier(node, name, "WeakMap") || needCollisionCheckForIdentifier(node, name, "WeakSet"))) potentialWeakMapSetCollisions.push(node); } function checkWeakMapSetCollision(node) { const enclosingBlockScope = getEnclosingBlockScopeContainer(node); - if (getNodeCheckFlags(enclosingBlockScope) & 4194304 /* ContainsClassWithPrivateIdentifiers */ ) { + if (getNodeCheckFlags(enclosingBlockScope) & 1048576 /* ContainsClassWithPrivateIdentifiers */ ) { Debug.assert(isNamedDeclaration(node) && isIdentifier(node.name) && typeof node.name.escapedText === "string", "The target of a WeakMap/WeakSet collision check should be an identifier"); errorSkippedOn("noEmit", node, Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, node.name.escapedText); } @@ -67536,15 +68287,15 @@ ${lanes.join("\n")} function checkReflectCollision(node) { let hasCollision = false; if (isClassExpression(node)) { - for (const member of node.members)if (getNodeCheckFlags(member) & 8388608 /* ContainsSuperPropertyInStaticInitializer */ ) { + for (const member of node.members)if (getNodeCheckFlags(member) & 2097152 /* ContainsSuperPropertyInStaticInitializer */ ) { hasCollision = true; break; } } else if (isFunctionExpression(node)) { - if (getNodeCheckFlags(node) & 8388608 /* ContainsSuperPropertyInStaticInitializer */ ) hasCollision = true; + if (getNodeCheckFlags(node) & 2097152 /* ContainsSuperPropertyInStaticInitializer */ ) hasCollision = true; } else { const container = getEnclosingBlockScopeContainer(node); - if (container && getNodeCheckFlags(container) & 8388608 /* ContainsSuperPropertyInStaticInitializer */ ) hasCollision = true; + if (container && getNodeCheckFlags(container) & 2097152 /* ContainsSuperPropertyInStaticInitializer */ ) hasCollision = true; } if (hasCollision) { Debug.assert(isNamedDeclaration(node) && isIdentifier(node.name), "The target of a Reflect collision check should be an identifier"); @@ -67559,24 +68310,23 @@ ${lanes.join("\n")} recordPotentialCollisionWithReflectInGeneratedCode(node, name); if (isClassLike(node)) { checkTypeNameIsReserved(name, Diagnostics.Class_name_cannot_be_0); - if (!(node.flags & 16777216 /* Ambient */ )) checkClassNameCollisionWithObject(name); + if (!(node.flags & 33554432 /* Ambient */ )) checkClassNameCollisionWithObject(name); } else if (isEnumDeclaration(node)) checkTypeNameIsReserved(name, Diagnostics.Enum_name_cannot_be_0); } function checkVarDeclaredNamesNotShadowed(node) { - if ((getCombinedNodeFlags(node) & 3 /* BlockScoped */ ) !== 0 || isParameterDeclaration(node)) return; - if (node.kind === 257 /* VariableDeclaration */ && !node.initializer) return; + if ((getCombinedNodeFlagsCached(node) & 7 /* BlockScoped */ ) !== 0 || isParameterDeclaration(node)) return; const symbol = getSymbolOfDeclaration(node); if (symbol.flags & 1 /* FunctionScopedVariable */ ) { if (!isIdentifier(node.name)) return Debug.fail(); - const localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */ , /*nodeNotFoundErrorMessage*/ void 0, /*nameArg*/ void 0, /*isUse*/ false); + const localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */ , /*nameNotFoundMessage*/ void 0, /*nameArg*/ void 0, /*isUse*/ false); if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */ ) { - if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */ ) { - const varDeclList = getAncestor(localDeclarationSymbol.valueDeclaration, 258 /* VariableDeclarationList */ ); - const container = varDeclList.parent.kind === 240 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent : void 0; - const namesShareScope = container && (container.kind === 238 /* Block */ && isFunctionLike(container.parent) || container.kind === 265 /* ModuleBlock */ || container.kind === 264 /* ModuleDeclaration */ || container.kind === 308 /* SourceFile */ ); + if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 7 /* BlockScoped */ ) { + const varDeclList = getAncestor(localDeclarationSymbol.valueDeclaration, 261 /* VariableDeclarationList */ ); + const container = varDeclList.parent.kind === 243 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent : void 0; + const namesShareScope = container && (container.kind === 241 /* Block */ && isFunctionLike(container.parent) || container.kind === 268 /* ModuleBlock */ || container.kind === 267 /* ModuleDeclaration */ || container.kind === 312 /* SourceFile */ ); if (!namesShareScope) { const name = symbolToString(localDeclarationSymbol); - error(node, Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); + error2(node, Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); } } } @@ -67586,11 +68336,11 @@ ${lanes.join("\n")} return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; } function checkVariableLikeDeclaration(node) { - var _a2; + var _a; checkDecorators(node); if (!isBindingElement(node)) checkSourceElement(node.type); if (!node.name) return; - if (node.name.kind === 164 /* ComputedPropertyName */ ) { + if (node.name.kind === 167 /* ComputedPropertyName */ ) { checkComputedPropertyName(node.name); if (hasOnlyExpressionInitializer(node) && node.initializer) checkExpressionCached(node.initializer); } @@ -67600,7 +68350,7 @@ ${lanes.join("\n")} return; } if (isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < 5 /* ES2018 */ ) checkExternalEmitHelpers(node, 4 /* Rest */ ); - if (node.propertyName && node.propertyName.kind === 164 /* ComputedPropertyName */ ) checkComputedPropertyName(node.propertyName); + if (node.propertyName && node.propertyName.kind === 167 /* ComputedPropertyName */ ) checkComputedPropertyName(node.propertyName); const parent2 = node.parent.parent; const parentCheckMode = node.dotDotDotToken ? 64 /* RestBindingElement */ : 0 /* Normal */ ; const parentType = getTypeForBindingElementParent(parent2, parentCheckMode); @@ -67612,21 +68362,22 @@ ${lanes.join("\n")} const property = getPropertyOfType(parentType, nameText); if (property) { markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ void 0, /*isSelfTypeAccess*/ false); - checkPropertyAccessibility(node, !!parent2.initializer && parent2.initializer.kind === 106 /* SuperKeyword */ , /*writing*/ false, parentType, property); + checkPropertyAccessibility(node, !!parent2.initializer && parent2.initializer.kind === 108 /* SuperKeyword */ , /*writing*/ false, parentType, property); } } } } if (isBindingPattern(node.name)) { - if (node.name.kind === 204 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) checkExternalEmitHelpers(node, 512 /* Read */ ); + if (node.name.kind === 207 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) checkExternalEmitHelpers(node, 512 /* Read */ ); forEach(node.name.elements, checkSourceElement); } if (isParameter(node) && node.initializer && nodeIsMissing(getContainingFunction(node).body)) { - error(node, Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); + error2(node, Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } if (isBindingPattern(node.name)) { - const needCheckInitializer = hasOnlyExpressionInitializer(node) && node.initializer && node.parent.parent.kind !== 246 /* ForInStatement */ ; + if (isInAmbientOrTypeNode(node)) return; + const needCheckInitializer = hasOnlyExpressionInitializer(node) && node.initializer && node.parent.parent.kind !== 249 /* ForInStatement */ ; const needCheckWidenedType = !some(node.name.elements, not(isOmittedExpression)); if (needCheckInitializer || needCheckWidenedType) { const widenedType = getWidenedTypeForVariableLikeDeclaration(node); @@ -67651,40 +68402,67 @@ ${lanes.join("\n")} if (node === symbol.valueDeclaration) { const initializer = hasOnlyExpressionInitializer(node) && getEffectiveInitializer(node); if (initializer) { - const isJSObjectLiteralInitializer = isInJSFile(node) && isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAccess(node.name)) && !!((_a2 = symbol.exports) == null ? void 0 : _a2.size); - if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 246 /* ForInStatement */ ) checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ void 0); + const isJSObjectLiteralInitializer = isInJSFile(node) && isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAccess(node.name)) && !!((_a = symbol.exports) == null ? void 0 : _a.size); + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 249 /* ForInStatement */ ) { + const initializerType = checkExpressionCached(initializer); + checkTypeAssignableToAndOptionallyElaborate(initializerType, type, node, initializer, /*headMessage*/ void 0); + const blockScopeKind = getCombinedNodeFlagsCached(node) & 7 /* BlockScoped */ ; + if (blockScopeKind === 6 /* AwaitUsing */ ) { + const globalAsyncDisposableType = getGlobalAsyncDisposableType(/*reportErrors*/ true); + const globalDisposableType = getGlobalDisposableType(/*reportErrors*/ true); + if (globalAsyncDisposableType !== emptyObjectType && globalDisposableType !== emptyObjectType) { + const optionalDisposableType = getUnionType([ + globalAsyncDisposableType, + globalDisposableType, + nullType, + undefinedType + ]); + checkTypeAssignableTo(initializerType, optionalDisposableType, initializer, Diagnostics.The_initializer_of_an_await_using_declaration_must_be_either_an_object_with_a_Symbol_asyncDispose_or_Symbol_dispose_method_or_be_null_or_undefined); + } + } else if (blockScopeKind === 4 /* Using */ ) { + const globalDisposableType = getGlobalDisposableType(/*reportErrors*/ true); + if (globalDisposableType !== emptyObjectType) { + const optionalDisposableType = getUnionType([ + globalDisposableType, + nullType, + undefinedType + ]); + checkTypeAssignableTo(initializerType, optionalDisposableType, initializer, Diagnostics.The_initializer_of_a_using_declaration_must_be_either_an_object_with_a_Symbol_dispose_method_or_be_null_or_undefined); + } + } + } } if (symbol.declarations && symbol.declarations.length > 1) { - if (some(symbol.declarations, (d)=>d !== node && isVariableLike(d) && !areDeclarationFlagsIdentical(d, node))) error(node.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name)); + if (some(symbol.declarations, (d)=>d !== node && isVariableLike(d) && !areDeclarationFlagsIdentical(d, node))) error2(node.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name)); } } else { const declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (!isErrorType(type) && !isErrorType(declarationType) && !isTypeIdenticalTo(type, declarationType) && !(symbol.flags & 67108864 /* Assignment */ )) errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType); if (hasOnlyExpressionInitializer(node) && node.initializer) checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ void 0); - if (symbol.valueDeclaration && !areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) error(node.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name)); + if (symbol.valueDeclaration && !areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) error2(node.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name)); } - if (node.kind !== 169 /* PropertyDeclaration */ && node.kind !== 168 /* PropertySignature */ ) { + if (node.kind !== 172 /* PropertyDeclaration */ && node.kind !== 171 /* PropertySignature */ ) { checkExportsOnMergedDeclarations(node); - if (node.kind === 257 /* VariableDeclaration */ || node.kind === 205 /* BindingElement */ ) checkVarDeclaredNamesNotShadowed(node); + if (node.kind === 260 /* VariableDeclaration */ || node.kind === 208 /* BindingElement */ ) checkVarDeclaredNamesNotShadowed(node); checkCollisionsForDeclarationName(node, node.name); } } function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) { const nextDeclarationName = getNameOfDeclaration(nextDeclaration); - const message = nextDeclaration.kind === 169 /* PropertyDeclaration */ || nextDeclaration.kind === 168 /* PropertySignature */ ? Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; + const message = nextDeclaration.kind === 172 /* PropertyDeclaration */ || nextDeclaration.kind === 171 /* PropertySignature */ ? Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; const declName = declarationNameToString(nextDeclarationName); - const err = error(nextDeclarationName, message, declName, typeToString(firstType), typeToString(nextType)); + const err = error2(nextDeclarationName, message, declName, typeToString(firstType), typeToString(nextType)); if (firstDeclaration) addRelatedInfo(err, createDiagnosticForNode(firstDeclaration, Diagnostics._0_was_also_declared_here, declName)); } function areDeclarationFlagsIdentical(left, right) { - if (left.kind === 166 /* Parameter */ && right.kind === 257 /* VariableDeclaration */ || left.kind === 257 /* VariableDeclaration */ && right.kind === 166 /* Parameter */ ) return true; + if (left.kind === 169 /* Parameter */ && right.kind === 260 /* VariableDeclaration */ || left.kind === 260 /* VariableDeclaration */ && right.kind === 169 /* Parameter */ ) return true; if (hasQuestionToken(left) !== hasQuestionToken(right)) return false; const interestingFlags = 888 /* Static */ ; return getSelectedEffectiveModifierFlags(left, interestingFlags) === getSelectedEffectiveModifierFlags(right, interestingFlags); } function checkVariableDeclaration(node) { - var _a2, _b; - (_a2 = tracing) == null || _a2.push(tracing.Phase.Check, "checkVariableDeclaration", { + var _a, _b; + (_a = tracing) == null || _a.push(tracing.Phase.Check, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end, @@ -67698,9 +68476,14 @@ ${lanes.join("\n")} checkGrammarBindingElement(node); return checkVariableLikeDeclaration(node); } + function checkVariableDeclarationList(node) { + const blockScopeKind = getCombinedNodeFlags(node) & 7 /* BlockScoped */ ; + if (blockScopeKind === 4 /* Using */ || blockScopeKind === 6 /* AwaitUsing */ ) checkExternalEmitHelpers(node, 33554432 /* AddDisposableResourceAndDisposeResources */ ); + forEach(node.declarations, checkSourceElement); + } function checkVariableStatement(node) { - if (!checkGrammarModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) checkGrammarForDisallowedLetOrConstStatement(node); - forEach(node.declarationList.declarations, checkSourceElement); + if (!checkGrammarModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) checkGrammarForDisallowedBlockScopedVariableStatement(node); + checkVariableDeclarationList(node.declarationList); } function checkExpressionStatement(node) { checkGrammarStatementInAmbientContext(node); @@ -67711,7 +68494,7 @@ ${lanes.join("\n")} const type = checkTruthinessExpression(node.expression); checkTestingKnownTruthyCallableOrAwaitableType(node.expression, type, node.thenStatement); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 239 /* EmptyStatement */ ) error(node.thenStatement, Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); + if (node.thenStatement.kind === 242 /* EmptyStatement */ ) error2(node.thenStatement, Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); checkSourceElement(node.elseStatement); } function checkTestingKnownTruthyCallableOrAwaitableType(condExpr, condType, body) { @@ -67720,7 +68503,7 @@ ${lanes.join("\n")} function bothHelper(condExpr2, body2) { condExpr2 = skipParentheses(condExpr2); helper(condExpr2, body2); - while(isBinaryExpression(condExpr2) && (condExpr2.operatorToken.kind === 56 /* BarBarToken */ || condExpr2.operatorToken.kind === 60 /* QuestionQuestionToken */ )){ + while(isBinaryExpression(condExpr2) && (condExpr2.operatorToken.kind === 57 /* BarBarToken */ || condExpr2.operatorToken.kind === 61 /* QuestionQuestionToken */ )){ condExpr2 = skipParentheses(condExpr2.left); helper(condExpr2, body2); } @@ -67744,7 +68527,7 @@ ${lanes.join("\n")} const isUsed = testedSymbol && isBinaryExpression(condExpr2.parent) && isSymbolUsedInBinaryExpressionChain(condExpr2.parent, testedSymbol) || testedSymbol && body2 && isSymbolUsedInConditionBody(condExpr2, body2, testedNode, testedSymbol); if (!isUsed) { if (isPromise) errorAndMaybeSuggestAwait(location, /*maybeMissingAwait*/ true, Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined, getTypeNameForErrorDisplay(type)); - else error(location, Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead); + else error2(location, Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead); } } } @@ -67757,7 +68540,7 @@ ${lanes.join("\n")} let testedExpression = testedNode.parent; let childExpression = childNode.parent; while(testedExpression && childExpression){ - if (isIdentifier(testedExpression) && isIdentifier(childExpression) || testedExpression.kind === 108 /* ThisKeyword */ && childExpression.kind === 108 /* ThisKeyword */ ) return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression); + if (isIdentifier(testedExpression) && isIdentifier(childExpression) || testedExpression.kind === 110 /* ThisKeyword */ && childExpression.kind === 110 /* ThisKeyword */ ) return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression); else if (isPropertyAccessExpression(testedExpression) && isPropertyAccessExpression(childExpression)) { if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) return false; childExpression = childExpression.expression; @@ -67773,7 +68556,7 @@ ${lanes.join("\n")} }); } function isSymbolUsedInBinaryExpressionChain(node, testedSymbol) { - while(isBinaryExpression(node) && node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ ){ + while(isBinaryExpression(node) && node.operatorToken.kind === 56 /* AmpersandAmpersandToken */ ){ const isUsed = forEachChild(node.right, function visit(child) { if (isIdentifier(child)) { const symbol = getSymbolAtLocation(child); @@ -67797,7 +68580,7 @@ ${lanes.join("\n")} checkSourceElement(node.statement); } function checkTruthinessOfType(type, node) { - if (type.flags & 16384 /* Void */ ) error(node, Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness); + if (type.flags & 16384 /* Void */ ) error2(node, Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness); return type; } function checkTruthinessExpression(node, checkMode) { @@ -67805,10 +68588,10 @@ ${lanes.join("\n")} } function checkForStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 258 /* VariableDeclarationList */ ) checkGrammarVariableDeclarationList(node.initializer); + if (node.initializer && node.initializer.kind === 261 /* VariableDeclarationList */ ) checkGrammarVariableDeclarationList(node.initializer); } if (node.initializer) { - if (node.initializer.kind === 258 /* VariableDeclarationList */ ) forEach(node.initializer.declarations, checkVariableDeclaration); + if (node.initializer.kind === 261 /* VariableDeclarationList */ ) checkVariableDeclarationList(node.initializer); else checkExpression(node.initializer); } if (node.condition) checkTruthinessExpression(node.condition); @@ -67820,17 +68603,17 @@ ${lanes.join("\n")} checkGrammarForInOrForOfStatement(node); const container = getContainingFunctionOrClassStaticBlock(node); if (node.awaitModifier) { - if (container && isClassStaticBlockDeclaration(container)) grammarErrorOnNode(node.awaitModifier, Diagnostics.For_await_loops_cannot_be_used_inside_a_class_static_block); + if (container && isClassStaticBlockDeclaration(container)) grammarErrorOnNode(node.awaitModifier, Diagnostics.for_await_loops_cannot_be_used_inside_a_class_static_block); else { const functionFlags = getFunctionFlags(container); if ((functionFlags & 6 /* Async */ ) === 2 /* Async */ && languageVersion < 99 /* ESNext */ ) checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */ ); } } else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */ ) checkExternalEmitHelpers(node, 256 /* ForOfIncludes */ ); - if (node.initializer.kind === 258 /* VariableDeclarationList */ ) checkForInOrForOfVariableDeclaration(node); + if (node.initializer.kind === 261 /* VariableDeclarationList */ ) checkVariableDeclarationList(node.initializer); else { const varExpr = node.initializer; const iteratedType = checkRightHandSideOfForOf(node); - if (varExpr.kind === 206 /* ArrayLiteralExpression */ || varExpr.kind === 207 /* ObjectLiteralExpression */ ) checkDestructuringAssignment(varExpr, iteratedType || errorType); + if (varExpr.kind === 209 /* ArrayLiteralExpression */ || varExpr.kind === 210 /* ObjectLiteralExpression */ ) checkDestructuringAssignment(varExpr, iteratedType || errorType); else { const leftType = checkExpression(varExpr); checkReferenceExpression(varExpr, Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access, Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access); @@ -67843,28 +68626,21 @@ ${lanes.join("\n")} function checkForInStatement(node) { checkGrammarForInOrForOfStatement(node); const rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression)); - if (node.initializer.kind === 258 /* VariableDeclarationList */ ) { + if (node.initializer.kind === 261 /* VariableDeclarationList */ ) { const variable = node.initializer.declarations[0]; - if (variable && isBindingPattern(variable.name)) error(variable.name, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); - checkForInOrForOfVariableDeclaration(node); + if (variable && isBindingPattern(variable.name)) error2(variable.name, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + checkVariableDeclarationList(node.initializer); } else { const varExpr = node.initializer; const leftType = checkExpression(varExpr); - if (varExpr.kind === 206 /* ArrayLiteralExpression */ || varExpr.kind === 207 /* ObjectLiteralExpression */ ) error(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); - else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) error(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); + if (varExpr.kind === 209 /* ArrayLiteralExpression */ || varExpr.kind === 210 /* ObjectLiteralExpression */ ) error2(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) error2(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); else checkReferenceExpression(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access, Diagnostics.The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access); } - if (rightType === neverType || !isTypeAssignableToKind(rightType, 126091264 /* InstantiableNonPrimitive */ )) error(node.expression, Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType)); + if (rightType === neverType || !isTypeAssignableToKind(rightType, 126091264 /* InstantiableNonPrimitive */ )) error2(node.expression, Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType)); checkSourceElement(node.statement); if (node.locals) registerForUnusedIdentifiersCheck(node); } - function checkForInOrForOfVariableDeclaration(iterationStatement) { - const variableDeclarationList = iterationStatement.initializer; - if (variableDeclarationList.declarations.length >= 1) { - const decl = variableDeclarationList.declarations[0]; - checkVariableDeclaration(decl); - } - } function checkRightHandSideOfForOf(statement) { const use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */ ; return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression); @@ -67905,7 +68681,7 @@ ${lanes.join("\n")} if (hasStringConstituent) { if (languageVersion < 1 /* ES5 */ ) { if (errorNode) { - error(errorNode, Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); + error2(errorNode, Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); reportedError = true; } } @@ -67934,7 +68710,7 @@ ${lanes.join("\n")} } return use & 128 /* PossiblyOutOfBounds */ ? includeUndefinedInIndexSignature(arrayElementType) : arrayElementType; function getIterationDiagnosticDetails(allowsStrings, downlevelIteration2) { - var _a2; + var _a; if (downlevelIteration2) return allowsStrings ? [ Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true @@ -67947,7 +68723,7 @@ ${lanes.join("\n")} Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher, false ]; - if (isES2015OrLaterIterable((_a2 = inputType.symbol) == null ? void 0 : _a2.escapedName)) return [ + if (isES2015OrLaterIterable((_a = inputType.symbol) == null ? void 0 : _a.escapedName)) return [ Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher, true ]; @@ -68026,7 +68802,7 @@ ${lanes.join("\n")} return type[cacheKey] = cachedTypes2; } function getIterationTypesOfIterable(type, use, errorNode) { - var _a2, _b; + var _a, _b; if (isTypeAny(type)) return anyIterationTypes; if (!(type.flags & 1048576 /* Union */ )) { const errorOutputContainer = errorNode ? { @@ -68039,7 +68815,7 @@ ${lanes.join("\n")} if (errorOutputContainer == null ? void 0 : errorOutputContainer.errors) addRelatedInfo(rootDiag, ...errorOutputContainer.errors); } return void 0; - } else if ((_a2 = errorOutputContainer == null ? void 0 : errorOutputContainer.errors) == null ? void 0 : _a2.length) for (const diag2 of errorOutputContainer.errors)diagnostics.add(diag2); + } else if ((_a = errorOutputContainer == null ? void 0 : errorOutputContainer.errors) == null ? void 0 : _a.length) for (const diag2 of errorOutputContainer.errors)diagnostics.add(diag2); return iterationTypes2; } const cacheKey = use & 2 /* AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable"; @@ -68068,7 +68844,7 @@ ${lanes.join("\n")} function getAsyncFromSyncIterationTypes(iterationTypes, errorNode) { if (iterationTypes === noIterationTypes) return noIterationTypes; if (iterationTypes === anyIterationTypes) return anyIterationTypes; - const { yieldType: yieldType , returnType: returnType , nextType: nextType } = iterationTypes; + const { yieldType: yieldType, returnType: returnType, nextType: nextType } = iterationTypes; if (errorNode) getGlobalAwaitedSymbol(/*reportErrors*/ true); return createIterationTypes(getAwaitedType(yieldType, errorNode) || anyType, getAwaitedType(returnType, errorNode) || anyType, nextType); } @@ -68122,7 +68898,7 @@ ${lanes.join("\n")} let globalType; if (isReferenceToType2(type, globalType = resolver.getGlobalIterableType(/*reportErrors*/ false)) || isReferenceToType2(type, globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false))) { const [yieldType] = getTypeArguments(type); - const { returnType: returnType , nextType: nextType } = getIterationTypesOfGlobalIterableType(globalType, resolver); + const { returnType: returnType, nextType: nextType } = getIterationTypesOfGlobalIterableType(globalType, resolver); return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(resolver.resolveIterationType(yieldType, /*errorNode*/ void 0) || yieldType, resolver.resolveIterationType(returnType, /*errorNode*/ void 0) || returnType, nextType)); } if (isReferenceToType2(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) { @@ -68136,20 +68912,19 @@ ${lanes.join("\n")} return uniqueType && isTypeUsableAsPropertyName(uniqueType) ? getPropertyNameFromType(uniqueType) : `__@${symbolName2}`; } function getIterationTypesOfIterableSlow(type, resolver, errorNode, errorOutputContainer, noCache) { - var _a2; const method = getPropertyOfType(type, getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); const methodType = method && !(method.flags & 16777216 /* Optional */ ) ? getTypeOfSymbol(method) : void 0; if (isTypeAny(methodType)) return noCache ? anyIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); const signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */ ) : void 0; if (!some(signatures)) return noCache ? noIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes); const iteratorType = getIntersectionType(map(signatures, getReturnTypeOfSignature)); - const iterationTypes = (_a2 = getIterationTypesOfIteratorWorker(iteratorType, resolver, errorNode, errorOutputContainer, noCache)) != null ? _a2 : noIterationTypes; + const iterationTypes = getIterationTypesOfIteratorWorker(iteratorType, resolver, errorNode, errorOutputContainer, noCache) ?? noIterationTypes; return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes); } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { const message = allowAsyncIterables ? Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator : Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator; const suggestAwait = // for (const x of Promise<...>) or [...Promise<...>] - !!getAwaitedTypeOfPromise(type) || !allowAsyncIterables && isForOfStatement(errorNode.parent) && errorNode.parent.expression === errorNode && getGlobalAsyncIterableType(/** reportErrors */ false) !== emptyGenericType && isTypeAssignableTo(type, getGlobalAsyncIterableType(/** reportErrors */ false)); + !!getAwaitedTypeOfPromise(type) || !allowAsyncIterables && isForOfStatement(errorNode.parent) && errorNode.parent.expression === errorNode && getGlobalAsyncIterableType(/*reportErrors*/ false) !== emptyGenericType && isTypeAssignableTo(type, getGlobalAsyncIterableType(/*reportErrors*/ false)); return errorAndMaybeSuggestAwait(errorNode, suggestAwait, message, typeToString(type)); } function getIterationTypesOfIterator(type, resolver, errorNode, errorOutputContainer) { @@ -68162,7 +68937,7 @@ ${lanes.join("\n")} iterationTypes = void 0; noCache = true; } - iterationTypes != null ? iterationTypes : iterationTypes = getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache); + iterationTypes ?? (iterationTypes = getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache)); return iterationTypes === noIterationTypes ? void 0 : iterationTypes; } function getIterationTypesOfIteratorCached(type, resolver) { @@ -68173,7 +68948,7 @@ ${lanes.join("\n")} if (isReferenceToType2(type, globalType)) { const [yieldType] = getTypeArguments(type); const globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) || getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ void 0, /*errorOutputContainer*/ void 0, /*noCache*/ false); - const { returnType: returnType , nextType: nextType } = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes; + const { returnType: returnType, nextType: nextType } = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes; return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType)); } if (isReferenceToType2(type, resolver.getGlobalIteratorType(/*reportErrors*/ false)) || isReferenceToType2(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) { @@ -68211,7 +68986,7 @@ ${lanes.join("\n")} return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType, returnType || voidType, /*nextType*/ void 0)); } function getIterationTypesOfMethod(type, resolver, methodName, errorNode, errorOutputContainer) { - var _a2, _b, _c, _d, _e, _f; + var _a, _b, _c, _d; const method = getPropertyOfType(type, methodName); if (!method && methodName !== "next") return void 0; const methodType = method && !(methodName === "next" && method.flags & 16777216 /* Optional */ ) ? methodName === "next" ? getTypeOfSymbol(method) : getTypeWithFacts(getTypeOfSymbol(method), 2097152 /* NEUndefinedOrNull */ ) : void 0; @@ -68221,20 +68996,20 @@ ${lanes.join("\n")} if (errorNode) { const diagnostic = methodName === "next" ? resolver.mustHaveANextMethodDiagnostic : resolver.mustBeAMethodDiagnostic; if (errorOutputContainer) { - (_a2 = errorOutputContainer.errors) != null ? _a2 : errorOutputContainer.errors = []; + errorOutputContainer.errors ?? (errorOutputContainer.errors = []); errorOutputContainer.errors.push(createDiagnosticForNode(errorNode, diagnostic, methodName)); - } else error(errorNode, diagnostic, methodName); + } else error2(errorNode, diagnostic, methodName); } return methodName === "next" ? noIterationTypes : void 0; } if ((methodType == null ? void 0 : methodType.symbol) && methodSignatures.length === 1) { const globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false); const globalIteratorType = resolver.getGlobalIteratorType(/*reportErrors*/ false); - const isGeneratorMethod = ((_c = (_b = globalGeneratorType.symbol) == null ? void 0 : _b.members) == null ? void 0 : _c.get(methodName)) === methodType.symbol; - const isIteratorMethod = !isGeneratorMethod && ((_e = (_d = globalIteratorType.symbol) == null ? void 0 : _d.members) == null ? void 0 : _e.get(methodName)) === methodType.symbol; + const isGeneratorMethod = ((_b = (_a = globalGeneratorType.symbol) == null ? void 0 : _a.members) == null ? void 0 : _b.get(methodName)) === methodType.symbol; + const isIteratorMethod = !isGeneratorMethod && ((_d = (_c = globalIteratorType.symbol) == null ? void 0 : _c.members) == null ? void 0 : _d.get(methodName)) === methodType.symbol; if (isGeneratorMethod || isIteratorMethod) { const globalType = isGeneratorMethod ? globalGeneratorType : globalIteratorType; - const { mapper: mapper } = methodType; + const { mapper: mapper } = methodType; return createIterationTypes(getMappedType(globalType.typeParameters[0], mapper), getMappedType(globalType.typeParameters[1], mapper), methodName === "next" ? getMappedType(globalType.typeParameters[2], mapper) : void 0); } } @@ -68261,9 +69036,9 @@ ${lanes.join("\n")} if (iterationTypes === noIterationTypes) { if (errorNode) { if (errorOutputContainer) { - (_f = errorOutputContainer.errors) != null ? _f : errorOutputContainer.errors = []; + errorOutputContainer.errors ?? (errorOutputContainer.errors = []); errorOutputContainer.errors.push(createDiagnosticForNode(errorNode, resolver.mustHaveAValueDiagnostic, methodName)); - } else error(errorNode, resolver.mustHaveAValueDiagnostic, methodName); + } else error2(errorNode, resolver.mustHaveAValueDiagnostic, methodName); } yieldType = anyType; returnTypes = append(returnTypes, anyType); @@ -68305,12 +69080,11 @@ ${lanes.join("\n")} } return isAsync ? getAwaitedTypeNoAlias(returnType) || errorType : returnType; } - function isUnwrappedReturnTypeVoidOrAny(func, returnType) { - const unwrappedReturnType = unwrapReturnType(returnType, getFunctionFlags(func)); - return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16387 /* AnyOrUnknown */ ); + function isUnwrappedReturnTypeUndefinedVoidOrAny(func, returnType) { + const type = unwrapReturnType(returnType, getFunctionFlags(func)); + return !!(type && (maybeTypeOfKind(type, 16384 /* Void */ ) || type.flags & 32769 /* Undefined */ )); } function checkReturnStatement(node) { - var _a2; if (checkGrammarStatementInAmbientContext(node)) return; const container = getContainingFunctionOrClassStaticBlock(node); if (container && isClassStaticBlockDeclaration(container)) { @@ -68326,20 +69100,20 @@ ${lanes.join("\n")} const functionFlags = getFunctionFlags(container); if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */ ) { const exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - if (container.kind === 175 /* SetAccessor */ ) { - if (node.expression) error(node, Diagnostics.Setters_cannot_return_a_value); - } else if (container.kind === 173 /* Constructor */ ) { - if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) error(node, Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); + if (container.kind === 178 /* SetAccessor */ ) { + if (node.expression) error2(node, Diagnostics.Setters_cannot_return_a_value); + } else if (container.kind === 176 /* Constructor */ ) { + if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) error2(node, Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } else if (getReturnTypeFromAnnotation(container)) { - const unwrappedReturnType = (_a2 = unwrapReturnType(returnType, functionFlags)) != null ? _a2 : returnType; + const unwrappedReturnType = unwrapReturnType(returnType, functionFlags) ?? returnType; const unwrappedExprType = functionFlags & 2 /* Async */ ? checkAwaitedType(exprType, /*withAlias*/ false, node, Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) : exprType; if (unwrappedReturnType) checkTypeAssignableToAndOptionallyElaborate(unwrappedExprType, unwrappedReturnType, node, node.expression); } - } else if (container.kind !== 173 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(container, returnType)) error(node, Diagnostics.Not_all_code_paths_return_a_value); + } else if (container.kind !== 176 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeUndefinedVoidOrAny(container, returnType)) error2(node, Diagnostics.Not_all_code_paths_return_a_value); } function checkWithStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.flags & 32768 /* AwaitContext */ ) grammarErrorOnFirstToken(node, Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); + if (node.flags & 65536 /* AwaitContext */ ) grammarErrorOnFirstToken(node, Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); } checkExpression(node.expression); const sourceFile = getSourceFileOfNode(node); @@ -68355,16 +69129,16 @@ ${lanes.join("\n")} let hasDuplicateDefaultClause = false; const expressionType = checkExpression(node.expression); forEach(node.caseBlock.clauses, (clause)=>{ - if (clause.kind === 293 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 297 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === void 0) firstDefaultClause = clause; else { grammarErrorOnNode(clause, Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); hasDuplicateDefaultClause = true; } } - if (clause.kind === 292 /* CaseClause */ ) addLazyDiagnostic(createLazyCaseClauseDiagnostics(clause)); + if (clause.kind === 296 /* CaseClause */ ) addLazyDiagnostic(createLazyCaseClauseDiagnostics(clause)); forEach(clause.statements, checkSourceElement); - if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) error(clause, Diagnostics.Fallthrough_case_in_switch); + if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) error2(clause, Diagnostics.Fallthrough_case_in_switch); function createLazyCaseClauseDiagnostics(clause2) { return ()=>{ const caseType = checkExpression(clause2.expression); @@ -68377,7 +69151,7 @@ ${lanes.join("\n")} function checkLabeledStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) findAncestor(node.parent, (current)=>{ if (isFunctionLike(current)) return "quit"; - if (current.kind === 253 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + if (current.kind === 256 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { grammarErrorOnNode(node.label, Diagnostics.Duplicate_label_0, getTextOfNode(node.label)); return true; } @@ -68408,7 +69182,7 @@ ${lanes.join("\n")} const blockLocals = catchClause.block.locals; if (blockLocals) forEachKey(catchClause.locals, (caughtName)=>{ const blockLocal = blockLocals.get(caughtName); - if ((blockLocal == null ? void 0 : blockLocal.valueDeclaration) && (blockLocal.flags & 2 /* BlockScopedVariable */ ) !== 0) grammarErrorOnNode(blockLocal.valueDeclaration, Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); + if ((blockLocal == null ? void 0 : blockLocal.valueDeclaration) && (blockLocal.flags & 2 /* BlockScopedVariable */ ) !== 0) grammarErrorOnNode(blockLocal.valueDeclaration, Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, unescapeLeadingUnderscores(caughtName)); }); } } @@ -68434,8 +69208,8 @@ ${lanes.join("\n")} const name = getNameOfDeclaration(declaration); if (name && isPrivateIdentifier(name)) return; const indexInfos = getApplicableIndexInfos(type, propNameType); - const interfaceDeclaration = getObjectFlags(type) & 2 /* Interface */ ? getDeclarationOfKind(type.symbol, 261 /* InterfaceDeclaration */ ) : void 0; - const propDeclaration = declaration && declaration.kind === 223 /* BinaryExpression */ || name && name.kind === 164 /* ComputedPropertyName */ ? declaration : void 0; + const interfaceDeclaration = getObjectFlags(type) & 2 /* Interface */ ? getDeclarationOfKind(type.symbol, 264 /* InterfaceDeclaration */ ) : void 0; + const propDeclaration = declaration && declaration.kind === 226 /* BinaryExpression */ || name && name.kind === 167 /* ComputedPropertyName */ ? declaration : void 0; const localPropDeclaration = getParentOfSymbol(prop) === type.symbol ? declaration : void 0; for (const info of indexInfos){ const localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfDeclaration(info.declaration)) === type.symbol ? info.declaration : void 0; @@ -68450,13 +69224,13 @@ ${lanes.join("\n")} function checkIndexConstraintForIndexSignature(type, checkInfo) { const declaration = checkInfo.declaration; const indexInfos = getApplicableIndexInfos(type, checkInfo.keyType); - const interfaceDeclaration = getObjectFlags(type) & 2 /* Interface */ ? getDeclarationOfKind(type.symbol, 261 /* InterfaceDeclaration */ ) : void 0; + const interfaceDeclaration = getObjectFlags(type) & 2 /* Interface */ ? getDeclarationOfKind(type.symbol, 264 /* InterfaceDeclaration */ ) : void 0; const localCheckDeclaration = declaration && getParentOfSymbol(getSymbolOfDeclaration(declaration)) === type.symbol ? declaration : void 0; for (const info of indexInfos){ if (info === checkInfo) continue; const localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfDeclaration(info.declaration)) === type.symbol ? info.declaration : void 0; const errorNode = localCheckDeclaration || localIndexDeclaration || (interfaceDeclaration && !some(getBaseTypes(type), (base)=>!!getIndexInfoOfType(base, checkInfo.keyType) && !!getIndexTypeOfType(base, info.keyType)) ? interfaceDeclaration : void 0); - if (errorNode && !isTypeAssignableTo(checkInfo.type, info.type)) error(errorNode, Diagnostics._0_index_type_1_is_not_assignable_to_2_index_type_3, typeToString(checkInfo.keyType), typeToString(checkInfo.type), typeToString(info.keyType), typeToString(info.type)); + if (errorNode && !isTypeAssignableTo(checkInfo.type, info.type)) error2(errorNode, Diagnostics._0_index_type_1_is_not_assignable_to_2_index_type_3, typeToString(checkInfo.keyType), typeToString(checkInfo.type), typeToString(info.keyType), typeToString(info.type)); } } function checkTypeNameIsReserved(name, message) { @@ -68471,11 +69245,11 @@ ${lanes.join("\n")} case "symbol": case "void": case "object": - error(name, message, name.escapedText); + error2(name, message, name.escapedText); } } function checkClassNameCollisionWithObject(name) { - if (languageVersion >= 1 /* ES5 */ && name.escapedText === "Object" && (moduleKind < 5 /* ES2015 */ || getSourceFileOfNode(name).impliedNodeFormat === 1 /* CommonJS */ )) error(name, Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ModuleKind[moduleKind]); + if (languageVersion >= 1 /* ES5 */ && name.escapedText === "Object" && (moduleKind < 5 /* ES2015 */ || getSourceFileOfNode(name).impliedNodeFormat === 1 /* CommonJS */ )) error2(name, Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ModuleKind[moduleKind]); } function checkUnmatchedJSDocParameters(node) { const jsdocParameters = filter(getJSDocTags(node), isJSDocParameterTag); @@ -68483,7 +69257,7 @@ ${lanes.join("\n")} const isJs = isInJSFile(node); const parameters = /* @__PURE__ */ new Set(); const excludedParameters = /* @__PURE__ */ new Set(); - forEach(node.parameters, ({ name: name }, index)=>{ + forEach(node.parameters, ({ name: name }, index)=>{ if (isIdentifier(name)) parameters.add(name.escapedText); if (isBindingPattern(name)) excludedParameters.add(index); }); @@ -68491,11 +69265,11 @@ ${lanes.join("\n")} if (containsArguments) { const lastJSDocParamIndex = jsdocParameters.length - 1; const lastJSDocParam = jsdocParameters[lastJSDocParamIndex]; - if (isJs && lastJSDocParam && isIdentifier(lastJSDocParam.name) && lastJSDocParam.typeExpression && lastJSDocParam.typeExpression.type && !parameters.has(lastJSDocParam.name.escapedText) && !excludedParameters.has(lastJSDocParamIndex) && !isArrayType(getTypeFromTypeNode(lastJSDocParam.typeExpression.type))) error(lastJSDocParam.name, Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, idText(lastJSDocParam.name)); - } else forEach(jsdocParameters, ({ name: name , isNameFirst: isNameFirst }, index)=>{ + if (isJs && lastJSDocParam && isIdentifier(lastJSDocParam.name) && lastJSDocParam.typeExpression && lastJSDocParam.typeExpression.type && !parameters.has(lastJSDocParam.name.escapedText) && !excludedParameters.has(lastJSDocParamIndex) && !isArrayType(getTypeFromTypeNode(lastJSDocParam.typeExpression.type))) error2(lastJSDocParam.name, Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, idText(lastJSDocParam.name)); + } else forEach(jsdocParameters, ({ name: name, isNameFirst: isNameFirst }, index)=>{ if (excludedParameters.has(index) || isIdentifier(name) && parameters.has(name.escapedText)) return; if (isQualifiedName(name)) { - if (isJs) error(name, Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, entityNameToString(name), entityNameToString(name.left)); + if (isJs) error2(name, Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, entityNameToString(name), entityNameToString(name.left)); } else if (!isNameFirst) errorOrSuggestion(isJs, name, Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, idText(name)); }); } @@ -68511,18 +69285,18 @@ ${lanes.join("\n")} if (node.default) { seenDefault = true; checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i); - } else if (seenDefault) error(node, Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); - for(let j = 0; j < i; j++)if (typeParameterDeclarations[j].symbol === node.symbol) error(node.name, Diagnostics.Duplicate_identifier_0, declarationNameToString(node.name)); + } else if (seenDefault) error2(node, Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); + for(let j = 0; j < i; j++)if (typeParameterDeclarations[j].symbol === node.symbol) error2(node.name, Diagnostics.Duplicate_identifier_0, declarationNameToString(node.name)); }; } } function checkTypeParametersNotReferenced(root, typeParameters, index) { visit(root); function visit(node) { - if (node.kind === 180 /* TypeReference */ ) { + if (node.kind === 183 /* TypeReference */ ) { const type = getTypeFromTypeReference(node); if (type.flags & 262144 /* TypeParameter */ ) { - for(let i = index; i < typeParameters.length; i++)if (type.symbol === getSymbolOfDeclaration(typeParameters[i])) error(node, Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters); + for(let i = index; i < typeParameters.length; i++)if (type.symbol === getSymbolOfDeclaration(typeParameters[i])) error2(node, Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters); } } forEachChild(node, visit); @@ -68538,7 +69312,7 @@ ${lanes.join("\n")} const type = getDeclaredTypeOfSymbol(symbol); if (!areTypeParametersIdentical(declarations, type.localTypeParameters, getEffectiveTypeParameterDeclarations)) { const name = symbolToString(symbol); - for (const declaration of declarations)error(declaration.name, Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); + for (const declaration of declarations)error2(declaration.name, Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); } } } @@ -68565,12 +69339,11 @@ ${lanes.join("\n")} return true; } function getFirstTransformableStaticClassElement(node) { - var _a2; const willTransformStaticElementsOfDecoratedClass = !legacyDecorators && languageVersion < 99 /* ESNext */ && classOrConstructorParameterIsDecorated(/*useLegacyDecorators*/ false, node); const willTransformPrivateElementsOrClassStaticBlocks = languageVersion <= 9 /* ES2022 */ ; - const willTransformInitializers = !useDefineForClassFields || languageVersion < 9 /* ES2022 */ ; + const willTransformInitializers = !emitStandardClassFields; if (willTransformStaticElementsOfDecoratedClass || willTransformPrivateElementsOrClassStaticBlocks) for (const member of node.members){ - if (willTransformStaticElementsOfDecoratedClass && classElementOrClassElementParameterIsDecorated(/*useLegacyDecorators*/ false, member, node)) return (_a2 = firstOrUndefined(getDecorators(node))) != null ? _a2 : node; + if (willTransformStaticElementsOfDecoratedClass && classElementOrClassElementParameterIsDecorated(/*useLegacyDecorators*/ false, member, node)) return firstOrUndefined(getDecorators(node)) ?? node; else if (willTransformPrivateElementsOrClassStaticBlocks) { if (isClassStaticBlockDeclaration(member)) return member; else if (isStatic(member)) { @@ -68580,13 +69353,12 @@ ${lanes.join("\n")} } } function checkClassExpressionExternalHelpers(node) { - var _a2; if (node.name) return; const parent2 = walkUpOuterExpressions(node); if (!isNamedEvaluationSource(parent2)) return; const willTransformESDecorators = !legacyDecorators && languageVersion < 99 /* ESNext */ ; let location; - if (willTransformESDecorators && classOrConstructorParameterIsDecorated(/*useLegacyDecorators*/ false, node)) location = (_a2 = firstOrUndefined(getDecorators(node))) != null ? _a2 : node; + if (willTransformESDecorators && classOrConstructorParameterIsDecorated(/*useLegacyDecorators*/ false, node)) location = firstOrUndefined(getDecorators(node)) ?? node; else location = getFirstTransformableStaticClassElement(node); if (location) { checkExternalEmitHelpers(location, 8388608 /* SetFunctionName */ ); @@ -68624,7 +69396,7 @@ ${lanes.join("\n")} checkTypeParameterListsIdentical(symbol); checkFunctionOrConstructorSymbol(symbol); checkClassForDuplicateDeclarations(node); - const nodeInAmbientContext = !!(node.flags & 16777216 /* Ambient */ ); + const nodeInAmbientContext = !!(node.flags & 33554432 /* Ambient */ ); if (!nodeInAmbientContext) checkClassForStaticPropertyNameConflicts(node); const baseTypeNode = getEffectiveBaseTypeNode(node); if (baseTypeNode) { @@ -68649,15 +69421,15 @@ ${lanes.join("\n")} if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ void 0)) issueMemberSpecificError(node, typeWithThis, baseWithThis, Diagnostics.Class_0_incorrectly_extends_base_class_1); else checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); if (baseConstructorType.flags & 8650752 /* TypeVariable */ ) { - if (!isMixinConstructorType(staticType)) error(node.name || node, Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); + if (!isMixinConstructorType(staticType)) error2(node.name || node, Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); else { const constructSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */ ); - if (constructSignatures.some((signature)=>signature.flags & 4 /* Abstract */ ) && !hasSyntacticModifier(node, 256 /* Abstract */ )) error(node.name || node, Diagnostics.A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract); + if (constructSignatures.some((signature)=>signature.flags & 4 /* Abstract */ ) && !hasSyntacticModifier(node, 256 /* Abstract */ )) error2(node.name || node, Diagnostics.A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract); } } if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */ ) && !(baseConstructorType.flags & 8650752 /* TypeVariable */ )) { const constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (forEach(constructors, (sig)=>!isJSConstructor(sig.declaration) && !isTypeIdenticalTo(getReturnTypeOfSignature(sig), baseType))) error(baseTypeNode.expression, Diagnostics.Base_constructors_must_all_have_the_same_return_type); + if (forEach(constructors, (sig)=>!isJSConstructor(sig.declaration) && !isTypeIdenticalTo(getReturnTypeOfSignature(sig), baseType))) error2(baseTypeNode.expression, Diagnostics.Base_constructors_must_all_have_the_same_return_type); } checkKindsOfPropertyMemberOverrides(type, baseType); }); @@ -68665,7 +69437,7 @@ ${lanes.join("\n")} checkMembersForOverrideModifier(node, type, typeWithThis, staticType); const implementedTypeNodes = getEffectiveImplementsTypeNodes(node); if (implementedTypeNodes) for (const typeRefNode of implementedTypeNodes){ - if (!isEntityNameExpression(typeRefNode.expression) || isOptionalChain(typeRefNode.expression)) error(typeRefNode.expression, Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); + if (!isEntityNameExpression(typeRefNode.expression) || isOptionalChain(typeRefNode.expression)) error2(typeRefNode.expression, Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); checkTypeReferenceNode(typeRefNode); addLazyDiagnostic(createImplementsDiagnostics(typeRefNode)); } @@ -68683,7 +69455,7 @@ ${lanes.join("\n")} const genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : Diagnostics.Class_0_incorrectly_implements_interface_1; const baseWithThis = getTypeWithThisArgument(t, type.thisType); if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ void 0)) issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag); - } else error(typeRefNode, Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members); + } else error2(typeRefNode, Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members); } }; } @@ -68696,9 +69468,9 @@ ${lanes.join("\n")} for (const member of node.members){ if (hasAmbientModifier(member)) continue; if (isConstructorDeclaration(member)) forEach(member.parameters, (param)=>{ - if (isParameterPropertyDeclaration(param, member)) checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, param, /* memberIsParameterProperty */ true); + if (isParameterPropertyDeclaration(param, member)) checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, param, /*memberIsParameterProperty*/ true); }); - checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, /* memberIsParameterProperty */ false); + checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, /*memberIsParameterProperty*/ false); } } function checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, memberIsParameterProperty, reportErrors2 = true) { @@ -68708,7 +69480,7 @@ ${lanes.join("\n")} } function checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, memberHasAbstractModifier, memberIsStatic, memberIsParameterProperty, memberName, errorNode) { const isJs = isInJSFile(node); - const nodeInAmbientContext = !!(node.flags & 16777216 /* Ambient */ ); + const nodeInAmbientContext = !!(node.flags & 33554432 /* Ambient */ ); if (baseWithThis && (memberHasOverrideModifier || compilerOptions.noImplicitOverride)) { const memberEscapedName = escapeLeadingUnderscores(memberName); const thisType = memberIsStatic ? staticType : typeWithThis; @@ -68719,7 +69491,7 @@ ${lanes.join("\n")} if (prop && !baseProp && memberHasOverrideModifier) { if (errorNode) { const suggestion = getSuggestedSymbolForNonexistentClassMember(memberName, baseType); - suggestion ? error(errorNode, isJs ? Diagnostics.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 : Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1, baseClassName, symbolToString(suggestion)) : error(errorNode, isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0 : Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName); + suggestion ? error2(errorNode, isJs ? Diagnostics.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 : Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1, baseClassName, symbolToString(suggestion)) : error2(errorNode, isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0 : Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName); } return 2 /* HasInvalidOverride */ ; } else if (prop && (baseProp == null ? void 0 : baseProp.declarations) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) { @@ -68728,18 +69500,18 @@ ${lanes.join("\n")} if (!baseHasAbstract) { if (errorNode) { const diag2 = memberIsParameterProperty ? isJs ? Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : isJs ? Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; - error(errorNode, diag2, baseClassName); + error2(errorNode, diag2, baseClassName); } return 1 /* NeedsOverride */ ; } else if (memberHasAbstractModifier && baseHasAbstract) { - if (errorNode) error(errorNode, Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName); + if (errorNode) error2(errorNode, Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName); return 1 /* NeedsOverride */ ; } } } else if (memberHasOverrideModifier) { if (errorNode) { const className = typeToString(type); - error(errorNode, isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class : Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class, className); + error2(errorNode, isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class : Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class, className); } return 2 /* HasInvalidOverride */ ; } @@ -68755,7 +69527,7 @@ ${lanes.join("\n")} const baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); if (prop && baseProp) { const rootChain = ()=>chainDiagnosticMessages(/*details*/ void 0, Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, symbolToString(declaredProp), typeToString(typeWithThis), typeToString(baseWithThis)); - if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ void 0, rootChain)) issuedMemberError = true; + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*headMessage*/ void 0, rootChain)) issuedMemberError = true; } } } @@ -68767,7 +69539,7 @@ ${lanes.join("\n")} const declaration = signatures[0].declaration; if (declaration && hasEffectiveModifier(declaration, 8 /* Private */ )) { const typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); - if (!isNodeWithinClass(node, typeClassDeclaration)) error(node, Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); + if (!isNodeWithinClass(node, typeClassDeclaration)) error2(node, Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); } } } @@ -68782,17 +69554,18 @@ ${lanes.join("\n")} const baseWithThis = (baseTypes == null ? void 0 : baseTypes.length) ? getTypeWithThisArgument(first(baseTypes), type.thisType) : void 0; const baseStaticType = getBaseConstructorTypeOfClass(type); const memberHasOverrideModifier = member.parent ? hasOverrideModifier(member) : hasSyntacticModifier(member, 16384 /* Override */ ); - return checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, hasAbstractModifier(member), isStatic(member), /* memberIsParameterProperty */ false, symbolName(memberSymbol)); + return checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, hasAbstractModifier(member), isStatic(member), /*memberIsParameterProperty*/ false, symbolName(memberSymbol)); } function getTargetSymbol(s) { return getCheckFlags(s) & 1 /* Instantiated */ ? s.links.target : s; } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { - return filter(symbol.declarations, (d)=>d.kind === 260 /* ClassDeclaration */ || d.kind === 261 /* InterfaceDeclaration */ ); + return filter(symbol.declarations, (d)=>d.kind === 263 /* ClassDeclaration */ || d.kind === 264 /* InterfaceDeclaration */ ); } function checkKindsOfPropertyMemberOverrides(type, baseType) { - var _a2, _b, _c, _d; + var _a, _b, _c, _d; const baseProperties = getPropertiesOfType(baseType); + let inheritedAbstractMemberNotImplementedError; basePropertyCheck: for (const baseProperty of baseProperties){ const base = getTargetSymbol(baseProperty); if (base.flags & 4194304 /* Prototype */ ) continue; @@ -68810,8 +69583,9 @@ ${lanes.join("\n")} const derivedElsewhere = baseSymbol2 && getTargetSymbol(baseSymbol2); if (derivedElsewhere && derivedElsewhere !== base) continue basePropertyCheck; } - if (derivedClassDecl.kind === 228 /* ClassExpression */ ) error(derivedClassDecl, Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); - else error(derivedClassDecl, Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType)); + if (!inheritedAbstractMemberNotImplementedError) inheritedAbstractMemberNotImplementedError = error2(derivedClassDecl, Diagnostics.Non_abstract_class_0_does_not_implement_all_abstract_members_of_1, typeToString(type), typeToString(baseType)); + if (derivedClassDecl.kind === 231 /* ClassExpression */ ) addRelatedInfo(inheritedAbstractMemberNotImplementedError, createDiagnosticForNode(baseProperty.valueDeclaration ?? (baseProperty.declarations && first(baseProperty.declarations)) ?? derivedClassDecl, Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType))); + else addRelatedInfo(inheritedAbstractMemberNotImplementedError, createDiagnosticForNode(baseProperty.valueDeclaration ?? (baseProperty.declarations && first(baseProperty.declarations)) ?? derivedClassDecl, Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType))); } } else { const derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); @@ -68820,20 +69594,20 @@ ${lanes.join("\n")} const basePropertyFlags = base.flags & 98308 /* PropertyOrAccessor */ ; const derivedPropertyFlags = derived.flags & 98308 /* PropertyOrAccessor */ ; if (basePropertyFlags && derivedPropertyFlags) { - if ((getCheckFlags(base) & 6 /* Synthetic */ ? (_a2 = base.declarations) == null ? void 0 : _a2.some((d)=>isPropertyAbstractOrInterface(d, baseDeclarationFlags)) : (_b = base.declarations) == null ? void 0 : _b.every((d)=>isPropertyAbstractOrInterface(d, baseDeclarationFlags))) || getCheckFlags(base) & 262144 /* Mapped */ || derived.valueDeclaration && isBinaryExpression(derived.valueDeclaration)) continue; + if ((getCheckFlags(base) & 6 /* Synthetic */ ? (_a = base.declarations) == null ? void 0 : _a.some((d)=>isPropertyAbstractOrInterface(d, baseDeclarationFlags)) : (_b = base.declarations) == null ? void 0 : _b.every((d)=>isPropertyAbstractOrInterface(d, baseDeclarationFlags))) || getCheckFlags(base) & 262144 /* Mapped */ || derived.valueDeclaration && isBinaryExpression(derived.valueDeclaration)) continue; const overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */ ; const overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */ ; if (overriddenInstanceProperty || overriddenInstanceAccessor) { const errorMessage2 = overriddenInstanceProperty ? Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property : Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor; - error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType), typeToString(type)); + error2(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType), typeToString(type)); } else if (useDefineForClassFields) { - const uninitialized = (_c = derived.declarations) == null ? void 0 : _c.find((d)=>d.kind === 169 /* PropertyDeclaration */ && !d.initializer); - if (uninitialized && !(derived.flags & 33554432 /* Transient */ ) && !(baseDeclarationFlags & 256 /* Abstract */ ) && !(derivedDeclarationFlags & 256 /* Abstract */ ) && !((_d = derived.declarations) == null ? void 0 : _d.some((d)=>!!(d.flags & 16777216 /* Ambient */ )))) { + const uninitialized = (_c = derived.declarations) == null ? void 0 : _c.find((d)=>d.kind === 172 /* PropertyDeclaration */ && !d.initializer); + if (uninitialized && !(derived.flags & 33554432 /* Transient */ ) && !(baseDeclarationFlags & 256 /* Abstract */ ) && !(derivedDeclarationFlags & 256 /* Abstract */ ) && !((_d = derived.declarations) == null ? void 0 : _d.some((d)=>!!(d.flags & 33554432 /* Ambient */ )))) { const constructor = findConstructorDeclaration(getClassLikeDeclarationOfSymbol(type.symbol)); const propName = uninitialized.name; if (uninitialized.exclamationToken || !constructor || !isIdentifier(propName) || !strictNullChecks || !isPropertyInitializedInConstructor(propName, type, constructor)) { const errorMessage2 = Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration; - error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType)); + error2(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType)); } } } @@ -68846,7 +69620,7 @@ ${lanes.join("\n")} } } else if (base.flags & 98304 /* Accessor */ ) errorMessage = Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; else errorMessage = Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; - error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error2(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -68903,7 +69677,7 @@ ${lanes.join("\n")} return ok; } function checkPropertyInitialization(node) { - if (!strictNullChecks || !strictPropertyInitialization || node.flags & 16777216 /* Ambient */ ) return; + if (!strictNullChecks || !strictPropertyInitialization || node.flags & 33554432 /* Ambient */ ) return; const constructor = findConstructorDeclaration(node); for (const member of node.members){ if (getEffectiveModifierFlags(member) & 2 /* Ambient */ ) continue; @@ -68912,14 +69686,14 @@ ${lanes.join("\n")} if (isIdentifier(propName) || isPrivateIdentifier(propName) || isComputedPropertyName(propName)) { const type = getTypeOfSymbol(getSymbolOfDeclaration(member)); if (!(type.flags & 3 /* AnyOrUnknown */ || containsUndefinedType(type))) { - if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) error(member.name, Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, declarationNameToString(propName)); + if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) error2(member.name, Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, declarationNameToString(propName)); } } } } } function isPropertyWithoutInitializer(node) { - return node.kind === 169 /* PropertyDeclaration */ && !hasAbstractModifier(node) && !node.exclamationToken && !node.initializer; + return node.kind === 172 /* PropertyDeclaration */ && !hasAbstractModifier(node) && !node.exclamationToken && !node.initializer; } function isPropertyInitializedInStaticBlocks(propName, propType, staticBlocks, startPos, endPos) { for (const staticBlock of staticBlocks)if (staticBlock.pos >= startPos && staticBlock.pos <= endPos) { @@ -68948,7 +69722,7 @@ ${lanes.join("\n")} checkExportsOnMergedDeclarations(node); const symbol = getSymbolOfDeclaration(node); checkTypeParameterListsIdentical(symbol); - const firstInterfaceDecl = getDeclarationOfKind(symbol, 261 /* InterfaceDeclaration */ ); + const firstInterfaceDecl = getDeclarationOfKind(symbol, 264 /* InterfaceDeclaration */ ); if (node === firstInterfaceDecl) { const type = getDeclaredTypeOfSymbol(symbol); const typeWithThis = getTypeWithThisArgument(type); @@ -68960,7 +69734,7 @@ ${lanes.join("\n")} checkObjectTypeForDuplicateDeclarations(node); }); forEach(getInterfaceBaseTypeNodes(node), (heritageElement)=>{ - if (!isEntityNameExpression(heritageElement.expression) || isOptionalChain(heritageElement.expression)) error(heritageElement.expression, Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); + if (!isEntityNameExpression(heritageElement.expression) || isOptionalChain(heritageElement.expression)) error2(heritageElement.expression, Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); checkTypeReferenceNode(heritageElement); }); forEach(node.members, checkSourceElement); @@ -68974,8 +69748,8 @@ ${lanes.join("\n")} checkTypeNameIsReserved(node.name, Diagnostics.Type_alias_name_cannot_be_0); checkExportsOnMergedDeclarations(node); checkTypeParameters(node.typeParameters); - if (node.type.kind === 139 /* IntrinsicKeyword */ ) { - if (!intrinsicTypeKinds.has(node.name.escapedText) || length(node.typeParameters) !== 1) error(node.type, Diagnostics.The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types); + if (node.type.kind === 141 /* IntrinsicKeyword */ ) { + if (!intrinsicTypeKinds.has(node.name.escapedText) || length(node.typeParameters) !== 1) error2(node.type, Diagnostics.The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types); } else { checkSourceElement(node.type); registerForUnusedIdentifiersCheck(node); @@ -68994,15 +69768,15 @@ ${lanes.join("\n")} } } function computeMemberValue(member, autoValue) { - if (isComputedNonLiteralName(member.name)) error(member.name, Diagnostics.Computed_property_names_are_not_allowed_in_enums); + if (isComputedNonLiteralName(member.name)) error2(member.name, Diagnostics.Computed_property_names_are_not_allowed_in_enums); else { const text = getTextOfPropertyName(member.name); - if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) error(member.name, Diagnostics.An_enum_member_cannot_have_a_numeric_name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) error2(member.name, Diagnostics.An_enum_member_cannot_have_a_numeric_name); } if (member.initializer) return computeConstantValue(member); - if (member.parent.flags & 16777216 /* Ambient */ && !isEnumConst(member.parent)) return void 0; + if (member.parent.flags & 33554432 /* Ambient */ && !isEnumConst(member.parent)) return void 0; if (autoValue !== void 0) return autoValue; - error(member.name, Diagnostics.Enum_member_must_have_initializer); + error2(member.name, Diagnostics.Enum_member_must_have_initializer); return void 0; } function computeConstantValue(member) { @@ -69010,88 +69784,91 @@ ${lanes.join("\n")} const initializer = member.initializer; const value1 = evaluate(initializer, member); if (value1 !== void 0) { - if (isConstEnum && typeof value1 === "number" && !isFinite(value1)) error(initializer, isNaN(value1) ? Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); - } else if (isConstEnum) error(initializer, Diagnostics.const_enum_member_initializers_must_be_constant_expressions); - else if (member.parent.flags & 16777216 /* Ambient */ ) error(initializer, Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + if (isConstEnum && typeof value1 === "number" && !isFinite(value1)) error2(initializer, isNaN(value1) ? Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } else if (isConstEnum) error2(initializer, Diagnostics.const_enum_member_initializers_must_be_constant_expressions); + else if (member.parent.flags & 33554432 /* Ambient */ ) error2(initializer, Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); else checkTypeAssignableTo(checkExpression(initializer), numberType, initializer, Diagnostics.Type_0_is_not_assignable_to_type_1_as_required_for_computed_enum_member_values); return value1; } function evaluate(expr, location) { switch(expr.kind){ - case 221 /* PrefixUnaryExpression */ : + case 224 /* PrefixUnaryExpression */ : const value1 = evaluate(expr.operand, location); if (typeof value1 === "number") switch(expr.operator){ - case 39 /* PlusToken */ : + case 40 /* PlusToken */ : return value1; - case 40 /* MinusToken */ : + case 41 /* MinusToken */ : return -value1; - case 54 /* TildeToken */ : + case 55 /* TildeToken */ : return ~value1; } break; - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : const left = evaluate(expr.left, location); const right = evaluate(expr.right, location); if (typeof left === "number" && typeof right === "number") switch(expr.operatorToken.kind){ - case 51 /* BarToken */ : + case 52 /* BarToken */ : return left | right; - case 50 /* AmpersandToken */ : + case 51 /* AmpersandToken */ : return left & right; - case 48 /* GreaterThanGreaterThanToken */ : + case 49 /* GreaterThanGreaterThanToken */ : return left >> right; - case 49 /* GreaterThanGreaterThanGreaterThanToken */ : + case 50 /* GreaterThanGreaterThanGreaterThanToken */ : return left >>> right; - case 47 /* LessThanLessThanToken */ : + case 48 /* LessThanLessThanToken */ : return left << right; - case 52 /* CaretToken */ : + case 53 /* CaretToken */ : return left ^ right; - case 41 /* AsteriskToken */ : + case 42 /* AsteriskToken */ : return left * right; - case 43 /* SlashToken */ : + case 44 /* SlashToken */ : return left / right; - case 39 /* PlusToken */ : + case 40 /* PlusToken */ : return left + right; - case 40 /* MinusToken */ : + case 41 /* MinusToken */ : return left - right; - case 44 /* PercentToken */ : + case 45 /* PercentToken */ : return left % right; - case 42 /* AsteriskAsteriskToken */ : + case 43 /* AsteriskAsteriskToken */ : return left ** right; } - else if ((typeof left === "string" || typeof left === "number") && (typeof right === "string" || typeof right === "number") && expr.operatorToken.kind === 39 /* PlusToken */ ) return "" + left + right; + else if ((typeof left === "string" || typeof left === "number") && (typeof right === "string" || typeof right === "number") && expr.operatorToken.kind === 40 /* PlusToken */ ) return "" + left + right; break; - case 10 /* StringLiteral */ : - case 14 /* NoSubstitutionTemplateLiteral */ : + case 11 /* StringLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : return expr.text; - case 225 /* TemplateExpression */ : + case 228 /* TemplateExpression */ : return evaluateTemplateExpression(expr, location); - case 8 /* NumericLiteral */ : + case 9 /* NumericLiteral */ : checkGrammarNumericLiteral(expr); return +expr.text; - case 214 /* ParenthesizedExpression */ : + case 217 /* ParenthesizedExpression */ : return evaluate(expr.expression, location); - case 79 /* Identifier */ : - if (isInfinityOrNaNString(expr.escapedText)) return +expr.escapedText; - case 208 /* PropertyAccessExpression */ : + case 80 /* Identifier */ : + { + const identifier = expr; + if (isInfinityOrNaNString(identifier.escapedText) && resolveEntityName(identifier, 111551 /* Value */ , /*ignoreErrors*/ true) === getGlobalSymbol(identifier.escapedText, 111551 /* Value */ , /*diagnostic*/ void 0)) return +identifier.escapedText; + } + case 211 /* PropertyAccessExpression */ : if (isEntityNameExpression(expr)) { const symbol = resolveEntityName(expr, 111551 /* Value */ , /*ignoreErrors*/ true); if (symbol) { - if (symbol.flags & 8 /* EnumMember */ ) return evaluateEnumMember(expr, symbol, location); - if (isConstVariable(symbol)) { + if (symbol.flags & 8 /* EnumMember */ ) return location ? evaluateEnumMember(expr, symbol, location) : getEnumMemberValue(symbol.valueDeclaration); + if (isConstantVariable(symbol)) { const declaration = symbol.valueDeclaration; - if (declaration && !declaration.type && declaration.initializer && declaration !== location && isBlockScopedNameDeclaredBeforeUse(declaration, location)) return evaluate(declaration.initializer, declaration); + if (declaration && !declaration.type && declaration.initializer && (!location || declaration !== location && isBlockScopedNameDeclaredBeforeUse(declaration, location))) return evaluate(declaration.initializer, declaration); } } } break; - case 209 /* ElementAccessExpression */ : + case 212 /* ElementAccessExpression */ : const root = expr.expression; if (isEntityNameExpression(root) && isStringLiteralLike(expr.argumentExpression)) { const rootSymbol = resolveEntityName(root, 111551 /* Value */ , /*ignoreErrors*/ true); if (rootSymbol && rootSymbol.flags & 384 /* Enum */ ) { const name = escapeLeadingUnderscores(expr.argumentExpression.text); const member = rootSymbol.exports.get(name); - if (member) return evaluateEnumMember(expr, member, location); + if (member) return location ? evaluateEnumMember(expr, member, location) : getEnumMemberValue(member.valueDeclaration); } } break; @@ -69101,11 +69878,11 @@ ${lanes.join("\n")} function evaluateEnumMember(expr, symbol, location) { const declaration = symbol.valueDeclaration; if (!declaration || declaration === location) { - error(expr, Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(symbol)); + error2(expr, Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(symbol)); return void 0; } if (!isBlockScopedNameDeclaredBeforeUse(declaration, location)) { - error(expr, Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); + error2(expr, Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); return 0; } return getEnumMemberValue(declaration); @@ -69135,30 +69912,30 @@ ${lanes.join("\n")} if (enumSymbol.declarations && enumSymbol.declarations.length > 1) { const enumIsConst = isEnumConst(node); forEach(enumSymbol.declarations, (decl)=>{ - if (isEnumDeclaration(decl) && isEnumConst(decl) !== enumIsConst) error(getNameOfDeclaration(decl), Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + if (isEnumDeclaration(decl) && isEnumConst(decl) !== enumIsConst) error2(getNameOfDeclaration(decl), Diagnostics.Enum_declarations_must_all_be_const_or_non_const); }); } let seenEnumMissingInitialInitializer = false; forEach(enumSymbol.declarations, (declaration)=>{ - if (declaration.kind !== 263 /* EnumDeclaration */ ) return false; + if (declaration.kind !== 266 /* EnumDeclaration */ ) return false; const enumDeclaration = declaration; if (!enumDeclaration.members.length) return false; const firstEnumMember = enumDeclaration.members[0]; if (!firstEnumMember.initializer) { - if (seenEnumMissingInitialInitializer) error(firstEnumMember.name, Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); + if (seenEnumMissingInitialInitializer) error2(firstEnumMember.name, Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); else seenEnumMissingInitialInitializer = true; } }); } } function checkEnumMember(node) { - if (isPrivateIdentifier(node.name)) error(node, Diagnostics.An_enum_member_cannot_be_named_with_a_private_identifier); + if (isPrivateIdentifier(node.name)) error2(node, Diagnostics.An_enum_member_cannot_be_named_with_a_private_identifier); if (node.initializer) checkExpression(node.initializer); } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { const declarations = symbol.declarations; if (declarations) for (const declaration of declarations){ - if ((declaration.kind === 260 /* ClassDeclaration */ || declaration.kind === 259 /* FunctionDeclaration */ && nodeIsPresent(declaration.body)) && !(declaration.flags & 16777216 /* Ambient */ )) return declaration; + if ((declaration.kind === 263 /* ClassDeclaration */ || declaration.kind === 262 /* FunctionDeclaration */ && nodeIsPresent(declaration.body)) && !(declaration.flags & 33554432 /* Ambient */ )) return declaration; } return void 0; } @@ -69176,33 +69953,33 @@ ${lanes.join("\n")} } addLazyDiagnostic(checkModuleDeclarationDiagnostics); function checkModuleDeclarationDiagnostics() { - var _a2, _b; + var _a, _b; const isGlobalAugmentation = isGlobalScopeAugmentation(node); - const inAmbientContext = node.flags & 16777216 /* Ambient */ ; - if (isGlobalAugmentation && !inAmbientContext) error(node.name, Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); + const inAmbientContext = node.flags & 33554432 /* Ambient */ ; + if (isGlobalAugmentation && !inAmbientContext) error2(node.name, Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); const isAmbientExternalModule = isAmbientModule(node); const contextErrorMessage = isAmbientExternalModule ? Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file : Diagnostics.A_namespace_declaration_is_only_allowed_at_the_top_level_of_a_namespace_or_module; if (checkGrammarModuleElementContext(node, contextErrorMessage)) return; if (!checkGrammarModifiers(node)) { - if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */ ) grammarErrorOnNode(node.name, Diagnostics.Only_ambient_modules_can_use_quoted_names); + if (!inAmbientContext && node.name.kind === 11 /* StringLiteral */ ) grammarErrorOnNode(node.name, Diagnostics.Only_ambient_modules_can_use_quoted_names); } if (isIdentifier(node.name)) checkCollisionsForDeclarationName(node, node.name); checkExportsOnMergedDeclarations(node); const symbol = getSymbolOfDeclaration(node); if (symbol.flags & 512 /* ValueModule */ && !inAmbientContext && isInstantiatedModule(node, shouldPreserveConstEnums(compilerOptions))) { - if (getIsolatedModules(compilerOptions) && !getSourceFileOfNode(node).externalModuleIndicator) error(node.name, Diagnostics.Namespaces_are_not_allowed_in_global_script_files_when_0_is_enabled_If_this_file_is_not_intended_to_be_a_global_script_set_moduleDetection_to_force_or_add_an_empty_export_statement, isolatedModulesLikeFlagName); - if (((_a2 = symbol.declarations) == null ? void 0 : _a2.length) > 1) { + if (getIsolatedModules(compilerOptions) && !getSourceFileOfNode(node).externalModuleIndicator) error2(node.name, Diagnostics.Namespaces_are_not_allowed_in_global_script_files_when_0_is_enabled_If_this_file_is_not_intended_to_be_a_global_script_set_moduleDetection_to_force_or_add_an_empty_export_statement, isolatedModulesLikeFlagName); + if (((_a = symbol.declarations) == null ? void 0 : _a.length) > 1) { const firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { - if (getSourceFileOfNode(node) !== getSourceFileOfNode(firstNonAmbientClassOrFunc)) error(node.name, Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); - else if (node.pos < firstNonAmbientClassOrFunc.pos) error(node.name, Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); + if (getSourceFileOfNode(node) !== getSourceFileOfNode(firstNonAmbientClassOrFunc)) error2(node.name, Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); + else if (node.pos < firstNonAmbientClassOrFunc.pos) error2(node.name, Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); } - const mergedClass = getDeclarationOfKind(symbol, 260 /* ClassDeclaration */ ); + const mergedClass = getDeclarationOfKind(symbol, 263 /* ClassDeclaration */ ); if (mergedClass && inSameLexicalScope(node, mergedClass)) getNodeLinks(node).flags |= 2048 /* LexicalModuleMergesWithClass */ ; } - if (compilerOptions.verbatimModuleSyntax && node.parent.kind === 308 /* SourceFile */ && (moduleKind === 1 /* CommonJS */ || node.parent.impliedNodeFormat === 1 /* CommonJS */ )) { - const exportModifier = (_b = node.modifiers) == null ? void 0 : _b.find((m)=>m.kind === 93 /* ExportKeyword */ ); - if (exportModifier) error(exportModifier, Diagnostics.A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled); + if (compilerOptions.verbatimModuleSyntax && node.parent.kind === 312 /* SourceFile */ && (moduleKind === 1 /* CommonJS */ || node.parent.impliedNodeFormat === 1 /* CommonJS */ )) { + const exportModifier = (_b = node.modifiers) == null ? void 0 : _b.find((m)=>m.kind === 95 /* ExportKeyword */ ); + if (exportModifier) error2(exportModifier, Diagnostics.A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled); } } if (isAmbientExternalModule) { @@ -69210,56 +69987,56 @@ ${lanes.join("\n")} const checkBody = isGlobalAugmentation || getSymbolOfDeclaration(node).flags & 33554432 /* Transient */ ; if (checkBody && node.body) for (const statement of node.body.statements)checkModuleAugmentationElement(statement, isGlobalAugmentation); } else if (isGlobalSourceFile(node.parent)) { - if (isGlobalAugmentation) error(node.name, Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); - else if (isExternalModuleNameRelative(getTextOfIdentifierOrLiteral(node.name))) error(node.name, Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); - } else if (isGlobalAugmentation) error(node.name, Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); - else error(node.name, Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + if (isGlobalAugmentation) error2(node.name, Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + else if (isExternalModuleNameRelative(getTextOfIdentifierOrLiteral(node.name))) error2(node.name, Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + } else if (isGlobalAugmentation) error2(node.name, Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + else error2(node.name, Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); } } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch(node.kind){ - case 240 /* VariableStatement */ : + case 243 /* VariableStatement */ : for (const decl of node.declarationList.declarations)checkModuleAugmentationElement(decl, isGlobalAugmentation); break; - case 274 /* ExportAssignment */ : - case 275 /* ExportDeclaration */ : + case 277 /* ExportAssignment */ : + case 278 /* ExportDeclaration */ : grammarErrorOnFirstToken(node, Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 268 /* ImportEqualsDeclaration */ : - case 269 /* ImportDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : + case 272 /* ImportDeclaration */ : grammarErrorOnFirstToken(node, Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 205 /* BindingElement */ : - case 257 /* VariableDeclaration */ : + case 208 /* BindingElement */ : + case 260 /* VariableDeclaration */ : const name = node.name; if (isBindingPattern(name)) { for (const el of name.elements)checkModuleAugmentationElement(el, isGlobalAugmentation); break; } - case 260 /* ClassDeclaration */ : - case 263 /* EnumDeclaration */ : - case 259 /* FunctionDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 264 /* ModuleDeclaration */ : - case 262 /* TypeAliasDeclaration */ : + case 263 /* ClassDeclaration */ : + case 266 /* EnumDeclaration */ : + case 262 /* FunctionDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 267 /* ModuleDeclaration */ : + case 265 /* TypeAliasDeclaration */ : if (isGlobalAugmentation) return; break; } } function getFirstNonModuleExportsIdentifier(node) { switch(node.kind){ - case 79 /* Identifier */ : + case 80 /* Identifier */ : return node; - case 163 /* QualifiedName */ : + case 166 /* QualifiedName */ : do node = node.left; - while (node.kind !== 79 /* Identifier */ ); + while (node.kind !== 80 /* Identifier */ ); return node; - case 208 /* PropertyAccessExpression */ : + case 211 /* PropertyAccessExpression */ : do { if (isModuleExportsAccessExpression(node.expression) && !isPrivateIdentifier(node.name)) return node.name; node = node.expression; - }while (node.kind !== 79 /* Identifier */ ); + }while (node.kind !== 80 /* Identifier */ ); return node; } } @@ -69267,17 +70044,17 @@ ${lanes.join("\n")} const moduleName = getExternalModuleName(node); if (!moduleName || nodeIsMissing(moduleName)) return false; if (!isStringLiteral(moduleName)) { - error(moduleName, Diagnostics.String_literal_expected); + error2(moduleName, Diagnostics.String_literal_expected); return false; } - const inAmbientExternalModule = node.parent.kind === 265 /* ModuleBlock */ && isAmbientModule(node.parent.parent); - if (node.parent.kind !== 308 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 275 /* ExportDeclaration */ ? Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); + const inAmbientExternalModule = node.parent.kind === 268 /* ModuleBlock */ && isAmbientModule(node.parent.parent); + if (node.parent.kind !== 312 /* SourceFile */ && !inAmbientExternalModule) { + error2(moduleName, node.kind === 278 /* ExportDeclaration */ ? Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; } if (inAmbientExternalModule && isExternalModuleNameRelative(moduleName.text)) { if (!isTopLevelInExternalModuleAugmentation(node)) { - error(node, Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); + error2(node, Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); return false; } } @@ -69285,79 +70062,76 @@ ${lanes.join("\n")} let hasError = false; for (const clause of node.assertClause.elements)if (!isStringLiteral(clause.value)) { hasError = true; - error(clause.value, Diagnostics.Import_assertion_values_must_be_string_literal_expressions); + error2(clause.value, Diagnostics.Import_assertion_values_must_be_string_literal_expressions); } return !hasError; } return true; } function checkAliasSymbol(node) { - var _a2, _b, _c, _d, _e; + var _a, _b, _c, _d; let symbol = getSymbolOfDeclaration(node); const target = resolveAlias(symbol); if (target !== unknownSymbol) { symbol = getMergedSymbol(symbol.exportSymbol || symbol); if (isInJSFile(node) && !(target.flags & 111551 /* Value */ ) && !isTypeOnlyImportOrExportDeclaration(node)) { const errorNode = isImportOrExportSpecifier(node) ? node.propertyName || node.name : isNamedDeclaration(node) ? node.name : node; - Debug.assert(node.kind !== 277 /* NamespaceExport */ ); - if (node.kind === 278 /* ExportSpecifier */ ) { - const diag2 = error(errorNode, Diagnostics.Types_cannot_appear_in_export_declarations_in_JavaScript_files); - const alreadyExportedSymbol = (_b = (_a2 = getSourceFileOfNode(node).symbol) == null ? void 0 : _a2.exports) == null ? void 0 : _b.get((node.propertyName || node.name).escapedText); + Debug.assert(node.kind !== 280 /* NamespaceExport */ ); + if (node.kind === 281 /* ExportSpecifier */ ) { + const diag2 = error2(errorNode, Diagnostics.Types_cannot_appear_in_export_declarations_in_JavaScript_files); + const alreadyExportedSymbol = (_b = (_a = getSourceFileOfNode(node).symbol) == null ? void 0 : _a.exports) == null ? void 0 : _b.get((node.propertyName || node.name).escapedText); if (alreadyExportedSymbol === target) { const exportingDeclaration = (_c = alreadyExportedSymbol.declarations) == null ? void 0 : _c.find(isJSDocNode); if (exportingDeclaration) addRelatedInfo(diag2, createDiagnosticForNode(exportingDeclaration, Diagnostics._0_is_automatically_exported_here, unescapeLeadingUnderscores(alreadyExportedSymbol.escapedName))); } } else { - Debug.assert(node.kind !== 257 /* VariableDeclaration */ ); + Debug.assert(node.kind !== 260 /* VariableDeclaration */ ); const importDeclaration = findAncestor(node, or(isImportDeclaration, isImportEqualsDeclaration)); - const moduleSpecifier = (_e = importDeclaration && ((_d = tryGetModuleSpecifierFromDeclaration(importDeclaration)) == null ? void 0 : _d.text)) != null ? _e : "..."; + const moduleSpecifier = (importDeclaration && ((_d = tryGetModuleSpecifierFromDeclaration(importDeclaration)) == null ? void 0 : _d.text)) ?? "..."; const importedIdentifier = unescapeLeadingUnderscores(isIdentifier(errorNode) ? errorNode.escapedText : symbol.escapedName); - error(errorNode, Diagnostics._0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation, importedIdentifier, `import("${moduleSpecifier}").${importedIdentifier}`); + error2(errorNode, Diagnostics._0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation, importedIdentifier, `import("${moduleSpecifier}").${importedIdentifier}`); } return; } - const targetFlags = getAllSymbolFlags(target); + const targetFlags = getSymbolFlags(target); const excludedMeanings = (symbol.flags & 1160127 /* ExportValue */ ? 111551 /* Value */ : 0) | (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (targetFlags & excludedMeanings) { - const message = node.kind === 278 /* ExportSpecifier */ ? Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; - error(node, message, symbolToString(symbol)); + const message = node.kind === 281 /* ExportSpecifier */ ? Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; + error2(node, message, symbolToString(symbol)); } - if (getIsolatedModules(compilerOptions) && !isTypeOnlyImportOrExportDeclaration(node) && !(node.flags & 16777216 /* Ambient */ )) { + if (getIsolatedModules(compilerOptions) && !isTypeOnlyImportOrExportDeclaration(node) && !(node.flags & 33554432 /* Ambient */ )) { const typeOnlyAlias = getTypeOnlyAliasDeclaration(symbol); const isType = !(targetFlags & 111551 /* Value */ ); if (isType || typeOnlyAlias) switch(node.kind){ - case 270 /* ImportClause */ : - case 273 /* ImportSpecifier */ : - case 268 /* ImportEqualsDeclaration */ : + case 273 /* ImportClause */ : + case 276 /* ImportSpecifier */ : + case 271 /* ImportEqualsDeclaration */ : if (compilerOptions.preserveValueImports || compilerOptions.verbatimModuleSyntax) { Debug.assertIsDefined(node.name, "An ImportClause with a symbol should have a name"); const message = compilerOptions.verbatimModuleSyntax && isInternalModuleImportEqualsDeclaration(node) ? Diagnostics.An_import_alias_cannot_resolve_to_a_type_or_type_only_declaration_when_verbatimModuleSyntax_is_enabled : isType ? compilerOptions.verbatimModuleSyntax ? Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled : Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedModules_are_both_enabled : compilerOptions.verbatimModuleSyntax ? Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled : Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedModules_are_both_enabled; - const name = idText(node.kind === 273 /* ImportSpecifier */ ? node.propertyName || node.name : node.name); - addTypeOnlyDeclarationRelatedInfo(error(node, message, name), isType ? void 0 : typeOnlyAlias, name); + const name = idText(node.kind === 276 /* ImportSpecifier */ ? node.propertyName || node.name : node.name); + addTypeOnlyDeclarationRelatedInfo(error2(node, message, name), isType ? void 0 : typeOnlyAlias, name); } - if (isType && node.kind === 268 /* ImportEqualsDeclaration */ && hasEffectiveModifier(node, 1 /* Export */ )) error(node, Diagnostics.Cannot_use_export_import_on_a_type_or_type_only_namespace_when_0_is_enabled, isolatedModulesLikeFlagName); + if (isType && node.kind === 271 /* ImportEqualsDeclaration */ && hasEffectiveModifier(node, 1 /* Export */ )) error2(node, Diagnostics.Cannot_use_export_import_on_a_type_or_type_only_namespace_when_0_is_enabled, isolatedModulesLikeFlagName); break; - case 278 /* ExportSpecifier */ : + case 281 /* ExportSpecifier */ : if (compilerOptions.verbatimModuleSyntax || getSourceFileOfNode(typeOnlyAlias) !== getSourceFileOfNode(node)) { const name = idText(node.propertyName || node.name); - const diagnostic = isType ? error(node, Diagnostics.Re_exporting_a_type_when_0_is_enabled_requires_using_export_type, isolatedModulesLikeFlagName) : error(node, Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_1_is_enabled, name, isolatedModulesLikeFlagName); + const diagnostic = isType ? error2(node, Diagnostics.Re_exporting_a_type_when_0_is_enabled_requires_using_export_type, isolatedModulesLikeFlagName) : error2(node, Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_1_is_enabled, name, isolatedModulesLikeFlagName); addTypeOnlyDeclarationRelatedInfo(diagnostic, isType ? void 0 : typeOnlyAlias, name); break; } } - if (compilerOptions.verbatimModuleSyntax && node.kind !== 268 /* ImportEqualsDeclaration */ && !isInJSFile(node) && (moduleKind === 1 /* CommonJS */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */ )) error(node, Diagnostics.ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled); + if (compilerOptions.verbatimModuleSyntax && node.kind !== 271 /* ImportEqualsDeclaration */ && !isInJSFile(node) && (moduleKind === 1 /* CommonJS */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */ )) error2(node, Diagnostics.ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled); } if (isImportSpecifier(node)) { - const targetSymbol = checkDeprecatedAliasedSymbol(symbol, node); - if (isDeprecatedAliasedSymbol(targetSymbol) && targetSymbol.declarations) addDeprecatedSuggestion(node, targetSymbol.declarations, targetSymbol.escapedName); + const targetSymbol = resolveAliasWithDeprecationCheck(symbol, node); + if (isDeprecatedSymbol(targetSymbol) && targetSymbol.declarations) addDeprecatedSuggestion(node, targetSymbol.declarations, targetSymbol.escapedName); } } } - function isDeprecatedAliasedSymbol(symbol) { - return !!symbol.declarations && every(symbol.declarations, (d)=>!!(getCombinedNodeFlags(d) & 268435456 /* Deprecated */ )); - } - function checkDeprecatedAliasedSymbol(symbol, location) { - if (!(symbol.flags & 2097152 /* Alias */ )) return symbol; + function resolveAliasWithDeprecationCheck(symbol, location) { + if (!(symbol.flags & 2097152 /* Alias */ ) || isDeprecatedSymbol(symbol) || !getDeclarationOfAliasSymbol(symbol)) return symbol; const targetSymbol = resolveAlias(symbol); if (targetSymbol === unknownSymbol) return targetSymbol; while(symbol.flags & 2097152 /* Alias */ ){ @@ -69365,7 +70139,7 @@ ${lanes.join("\n")} if (target) { if (target === targetSymbol) break; if (target.declarations && length(target.declarations)) { - if (isDeprecatedAliasedSymbol(target)) { + if (isDeprecatedSymbol(target)) { addDeprecatedSuggestion(location, target.declarations, target.escapedName); break; } else { @@ -69380,10 +70154,10 @@ ${lanes.join("\n")} function checkImportBinding(node) { checkCollisionsForDeclarationName(node, node.name); checkAliasSymbol(node); - if (node.kind === 273 /* ImportSpecifier */ && idText(node.propertyName || node.name) === "default" && getESModuleInterop(compilerOptions) && moduleKind !== 4 /* System */ && (moduleKind < 5 /* ES2015 */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */ )) checkExternalEmitHelpers(node, 131072 /* ImportDefault */ ); + if (node.kind === 276 /* ImportSpecifier */ && idText(node.propertyName || node.name) === "default" && getESModuleInterop(compilerOptions) && moduleKind !== 4 /* System */ && (moduleKind < 5 /* ES2015 */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */ )) checkExternalEmitHelpers(node, 131072 /* ImportDefault */ ); } function checkAssertClause(declaration) { - var _a2; + var _a; if (declaration.assertClause) { const validForTypeAssertions = isExclusivelyTypeOnlyImportOrExport(declaration); const override = getResolutionModeOverrideForClause(declaration.assertClause, validForTypeAssertions ? grammarErrorOnNode : void 0); @@ -69394,7 +70168,7 @@ ${lanes.join("\n")} } const mode = moduleKind === 199 /* NodeNext */ && declaration.moduleSpecifier && getUsageModeForExpression(declaration.moduleSpecifier); if (mode !== 99 /* ESNext */ && moduleKind !== 99 /* ESNext */ ) return grammarErrorOnNode(declaration.assertClause, moduleKind === 199 /* NodeNext */ ? Diagnostics.Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls : Diagnostics.Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_or_nodenext); - if (isImportDeclaration(declaration) ? (_a2 = declaration.importClause) == null ? void 0 : _a2.isTypeOnly : declaration.isTypeOnly) return grammarErrorOnNode(declaration.assertClause, Diagnostics.Import_assertions_cannot_be_used_with_type_only_imports_or_exports); + if (isImportDeclaration(declaration) ? (_a = declaration.importClause) == null ? void 0 : _a.isTypeOnly : declaration.isTypeOnly) return grammarErrorOnNode(declaration.assertClause, Diagnostics.Import_assertions_cannot_be_used_with_type_only_imports_or_exports); if (override) return grammarErrorOnNode(declaration.assertClause, Diagnostics.resolution_mode_can_only_be_set_for_type_only_imports); } } @@ -69406,7 +70180,7 @@ ${lanes.join("\n")} if (importClause && !checkGrammarImportClause(importClause)) { if (importClause.name) checkImportBinding(importClause); if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 271 /* NamespaceImport */ ) { + if (importClause.namedBindings.kind === 274 /* NamespaceImport */ ) { checkImportBinding(importClause.namedBindings); if (moduleKind !== 4 /* System */ && (moduleKind < 5 /* ES2015 */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */ ) && getESModuleInterop(compilerOptions)) checkExternalEmitHelpers(node, 65536 /* ImportStar */ ); } else { @@ -69424,18 +70198,18 @@ ${lanes.join("\n")} if (isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); if (hasSyntacticModifier(node, 1 /* Export */ )) markExportAsReferenced(node); - if (node.moduleReference.kind !== 280 /* ExternalModuleReference */ ) { + if (node.moduleReference.kind !== 283 /* ExternalModuleReference */ ) { const target = resolveAlias(getSymbolOfDeclaration(node)); if (target !== unknownSymbol) { - const targetFlags = getAllSymbolFlags(target); + const targetFlags = getSymbolFlags(target); if (targetFlags & 111551 /* Value */ ) { const moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 112575 /* Namespace */ ).flags & 1920 /* Namespace */ )) error(moduleName, Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, declarationNameToString(moduleName)); + if (!(resolveEntityName(moduleName, 112575 /* Namespace */ ).flags & 1920 /* Namespace */ )) error2(moduleName, Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, declarationNameToString(moduleName)); } if (targetFlags & 788968 /* Type */ ) checkTypeNameIsReserved(node.name, Diagnostics.Import_name_cannot_be_0); } if (node.isTypeOnly) grammarErrorOnNode(node, Diagnostics.An_import_alias_cannot_use_import_type); - } else if (moduleKind >= 5 /* ES2015 */ && getSourceFileOfNode(node).impliedNodeFormat === void 0 && !node.isTypeOnly && !(node.flags & 16777216 /* Ambient */ )) grammarErrorOnNode(node, Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); + } else if (moduleKind >= 5 /* ES2015 */ && getSourceFileOfNode(node).impliedNodeFormat === void 0 && !node.isTypeOnly && !(node.flags & 33554432 /* Ambient */ )) grammarErrorOnNode(node, Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); } } function checkExportDeclaration(node) { @@ -69446,12 +70220,12 @@ ${lanes.join("\n")} if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { if (node.exportClause && !isNamespaceExport(node.exportClause)) { forEach(node.exportClause.elements, checkExportSpecifier); - const inAmbientExternalModule = node.parent.kind === 265 /* ModuleBlock */ && isAmbientModule(node.parent.parent); - const inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 265 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 16777216 /* Ambient */ ; - if (node.parent.kind !== 308 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) error(node, Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); + const inAmbientExternalModule = node.parent.kind === 268 /* ModuleBlock */ && isAmbientModule(node.parent.parent); + const inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 268 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 33554432 /* Ambient */ ; + if (node.parent.kind !== 312 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) error2(node, Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } else { const moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); - if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) error(node.moduleSpecifier, Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); + if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) error2(node.moduleSpecifier, Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); else if (node.exportClause) checkAliasSymbol(node.exportClause); if (moduleKind !== 4 /* System */ && (moduleKind < 5 /* ES2015 */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */ )) { if (node.exportClause) { @@ -69463,12 +70237,12 @@ ${lanes.join("\n")} checkAssertClause(node); } function checkGrammarExportDeclaration(node) { - var _a2; - if (node.isTypeOnly && ((_a2 = node.exportClause) == null ? void 0 : _a2.kind) === 276 /* NamedExports */ ) return checkGrammarNamedImportsOrExports(node.exportClause); + var _a; + if (node.isTypeOnly && ((_a = node.exportClause) == null ? void 0 : _a.kind) === 279 /* NamedExports */ ) return checkGrammarNamedImportsOrExports(node.exportClause); return false; } function checkGrammarModuleElementContext(node, errorMessage) { - const isInAppropriateContext = node.parent.kind === 308 /* SourceFile */ || node.parent.kind === 265 /* ModuleBlock */ || node.parent.kind === 264 /* ModuleDeclaration */ ; + const isInAppropriateContext = node.parent.kind === 312 /* SourceFile */ || node.parent.kind === 268 /* ModuleBlock */ || node.parent.kind === 267 /* ModuleDeclaration */ ; if (!isInAppropriateContext) grammarErrorOnFirstToken(node, errorMessage); return !isInAppropriateContext; } @@ -69489,7 +70263,8 @@ ${lanes.join("\n")} return isImportEqualsDeclaration(statement) && isExternalModuleReference(statement.moduleReference) && !statement.isTypeOnly && getSymbolOfDeclaration(statement).isReferenced && !isReferencedAliasDeclaration(statement, /*checkChildren*/ false) && !getSymbolLinks(getSymbolOfDeclaration(statement)).constEnumReferenced; } function checkImportsForTypeOnlyConversion(sourceFile) { - for (const statement of sourceFile.statements)if (canConvertImportDeclarationToTypeOnly(statement) || canConvertImportEqualsDeclarationToTypeOnly(statement)) error(statement, Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set_to_error); + if (!canCollectSymbolAliasAccessabilityData) return; + for (const statement of sourceFile.statements)if (canConvertImportDeclarationToTypeOnly(statement) || canConvertImportEqualsDeclarationToTypeOnly(statement)) error2(statement, Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set_to_error); } function checkExportSpecifier(node) { checkAliasSymbol(node); @@ -69497,45 +70272,45 @@ ${lanes.join("\n")} if (!node.parent.parent.moduleSpecifier) { const exportedName = node.propertyName || node.name; const symbol = resolveName(exportedName, exportedName.escapedText, 2998271 /* Alias */ , /*nameNotFoundMessage*/ void 0, /*nameArg*/ void 0, /*isUse*/ true); - if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) error(exportedName, Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, idText(exportedName)); + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) error2(exportedName, Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, idText(exportedName)); else { if (!node.isTypeOnly && !node.parent.parent.isTypeOnly) markExportAsReferenced(node); const target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol); - if (!target || getAllSymbolFlags(target) & 111551 /* Value */ ) checkExpressionCached(node.propertyName || node.name); + if (!target || getSymbolFlags(target) & 111551 /* Value */ ) checkExpressionCached(node.propertyName || node.name); } } else if (getESModuleInterop(compilerOptions) && moduleKind !== 4 /* System */ && (moduleKind < 5 /* ES2015 */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */ ) && idText(node.propertyName || node.name) === "default") checkExternalEmitHelpers(node, 131072 /* ImportDefault */ ); } function checkExportAssignment(node) { const illegalContextMessage = node.isExportEquals ? Diagnostics.An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration : Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration; if (checkGrammarModuleElementContext(node, illegalContextMessage)) return; - const container = node.parent.kind === 308 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 264 /* ModuleDeclaration */ && !isAmbientModule(container)) { - if (node.isExportEquals) error(node, Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); - else error(node, Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + const container = node.parent.kind === 312 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 267 /* ModuleDeclaration */ && !isAmbientModule(container)) { + if (node.isExportEquals) error2(node, Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); + else error2(node, Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); return; } if (!checkGrammarModifiers(node) && hasEffectiveModifiers(node)) grammarErrorOnFirstToken(node, Diagnostics.An_export_assignment_cannot_have_modifiers); const typeAnnotationNode = getEffectiveTypeAnnotationNode(node); if (typeAnnotationNode) checkTypeAssignableTo(checkExpressionCached(node.expression), getTypeFromTypeNode(typeAnnotationNode), node.expression); - const isIllegalExportDefaultInCJS = !node.isExportEquals && !(node.flags & 16777216 /* Ambient */ ) && compilerOptions.verbatimModuleSyntax && (moduleKind === 1 /* CommonJS */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */ ); - if (node.expression.kind === 79 /* Identifier */ ) { + const isIllegalExportDefaultInCJS = !node.isExportEquals && !(node.flags & 33554432 /* Ambient */ ) && compilerOptions.verbatimModuleSyntax && (moduleKind === 1 /* CommonJS */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */ ); + if (node.expression.kind === 80 /* Identifier */ ) { const id = node.expression; const sym = getExportSymbolOfValueSymbolIfExported(resolveEntityName(id, 67108863 /* All */ , /*ignoreErrors*/ true, /*dontResolveAlias*/ true, node)); if (sym) { markAliasReferenced(sym, id); - if (getAllSymbolFlags(sym) & 111551 /* Value */ ) { + if (getSymbolFlags(sym) & 111551 /* Value */ ) { checkExpressionCached(id); - if (!isIllegalExportDefaultInCJS && !(node.flags & 16777216 /* Ambient */ ) && compilerOptions.verbatimModuleSyntax && getTypeOnlyAliasDeclaration(sym, 111551 /* Value */ )) error(id, node.isExportEquals ? Diagnostics.An_export_declaration_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_a_type_only_declaration : Diagnostics.An_export_default_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_a_type_only_declaration, idText(id)); - } else if (!isIllegalExportDefaultInCJS && !(node.flags & 16777216 /* Ambient */ ) && compilerOptions.verbatimModuleSyntax) error(id, node.isExportEquals ? Diagnostics.An_export_declaration_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_type : Diagnostics.An_export_default_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_type, idText(id)); + if (!isIllegalExportDefaultInCJS && !(node.flags & 33554432 /* Ambient */ ) && compilerOptions.verbatimModuleSyntax && getTypeOnlyAliasDeclaration(sym, 111551 /* Value */ )) error2(id, node.isExportEquals ? Diagnostics.An_export_declaration_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_a_type_only_declaration : Diagnostics.An_export_default_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_a_type_only_declaration, idText(id)); + } else if (!isIllegalExportDefaultInCJS && !(node.flags & 33554432 /* Ambient */ ) && compilerOptions.verbatimModuleSyntax) error2(id, node.isExportEquals ? Diagnostics.An_export_declaration_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_type : Diagnostics.An_export_default_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_type, idText(id)); } else checkExpressionCached(id); if (getEmitDeclarations(compilerOptions)) collectLinkedAliases(id, /*setVisibility*/ true); } else checkExpressionCached(node.expression); - if (isIllegalExportDefaultInCJS) error(node, Diagnostics.ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled); + if (isIllegalExportDefaultInCJS) error2(node, Diagnostics.ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled); checkExternalModuleExports(container); - if (node.flags & 16777216 /* Ambient */ && !isEntityNameExpression(node.expression)) grammarErrorOnNode(node.expression, Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); + if (node.flags & 33554432 /* Ambient */ && !isEntityNameExpression(node.expression)) grammarErrorOnNode(node.expression, Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); if (node.isExportEquals) { - if (moduleKind >= 5 /* ES2015 */ && (node.flags & 16777216 /* Ambient */ && getSourceFileOfNode(node).impliedNodeFormat === 99 /* ESNext */ || !(node.flags & 16777216 /* Ambient */ ) && getSourceFileOfNode(node).impliedNodeFormat !== 1 /* CommonJS */ )) grammarErrorOnNode(node, Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); - else if (moduleKind === 4 /* System */ && !(node.flags & 16777216 /* Ambient */ )) grammarErrorOnNode(node, Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); + if (moduleKind >= 5 /* ES2015 */ && (node.flags & 33554432 /* Ambient */ && getSourceFileOfNode(node).impliedNodeFormat === 99 /* ESNext */ || !(node.flags & 33554432 /* Ambient */ ) && getSourceFileOfNode(node).impliedNodeFormat !== 1 /* CommonJS */ )) grammarErrorOnNode(node, Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); + else if (moduleKind === 4 /* System */ && !(node.flags & 33554432 /* Ambient */ )) grammarErrorOnNode(node, Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); } } function hasExportedMembers(moduleSymbol) { @@ -69548,10 +70323,10 @@ ${lanes.join("\n")} const exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { const declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (declaration && !isTopLevelInExternalModuleAugmentation(declaration) && !isInJSFile(declaration)) error(declaration, Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + if (declaration && !isTopLevelInExternalModuleAugmentation(declaration) && !isInJSFile(declaration)) error2(declaration, Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } const exports = getExportsOfModule(moduleSymbol); - if (exports) exports.forEach(({ declarations: declarations , flags: flags }, id)=>{ + if (exports) exports.forEach(({ declarations: declarations, flags: flags }, id)=>{ if (id === "__export") return; if (flags & 1920 /* Enum */ ) return; const exportedDeclarationsCount = countWhere(declarations, and(isNotOverloadAndNotAccessor, not(isInterfaceDeclaration))); @@ -69578,7 +70353,7 @@ ${lanes.join("\n")} } } function checkSourceElementWorker(node) { - if (canHaveJSDoc(node)) forEach(node.jsDoc, ({ comment: comment , tags: tags })=>{ + if (canHaveJSDoc(node)) forEach(node.jsDoc, ({ comment: comment, tags: tags })=>{ checkJSDocCommentWorker(comment); forEach(tags, (tag)=>{ checkJSDocCommentWorker(tag.comment); @@ -69587,179 +70362,179 @@ ${lanes.join("\n")} }); const kind = node.kind; if (cancellationToken) switch(kind){ - case 264 /* ModuleDeclaration */ : - case 260 /* ClassDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 259 /* FunctionDeclaration */ : + case 267 /* ModuleDeclaration */ : + case 263 /* ClassDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 262 /* FunctionDeclaration */ : cancellationToken.throwIfCancellationRequested(); } - if (kind >= 240 /* FirstStatement */ && kind <= 256 /* LastStatement */ && canHaveFlowNode(node) && node.flowNode && !isReachableFlowNode(node.flowNode)) errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, Diagnostics.Unreachable_code_detected); + if (kind >= 243 /* FirstStatement */ && kind <= 259 /* LastStatement */ && canHaveFlowNode(node) && node.flowNode && !isReachableFlowNode(node.flowNode)) errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, Diagnostics.Unreachable_code_detected); switch(kind){ - case 165 /* TypeParameter */ : + case 168 /* TypeParameter */ : return checkTypeParameter(node); - case 166 /* Parameter */ : + case 169 /* Parameter */ : return checkParameter(node); - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : return checkPropertyDeclaration(node); - case 168 /* PropertySignature */ : + case 171 /* PropertySignature */ : return checkPropertySignature(node); - case 182 /* ConstructorType */ : - case 181 /* FunctionType */ : - case 176 /* CallSignature */ : - case 177 /* ConstructSignature */ : - case 178 /* IndexSignature */ : + case 185 /* ConstructorType */ : + case 184 /* FunctionType */ : + case 179 /* CallSignature */ : + case 180 /* ConstructSignature */ : + case 181 /* IndexSignature */ : return checkSignatureDeclaration(node); - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : return checkMethodDeclaration(node); - case 172 /* ClassStaticBlockDeclaration */ : + case 175 /* ClassStaticBlockDeclaration */ : return checkClassStaticBlockDeclaration(node); - case 173 /* Constructor */ : + case 176 /* Constructor */ : return checkConstructorDeclaration(node); - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : return checkAccessorDeclaration(node); - case 180 /* TypeReference */ : + case 183 /* TypeReference */ : return checkTypeReferenceNode(node); - case 179 /* TypePredicate */ : + case 182 /* TypePredicate */ : return checkTypePredicate(node); - case 183 /* TypeQuery */ : + case 186 /* TypeQuery */ : return checkTypeQuery(node); - case 184 /* TypeLiteral */ : + case 187 /* TypeLiteral */ : return checkTypeLiteral(node); - case 185 /* ArrayType */ : + case 188 /* ArrayType */ : return checkArrayType(node); - case 186 /* TupleType */ : + case 189 /* TupleType */ : return checkTupleType(node); - case 189 /* UnionType */ : - case 190 /* IntersectionType */ : + case 192 /* UnionType */ : + case 193 /* IntersectionType */ : return checkUnionOrIntersectionType(node); - case 193 /* ParenthesizedType */ : - case 187 /* OptionalType */ : - case 188 /* RestType */ : + case 196 /* ParenthesizedType */ : + case 190 /* OptionalType */ : + case 191 /* RestType */ : return checkSourceElement(node.type); - case 194 /* ThisType */ : + case 197 /* ThisType */ : return checkThisType(node); - case 195 /* TypeOperator */ : + case 198 /* TypeOperator */ : return checkTypeOperator(node); - case 191 /* ConditionalType */ : + case 194 /* ConditionalType */ : return checkConditionalType(node); - case 192 /* InferType */ : + case 195 /* InferType */ : return checkInferType(node); - case 200 /* TemplateLiteralType */ : + case 203 /* TemplateLiteralType */ : return checkTemplateLiteralType(node); - case 202 /* ImportType */ : + case 205 /* ImportType */ : return checkImportType(node); - case 199 /* NamedTupleMember */ : + case 202 /* NamedTupleMember */ : return checkNamedTupleMember(node); - case 331 /* JSDocAugmentsTag */ : + case 335 /* JSDocAugmentsTag */ : return checkJSDocAugmentsTag(node); - case 332 /* JSDocImplementsTag */ : + case 336 /* JSDocImplementsTag */ : return checkJSDocImplementsTag(node); - case 349 /* JSDocTypedefTag */ : - case 341 /* JSDocCallbackTag */ : - case 343 /* JSDocEnumTag */ : + case 353 /* JSDocTypedefTag */ : + case 345 /* JSDocCallbackTag */ : + case 347 /* JSDocEnumTag */ : return checkJSDocTypeAliasTag(node); - case 348 /* JSDocTemplateTag */ : + case 352 /* JSDocTemplateTag */ : return checkJSDocTemplateTag(node); - case 347 /* JSDocTypeTag */ : + case 351 /* JSDocTypeTag */ : return checkJSDocTypeTag(node); - case 327 /* JSDocLink */ : - case 328 /* JSDocLinkCode */ : - case 329 /* JSDocLinkPlain */ : + case 331 /* JSDocLink */ : + case 332 /* JSDocLinkCode */ : + case 333 /* JSDocLinkPlain */ : return checkJSDocLinkLikeTag(node); - case 344 /* JSDocParameterTag */ : + case 348 /* JSDocParameterTag */ : return checkJSDocParameterTag(node); - case 351 /* JSDocPropertyTag */ : + case 355 /* JSDocPropertyTag */ : return checkJSDocPropertyTag(node); - case 320 /* JSDocFunctionType */ : + case 324 /* JSDocFunctionType */ : checkJSDocFunctionType(node); - case 318 /* JSDocNonNullableType */ : - case 317 /* JSDocNullableType */ : - case 315 /* JSDocAllType */ : - case 316 /* JSDocUnknownType */ : - case 325 /* JSDocTypeLiteral */ : + case 322 /* JSDocNonNullableType */ : + case 321 /* JSDocNullableType */ : + case 319 /* JSDocAllType */ : + case 320 /* JSDocUnknownType */ : + case 329 /* JSDocTypeLiteral */ : checkJSDocTypeIsInJsFile(node); forEachChild(node, checkSourceElement); return; - case 321 /* JSDocVariadicType */ : + case 325 /* JSDocVariadicType */ : checkJSDocVariadicType(node); return; - case 312 /* JSDocTypeExpression */ : + case 316 /* JSDocTypeExpression */ : return checkSourceElement(node.type); - case 336 /* JSDocPublicTag */ : - case 338 /* JSDocProtectedTag */ : - case 337 /* JSDocPrivateTag */ : + case 340 /* JSDocPublicTag */ : + case 342 /* JSDocProtectedTag */ : + case 341 /* JSDocPrivateTag */ : return checkJSDocAccessibilityModifiers(node); - case 353 /* JSDocSatisfiesTag */ : + case 357 /* JSDocSatisfiesTag */ : return checkJSDocSatisfiesTag(node); - case 196 /* IndexedAccessType */ : + case 199 /* IndexedAccessType */ : return checkIndexedAccessType(node); - case 197 /* MappedType */ : + case 200 /* MappedType */ : return checkMappedType(node); - case 259 /* FunctionDeclaration */ : + case 262 /* FunctionDeclaration */ : return checkFunctionDeclaration(node); - case 238 /* Block */ : - case 265 /* ModuleBlock */ : + case 241 /* Block */ : + case 268 /* ModuleBlock */ : return checkBlock(node); - case 240 /* VariableStatement */ : + case 243 /* VariableStatement */ : return checkVariableStatement(node); - case 241 /* ExpressionStatement */ : + case 244 /* ExpressionStatement */ : return checkExpressionStatement(node); - case 242 /* IfStatement */ : + case 245 /* IfStatement */ : return checkIfStatement(node); - case 243 /* DoStatement */ : + case 246 /* DoStatement */ : return checkDoStatement(node); - case 244 /* WhileStatement */ : + case 247 /* WhileStatement */ : return checkWhileStatement(node); - case 245 /* ForStatement */ : + case 248 /* ForStatement */ : return checkForStatement(node); - case 246 /* ForInStatement */ : + case 249 /* ForInStatement */ : return checkForInStatement(node); - case 247 /* ForOfStatement */ : + case 250 /* ForOfStatement */ : return checkForOfStatement(node); - case 248 /* ContinueStatement */ : - case 249 /* BreakStatement */ : + case 251 /* ContinueStatement */ : + case 252 /* BreakStatement */ : return checkBreakOrContinueStatement(node); - case 250 /* ReturnStatement */ : + case 253 /* ReturnStatement */ : return checkReturnStatement(node); - case 251 /* WithStatement */ : + case 254 /* WithStatement */ : return checkWithStatement(node); - case 252 /* SwitchStatement */ : + case 255 /* SwitchStatement */ : return checkSwitchStatement(node); - case 253 /* LabeledStatement */ : + case 256 /* LabeledStatement */ : return checkLabeledStatement(node); - case 254 /* ThrowStatement */ : + case 257 /* ThrowStatement */ : return checkThrowStatement(node); - case 255 /* TryStatement */ : + case 258 /* TryStatement */ : return checkTryStatement(node); - case 257 /* VariableDeclaration */ : + case 260 /* VariableDeclaration */ : return checkVariableDeclaration(node); - case 205 /* BindingElement */ : + case 208 /* BindingElement */ : return checkBindingElement(node); - case 260 /* ClassDeclaration */ : + case 263 /* ClassDeclaration */ : return checkClassDeclaration(node); - case 261 /* InterfaceDeclaration */ : + case 264 /* InterfaceDeclaration */ : return checkInterfaceDeclaration(node); - case 262 /* TypeAliasDeclaration */ : + case 265 /* TypeAliasDeclaration */ : return checkTypeAliasDeclaration(node); - case 263 /* EnumDeclaration */ : + case 266 /* EnumDeclaration */ : return checkEnumDeclaration(node); - case 264 /* ModuleDeclaration */ : + case 267 /* ModuleDeclaration */ : return checkModuleDeclaration(node); - case 269 /* ImportDeclaration */ : + case 272 /* ImportDeclaration */ : return checkImportDeclaration(node); - case 268 /* ImportEqualsDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : return checkImportEqualsDeclaration(node); - case 275 /* ExportDeclaration */ : + case 278 /* ExportDeclaration */ : return checkExportDeclaration(node); - case 274 /* ExportAssignment */ : + case 277 /* ExportAssignment */ : return checkExportAssignment(node); - case 239 /* EmptyStatement */ : - case 256 /* DebuggerStatement */ : + case 242 /* EmptyStatement */ : + case 259 /* DebuggerStatement */ : checkGrammarStatementInAmbientContext(node); return; - case 279 /* MissingDeclaration */ : + case 282 /* MissingDeclaration */ : return checkMissingDeclaration(node); } } @@ -69771,7 +70546,7 @@ ${lanes.join("\n")} function checkJSDocTypeIsInJsFile(node) { if (!isInJSFile(node)) { if (isJSDocNonNullableType(node) || isJSDocNullableType(node)) { - const token = tokenToString(isJSDocNonNullableType(node) ? 53 /* ExclamationToken */ : 57 /* QuestionToken */ ); + const token = tokenToString(isJSDocNonNullableType(node) ? 54 /* ExclamationToken */ : 58 /* QuestionToken */ ); const diagnostic = node.postfix ? Diagnostics._0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1 : Diagnostics._0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1; const typeNode = node.type; const type = getTypeFromTypeNode(typeNode); @@ -69785,25 +70560,25 @@ ${lanes.join("\n")} function checkJSDocVariadicType(node) { checkJSDocTypeIsInJsFile(node); checkSourceElement(node.type); - const { parent: parent2 } = node; + const { parent: parent2 } = node; if (isParameter(parent2) && isJSDocFunctionType(parent2.parent)) { - if (last(parent2.parent.parameters) !== parent2) error(node, Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + if (last(parent2.parent.parameters) !== parent2) error2(node, Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); return; } - if (!isJSDocTypeExpression(parent2)) error(node, Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + if (!isJSDocTypeExpression(parent2)) error2(node, Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); const paramTag = node.parent.parent; if (!isJSDocParameterTag(paramTag)) { - error(node, Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + error2(node, Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); return; } const param = getParameterSymbolFromJSDoc(paramTag); if (!param) return; const host2 = getHostSignatureFromJSDoc(paramTag); - if (!host2 || last(host2.parameters).symbol !== param) error(node, Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + if (!host2 || last(host2.parameters).symbol !== param) error2(node, Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); } function getTypeFromJSDocVariadicType(node) { const type = getTypeFromTypeNode(node.type); - const { parent: parent2 } = node; + const { parent: parent2 } = node; const paramTag = node.parent.parent; if (isJSDocTypeExpression(node.parent) && isJSDocParameterTag(paramTag)) { const host2 = getHostSignatureFromJSDoc(paramTag); @@ -69831,8 +70606,8 @@ ${lanes.join("\n")} links.deferredNodes = void 0; } function checkDeferredNode(node) { - var _a2, _b; - (_a2 = tracing) == null || _a2.push(tracing.Phase.Check, "checkDeferredNode", { + var _a, _b; + (_a = tracing) == null || _a.push(tracing.Phase.Check, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end, @@ -69842,42 +70617,46 @@ ${lanes.join("\n")} currentNode = node; instantiationCount = 0; switch(node.kind){ - case 210 /* CallExpression */ : - case 211 /* NewExpression */ : - case 212 /* TaggedTemplateExpression */ : - case 167 /* Decorator */ : - case 283 /* JsxOpeningElement */ : + case 213 /* CallExpression */ : + case 214 /* NewExpression */ : + case 215 /* TaggedTemplateExpression */ : + case 170 /* Decorator */ : + case 286 /* JsxOpeningElement */ : resolveUntypedCall(node); break; - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : checkAccessorDeclaration(node); break; - case 228 /* ClassExpression */ : + case 231 /* ClassExpression */ : checkClassExpressionDeferred(node); break; - case 165 /* TypeParameter */ : + case 168 /* TypeParameter */ : checkTypeParameterDeferred(node); break; - case 282 /* JsxSelfClosingElement */ : + case 285 /* JsxSelfClosingElement */ : checkJsxSelfClosingElementDeferred(node); break; - case 281 /* JsxElement */ : + case 284 /* JsxElement */ : checkJsxElementDeferred(node); break; + case 216 /* TypeAssertionExpression */ : + case 234 /* AsExpression */ : + case 217 /* ParenthesizedExpression */ : + checkAssertionDeferred(node); } currentNode = saveCurrentNode; (_b = tracing) == null || _b.pop(); } function checkSourceFile(node) { - var _a2, _b; - (_a2 = tracing) == null || _a2.push(tracing.Phase.Check, "checkSourceFile", { + var _a, _b; + (_a = tracing) == null || _a.push(tracing.Phase.Check, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); mark("beforeCheck"); @@ -69916,7 +70695,7 @@ ${lanes.join("\n")} if (isExternalOrCommonJsModule(node)) registerForUnusedIdentifiersCheck(node); addLazyDiagnostic(()=>{ if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), (containingNode, kind, diag2)=>{ - if (!containsParseError(containingNode) && unusedIsError(kind, !!(containingNode.flags & 16777216 /* Ambient */ ))) diagnostics.add(diag2); + if (!containsParseError(containingNode) && unusedIsError(kind, !!(containingNode.flags & 33554432 /* Ambient */ ))) diagnostics.add(diag2); }); if (!node.isDeclarationFile) checkPotentialUncheckedRenamedBindingElementsInTypes(); }); @@ -69982,7 +70761,7 @@ ${lanes.join("\n")} return diagnostics.getGlobalDiagnostics(); } function getSymbolsInScope(location, meaning) { - if (location.flags & 33554432 /* InWithStatement */ ) return []; + if (location.flags & 67108864 /* InWithStatement */ ) return []; const symbols = createSymbolTable(); let isStaticSymbol = false; populateSymbols(); @@ -69992,22 +70771,22 @@ ${lanes.join("\n")} while(location){ if (canHaveLocals(location) && location.locals && !isGlobalSourceFile(location)) copySymbols(location.locals, meaning); switch(location.kind){ - case 308 /* SourceFile */ : + case 312 /* SourceFile */ : if (!isExternalModule(location)) break; - case 264 /* ModuleDeclaration */ : + case 267 /* ModuleDeclaration */ : copyLocallyVisibleExportSymbols(getSymbolOfDeclaration(location).exports, meaning & 2623475 /* ModuleMember */ ); break; - case 263 /* EnumDeclaration */ : + case 266 /* EnumDeclaration */ : copySymbols(getSymbolOfDeclaration(location).exports, meaning & 8 /* EnumMember */ ); break; - case 228 /* ClassExpression */ : + case 231 /* ClassExpression */ : const className = location.name; if (className) copySymbol(location.symbol, meaning); - case 260 /* ClassDeclaration */ : - case 261 /* InterfaceDeclaration */ : + case 263 /* ClassDeclaration */ : + case 264 /* InterfaceDeclaration */ : if (!isStaticSymbol) copySymbols(getMembersOfSymbol(getSymbolOfDeclaration(location)), meaning & 788968 /* Type */ ); break; - case 215 /* FunctionExpression */ : + case 218 /* FunctionExpression */ : const funcName = location.name; if (funcName) copySymbol(location.symbol, meaning); break; @@ -70031,20 +70810,20 @@ ${lanes.join("\n")} } function copyLocallyVisibleExportSymbols(source, meaning2) { if (meaning2) source.forEach((symbol)=>{ - if (!getDeclarationOfKind(symbol, 278 /* ExportSpecifier */ ) && !getDeclarationOfKind(symbol, 277 /* NamespaceExport */ )) copySymbol(symbol, meaning2); + if (!getDeclarationOfKind(symbol, 281 /* ExportSpecifier */ ) && !getDeclarationOfKind(symbol, 280 /* NamespaceExport */ ) && symbol.escapedName !== "default" /* Default */ ) copySymbol(symbol, meaning2); }); } } function isTypeDeclarationName(name) { - return name.kind === 79 /* Identifier */ && isTypeDeclaration(name.parent) && getNameOfDeclaration(name.parent) === name; + return name.kind === 80 /* Identifier */ && isTypeDeclaration(name.parent) && getNameOfDeclaration(name.parent) === name; } function isTypeReferenceIdentifier(node) { - while(node.parent.kind === 163 /* QualifiedName */ )node = node.parent; - return node.parent.kind === 180 /* TypeReference */ ; + while(node.parent.kind === 166 /* QualifiedName */ )node = node.parent; + return node.parent.kind === 183 /* TypeReference */ ; } function isInNameOfExpressionWithTypeArguments(node) { - while(node.parent.kind === 208 /* PropertyAccessExpression */ )node = node.parent; - return node.parent.kind === 230 /* ExpressionWithTypeArguments */ ; + while(node.parent.kind === 211 /* PropertyAccessExpression */ )node = node.parent; + return node.parent.kind === 233 /* ExpressionWithTypeArguments */ ; } function forEachEnclosingClass(node, callback) { let result; @@ -70066,9 +70845,9 @@ ${lanes.join("\n")} return !!forEachEnclosingClass(node, (n)=>n === classDeclaration); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while(nodeOnRightSide.parent.kind === 163 /* QualifiedName */ )nodeOnRightSide = nodeOnRightSide.parent; - if (nodeOnRightSide.parent.kind === 268 /* ImportEqualsDeclaration */ ) return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : void 0; - if (nodeOnRightSide.parent.kind === 274 /* ExportAssignment */ ) return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : void 0; + while(nodeOnRightSide.parent.kind === 166 /* QualifiedName */ )nodeOnRightSide = nodeOnRightSide.parent; + if (nodeOnRightSide.parent.kind === 271 /* ImportEqualsDeclaration */ ) return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : void 0; + if (nodeOnRightSide.parent.kind === 277 /* ExportAssignment */ ) return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : void 0; return void 0; } function isInRightSideOfImportOrExportAssignment(node) { @@ -70092,22 +70871,35 @@ ${lanes.join("\n")} node = parent2; parent2 = parent2.parent; } - if (parent2 && parent2.kind === 202 /* ImportType */ && parent2.qualifier === node) return parent2; + if (parent2 && parent2.kind === 205 /* ImportType */ && parent2.qualifier === node) return parent2; return void 0; } + function isThisPropertyAndThisTyped(node) { + if (node.expression.kind === 110 /* ThisKeyword */ ) { + const container = getThisContainer(node, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false); + if (isFunctionLike(container)) { + const containingLiteral = getContainingObjectLiteral(container); + if (containingLiteral) { + const contextualType = getApparentTypeOfContextualType(containingLiteral, /*contextFlags*/ void 0); + const type = getThisTypeOfObjectLiteralFromContextualType(containingLiteral, contextualType); + return type && !isTypeAny(type); + } + } + } + } function getSymbolOfNameOrPropertyAccessExpression(name) { if (isDeclarationName(name)) return getSymbolOfNode(name.parent); - if (isInJSFile(name) && name.parent.kind === 208 /* PropertyAccessExpression */ && name.parent === name.parent.parent.left) { - if (!isPrivateIdentifier(name) && !isJSDocMemberName(name)) { + if (isInJSFile(name) && name.parent.kind === 211 /* PropertyAccessExpression */ && name.parent === name.parent.parent.left) { + if (!isPrivateIdentifier(name) && !isJSDocMemberName(name) && !isThisPropertyAndThisTyped(name.parent)) { const specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(name); if (specialPropertyAssignmentSymbol) return specialPropertyAssignmentSymbol; } } - if (name.parent.kind === 274 /* ExportAssignment */ && isEntityNameExpression(name)) { + if (name.parent.kind === 277 /* ExportAssignment */ && isEntityNameExpression(name)) { const success = resolveEntityName(name, /*all meanings*/ 2998271 /* Alias */ , /*ignoreErrors*/ true); if (success && success !== unknownSymbol) return success; } else if (isEntityName(name) && isInRightSideOfImportOrExportAssignment(name)) { - const importEqualsDeclaration = getAncestor(name, 268 /* ImportEqualsDeclaration */ ); + const importEqualsDeclaration = getAncestor(name, 271 /* ImportEqualsDeclaration */ ); Debug.assert(importEqualsDeclaration !== void 0); return getSymbolOfPartOfRightHandSideOfImportEquals(name, /*dontResolveAlias*/ true); } @@ -70122,16 +70914,16 @@ ${lanes.join("\n")} while(isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName(name))name = name.parent; if (isInNameOfExpressionWithTypeArguments(name)) { let meaning = 0 /* None */ ; - if (name.parent.kind === 230 /* ExpressionWithTypeArguments */ ) { + if (name.parent.kind === 233 /* ExpressionWithTypeArguments */ ) { meaning = isPartOfTypeNode(name) ? 788968 /* Type */ : 111551 /* Value */ ; if (isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) meaning |= 111551 /* Value */ ; } else meaning = 1920 /* Namespace */ ; meaning |= 2097152 /* Alias */ ; - const entityNameSymbol = isEntityNameExpression(name) ? resolveEntityName(name, meaning) : void 0; + const entityNameSymbol = isEntityNameExpression(name) ? resolveEntityName(name, meaning, /*ignoreErrors*/ true) : void 0; if (entityNameSymbol) return entityNameSymbol; } - if (name.parent.kind === 344 /* JSDocParameterTag */ ) return getParameterSymbolFromJSDoc(name.parent); - if (name.parent.kind === 165 /* TypeParameter */ && name.parent.parent.kind === 348 /* JSDocTemplateTag */ ) { + if (name.parent.kind === 348 /* JSDocParameterTag */ ) return getParameterSymbolFromJSDoc(name.parent); + if (name.parent.kind === 168 /* TypeParameter */ && name.parent.parent.kind === 352 /* JSDocTemplateTag */ ) { Debug.assert(!isInJSFile(name)); const typeParameter = getTypeParameterFromJsDoc(name.parent); return typeParameter && typeParameter.symbol; @@ -70140,26 +70932,26 @@ ${lanes.join("\n")} if (nodeIsMissing(name)) return void 0; const isJSDoc2 = findAncestor(name, or(isJSDocLinkLike, isJSDocNameReference, isJSDocMemberName)); const meaning = isJSDoc2 ? 901119 /* Value */ : 111551 /* Value */ ; - if (name.kind === 79 /* Identifier */ ) { - if (isJSXTagName(name) && isJsxIntrinsicIdentifier(name)) { + if (name.kind === 80 /* Identifier */ ) { + if (isJSXTagName(name) && isJsxIntrinsicTagName(name)) { const symbol = getIntrinsicTagSymbol(name.parent); return symbol === unknownSymbol ? void 0 : symbol; } - const result = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /* dontResolveAlias */ true, getHostSignatureFromJSDoc(name)); + const result = resolveEntityName(name, meaning, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, getHostSignatureFromJSDoc(name)); if (!result && isJSDoc2) { const container = findAncestor(name, or(isClassLike, isInterfaceDeclaration)); - if (container) return resolveJSDocMemberName(name, /*ignoreErrors*/ false, getSymbolOfDeclaration(container)); + if (container) return resolveJSDocMemberName(name, /*ignoreErrors*/ true, getSymbolOfDeclaration(container)); } if (result && isJSDoc2) { const container = getJSDocHost(name); - if (container && isEnumMember(container) && container === result.valueDeclaration) return resolveEntityName(name, meaning, /*ignoreErrors*/ true, /* dontResolveAlias */ true, getSourceFileOfNode(container)) || result; + if (container && isEnumMember(container) && container === result.valueDeclaration) return resolveEntityName(name, meaning, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, getSourceFileOfNode(container)) || result; } return result; } else if (isPrivateIdentifier(name)) return getSymbolForPrivateIdentifierExpression(name); - else if (name.kind === 208 /* PropertyAccessExpression */ || name.kind === 163 /* QualifiedName */ ) { + else if (name.kind === 211 /* PropertyAccessExpression */ || name.kind === 166 /* QualifiedName */ ) { const links = getNodeLinks(name); if (links.resolvedSymbol) return links.resolvedSymbol; - if (name.kind === 208 /* PropertyAccessExpression */ ) { + if (name.kind === 211 /* PropertyAccessExpression */ ) { checkPropertyAccessExpression(name, 0 /* Normal */ ); if (!links.resolvedSymbol) { const expressionType = checkExpressionCached(name.expression); @@ -70189,11 +70981,11 @@ ${lanes.join("\n")} return links.resolvedSymbol; } else if (isJSDocMemberName(name)) return resolveJSDocMemberName(name); } else if (isTypeReferenceIdentifier(name)) { - const meaning = name.parent.kind === 180 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */ ; + const meaning = name.parent.kind === 183 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */ ; const symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); return symbol && symbol !== unknownSymbol ? symbol : getUnresolvedSymbolForEntityName(name); } - if (name.parent.kind === 179 /* TypePredicate */ ) return resolveEntityName(name, /*meaning*/ 1 /* FunctionScopedVariable */ ); + if (name.parent.kind === 182 /* TypePredicate */ ) return resolveEntityName(name, /*meaning*/ 1 /* FunctionScopedVariable */ ); return void 0; } function resolveJSDocMemberName(name, ignoreErrors, container) { @@ -70213,67 +71005,72 @@ ${lanes.join("\n")} } function getSymbolAtLocation(node, ignoreErrors) { if (isSourceFile(node)) return isExternalModule(node) ? getMergedSymbol(node.symbol) : void 0; - const { parent: parent2 } = node; + const { parent: parent2 } = node; const grandParent = parent2.parent; - if (node.flags & 33554432 /* InWithStatement */ ) return void 0; + if (node.flags & 67108864 /* InWithStatement */ ) return void 0; if (isDeclarationNameOrImportPropertyName(node)) { const parentSymbol = getSymbolOfDeclaration(parent2); return isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node ? getImmediateAliasedSymbol(parentSymbol) : parentSymbol; } else if (isLiteralComputedPropertyDeclarationName(node)) return getSymbolOfDeclaration(parent2.parent); - if (node.kind === 79 /* Identifier */ ) { + if (node.kind === 80 /* Identifier */ ) { if (isInRightSideOfImportOrExportAssignment(node)) return getSymbolOfNameOrPropertyAccessExpression(node); - else if (parent2.kind === 205 /* BindingElement */ && grandParent.kind === 203 /* ObjectBindingPattern */ && node === parent2.propertyName) { + else if (parent2.kind === 208 /* BindingElement */ && grandParent.kind === 206 /* ObjectBindingPattern */ && node === parent2.propertyName) { const typeOfPattern = getTypeOfNode(grandParent); const propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); if (propertyDeclaration) return propertyDeclaration; } else if (isMetaProperty(parent2) && parent2.name === node) { - if (parent2.keywordToken === 103 /* NewKeyword */ && idText(node) === "target") return checkNewTargetMetaProperty(parent2).symbol; - if (parent2.keywordToken === 100 /* ImportKeyword */ && idText(node) === "meta") return getGlobalImportMetaExpressionType().members.get("meta"); + if (parent2.keywordToken === 105 /* NewKeyword */ && idText(node) === "target") return checkNewTargetMetaProperty(parent2).symbol; + if (parent2.keywordToken === 102 /* ImportKeyword */ && idText(node) === "meta") return getGlobalImportMetaExpressionType().members.get("meta"); return void 0; } } switch(node.kind){ - case 79 /* Identifier */ : - case 80 /* PrivateIdentifier */ : - case 208 /* PropertyAccessExpression */ : - case 163 /* QualifiedName */ : + case 80 /* Identifier */ : + case 81 /* PrivateIdentifier */ : + case 211 /* PropertyAccessExpression */ : + case 166 /* QualifiedName */ : if (!isThisInTypeQuery(node)) return getSymbolOfNameOrPropertyAccessExpression(node); - case 108 /* ThisKeyword */ : + case 110 /* ThisKeyword */ : const container = getThisContainer(node, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false); if (isFunctionLike(container)) { const sig = getSignatureFromDeclaration(container); if (sig.thisParameter) return sig.thisParameter; } if (isInExpressionContext(node)) return checkExpression(node).symbol; - case 194 /* ThisType */ : + case 197 /* ThisType */ : return getTypeFromThisTypeNode(node).symbol; - case 106 /* SuperKeyword */ : + case 108 /* SuperKeyword */ : return checkExpression(node).symbol; - case 135 /* ConstructorKeyword */ : + case 137 /* ConstructorKeyword */ : const constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 173 /* Constructor */ ) return constructorDeclaration.parent.symbol; + if (constructorDeclaration && constructorDeclaration.kind === 176 /* Constructor */ ) return constructorDeclaration.parent.symbol; return void 0; - case 10 /* StringLiteral */ : - case 14 /* NoSubstitutionTemplateLiteral */ : - if (isExternalModuleImportEqualsDeclaration(node.parent.parent) && getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node || (node.parent.kind === 269 /* ImportDeclaration */ || node.parent.kind === 275 /* ExportDeclaration */ ) && node.parent.moduleSpecifier === node || isInJSFile(node) && getEmitModuleResolutionKind(compilerOptions) !== 100 /* Bundler */ && isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) || isImportCall(node.parent) || isLiteralTypeNode(node.parent) && isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent) return resolveExternalModuleName(node, node, ignoreErrors); + case 11 /* StringLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + if (isExternalModuleImportEqualsDeclaration(node.parent.parent) && getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node || (node.parent.kind === 272 /* ImportDeclaration */ || node.parent.kind === 278 /* ExportDeclaration */ ) && node.parent.moduleSpecifier === node || isInJSFile(node) && getEmitModuleResolutionKind(compilerOptions) !== 100 /* Bundler */ && isRequireCall(node.parent, /*requireStringLiteralLikeArgument*/ false) || isImportCall(node.parent) || isLiteralTypeNode(node.parent) && isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent) return resolveExternalModuleName(node, node, ignoreErrors); if (isCallExpression(parent2) && isBindableObjectDefinePropertyCall(parent2) && parent2.arguments[1] === node) return getSymbolOfDeclaration(parent2); - case 8 /* NumericLiteral */ : + case 9 /* NumericLiteral */ : const objectType = isElementAccessExpression(parent2) ? parent2.argumentExpression === node ? getTypeOfExpression(parent2.expression) : void 0 : isLiteralTypeNode(parent2) && isIndexedAccessTypeNode(grandParent) ? getTypeFromTypeNode(grandParent.objectType) : void 0; return objectType && getPropertyOfType(objectType, escapeLeadingUnderscores(node.text)); - case 88 /* DefaultKeyword */ : - case 98 /* FunctionKeyword */ : - case 38 /* EqualsGreaterThanToken */ : - case 84 /* ClassKeyword */ : + case 90 /* DefaultKeyword */ : + case 100 /* FunctionKeyword */ : + case 39 /* EqualsGreaterThanToken */ : + case 86 /* ClassKeyword */ : return getSymbolOfNode(node.parent); - case 202 /* ImportType */ : + case 205 /* ImportType */ : return isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : void 0; - case 93 /* ExportKeyword */ : + case 95 /* ExportKeyword */ : return isExportAssignment(node.parent) ? Debug.checkDefined(node.parent.symbol) : void 0; - case 100 /* ImportKeyword */ : - case 103 /* NewKeyword */ : + case 102 /* ImportKeyword */ : + case 105 /* NewKeyword */ : return isMetaProperty(node.parent) ? checkMetaPropertyKeyword(node.parent).symbol : void 0; - case 233 /* MetaProperty */ : + case 236 /* MetaProperty */ : return checkExpression(node).symbol; + case 295 /* JsxNamespacedName */ : + if (isJSXTagName(node) && isJsxIntrinsicTagName(node)) { + const symbol = getIntrinsicTagSymbol(node.parent); + return symbol === unknownSymbol ? void 0 : symbol; + } default: return void 0; } @@ -70290,7 +71087,7 @@ ${lanes.join("\n")} return void 0; } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 300 /* ShorthandPropertyAssignment */ ) return resolveEntityName(location.name, 2208703 /* Alias */ ); + if (location && location.kind === 304 /* ShorthandPropertyAssignment */ ) return resolveEntityName(location.name, 2208703 /* Alias */ ); return void 0; } function getExportSpecifierLocalTargetSymbol(node) { @@ -70299,7 +71096,7 @@ ${lanes.join("\n")} } function getTypeOfNode(node) { if (isSourceFile(node) && !isExternalModule(node)) return errorType; - if (node.flags & 33554432 /* InWithStatement */ ) return errorType; + if (node.flags & 67108864 /* InWithStatement */ ) return errorType; const classDecl = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); const classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(classDecl.class)); if (isPartOfTypeNode(node)) { @@ -70319,6 +71116,7 @@ ${lanes.join("\n")} const symbol = getSymbolAtLocation(node); return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; } + if (isBindingElement(node)) return getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ true, 0 /* Normal */ ) || errorType; if (isDeclaration(node)) { const symbol = getSymbolOfDeclaration(node); return symbol ? getTypeOfSymbol(symbol) : errorType; @@ -70340,16 +71138,16 @@ ${lanes.join("\n")} return errorType; } function getTypeOfAssignmentPattern(expr) { - Debug.assert(expr.kind === 207 /* ObjectLiteralExpression */ || expr.kind === 206 /* ArrayLiteralExpression */ ); - if (expr.parent.kind === 247 /* ForOfStatement */ ) { + Debug.assert(expr.kind === 210 /* ObjectLiteralExpression */ || expr.kind === 209 /* ArrayLiteralExpression */ ); + if (expr.parent.kind === 250 /* ForOfStatement */ ) { const iteratedType = checkRightHandSideOfForOf(expr.parent); return checkDestructuringAssignment(expr, iteratedType || errorType); } - if (expr.parent.kind === 223 /* BinaryExpression */ ) { + if (expr.parent.kind === 226 /* BinaryExpression */ ) { const iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || errorType); } - if (expr.parent.kind === 299 /* PropertyAssignment */ ) { + if (expr.parent.kind === 303 /* PropertyAssignment */ ) { const node2 = cast(expr.parent.parent, isObjectLiteralExpression); const typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node2) || errorType; const propertyIndex = indexOfNode(node2.properties, expr.parent); @@ -70375,12 +71173,12 @@ ${lanes.join("\n")} function getClassElementPropertyKeyType(element) { const name = element.name; switch(name.kind){ - case 79 /* Identifier */ : + case 80 /* Identifier */ : return getStringLiteralType(idText(name)); - case 8 /* NumericLiteral */ : - case 10 /* StringLiteral */ : + case 9 /* NumericLiteral */ : + case 11 /* StringLiteral */ : return getStringLiteralType(name.text); - case 164 /* ComputedPropertyName */ : + case 167 /* ComputedPropertyName */ : const nameType = checkComputedPropertyName(name); return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */ ) ? nameType : stringType; default: @@ -70408,7 +71206,7 @@ ${lanes.join("\n")} function getImmediateRootSymbols(symbol) { if (getCheckFlags(symbol) & 6 /* Synthetic */ ) return mapDefined(getSymbolLinks(symbol).containingType.types, (type)=>getPropertyOfType(type, symbol.escapedName)); else if (symbol.flags & 33554432 /* Transient */ ) { - const { links: { leftSpread: leftSpread , rightSpread: rightSpread , syntheticOrigin: syntheticOrigin } } = symbol; + const { links: { leftSpread: leftSpread, rightSpread: rightSpread, syntheticOrigin: syntheticOrigin } } = symbol; return leftSpread ? [ leftSpread, rightSpread @@ -70443,14 +71241,14 @@ ${lanes.join("\n")} return symbolLinks2.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(getAllSymbolFlags(s) & 111551 /* Value */ ); + return s && !!(getSymbolFlags(s) & 111551 /* Value */ ); } } function isNameOfModuleOrEnumDeclaration(node) { return isModuleOrEnumDeclaration(node.parent) && node === node.parent.name; } function getReferencedExportContainer(nodeIn, prefixLocals) { - var _a2; + var _a; const node = getParseTreeNode(nodeIn, isIdentifier); if (node) { let symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node)); @@ -70462,7 +71260,7 @@ ${lanes.join("\n")} } const parentSymbol = getParentOfSymbol(symbol); if (parentSymbol) { - if (parentSymbol.flags & 512 /* ValueModule */ && ((_a2 = parentSymbol.valueDeclaration) == null ? void 0 : _a2.kind) === 308 /* SourceFile */ ) { + if (parentSymbol.flags & 512 /* ValueModule */ && ((_a = parentSymbol.valueDeclaration) == null ? void 0 : _a.kind) === 312 /* SourceFile */ ) { const symbolFile = parentSymbol.valueDeclaration; const referenceFile = getSourceFileOfNode(node); const symbolIsUmdExport = symbolFile !== referenceFile; @@ -70484,7 +71282,7 @@ ${lanes.join("\n")} return void 0; } function isSymbolOfDestructuredElementOfCatchBinding(symbol) { - return symbol.valueDeclaration && isBindingElement(symbol.valueDeclaration) && walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 295 /* CatchClause */ ; + return symbol.valueDeclaration && isBindingElement(symbol.valueDeclaration) && walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 299 /* CatchClause */ ; } function isSymbolOfDeclarationWithCollidingName(symbol) { if (symbol.flags & 418 /* BlockScoped */ && symbol.valueDeclaration && !isSourceFile(symbol.valueDeclaration)) { @@ -70497,7 +71295,7 @@ ${lanes.join("\n")} else if (nodeLinks2.flags & 16384 /* CapturedBlockScopedBinding */ ) { const isDeclaredInLoop = nodeLinks2.flags & 32768 /* BlockScopedBindingInLoop */ ; const inLoopInitializer = isIterationStatement(container, /*lookInLabeledStatements*/ false); - const inLoopBodyBlock = container.kind === 238 /* Block */ && isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + const inLoopBodyBlock = container.kind === 241 /* Block */ && isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || !inLoopInitializer && !inLoopBodyBlock); } else links.isDeclarationWithCollidingName = false; } @@ -70525,48 +71323,47 @@ ${lanes.join("\n")} return false; } function isValueAliasDeclaration(node) { - Debug.assert(!compilerOptions.verbatimModuleSyntax); + Debug.assert(canCollectSymbolAliasAccessabilityData); switch(node.kind){ - case 268 /* ImportEqualsDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : return isAliasResolvedToValue(getSymbolOfDeclaration(node)); - case 270 /* ImportClause */ : - case 271 /* NamespaceImport */ : - case 273 /* ImportSpecifier */ : - case 278 /* ExportSpecifier */ : + case 273 /* ImportClause */ : + case 274 /* NamespaceImport */ : + case 276 /* ImportSpecifier */ : + case 281 /* ExportSpecifier */ : const symbol = getSymbolOfDeclaration(node); - return !!symbol && isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* Value */ ); - case 275 /* ExportDeclaration */ : + return !!symbol && isAliasResolvedToValue(symbol, /*excludeTypeOnlyValues*/ true); + case 278 /* ExportDeclaration */ : const exportClause = node.exportClause; return !!exportClause && (isNamespaceExport(exportClause) || some(exportClause.elements, isValueAliasDeclaration)); - case 274 /* ExportAssignment */ : - return node.expression && node.expression.kind === 79 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfDeclaration(node)) : true; + case 277 /* ExportAssignment */ : + return node.expression && node.expression.kind === 80 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfDeclaration(node)) : true; } return false; } function isTopLevelValueImportEqualsWithEntityName(nodeIn) { const node = getParseTreeNode(nodeIn, isImportEqualsDeclaration); - if (node === void 0 || node.parent.kind !== 308 /* SourceFile */ || !isInternalModuleImportEqualsDeclaration(node)) return false; + if (node === void 0 || node.parent.kind !== 312 /* SourceFile */ || !isInternalModuleImportEqualsDeclaration(node)) return false; const isValue = isAliasResolvedToValue(getSymbolOfDeclaration(node)); return isValue && node.moduleReference && !nodeIsMissing(node.moduleReference); } - function isAliasResolvedToValue(symbol) { - var _a2; + function isAliasResolvedToValue(symbol, excludeTypeOnlyValues) { if (!symbol) return false; const target = getExportSymbolOfValueSymbolIfExported(resolveAlias(symbol)); if (target === unknownSymbol) return true; - return !!(((_a2 = getAllSymbolFlags(target)) != null ? _a2 : -1) & 111551 /* Value */ ) && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); + return !!(getSymbolFlags(symbol, excludeTypeOnlyValues, /*excludeLocalMeanings*/ true) & 111551 /* Value */ ) && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; } function isReferencedAliasDeclaration(node, checkChildren) { - Debug.assert(!compilerOptions.verbatimModuleSyntax); + Debug.assert(canCollectSymbolAliasAccessabilityData); if (isAliasSymbolDeclaration2(node)) { const symbol = getSymbolOfDeclaration(node); const links = symbol && getSymbolLinks(symbol); if (links == null ? void 0 : links.referenced) return true; const target = getSymbolLinks(symbol).aliasTarget; - if (target && getEffectiveModifierFlags(node) & 1 /* Export */ && getAllSymbolFlags(target) & 111551 /* Value */ && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) return true; + if (target && getEffectiveModifierFlags(node) & 1 /* Export */ && getSymbolFlags(target) & 111551 /* Value */ && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) return true; } if (checkChildren) return !!forEachChild(node, (node2)=>isReferencedAliasDeclaration(node2, checkChildren)); return false; @@ -70605,10 +71402,10 @@ ${lanes.join("\n")} return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || emptyArray; } function getNodeCheckFlags(node) { - var _a2; + var _a; const nodeId = node.id || 0; if (nodeId < 0 || nodeId >= nodeLinks.length) return 0; - return ((_a2 = nodeLinks[nodeId]) == null ? void 0 : _a2.flags) || 0; + return ((_a = nodeLinks[nodeId]) == null ? void 0 : _a.flags) || 0; } function getEnumMemberValue(node) { computeEnumMemberValues(node.parent); @@ -70616,15 +71413,15 @@ ${lanes.join("\n")} } function canHaveConstantValue(node) { switch(node.kind){ - case 302 /* EnumMember */ : - case 208 /* PropertyAccessExpression */ : - case 209 /* ElementAccessExpression */ : + case 306 /* EnumMember */ : + case 211 /* PropertyAccessExpression */ : + case 212 /* ElementAccessExpression */ : return true; } return false; } function getConstantValue2(node) { - if (node.kind === 302 /* EnumMember */ ) return getEnumMemberValue(node); + if (node.kind === 306 /* EnumMember */ ) return getEnumMemberValue(node); const symbol = getNodeLinks(node).resolvedSymbol; if (symbol && symbol.flags & 8 /* EnumMember */ ) { const member = symbol.valueDeclaration; @@ -70636,7 +71433,7 @@ ${lanes.join("\n")} return !!(type.flags & 524288 /* Object */ ) && getSignaturesOfType(type, 0 /* Call */ ).length > 0; } function getTypeReferenceSerializationKind(typeNameIn, location) { - var _a2; + var _a; const typeName = getParseTreeNode(typeNameIn, isEntityName); if (!typeName) return 0 /* Unknown */ ; if (location) { @@ -70646,7 +71443,7 @@ ${lanes.join("\n")} let isTypeOnly = false; if (isQualifiedName(typeName)) { const rootValueSymbol = resolveEntityName(getFirstIdentifier(typeName), 111551 /* Value */ , /*ignoreErrors*/ true, /*dontResolveAlias*/ true, location); - isTypeOnly = !!((_a2 = rootValueSymbol == null ? void 0 : rootValueSymbol.declarations) == null ? void 0 : _a2.every(isTypeOnlyImportOrExportDeclaration)); + isTypeOnly = !!((_a = rootValueSymbol == null ? void 0 : rootValueSymbol.declarations) == null ? void 0 : _a.every(isTypeOnlyImportOrExportDeclaration)); } const valueSymbol = resolveEntityName(typeName, 111551 /* Value */ , /*ignoreErrors*/ true, /*dontResolveAlias*/ true, location); const resolvedSymbol = valueSymbol && valueSymbol.flags & 2097152 /* Alias */ ? resolveAlias(valueSymbol) : valueSymbol; @@ -70675,7 +71472,7 @@ ${lanes.join("\n")} } function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) { const declaration = getParseTreeNode(declarationIn, isVariableLikeOrAccessor); - if (!declaration) return factory.createToken(131 /* AnyKeyword */ ); + if (!declaration) return factory.createToken(133 /* AnyKeyword */ ); const symbol = getSymbolOfDeclaration(declaration); let type = symbol && !(symbol.flags & 133120 /* Signature */ ) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : errorType; if (type.flags & 8192 /* UniqueESSymbol */ && type.symbol === symbol) flags |= 1048576 /* AllowUniqueESSymbolType */ ; @@ -70684,13 +71481,13 @@ ${lanes.join("\n")} } function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) { const signatureDeclaration = getParseTreeNode(signatureDeclarationIn, isFunctionLike); - if (!signatureDeclaration) return factory.createToken(131 /* AnyKeyword */ ); + if (!signatureDeclaration) return factory.createToken(133 /* AnyKeyword */ ); const signature = getSignatureFromDeclaration(signatureDeclaration); return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */ , tracker); } function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) { const expr = getParseTreeNode(exprIn, isExpression); - if (!expr) return factory.createToken(131 /* AnyKeyword */ ); + if (!expr) return factory.createToken(133 /* AnyKeyword */ ); const type = getWidenedType(getRegularTypeOfExpression(expr)); return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */ , tracker); } @@ -70705,12 +71502,12 @@ ${lanes.join("\n")} const parent2 = reference.parent; if (isDeclaration(parent2) && reference === parent2.name) location = getDeclarationContainer(parent2); } - return resolveName(location, reference.escapedText, 3257279 /* Alias */ , /*nodeNotFoundMessage*/ void 0, /*nameArg*/ void 0, /*isUse*/ true); + return resolveName(location, reference.escapedText, 3257279 /* Alias */ , /*nameNotFoundMessage*/ void 0, /*nameArg*/ void 0, /*isUse*/ true); } function getReferencedValueOrAliasSymbol(reference) { const resolvedSymbol = getNodeLinks(reference).resolvedSymbol; if (resolvedSymbol && resolvedSymbol !== unknownSymbol) return resolvedSymbol; - return resolveName(reference, reference.escapedText, 3257279 /* Alias */ , /*nodeNotFoundMessage*/ void 0, /*nameArg*/ void 0, /*isUse*/ true, /*excludeGlobals*/ void 0, /*getSpellingSuggestions*/ void 0); + return resolveName(reference, reference.escapedText, 3257279 /* Alias */ , /*nameNotFoundMessage*/ void 0, /*nameArg*/ void 0, /*isUse*/ true, /*excludeGlobals*/ void 0, /*getSpellingSuggestions*/ void 0); } function getReferencedValueDeclaration(referenceIn) { if (!isGeneratedIdentifier(referenceIn)) { @@ -70722,8 +71519,41 @@ ${lanes.join("\n")} } return void 0; } + function getReferencedValueDeclarations(referenceIn) { + if (!isGeneratedIdentifier(referenceIn)) { + const reference = getParseTreeNode(referenceIn, isIdentifier); + if (reference) { + const symbol = getReferencedValueSymbol(reference); + if (symbol) return filter(getExportSymbolOfValueSymbolIfExported(symbol).declarations, (declaration)=>{ + switch(declaration.kind){ + case 260 /* VariableDeclaration */ : + case 169 /* Parameter */ : + case 208 /* BindingElement */ : + case 172 /* PropertyDeclaration */ : + case 303 /* PropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : + case 306 /* EnumMember */ : + case 210 /* ObjectLiteralExpression */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 266 /* EnumDeclaration */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 267 /* ModuleDeclaration */ : + return true; + } + return false; + }); + } + } + return void 0; + } function isLiteralConstDeclaration(node) { - if (isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConst(node)) return isFreshLiteralType(getTypeOfSymbol(getSymbolOfDeclaration(node))); + if (isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConstLike(node)) return isFreshLiteralType(getTypeOfSymbol(getSymbolOfDeclaration(node))); return false; } function literalTypeToNode(type, enclosing, tracker) { @@ -70759,7 +71589,7 @@ ${lanes.join("\n")} let fileToDirective; if (resolvedTypeReferenceDirectives) { fileToDirective = /* @__PURE__ */ new Map(); - resolvedTypeReferenceDirectives.forEach(({ resolvedTypeReferenceDirective: resolvedTypeReferenceDirective }, key, mode)=>{ + resolvedTypeReferenceDirectives.forEach(({ resolvedTypeReferenceDirective: resolvedTypeReferenceDirective }, key, mode)=>{ if (!(resolvedTypeReferenceDirective == null ? void 0 : resolvedTypeReferenceDirective.resolvedFileName)) return; const file = host.getSourceFile(resolvedTypeReferenceDirective.resolvedFileName); if (file) addReferencedFilesToTypeDirective(file, key, mode); @@ -70772,12 +71602,12 @@ ${lanes.join("\n")} isDeclarationWithCollidingName: isDeclarationWithCollidingName, isValueAliasDeclaration: (nodeIn)=>{ const node = getParseTreeNode(nodeIn); - return node ? isValueAliasDeclaration(node) : true; + return node && canCollectSymbolAliasAccessabilityData ? isValueAliasDeclaration(node) : true; }, hasGlobalName: hasGlobalName, isReferencedAliasDeclaration: (nodeIn, checkChildren)=>{ const node = getParseTreeNode(nodeIn); - return node ? isReferencedAliasDeclaration(node, checkChildren) : true; + return node && canCollectSymbolAliasAccessabilityData ? isReferencedAliasDeclaration(node, checkChildren) : true; }, getNodeCheckFlags: (nodeIn)=>{ const node = getParseTreeNode(nodeIn); @@ -70802,6 +71632,7 @@ ${lanes.join("\n")} }, collectLinkedAliases: collectLinkedAliases, getReferencedValueDeclaration: getReferencedValueDeclaration, + getReferencedValueDeclarations: getReferencedValueDeclarations, getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, isOptionalParameter: isOptionalParameter, moduleExportsSomeValue: moduleExportsSomeValue, @@ -70822,12 +71653,12 @@ ${lanes.join("\n")} getJsxFragmentFactoryEntity: getJsxFragmentFactoryEntity, getAllAccessorDeclarations (accessor) { accessor = getParseTreeNode(accessor, isGetOrSetAccessorDeclaration); - const otherKind = accessor.kind === 175 /* SetAccessor */ ? 174 /* GetAccessor */ : 175 /* SetAccessor */ ; + const otherKind = accessor.kind === 178 /* SetAccessor */ ? 177 /* GetAccessor */ : 178 /* SetAccessor */ ; const otherAccessor = getDeclarationOfKind(getSymbolOfDeclaration(accessor), otherKind); const firstAccessor = otherAccessor && otherAccessor.pos < accessor.pos ? otherAccessor : accessor; const secondAccessor = otherAccessor && otherAccessor.pos < accessor.pos ? accessor : otherAccessor; - const setAccessor = accessor.kind === 175 /* SetAccessor */ ? accessor : otherAccessor; - const getAccessor = accessor.kind === 174 /* GetAccessor */ ? accessor : otherAccessor; + const setAccessor = accessor.kind === 178 /* SetAccessor */ ? accessor : otherAccessor; + const getAccessor = accessor.kind === 177 /* GetAccessor */ ? accessor : otherAccessor; return { firstAccessor: firstAccessor, secondAccessor: secondAccessor, @@ -70843,7 +71674,7 @@ ${lanes.join("\n")} }, getDeclarationStatementsForSourceFile: (node, flags, tracker, bundled)=>{ const n = getParseTreeNode(node); - Debug.assert(n && n.kind === 308 /* SourceFile */ , "Non-sourcefile node passed into getDeclarationsForSourceFile"); + Debug.assert(n && n.kind === 312 /* SourceFile */ , "Non-sourcefile node passed into getDeclarationsForSourceFile"); const sym = getSymbolOfDeclaration(node); if (!sym) return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled); return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker, bundled); @@ -70867,15 +71698,15 @@ ${lanes.join("\n")} return false; } function isInHeritageClause(node) { - return node.parent && node.parent.kind === 230 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 294 /* HeritageClause */ ; + return node.parent && node.parent.kind === 233 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 298 /* HeritageClause */ ; } function getTypeReferenceDirectivesForEntityName(node) { if (!fileToDirective) return void 0; let meaning; - if (node.parent.kind === 164 /* ComputedPropertyName */ ) meaning = 1160127 /* ExportValue */ ; + if (node.parent.kind === 167 /* ComputedPropertyName */ ) meaning = 1160127 /* ExportValue */ ; else { meaning = 790504 /* Namespace */ ; - if (node.kind === 79 /* Identifier */ && isInTypeQuery(node) || node.kind === 208 /* PropertyAccessExpression */ && !isInHeritageClause(node)) meaning = 1160127 /* ExportValue */ ; + if (node.kind === 80 /* Identifier */ && isInTypeQuery(node) || node.kind === 211 /* PropertyAccessExpression */ && !isInHeritageClause(node)) meaning = 1160127 /* ExportValue */ ; } const symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : void 0; @@ -70899,7 +71730,7 @@ ${lanes.join("\n")} if (parent2) current = parent2; else break; } - if (current.valueDeclaration && current.valueDeclaration.kind === 308 /* SourceFile */ && current.flags & 512 /* ValueModule */ ) return false; + if (current.valueDeclaration && current.valueDeclaration.kind === 312 /* SourceFile */ && current.flags & 512 /* ValueModule */ ) return false; for (const decl of symbol.declarations){ const file = getSourceFileOfNode(decl); if (fileToDirective.has(file.path)) return true; @@ -70912,7 +71743,7 @@ ${lanes.join("\n")} key, mode ]); - for (const { fileName: fileName , resolutionMode: resolutionMode } of file.referencedFiles){ + for (const { fileName: fileName, resolutionMode: resolutionMode } of file.referencedFiles){ const resolvedFile = resolveTripleslashReference(fileName, file.fileName); const referencedFile = host.getSourceFile(resolvedFile); if (referencedFile) addReferencedFilesToTypeDirective(referencedFile, key, resolutionMode || file.impliedNodeFormat); @@ -70920,10 +71751,10 @@ ${lanes.join("\n")} } } function getExternalModuleFileFromDeclaration(declaration) { - const specifier = declaration.kind === 264 /* ModuleDeclaration */ ? tryCast(declaration.name, isStringLiteral) : getExternalModuleName(declaration); + const specifier = declaration.kind === 267 /* ModuleDeclaration */ ? tryCast(declaration.name, isStringLiteral) : getExternalModuleName(declaration); const moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ void 0); if (!moduleSymbol) return void 0; - return getDeclarationOfKind(moduleSymbol, 308 /* SourceFile */ ); + return getDeclarationOfKind(moduleSymbol, 312 /* SourceFile */ ); } function initializeTypeChecker() { for (const file of host.getSourceFiles())bindSourceFile(file, compilerOptions); @@ -70968,7 +71799,7 @@ ${lanes.join("\n")} globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true); anyArrayType = createArrayType(anyType); autoArrayType = createArrayType(autoType); - if (autoArrayType === emptyObjectType) autoArrayType = createAnonymousType(void 0, emptySymbols, emptyArray, emptyArray, emptyArray); + if (autoArrayType === emptyObjectType) autoArrayType = createAnonymousType(/*symbol*/ void 0, emptySymbols, emptyArray, emptyArray, emptyArray); globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1) || globalArrayType; anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [ anyType @@ -70980,8 +71811,8 @@ ${lanes.join("\n")} mergeModuleAugmentation(augmentation); } } - amalgamatedDuplicates.forEach(({ firstFile: firstFile , secondFile: secondFile , conflictingSymbols: conflictingSymbols })=>{ - if (conflictingSymbols.size < 8) conflictingSymbols.forEach(({ isBlockScoped: isBlockScoped , firstFileLocations: firstFileLocations , secondFileLocations: secondFileLocations }, symbolName2)=>{ + amalgamatedDuplicates.forEach(({ firstFile: firstFile, secondFile: secondFile, conflictingSymbols: conflictingSymbols })=>{ + if (conflictingSymbols.size < 8) conflictingSymbols.forEach(({ isBlockScoped: isBlockScoped, firstFileLocations: firstFileLocations, secondFileLocations: secondFileLocations }, symbolName2)=>{ const message = isBlockScoped ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0; for (const node of firstFileLocations)addDuplicateDeclarationError(node, message, symbolName2, secondFileLocations); for (const node of secondFileLocations)addDuplicateDeclarationError(node, message, symbolName2, firstFileLocations); @@ -70997,22 +71828,22 @@ ${lanes.join("\n")} function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { const sourceFile = getSourceFileOfNode(location); - if (isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 16777216 /* Ambient */ )) { + if (isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 33554432 /* Ambient */ )) { const helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { const uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for(let helper = 1 /* FirstEmitHelper */ ; helper <= 16777216 /* LastEmitHelper */ ; helper <<= 1){ + for(let helper = 1 /* FirstEmitHelper */ ; helper <= 33554432 /* LastEmitHelper */ ; helper <<= 1){ if (uncheckedHelpers & helper) for (const name of getHelperNames(helper)){ if (requestedExternalEmitHelperNames.has(name)) continue; requestedExternalEmitHelperNames.add(name); - const symbol = getSymbol2(helpersModule.exports, escapeLeadingUnderscores(name), 111551 /* Value */ ); - if (!symbol) error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name); + const symbol = resolveSymbol(getSymbol2(getExportsOfModule(helpersModule), escapeLeadingUnderscores(name), 111551 /* Value */ )); + if (!symbol) error2(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name); else if (helper & 524288 /* ClassPrivateFieldGet */ ) { - if (!some(getSignaturesOfSymbol(symbol), (signature)=>getParameterCount(signature) > 3)) error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 4); + if (!some(getSignaturesOfSymbol(symbol), (signature)=>getParameterCount(signature) > 3)) error2(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 4); } else if (helper & 1048576 /* ClassPrivateFieldSet */ ) { - if (!some(getSignaturesOfSymbol(symbol), (signature)=>getParameterCount(signature) > 4)) error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 5); + if (!some(getSignaturesOfSymbol(symbol), (signature)=>getParameterCount(signature) > 4)) error2(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 5); } else if (helper & 1024 /* SpreadArray */ ) { - if (!some(getSignaturesOfSymbol(symbol), (signature)=>getParameterCount(signature) > 2)) error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 3); + if (!some(getSignaturesOfSymbol(symbol), (signature)=>getParameterCount(signature) > 2)) error2(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 3); } } } @@ -71126,6 +71957,11 @@ ${lanes.join("\n")} return [ "__propKey" ]; + case 33554432 /* AddDisposableResourceAndDisposeResources */ : + return [ + "__addDisposableResource", + "__disposeResources" + ]; default: return Debug.fail("Unrecognized helper"); } @@ -71138,15 +71974,16 @@ ${lanes.join("\n")} const quickResult = reportObviousDecoratorErrors(node) || reportObviousModifierErrors(node); if (quickResult !== void 0) return quickResult; if (isParameter(node) && parameterIsThisKeyword(node)) return grammarErrorOnFirstToken(node, Diagnostics.Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters); + const blockScopeKind = isVariableStatement(node) ? node.declarationList.flags & 7 /* BlockScoped */ : 0 /* None */ ; let lastStatic, lastDeclare, lastAsync, lastOverride, firstDecorator; let flags = 0 /* None */ ; let sawExportBeforeDecorators = false; let hasLeadingDecorators = false; for (const modifier of node.modifiers)if (isDecorator(modifier)) { if (!nodeCanBeDecorated(legacyDecorators, node, node.parent, node.parent.parent)) { - if (node.kind === 171 /* MethodDeclaration */ && !nodeIsPresent(node.body)) return grammarErrorOnFirstToken(node, Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + if (node.kind === 174 /* MethodDeclaration */ && !nodeIsPresent(node.body)) return grammarErrorOnFirstToken(node, Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); else return grammarErrorOnFirstToken(node, Diagnostics.Decorators_are_not_valid_here); - } else if (legacyDecorators && (node.kind === 174 /* GetAccessor */ || node.kind === 175 /* SetAccessor */ )) { + } else if (legacyDecorators && (node.kind === 177 /* GetAccessor */ || node.kind === 178 /* SetAccessor */ )) { const accessors = getAllAccessorDeclarations(node.parent.members, node); if (hasDecorators(accessors.firstAccessor) && node === accessors.secondAccessor) return grammarErrorOnFirstToken(node, Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); } @@ -71155,7 +71992,7 @@ ${lanes.join("\n")} Debug.assertIsDefined(firstDecorator); const sourceFile = getSourceFileOfNode(modifier); if (!hasParseDiagnostics(sourceFile)) { - addRelatedInfo(error(modifier, Diagnostics.Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export), createDiagnosticForNode(firstDecorator, Diagnostics.Decorator_used_before_export_here)); + addRelatedInfo(error2(modifier, Diagnostics.Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export), createDiagnosticForNode(firstDecorator, Diagnostics.Decorator_used_before_export_here)); return true; } return false; @@ -71163,22 +72000,22 @@ ${lanes.join("\n")} flags |= 131072 /* Decorator */ ; if (!(flags & 126975 /* Modifier */ )) hasLeadingDecorators = true; else if (flags & 1 /* Export */ ) sawExportBeforeDecorators = true; - firstDecorator != null ? firstDecorator : firstDecorator = modifier; + firstDecorator ?? (firstDecorator = modifier); } else { - if (modifier.kind !== 146 /* ReadonlyKeyword */ ) { - if (node.kind === 168 /* PropertySignature */ || node.kind === 170 /* MethodSignature */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_type_member, tokenToString(modifier.kind)); - if (node.kind === 178 /* IndexSignature */ && (modifier.kind !== 124 /* StaticKeyword */ || !isClassLike(node.parent))) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_index_signature, tokenToString(modifier.kind)); + if (modifier.kind !== 148 /* ReadonlyKeyword */ ) { + if (node.kind === 171 /* PropertySignature */ || node.kind === 173 /* MethodSignature */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_type_member, tokenToString(modifier.kind)); + if (node.kind === 181 /* IndexSignature */ && (modifier.kind !== 126 /* StaticKeyword */ || !isClassLike(node.parent))) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_index_signature, tokenToString(modifier.kind)); } - if (modifier.kind !== 101 /* InKeyword */ && modifier.kind !== 145 /* OutKeyword */ && modifier.kind !== 85 /* ConstKeyword */ ) { - if (node.kind === 165 /* TypeParameter */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_type_parameter, tokenToString(modifier.kind)); + if (modifier.kind !== 103 /* InKeyword */ && modifier.kind !== 147 /* OutKeyword */ && modifier.kind !== 87 /* ConstKeyword */ ) { + if (node.kind === 168 /* TypeParameter */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_type_parameter, tokenToString(modifier.kind)); } switch(modifier.kind){ - case 85 /* ConstKeyword */ : - if (node.kind !== 263 /* EnumDeclaration */ && node.kind !== 165 /* TypeParameter */ ) return grammarErrorOnNode(node, Diagnostics.A_class_member_cannot_have_the_0_keyword, tokenToString(85 /* ConstKeyword */ )); + case 87 /* ConstKeyword */ : + if (node.kind !== 266 /* EnumDeclaration */ && node.kind !== 168 /* TypeParameter */ ) return grammarErrorOnNode(node, Diagnostics.A_class_member_cannot_have_the_0_keyword, tokenToString(87 /* ConstKeyword */ )); const parent2 = node.parent; - if (node.kind === 165 /* TypeParameter */ && !(isFunctionLikeDeclaration(parent2) || isClassLike(parent2) || isFunctionTypeNode(parent2) || isConstructorTypeNode(parent2) || isCallSignatureDeclaration(parent2) || isConstructSignatureDeclaration(parent2) || isMethodSignature(parent2))) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_can_only_appear_on_a_type_parameter_of_a_function_method_or_class, tokenToString(modifier.kind)); + if (node.kind === 168 /* TypeParameter */ && !(isFunctionLikeDeclaration(parent2) || isClassLike(parent2) || isFunctionTypeNode(parent2) || isConstructorTypeNode(parent2) || isCallSignatureDeclaration(parent2) || isConstructSignatureDeclaration(parent2) || isMethodSignature(parent2))) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_can_only_appear_on_a_type_parameter_of_a_function_method_or_class, tokenToString(modifier.kind)); break; - case 161 /* OverrideKeyword */ : + case 164 /* OverrideKeyword */ : if (flags & 16384 /* Override */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "override"); else if (flags & 2 /* Ambient */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "override", "declare"); else if (flags & 64 /* Readonly */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "override", "readonly"); @@ -71187,9 +72024,9 @@ ${lanes.join("\n")} flags |= 16384 /* Override */ ; lastOverride = modifier; break; - case 123 /* PublicKeyword */ : - case 122 /* ProtectedKeyword */ : - case 121 /* PrivateKeyword */ : + case 125 /* PublicKeyword */ : + case 124 /* ProtectedKeyword */ : + case 123 /* PrivateKeyword */ : const text = visibilityToString(modifierToFlag(modifier.kind)); if (flags & 28 /* AccessibilityModifier */ ) return grammarErrorOnNode(modifier, Diagnostics.Accessibility_modifier_already_seen); else if (flags & 16384 /* Override */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "override"); @@ -71197,109 +72034,118 @@ ${lanes.join("\n")} else if (flags & 128 /* Accessor */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "accessor"); else if (flags & 64 /* Readonly */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); else if (flags & 512 /* Async */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); - else if (node.parent.kind === 265 /* ModuleBlock */ || node.parent.kind === 308 /* SourceFile */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); + else if (node.parent.kind === 268 /* ModuleBlock */ || node.parent.kind === 312 /* SourceFile */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); else if (flags & 256 /* Abstract */ ) { - if (modifier.kind === 121 /* PrivateKeyword */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); + if (modifier.kind === 123 /* PrivateKeyword */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); else return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); } else if (isPrivateIdentifierClassElementDeclaration(node)) return grammarErrorOnNode(modifier, Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier); flags |= modifierToFlag(modifier.kind); break; - case 124 /* StaticKeyword */ : + case 126 /* StaticKeyword */ : if (flags & 32 /* Static */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "static"); else if (flags & 64 /* Readonly */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); else if (flags & 512 /* Async */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); else if (flags & 128 /* Accessor */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "accessor"); - else if (node.parent.kind === 265 /* ModuleBlock */ || node.parent.kind === 308 /* SourceFile */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); - else if (node.kind === 166 /* Parameter */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); + else if (node.parent.kind === 268 /* ModuleBlock */ || node.parent.kind === 312 /* SourceFile */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); + else if (node.kind === 169 /* Parameter */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); else if (flags & 256 /* Abstract */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); else if (flags & 16384 /* Override */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "override"); flags |= 32 /* Static */ ; lastStatic = modifier; break; - case 127 /* AccessorKeyword */ : + case 129 /* AccessorKeyword */ : if (flags & 128 /* Accessor */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "accessor"); else if (flags & 64 /* Readonly */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "accessor", "readonly"); else if (flags & 2 /* Ambient */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "accessor", "declare"); - else if (node.kind !== 169 /* PropertyDeclaration */ ) return grammarErrorOnNode(modifier, Diagnostics.accessor_modifier_can_only_appear_on_a_property_declaration); + else if (node.kind !== 172 /* PropertyDeclaration */ ) return grammarErrorOnNode(modifier, Diagnostics.accessor_modifier_can_only_appear_on_a_property_declaration); flags |= 128 /* Accessor */ ; break; - case 146 /* ReadonlyKeyword */ : + case 148 /* ReadonlyKeyword */ : if (flags & 64 /* Readonly */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "readonly"); - else if (node.kind !== 169 /* PropertyDeclaration */ && node.kind !== 168 /* PropertySignature */ && node.kind !== 178 /* IndexSignature */ && node.kind !== 166 /* Parameter */ ) return grammarErrorOnNode(modifier, Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); + else if (node.kind !== 172 /* PropertyDeclaration */ && node.kind !== 171 /* PropertySignature */ && node.kind !== 181 /* IndexSignature */ && node.kind !== 169 /* Parameter */ ) return grammarErrorOnNode(modifier, Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); else if (flags & 128 /* Accessor */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "readonly", "accessor"); flags |= 64 /* Readonly */ ; break; - case 93 /* ExportKeyword */ : - if (compilerOptions.verbatimModuleSyntax && !(node.flags & 16777216 /* Ambient */ ) && node.kind !== 262 /* TypeAliasDeclaration */ && node.kind !== 261 /* InterfaceDeclaration */ && // ModuleDeclaration needs to be checked that it is uninstantiated later - node.kind !== 264 /* ModuleDeclaration */ && node.parent.kind === 308 /* SourceFile */ && (moduleKind === 1 /* CommonJS */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */ )) return grammarErrorOnNode(modifier, Diagnostics.A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled); + case 95 /* ExportKeyword */ : + if (compilerOptions.verbatimModuleSyntax && !(node.flags & 33554432 /* Ambient */ ) && node.kind !== 265 /* TypeAliasDeclaration */ && node.kind !== 264 /* InterfaceDeclaration */ && // ModuleDeclaration needs to be checked that it is uninstantiated later + node.kind !== 267 /* ModuleDeclaration */ && node.parent.kind === 312 /* SourceFile */ && (moduleKind === 1 /* CommonJS */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */ )) return grammarErrorOnNode(modifier, Diagnostics.A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled); if (flags & 1 /* Export */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "export"); else if (flags & 2 /* Ambient */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); else if (flags & 256 /* Abstract */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); else if (flags & 512 /* Async */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); else if (isClassLike(node.parent)) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "export"); - else if (node.kind === 166 /* Parameter */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); + else if (node.kind === 169 /* Parameter */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); + else if (blockScopeKind === 4 /* Using */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_using_declaration, "export"); + else if (blockScopeKind === 6 /* AwaitUsing */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "export"); flags |= 1 /* Export */ ; break; - case 88 /* DefaultKeyword */ : - const container = node.parent.kind === 308 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 264 /* ModuleDeclaration */ && !isAmbientModule(container)) return grammarErrorOnNode(modifier, Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + case 90 /* DefaultKeyword */ : + const container = node.parent.kind === 312 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 267 /* ModuleDeclaration */ && !isAmbientModule(container)) return grammarErrorOnNode(modifier, Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + else if (blockScopeKind === 4 /* Using */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_using_declaration, "default"); + else if (blockScopeKind === 6 /* AwaitUsing */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "default"); else if (!(flags & 1 /* Export */ )) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "default"); else if (sawExportBeforeDecorators) return grammarErrorOnNode(firstDecorator, Diagnostics.Decorators_are_not_valid_here); flags |= 1024 /* Default */ ; break; - case 136 /* DeclareKeyword */ : + case 138 /* DeclareKeyword */ : if (flags & 2 /* Ambient */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "declare"); else if (flags & 512 /* Async */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); else if (flags & 16384 /* Override */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "override"); else if (isClassLike(node.parent) && !isPropertyDeclaration(node)) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "declare"); - else if (node.kind === 166 /* Parameter */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); - else if (node.parent.flags & 16777216 /* Ambient */ && node.parent.kind === 265 /* ModuleBlock */ ) return grammarErrorOnNode(modifier, Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); + else if (node.kind === 169 /* Parameter */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); + else if (blockScopeKind === 4 /* Using */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_using_declaration, "declare"); + else if (blockScopeKind === 6 /* AwaitUsing */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "declare"); + else if (node.parent.flags & 33554432 /* Ambient */ && node.parent.kind === 268 /* ModuleBlock */ ) return grammarErrorOnNode(modifier, Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); else if (isPrivateIdentifierClassElementDeclaration(node)) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare"); else if (flags & 128 /* Accessor */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "declare", "accessor"); flags |= 2 /* Ambient */ ; lastDeclare = modifier; break; - case 126 /* AbstractKeyword */ : + case 128 /* AbstractKeyword */ : if (flags & 256 /* Abstract */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "abstract"); - if (node.kind !== 260 /* ClassDeclaration */ && node.kind !== 182 /* ConstructorType */ ) { - if (node.kind !== 171 /* MethodDeclaration */ && node.kind !== 169 /* PropertyDeclaration */ && node.kind !== 174 /* GetAccessor */ && node.kind !== 175 /* SetAccessor */ ) return grammarErrorOnNode(modifier, Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); - if (!(node.parent.kind === 260 /* ClassDeclaration */ && hasSyntacticModifier(node.parent, 256 /* Abstract */ ))) return grammarErrorOnNode(modifier, Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); + if (node.kind !== 263 /* ClassDeclaration */ && node.kind !== 185 /* ConstructorType */ ) { + if (node.kind !== 174 /* MethodDeclaration */ && node.kind !== 172 /* PropertyDeclaration */ && node.kind !== 177 /* GetAccessor */ && node.kind !== 178 /* SetAccessor */ ) return grammarErrorOnNode(modifier, Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); + if (!(node.parent.kind === 263 /* ClassDeclaration */ && hasSyntacticModifier(node.parent, 256 /* Abstract */ ))) { + const message = node.kind === 172 /* PropertyDeclaration */ ? Diagnostics.Abstract_properties_can_only_appear_within_an_abstract_class : Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class; + return grammarErrorOnNode(modifier, message); + } if (flags & 32 /* Static */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); if (flags & 8 /* Private */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); if (flags & 512 /* Async */ && lastAsync) return grammarErrorOnNode(lastAsync, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract"); if (flags & 16384 /* Override */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "override"); if (flags & 128 /* Accessor */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "accessor"); } - if (isNamedDeclaration(node) && node.name.kind === 80 /* PrivateIdentifier */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract"); + if (isNamedDeclaration(node) && node.name.kind === 81 /* PrivateIdentifier */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract"); flags |= 256 /* Abstract */ ; break; - case 132 /* AsyncKeyword */ : + case 134 /* AsyncKeyword */ : if (flags & 512 /* Async */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "async"); - else if (flags & 2 /* Ambient */ || node.parent.flags & 16777216 /* Ambient */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); - else if (node.kind === 166 /* Parameter */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); + else if (flags & 2 /* Ambient */ || node.parent.flags & 33554432 /* Ambient */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + else if (node.kind === 169 /* Parameter */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); if (flags & 256 /* Abstract */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract"); flags |= 512 /* Async */ ; lastAsync = modifier; break; - case 101 /* InKeyword */ : - case 145 /* OutKeyword */ : - const inOutFlag = modifier.kind === 101 /* InKeyword */ ? 32768 /* In */ : 65536 /* Out */ ; - const inOutText = modifier.kind === 101 /* InKeyword */ ? "in" : "out"; - if (node.kind !== 165 /* TypeParameter */ || !(isInterfaceDeclaration(node.parent) || isClassLike(node.parent) || isTypeAliasDeclaration(node.parent))) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias, inOutText); + case 103 /* InKeyword */ : + case 147 /* OutKeyword */ : + const inOutFlag = modifier.kind === 103 /* InKeyword */ ? 32768 /* In */ : 65536 /* Out */ ; + const inOutText = modifier.kind === 103 /* InKeyword */ ? "in" : "out"; + if (node.kind !== 168 /* TypeParameter */ || !(isInterfaceDeclaration(node.parent) || isClassLike(node.parent) || isTypeAliasDeclaration(node.parent))) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias, inOutText); if (flags & inOutFlag) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, inOutText); if (inOutFlag & 32768 /* In */ && flags & 65536 /* Out */ ) return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "in", "out"); flags |= inOutFlag; break; } } - if (node.kind === 173 /* Constructor */ ) { + if (node.kind === 176 /* Constructor */ ) { if (flags & 32 /* Static */ ) return grammarErrorOnNode(lastStatic, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); if (flags & 16384 /* Override */ ) return grammarErrorOnNode(lastOverride, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override"); if (flags & 512 /* Async */ ) return grammarErrorOnNode(lastAsync, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); return false; - } else if ((node.kind === 269 /* ImportDeclaration */ || node.kind === 268 /* ImportEqualsDeclaration */ ) && flags & 2 /* Ambient */ ) return grammarErrorOnNode(lastDeclare, Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); - else if (node.kind === 166 /* Parameter */ && flags & 16476 /* ParameterPropertyModifier */ && isBindingPattern(node.name)) return grammarErrorOnNode(node, Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); - else if (node.kind === 166 /* Parameter */ && flags & 16476 /* ParameterPropertyModifier */ && node.dotDotDotToken) return grammarErrorOnNode(node, Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); + } else if ((node.kind === 272 /* ImportDeclaration */ || node.kind === 271 /* ImportEqualsDeclaration */ ) && flags & 2 /* Ambient */ ) return grammarErrorOnNode(lastDeclare, Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); + else if (node.kind === 169 /* Parameter */ && flags & 16476 /* ParameterPropertyModifier */ && isBindingPattern(node.name)) return grammarErrorOnNode(node, Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + else if (node.kind === 169 /* Parameter */ && flags & 16476 /* ParameterPropertyModifier */ && node.dotDotDotToken) return grammarErrorOnNode(node, Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); if (flags & 512 /* Async */ ) return checkGrammarAsyncModifier(node, lastAsync); return false; } @@ -71314,45 +72160,46 @@ ${lanes.join("\n")} } function findFirstIllegalModifier(node) { switch(node.kind){ - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 173 /* Constructor */ : - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 178 /* IndexSignature */ : - case 264 /* ModuleDeclaration */ : - case 269 /* ImportDeclaration */ : - case 268 /* ImportEqualsDeclaration */ : - case 275 /* ExportDeclaration */ : - case 274 /* ExportAssignment */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - case 166 /* Parameter */ : - case 165 /* TypeParameter */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 176 /* Constructor */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 181 /* IndexSignature */ : + case 267 /* ModuleDeclaration */ : + case 272 /* ImportDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : + case 278 /* ExportDeclaration */ : + case 277 /* ExportAssignment */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + case 169 /* Parameter */ : + case 168 /* TypeParameter */ : return void 0; - case 172 /* ClassStaticBlockDeclaration */ : - case 299 /* PropertyAssignment */ : - case 300 /* ShorthandPropertyAssignment */ : - case 267 /* NamespaceExportDeclaration */ : - case 279 /* MissingDeclaration */ : + case 175 /* ClassStaticBlockDeclaration */ : + case 303 /* PropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : + case 270 /* NamespaceExportDeclaration */ : + case 282 /* MissingDeclaration */ : return find(node.modifiers, isModifier); default: - if (node.parent.kind === 265 /* ModuleBlock */ || node.parent.kind === 308 /* SourceFile */ ) return void 0; + if (node.parent.kind === 268 /* ModuleBlock */ || node.parent.kind === 312 /* SourceFile */ ) return void 0; switch(node.kind){ - case 259 /* FunctionDeclaration */ : - return findFirstModifierExcept(node, 132 /* AsyncKeyword */ ); - case 260 /* ClassDeclaration */ : - case 182 /* ConstructorType */ : - return findFirstModifierExcept(node, 126 /* AbstractKeyword */ ); - case 228 /* ClassExpression */ : - case 261 /* InterfaceDeclaration */ : - case 240 /* VariableStatement */ : - case 262 /* TypeAliasDeclaration */ : + case 262 /* FunctionDeclaration */ : + return findFirstModifierExcept(node, 134 /* AsyncKeyword */ ); + case 263 /* ClassDeclaration */ : + case 185 /* ConstructorType */ : + return findFirstModifierExcept(node, 128 /* AbstractKeyword */ ); + case 231 /* ClassExpression */ : + case 264 /* InterfaceDeclaration */ : + case 265 /* TypeAliasDeclaration */ : return find(node.modifiers, isModifier); - case 263 /* EnumDeclaration */ : - return findFirstModifierExcept(node, 85 /* ConstKeyword */ ); + case 243 /* VariableStatement */ : + return node.declarationList.flags & 4 /* Using */ ? findFirstModifierExcept(node, 135 /* AwaitKeyword */ ) : find(node.modifiers, isModifier); + case 266 /* EnumDeclaration */ : + return findFirstModifierExcept(node, 87 /* ConstKeyword */ ); default: Debug.assertNever(node); } @@ -71367,10 +72214,10 @@ ${lanes.join("\n")} } function checkGrammarAsyncModifier(node, asyncModifier) { switch(node.kind){ - case 171 /* MethodDeclaration */ : - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : + case 174 /* MethodDeclaration */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : return false; } return grammarErrorOnNode(asyncModifier, Diagnostics._0_modifier_cannot_be_used_here, "async"); @@ -71394,7 +72241,7 @@ ${lanes.join("\n")} const parameter = parameters[i]; if (parameter.dotDotDotToken) { if (i !== parameterCount - 1) return grammarErrorOnNode(parameter.dotDotDotToken, Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); - if (!(parameter.flags & 16777216 /* Ambient */ )) checkGrammarForDisallowedTrailingComma(parameters, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + if (!(parameter.flags & 33554432 /* Ambient */ )) checkGrammarForDisallowedTrailingComma(parameters, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); if (parameter.questionToken) return grammarErrorOnNode(parameter.questionToken, Diagnostics.A_rest_parameter_cannot_be_optional); if (parameter.initializer) return grammarErrorOnNode(parameter.name, Diagnostics.A_rest_parameter_cannot_have_an_initializer); } else if (isOptionalParameter(parameter)) { @@ -71413,10 +72260,10 @@ ${lanes.join("\n")} const nonSimpleParameters = getNonSimpleParameters(node.parameters); if (length(nonSimpleParameters)) { forEach(nonSimpleParameters, (parameter)=>{ - addRelatedInfo(error(parameter, Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), createDiagnosticForNode(useStrictDirective, Diagnostics.use_strict_directive_used_here)); + addRelatedInfo(error2(parameter, Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), createDiagnosticForNode(useStrictDirective, Diagnostics.use_strict_directive_used_here)); }); const diagnostics2 = nonSimpleParameters.map((parameter, index)=>index === 0 ? createDiagnosticForNode(parameter, Diagnostics.Non_simple_parameter_declared_here) : createDiagnosticForNode(parameter, Diagnostics.and_here)); - addRelatedInfo(error(useStrictDirective, Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list), ...diagnostics2); + addRelatedInfo(error2(useStrictDirective, Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list), ...diagnostics2); return true; } } @@ -71439,7 +72286,7 @@ ${lanes.join("\n")} ".cts" /* Cts */ ])) grammarErrorOnNode(node.typeParameters[0], Diagnostics.This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_constraint); } - const { equalsGreaterThanToken: equalsGreaterThanToken } = node; + const { equalsGreaterThanToken: equalsGreaterThanToken } = node; const startLine = getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line; const endLine = getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line; return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, Diagnostics.Line_terminator_not_permitted_before_arrow); @@ -71478,7 +72325,7 @@ ${lanes.join("\n")} return checkGrammarForDisallowedTrailingComma(typeArguments) || checkGrammarForAtLeastOneTypeArgument(node, typeArguments); } function checkGrammarTaggedTemplateChain(node) { - if (node.questionDotToken || node.flags & 32 /* OptionalChain */ ) return grammarErrorOnNode(node.template, Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain); + if (node.questionDotToken || node.flags & 64 /* OptionalChain */ ) return grammarErrorOnNode(node.template, Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain); return false; } function checkGrammarHeritageClause(node) { @@ -71498,13 +72345,13 @@ ${lanes.join("\n")} let seenExtendsClause = false; let seenImplementsClause = false; if (!checkGrammarModifiers(node) && node.heritageClauses) for (const heritageClause of node.heritageClauses){ - if (heritageClause.token === 94 /* ExtendsKeyword */ ) { + if (heritageClause.token === 96 /* ExtendsKeyword */ ) { if (seenExtendsClause) return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_already_seen); if (seenImplementsClause) return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_must_precede_implements_clause); if (heritageClause.types.length > 1) return grammarErrorOnFirstToken(heritageClause.types[1], Diagnostics.Classes_can_only_extend_a_single_class); seenExtendsClause = true; } else { - Debug.assert(heritageClause.token === 117 /* ImplementsKeyword */ ); + Debug.assert(heritageClause.token === 119 /* ImplementsKeyword */ ); if (seenImplementsClause) return grammarErrorOnFirstToken(heritageClause, Diagnostics.implements_clause_already_seen); seenImplementsClause = true; } @@ -71514,11 +72361,11 @@ ${lanes.join("\n")} function checkGrammarInterfaceDeclaration(node) { let seenExtendsClause = false; if (node.heritageClauses) for (const heritageClause of node.heritageClauses){ - if (heritageClause.token === 94 /* ExtendsKeyword */ ) { + if (heritageClause.token === 96 /* ExtendsKeyword */ ) { if (seenExtendsClause) return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_already_seen); seenExtendsClause = true; } else { - Debug.assert(heritageClause.token === 117 /* ImplementsKeyword */ ); + Debug.assert(heritageClause.token === 119 /* ImplementsKeyword */ ); return grammarErrorOnFirstToken(heritageClause, Diagnostics.Interface_declaration_cannot_have_implements_clause); } checkGrammarHeritageClause(heritageClause); @@ -71526,15 +72373,15 @@ ${lanes.join("\n")} return false; } function checkGrammarComputedPropertyName(node) { - if (node.kind !== 164 /* ComputedPropertyName */ ) return false; + if (node.kind !== 167 /* ComputedPropertyName */ ) return false; const computedPropertyName = node; - if (computedPropertyName.expression.kind === 223 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */ ) return grammarErrorOnNode(computedPropertyName.expression, Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); + if (computedPropertyName.expression.kind === 226 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 28 /* CommaToken */ ) return grammarErrorOnNode(computedPropertyName.expression, Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); return false; } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - Debug.assert(node.kind === 259 /* FunctionDeclaration */ || node.kind === 215 /* FunctionExpression */ || node.kind === 171 /* MethodDeclaration */ ); - if (node.flags & 16777216 /* Ambient */ ) return grammarErrorOnNode(node.asteriskToken, Diagnostics.Generators_are_not_allowed_in_an_ambient_context); + Debug.assert(node.kind === 262 /* FunctionDeclaration */ || node.kind === 218 /* FunctionExpression */ || node.kind === 174 /* MethodDeclaration */ ); + if (node.flags & 33554432 /* Ambient */ ) return grammarErrorOnNode(node.asteriskToken, Diagnostics.Generators_are_not_allowed_in_an_ambient_context); if (!node.body) return grammarErrorOnNode(node.asteriskToken, Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); } } @@ -71547,7 +72394,7 @@ ${lanes.join("\n")} function checkGrammarObjectLiteralExpression(node, inDestructuring) { const seen = /* @__PURE__ */ new Map(); for (const prop of node.properties){ - if (prop.kind === 301 /* SpreadAssignment */ ) { + if (prop.kind === 305 /* SpreadAssignment */ ) { if (inDestructuring) { const expression = skipParentheses(prop.expression); if (isArrayLiteralExpression(expression) || isObjectLiteralExpression(expression)) return grammarErrorOnNode(prop.expression, Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); @@ -71555,37 +72402,37 @@ ${lanes.join("\n")} continue; } const name = prop.name; - if (name.kind === 164 /* ComputedPropertyName */ ) checkGrammarComputedPropertyName(name); - if (prop.kind === 300 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) grammarErrorOnNode(prop.equalsToken, 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); - if (name.kind === 80 /* PrivateIdentifier */ ) grammarErrorOnNode(name, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + if (name.kind === 167 /* ComputedPropertyName */ ) checkGrammarComputedPropertyName(name); + if (prop.kind === 304 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) grammarErrorOnNode(prop.equalsToken, 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); + if (name.kind === 81 /* PrivateIdentifier */ ) grammarErrorOnNode(name, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); if (canHaveModifiers(prop) && prop.modifiers) { - for (const mod of prop.modifiers)if (isModifier(mod) && (mod.kind !== 132 /* AsyncKeyword */ || prop.kind !== 171 /* MethodDeclaration */ )) grammarErrorOnNode(mod, Diagnostics._0_modifier_cannot_be_used_here, getTextOfNode(mod)); + for (const mod of prop.modifiers)if (isModifier(mod) && (mod.kind !== 134 /* AsyncKeyword */ || prop.kind !== 174 /* MethodDeclaration */ )) grammarErrorOnNode(mod, Diagnostics._0_modifier_cannot_be_used_here, getTextOfNode(mod)); } else if (canHaveIllegalModifiers(prop) && prop.modifiers) { for (const mod of prop.modifiers)if (isModifier(mod)) grammarErrorOnNode(mod, Diagnostics._0_modifier_cannot_be_used_here, getTextOfNode(mod)); } let currentKind; switch(prop.kind){ - case 300 /* ShorthandPropertyAssignment */ : - case 299 /* PropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : + case 303 /* PropertyAssignment */ : checkGrammarForInvalidExclamationToken(prop.exclamationToken, Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); checkGrammarForInvalidQuestionMark(prop.questionToken, Diagnostics.An_object_member_cannot_be_declared_optional); - if (name.kind === 8 /* NumericLiteral */ ) checkGrammarNumericLiteral(name); + if (name.kind === 9 /* NumericLiteral */ ) checkGrammarNumericLiteral(name); currentKind = 4 /* PropertyAssignment */ ; break; - case 171 /* MethodDeclaration */ : + case 174 /* MethodDeclaration */ : currentKind = 8 /* Method */ ; break; - case 174 /* GetAccessor */ : + case 177 /* GetAccessor */ : currentKind = 1 /* GetAccessor */ ; break; - case 175 /* SetAccessor */ : + case 178 /* SetAccessor */ : currentKind = 2 /* SetAccessor */ ; break; default: - throw Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); + Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); } if (!inDestructuring) { - const effectiveName = getPropertyNameForPropertyNameNode(name); + const effectiveName = getEffectivePropertyNameForPropertyNameNode(name); if (effectiveName === void 0) continue; const existingKind = seen.get(effectiveName); if (!existingKind) seen.set(effectiveName, currentKind); @@ -71605,35 +72452,25 @@ ${lanes.join("\n")} checkGrammarTypeArguments(node, node.typeArguments); const seen = /* @__PURE__ */ new Map(); for (const attr of node.attributes.properties){ - if (attr.kind === 290 /* JsxSpreadAttribute */ ) continue; - const { name: name , initializer: initializer } = attr; - if (!seen.get(name.escapedText)) seen.set(name.escapedText, true); + if (attr.kind === 293 /* JsxSpreadAttribute */ ) continue; + const { name: name, initializer: initializer } = attr; + const escapedText = getEscapedTextOfJsxAttributeName(name); + if (!seen.get(escapedText)) seen.set(escapedText, true); else return grammarErrorOnNode(name, Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); - if (initializer && initializer.kind === 291 /* JsxExpression */ && !initializer.expression) return grammarErrorOnNode(initializer, Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); + if (initializer && initializer.kind === 294 /* JsxExpression */ && !initializer.expression) return grammarErrorOnNode(initializer, Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } function checkGrammarJsxName(node) { - if (isPropertyAccessExpression(node)) { - let propName = node; - do { - const check2 = checkGrammarJsxNestedIdentifier(propName.name); - if (check2) return check2; - propName = propName.expression; - }while (isPropertyAccessExpression(propName)); - const check = checkGrammarJsxNestedIdentifier(propName); - if (check) return check; - } - function checkGrammarJsxNestedIdentifier(name) { - if (isIdentifier(name) && idText(name).indexOf(":") !== -1) return grammarErrorOnNode(name, Diagnostics.JSX_property_access_expressions_cannot_include_JSX_namespace_names); - } + if (isPropertyAccessExpression(node) && isJsxNamespacedName(node.expression)) return grammarErrorOnNode(node.expression, Diagnostics.JSX_property_access_expressions_cannot_include_JSX_namespace_names); + if (isJsxNamespacedName(node) && getJSXTransformEnabled(compilerOptions) && !isIntrinsicJsxName(node.namespace.escapedText)) return grammarErrorOnNode(node, Diagnostics.React_components_cannot_include_JSX_namespace_names); } function checkGrammarJsxExpression(node) { if (node.expression && isCommaSequence(node.expression)) return grammarErrorOnNode(node.expression, Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array); } function checkGrammarForInOrForOfStatement(forInOrOfStatement) { if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) return true; - if (forInOrOfStatement.kind === 247 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { - if (!(forInOrOfStatement.flags & 32768 /* AwaitContext */ )) { + if (forInOrOfStatement.kind === 250 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if (!(forInOrOfStatement.flags & 65536 /* AwaitContext */ )) { const sourceFile = getSourceFileOfNode(forInOrOfStatement); if (isInTopLevelContext(forInOrOfStatement)) { if (!hasParseDiagnostics(sourceFile)) { @@ -71657,7 +72494,7 @@ ${lanes.join("\n")} } else if (!hasParseDiagnostics(sourceFile)) { const diagnostic = createDiagnosticForNode(forInOrOfStatement.awaitModifier, Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); const func = getContainingFunction(forInOrOfStatement); - if (func && func.kind !== 173 /* Constructor */ ) { + if (func && func.kind !== 176 /* Constructor */ ) { Debug.assert((getFunctionFlags(func) & 2 /* Async */ ) === 0, "Enclosing function should never be an async function."); const relatedInfo = createDiagnosticForNode(func, Diagnostics.Did_you_mean_to_mark_this_function_as_async); addRelatedInfo(diagnostic, relatedInfo); @@ -71668,26 +72505,26 @@ ${lanes.join("\n")} return false; } } - if (isForOfStatement(forInOrOfStatement) && !(forInOrOfStatement.flags & 32768 /* AwaitContext */ ) && isIdentifier(forInOrOfStatement.initializer) && forInOrOfStatement.initializer.escapedText === "async") { + if (isForOfStatement(forInOrOfStatement) && !(forInOrOfStatement.flags & 65536 /* AwaitContext */ ) && isIdentifier(forInOrOfStatement.initializer) && forInOrOfStatement.initializer.escapedText === "async") { grammarErrorOnNode(forInOrOfStatement.initializer, Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_async); return false; } - if (forInOrOfStatement.initializer.kind === 258 /* VariableDeclarationList */ ) { + if (forInOrOfStatement.initializer.kind === 261 /* VariableDeclarationList */ ) { const variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { const declarations = variableList.declarations; if (!declarations.length) return false; if (declarations.length > 1) { - const diagnostic = forInOrOfStatement.kind === 246 /* ForInStatement */ ? Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; + const diagnostic = forInOrOfStatement.kind === 249 /* ForInStatement */ ? Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } const firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - const diagnostic = forInOrOfStatement.kind === 246 /* ForInStatement */ ? Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; + const diagnostic = forInOrOfStatement.kind === 249 /* ForInStatement */ ? Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - const diagnostic = forInOrOfStatement.kind === 246 /* ForInStatement */ ? Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; + const diagnostic = forInOrOfStatement.kind === 249 /* ForInStatement */ ? Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); } } @@ -71695,18 +72532,18 @@ ${lanes.join("\n")} return false; } function checkGrammarAccessor(accessor) { - if (!(accessor.flags & 16777216 /* Ambient */ ) && accessor.parent.kind !== 184 /* TypeLiteral */ && accessor.parent.kind !== 261 /* InterfaceDeclaration */ ) { + if (!(accessor.flags & 33554432 /* Ambient */ ) && accessor.parent.kind !== 187 /* TypeLiteral */ && accessor.parent.kind !== 264 /* InterfaceDeclaration */ ) { if (languageVersion < 1 /* ES5 */ ) return grammarErrorOnNode(accessor.name, Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); if (languageVersion < 2 /* ES2015 */ && isPrivateIdentifier(accessor.name)) return grammarErrorOnNode(accessor.name, Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); if (accessor.body === void 0 && !hasSyntacticModifier(accessor, 256 /* Abstract */ )) return grammarErrorAtPos(accessor, accessor.end - 1, 1, Diagnostics._0_expected, "{"); } if (accessor.body) { if (hasSyntacticModifier(accessor, 256 /* Abstract */ )) return grammarErrorOnNode(accessor, Diagnostics.An_abstract_accessor_cannot_have_an_implementation); - if (accessor.parent.kind === 184 /* TypeLiteral */ || accessor.parent.kind === 261 /* InterfaceDeclaration */ ) return grammarErrorOnNode(accessor.body, Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); + if (accessor.parent.kind === 187 /* TypeLiteral */ || accessor.parent.kind === 264 /* InterfaceDeclaration */ ) return grammarErrorOnNode(accessor.body, Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); } if (accessor.typeParameters) return grammarErrorOnNode(accessor.name, Diagnostics.An_accessor_cannot_have_type_parameters); - if (!doesAccessorHaveCorrectParameterCount(accessor)) return grammarErrorOnNode(accessor.name, accessor.kind === 174 /* GetAccessor */ ? Diagnostics.A_get_accessor_cannot_have_parameters : Diagnostics.A_set_accessor_must_have_exactly_one_parameter); - if (accessor.kind === 175 /* SetAccessor */ ) { + if (!doesAccessorHaveCorrectParameterCount(accessor)) return grammarErrorOnNode(accessor.name, accessor.kind === 177 /* GetAccessor */ ? Diagnostics.A_get_accessor_cannot_have_parameters : Diagnostics.A_set_accessor_must_have_exactly_one_parameter); + if (accessor.kind === 178 /* SetAccessor */ ) { if (accessor.type) return grammarErrorOnNode(accessor.name, Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); const parameter = Debug.checkDefined(getSetAccessorValueParameter(accessor), "Return value does not match parameter count assertion."); if (parameter.dotDotDotToken) return grammarErrorOnNode(parameter.dotDotDotToken, Diagnostics.A_set_accessor_cannot_have_rest_parameter); @@ -71716,37 +72553,37 @@ ${lanes.join("\n")} return false; } function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 174 /* GetAccessor */ ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 177 /* GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 174 /* GetAccessor */ ? 1 : 2)) return getThisParameter(accessor); + if (accessor.parameters.length === (accessor.kind === 177 /* GetAccessor */ ? 1 : 2)) return getThisParameter(accessor); } function checkGrammarTypeOperatorNode(node) { - if (node.operator === 156 /* UniqueKeyword */ ) { - if (node.type.kind !== 153 /* SymbolKeyword */ ) return grammarErrorOnNode(node.type, Diagnostics._0_expected, tokenToString(153 /* SymbolKeyword */ )); + if (node.operator === 158 /* UniqueKeyword */ ) { + if (node.type.kind !== 155 /* SymbolKeyword */ ) return grammarErrorOnNode(node.type, Diagnostics._0_expected, tokenToString(155 /* SymbolKeyword */ )); let parent2 = walkUpParenthesizedTypes(node.parent); if (isInJSFile(parent2) && isJSDocTypeExpression(parent2)) { const host2 = getJSDocHost(parent2); if (host2) parent2 = getSingleVariableOfVariableStatement(host2) || host2; } switch(parent2.kind){ - case 257 /* VariableDeclaration */ : + case 260 /* VariableDeclaration */ : const decl = parent2; - if (decl.name.kind !== 79 /* Identifier */ ) return grammarErrorOnNode(node, Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); + if (decl.name.kind !== 80 /* Identifier */ ) return grammarErrorOnNode(node, Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); if (!isVariableDeclarationInVariableStatement(decl)) return grammarErrorOnNode(node, Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement); if (!(decl.parent.flags & 2 /* Const */ )) return grammarErrorOnNode(parent2.name, Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); break; - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : if (!isStatic(parent2) || !hasEffectiveReadonlyModifier(parent2)) return grammarErrorOnNode(parent2.name, Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); break; - case 168 /* PropertySignature */ : + case 171 /* PropertySignature */ : if (!hasSyntacticModifier(parent2, 64 /* Readonly */ )) return grammarErrorOnNode(parent2.name, Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); break; default: return grammarErrorOnNode(node, Diagnostics.unique_symbol_types_are_not_allowed_here); } - } else if (node.operator === 146 /* ReadonlyKeyword */ ) { - if (node.type.kind !== 185 /* ArrayType */ && node.type.kind !== 186 /* TupleType */ ) return grammarErrorOnFirstToken(node, Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, tokenToString(153 /* SymbolKeyword */ )); + } else if (node.operator === 148 /* ReadonlyKeyword */ ) { + if (node.type.kind !== 188 /* ArrayType */ && node.type.kind !== 189 /* TupleType */ ) return grammarErrorOnFirstToken(node, Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, tokenToString(155 /* SymbolKeyword */ )); } } function checkGrammarForInvalidDynamicName(node, message) { @@ -71754,9 +72591,9 @@ ${lanes.join("\n")} } function checkGrammarMethod(node) { if (checkGrammarFunctionLikeDeclaration(node)) return true; - if (node.kind === 171 /* MethodDeclaration */ ) { - if (node.parent.kind === 207 /* ObjectLiteralExpression */ ) { - if (node.modifiers && !(node.modifiers.length === 1 && first(node.modifiers).kind === 132 /* AsyncKeyword */ )) return grammarErrorOnFirstToken(node, Diagnostics.Modifiers_cannot_appear_here); + if (node.kind === 174 /* MethodDeclaration */ ) { + if (node.parent.kind === 210 /* ObjectLiteralExpression */ ) { + if (node.modifiers && !(node.modifiers.length === 1 && first(node.modifiers).kind === 134 /* AsyncKeyword */ )) return grammarErrorOnFirstToken(node, Diagnostics.Modifiers_cannot_appear_here); else if (checkGrammarForInvalidQuestionMark(node.questionToken, Diagnostics.An_object_member_cannot_be_declared_optional)) return true; else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) return true; else if (node.body === void 0) return grammarErrorAtPos(node, node.end - 1, 1, Diagnostics._0_expected, "{"); @@ -71765,37 +72602,37 @@ ${lanes.join("\n")} } if (isClassLike(node.parent)) { if (languageVersion < 2 /* ES2015 */ && isPrivateIdentifier(node.name)) return grammarErrorOnNode(node.name, Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); - if (node.flags & 16777216 /* Ambient */ ) return checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); - else if (node.kind === 171 /* MethodDeclaration */ && !node.body) return checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); - } else if (node.parent.kind === 261 /* InterfaceDeclaration */ ) return checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); - else if (node.parent.kind === 184 /* TypeLiteral */ ) return checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + if (node.flags & 33554432 /* Ambient */ ) return checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + else if (node.kind === 174 /* MethodDeclaration */ && !node.body) return checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } else if (node.parent.kind === 264 /* InterfaceDeclaration */ ) return checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + else if (node.parent.kind === 187 /* TypeLiteral */ ) return checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } function checkGrammarBreakOrContinueStatement(node) { let current = node; while(current){ if (isFunctionLikeOrClassStaticBlockDeclaration(current)) return grammarErrorOnNode(node, Diagnostics.Jump_target_cannot_cross_function_boundary); switch(current.kind){ - case 253 /* LabeledStatement */ : + case 256 /* LabeledStatement */ : if (node.label && current.label.escapedText === node.label.escapedText) { - const isMisplacedContinueLabel = node.kind === 248 /* ContinueStatement */ && !isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); + const isMisplacedContinueLabel = node.kind === 251 /* ContinueStatement */ && !isIterationStatement(current.statement, /*lookInLabeledStatements*/ true); if (isMisplacedContinueLabel) return grammarErrorOnNode(node, Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); return false; } break; - case 252 /* SwitchStatement */ : - if (node.kind === 249 /* BreakStatement */ && !node.label) return false; + case 255 /* SwitchStatement */ : + if (node.kind === 252 /* BreakStatement */ && !node.label) return false; break; default: - if (isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) return false; + if (isIterationStatement(current, /*lookInLabeledStatements*/ false) && !node.label) return false; break; } current = current.parent; } if (node.label) { - const message = node.kind === 249 /* BreakStatement */ ? Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; + const message = node.kind === 252 /* BreakStatement */ ? Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - const message = node.kind === 249 /* BreakStatement */ ? Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; + const message = node.kind === 252 /* BreakStatement */ ? Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } } @@ -71809,10 +72646,10 @@ ${lanes.join("\n")} if (node.dotDotDotToken && node.initializer) return grammarErrorAtPos(node, node.initializer.pos - 1, 1, Diagnostics.A_rest_element_cannot_have_an_initializer); } function isStringOrNumberLiteralExpression(expr) { - return isStringOrNumericLiteralLike(expr) || expr.kind === 221 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */ ; + return isStringOrNumericLiteralLike(expr) || expr.kind === 224 /* PrefixUnaryExpression */ && expr.operator === 41 /* MinusToken */ && expr.operand.kind === 9 /* NumericLiteral */ ; } function isBigIntLiteralExpression(expr) { - return expr.kind === 9 /* BigIntLiteral */ || expr.kind === 221 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ && expr.operand.kind === 9 /* BigIntLiteral */ ; + return expr.kind === 10 /* BigIntLiteral */ || expr.kind === 224 /* PrefixUnaryExpression */ && expr.operator === 41 /* MinusToken */ && expr.operand.kind === 10 /* BigIntLiteral */ ; } function isSimpleLiteralEnumReference(expr) { if ((isPropertyAccessExpression(expr) || isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression)) && isEntityNameExpression(expr.expression)) return !!(checkExpressionCached(expr).flags & 1056 /* EnumLike */ ); @@ -71820,31 +72657,45 @@ ${lanes.join("\n")} function checkAmbientInitializer(node) { const initializer = node.initializer; if (initializer) { - const isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) || isSimpleLiteralEnumReference(initializer) || initializer.kind === 110 /* TrueKeyword */ || initializer.kind === 95 /* FalseKeyword */ || isBigIntLiteralExpression(initializer)); - const isConstOrReadonly = isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConst(node); + const isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) || isSimpleLiteralEnumReference(initializer) || initializer.kind === 112 /* TrueKeyword */ || initializer.kind === 97 /* FalseKeyword */ || isBigIntLiteralExpression(initializer)); + const isConstOrReadonly = isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConstLike(node); if (isConstOrReadonly && !node.type) { if (isInvalidInitializer) return grammarErrorOnNode(initializer, Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); } else return grammarErrorOnNode(initializer, Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 246 /* ForInStatement */ && node.parent.parent.kind !== 247 /* ForOfStatement */ ) { - if (node.flags & 16777216 /* Ambient */ ) checkAmbientInitializer(node); + const nodeFlags = getCombinedNodeFlagsCached(node); + const blockScopeKind = nodeFlags & 7 /* BlockScoped */ ; + if (isBindingPattern(node.name)) switch(blockScopeKind){ + case 6 /* AwaitUsing */ : + return grammarErrorOnNode(node, Diagnostics._0_declarations_may_not_have_binding_patterns, "await using"); + case 4 /* Using */ : + return grammarErrorOnNode(node, Diagnostics._0_declarations_may_not_have_binding_patterns, "using"); + } + if (node.parent.parent.kind !== 249 /* ForInStatement */ && node.parent.parent.kind !== 250 /* ForOfStatement */ ) { + if (nodeFlags & 33554432 /* Ambient */ ) checkAmbientInitializer(node); else if (!node.initializer) { if (isBindingPattern(node.name) && !isBindingPattern(node.parent)) return grammarErrorOnNode(node, Diagnostics.A_destructuring_declaration_must_have_an_initializer); - if (isVarConst(node)) return grammarErrorOnNode(node, Diagnostics.const_declarations_must_be_initialized); + switch(blockScopeKind){ + case 6 /* AwaitUsing */ : + return grammarErrorOnNode(node, Diagnostics._0_declarations_must_be_initialized, "await using"); + case 4 /* Using */ : + return grammarErrorOnNode(node, Diagnostics._0_declarations_must_be_initialized, "using"); + case 2 /* Const */ : + return grammarErrorOnNode(node, Diagnostics._0_declarations_must_be_initialized, "const"); + } } } - if (node.exclamationToken && (node.parent.parent.kind !== 240 /* VariableStatement */ || !node.type || node.initializer || node.flags & 16777216 /* Ambient */ )) { + if (node.exclamationToken && (node.parent.parent.kind !== 243 /* VariableStatement */ || !node.type || node.initializer || nodeFlags & 33554432 /* Ambient */ )) { const message = node.initializer ? Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions : !node.type ? Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations : Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context; return grammarErrorOnNode(node.exclamationToken, message); } - if ((moduleKind < 5 /* ES2015 */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */ ) && moduleKind !== 4 /* System */ && !(node.parent.parent.flags & 16777216 /* Ambient */ ) && hasSyntacticModifier(node.parent.parent, 1 /* Export */ )) checkESModuleMarker(node.name); - const checkLetConstNames = isLet(node) || isVarConst(node); - return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); + if ((moduleKind < 5 /* ES2015 */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */ ) && moduleKind !== 4 /* System */ && !(node.parent.parent.flags & 33554432 /* Ambient */ ) && hasSyntacticModifier(node.parent.parent, 1 /* Export */ )) checkESModuleMarker(node.name); + return !!blockScopeKind && checkGrammarNameInLetOrConstDeclarations(node.name); } function checkESModuleMarker(name) { - if (name.kind === 79 /* Identifier */ ) { + if (name.kind === 80 /* Identifier */ ) { if (idText(name) === "__esModule") return grammarErrorOnNodeSkippedOn("noEmit", name, Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); } else { const elements = name.elements; @@ -71855,7 +72706,7 @@ ${lanes.join("\n")} return false; } function checkGrammarNameInLetOrConstDeclarations(name) { - if (name.kind === 79 /* Identifier */ ) { + if (name.kind === 80 /* Identifier */ ) { if (name.escapedText === "let") return grammarErrorOnNode(name, Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } else { const elements = name.elements; @@ -71867,72 +72718,78 @@ ${lanes.join("\n")} const declarations = declarationList.declarations; if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) return true; if (!declarationList.declarations.length) return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, Diagnostics.Variable_declaration_list_cannot_be_empty); + const blockScopeFlags = declarationList.flags & 7 /* BlockScoped */ ; + if ((blockScopeFlags === 4 /* Using */ || blockScopeFlags === 6 /* AwaitUsing */ ) && isForInStatement(declarationList.parent)) return grammarErrorOnNode(declarationList, blockScopeFlags === 4 /* Using */ ? Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration : Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration); + if (blockScopeFlags === 6 /* AwaitUsing */ ) return checkAwaitGrammar(declarationList); return false; } function allowLetAndConstDeclarations(parent2) { switch(parent2.kind){ - case 242 /* IfStatement */ : - case 243 /* DoStatement */ : - case 244 /* WhileStatement */ : - case 251 /* WithStatement */ : - case 245 /* ForStatement */ : - case 246 /* ForInStatement */ : - case 247 /* ForOfStatement */ : + case 245 /* IfStatement */ : + case 246 /* DoStatement */ : + case 247 /* WhileStatement */ : + case 254 /* WithStatement */ : + case 248 /* ForStatement */ : + case 249 /* ForInStatement */ : + case 250 /* ForOfStatement */ : return false; - case 253 /* LabeledStatement */ : + case 256 /* LabeledStatement */ : return allowLetAndConstDeclarations(parent2.parent); } return true; } - function checkGrammarForDisallowedLetOrConstStatement(node) { + function checkGrammarForDisallowedBlockScopedVariableStatement(node) { if (!allowLetAndConstDeclarations(node.parent)) { - if (isLet(node.declarationList)) return grammarErrorOnNode(node, Diagnostics.let_declarations_can_only_be_declared_inside_a_block); - else if (isVarConst(node.declarationList)) return grammarErrorOnNode(node, Diagnostics.const_declarations_can_only_be_declared_inside_a_block); + const blockScopeKind = getCombinedNodeFlagsCached(node.declarationList) & 7 /* BlockScoped */ ; + if (blockScopeKind) { + const keyword = blockScopeKind === 1 /* Let */ ? "let" : blockScopeKind === 2 /* Const */ ? "const" : blockScopeKind === 4 /* Using */ ? "using" : blockScopeKind === 6 /* AwaitUsing */ ? "await using" : Debug.fail("Unknown BlockScope flag"); + return grammarErrorOnNode(node, Diagnostics._0_declarations_can_only_be_declared_inside_a_block, keyword); + } } } function checkGrammarMetaProperty(node) { const escapedText = node.name.escapedText; switch(node.keywordToken){ - case 103 /* NewKeyword */ : - if (escapedText !== "target") return grammarErrorOnNode(node.name, Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, tokenToString(node.keywordToken), "target"); + case 105 /* NewKeyword */ : + if (escapedText !== "target") return grammarErrorOnNode(node.name, Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, unescapeLeadingUnderscores(node.name.escapedText), tokenToString(node.keywordToken), "target"); break; - case 100 /* ImportKeyword */ : - if (escapedText !== "meta") return grammarErrorOnNode(node.name, Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, tokenToString(node.keywordToken), "meta"); + case 102 /* ImportKeyword */ : + if (escapedText !== "meta") return grammarErrorOnNode(node.name, Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, unescapeLeadingUnderscores(node.name.escapedText), tokenToString(node.keywordToken), "meta"); break; } } function hasParseDiagnostics(sourceFile) { return sourceFile.parseDiagnostics.length > 0; } - function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { + function grammarErrorOnFirstToken(node, message, ...args) { const sourceFile = getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { const span = getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); + diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, message, ...args)); return true; } return false; } - function grammarErrorAtPos(nodeForSourceFile, start, length2, message, arg0, arg1, arg2) { + function grammarErrorAtPos(nodeForSourceFile, start, length2, message, ...args) { const sourceFile = getSourceFileOfNode(nodeForSourceFile); if (!hasParseDiagnostics(sourceFile)) { - diagnostics.add(createFileDiagnostic(sourceFile, start, length2, message, arg0, arg1, arg2)); + diagnostics.add(createFileDiagnostic(sourceFile, start, length2, message, ...args)); return true; } return false; } - function grammarErrorOnNodeSkippedOn(key, node, message, arg0, arg1, arg2) { + function grammarErrorOnNodeSkippedOn(key, node, message, ...args) { const sourceFile = getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - errorSkippedOn(key, node, message, arg0, arg1, arg2); + errorSkippedOn(key, node, message, ...args); return true; } return false; } - function grammarErrorOnNode(node, message, arg0, arg1, arg2) { + function grammarErrorOnNode(node, message, ...args) { const sourceFile = getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - diagnostics.add(createDiagnosticForNode(node, message, arg0, arg1, arg2)); + diagnostics.add(createDiagnosticForNode(node, message, ...args)); return true; } return false; @@ -71950,14 +72807,14 @@ ${lanes.join("\n")} if (type) return grammarErrorOnNode(type, Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); } function checkGrammarProperty(node) { - if (isComputedPropertyName(node.name) && isBinaryExpression(node.name.expression) && node.name.expression.operatorToken.kind === 101 /* InKeyword */ ) return grammarErrorOnNode(node.parent.members[0], Diagnostics.A_mapped_type_may_not_declare_properties_or_methods); + if (isComputedPropertyName(node.name) && isBinaryExpression(node.name.expression) && node.name.expression.operatorToken.kind === 103 /* InKeyword */ ) return grammarErrorOnNode(node.parent.members[0], Diagnostics.A_mapped_type_may_not_declare_properties_or_methods); if (isClassLike(node.parent)) { if (isStringLiteral(node.name) && node.name.text === "constructor") return grammarErrorOnNode(node.name, Diagnostics.Classes_may_not_have_a_field_named_constructor); if (checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_symbol_type)) return true; if (languageVersion < 2 /* ES2015 */ && isPrivateIdentifier(node.name)) return grammarErrorOnNode(node.name, Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); if (languageVersion < 2 /* ES2015 */ && isAutoAccessorPropertyDeclaration(node)) return grammarErrorOnNode(node.name, Diagnostics.Properties_with_the_accessor_modifier_are_only_available_when_targeting_ECMAScript_2015_and_higher); if (isAutoAccessorPropertyDeclaration(node) && checkGrammarForInvalidQuestionMark(node.questionToken, Diagnostics.An_accessor_property_cannot_be_declared_optional)) return true; - } else if (node.parent.kind === 261 /* InterfaceDeclaration */ ) { + } else if (node.parent.kind === 264 /* InterfaceDeclaration */ ) { if (checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) return true; Debug.assertNode(node, isPropertySignature); if (node.initializer) return grammarErrorOnNode(node.initializer, Diagnostics.An_interface_property_cannot_have_an_initializer); @@ -71966,30 +72823,30 @@ ${lanes.join("\n")} Debug.assertNode(node, isPropertySignature); if (node.initializer) return grammarErrorOnNode(node.initializer, Diagnostics.A_type_literal_property_cannot_have_an_initializer); } - if (node.flags & 16777216 /* Ambient */ ) checkAmbientInitializer(node); - if (isPropertyDeclaration(node) && node.exclamationToken && (!isClassLike(node.parent) || !node.type || node.initializer || node.flags & 16777216 /* Ambient */ || isStatic(node) || hasAbstractModifier(node))) { + if (node.flags & 33554432 /* Ambient */ ) checkAmbientInitializer(node); + if (isPropertyDeclaration(node) && node.exclamationToken && (!isClassLike(node.parent) || !node.type || node.initializer || node.flags & 33554432 /* Ambient */ || isStatic(node) || hasAbstractModifier(node))) { const message = node.initializer ? Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions : !node.type ? Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations : Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context; return grammarErrorOnNode(node.exclamationToken, message); } } function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - if (node.kind === 261 /* InterfaceDeclaration */ || node.kind === 262 /* TypeAliasDeclaration */ || node.kind === 269 /* ImportDeclaration */ || node.kind === 268 /* ImportEqualsDeclaration */ || node.kind === 275 /* ExportDeclaration */ || node.kind === 274 /* ExportAssignment */ || node.kind === 267 /* NamespaceExportDeclaration */ || hasSyntacticModifier(node, 1027 /* Default */ )) return false; + if (node.kind === 264 /* InterfaceDeclaration */ || node.kind === 265 /* TypeAliasDeclaration */ || node.kind === 272 /* ImportDeclaration */ || node.kind === 271 /* ImportEqualsDeclaration */ || node.kind === 278 /* ExportDeclaration */ || node.kind === 277 /* ExportAssignment */ || node.kind === 270 /* NamespaceExportDeclaration */ || hasSyntacticModifier(node, 1027 /* Default */ )) return false; return grammarErrorOnFirstToken(node, Diagnostics.Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier); } function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { - for (const decl of file.statements)if (isDeclaration(decl) || decl.kind === 240 /* VariableStatement */ ) { + for (const decl of file.statements)if (isDeclaration(decl) || decl.kind === 243 /* VariableStatement */ ) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) return true; } return false; } function checkGrammarSourceFile(node) { - return !!(node.flags & 16777216 /* Ambient */ ) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); + return !!(node.flags & 33554432 /* Ambient */ ) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); } function checkGrammarStatementInAmbientContext(node) { - if (node.flags & 16777216 /* Ambient */ ) { + if (node.flags & 33554432 /* Ambient */ ) { const links = getNodeLinks(node); if (!links.hasReportedStatementInAmbientContext && (isFunctionLike(node.parent) || isAccessor(node.parent))) return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); - if (node.parent.kind === 238 /* Block */ || node.parent.kind === 265 /* ModuleBlock */ || node.parent.kind === 308 /* SourceFile */ ) { + if (node.parent.kind === 241 /* Block */ || node.parent.kind === 268 /* ModuleBlock */ || node.parent.kind === 312 /* SourceFile */ ) { const links2 = getNodeLinks(node.parent); if (!links2.hasReportedStatementInAmbientContext) return links2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, Diagnostics.Statements_are_not_allowed_in_ambient_contexts); } @@ -71997,21 +72854,6 @@ ${lanes.join("\n")} return false; } function checkGrammarNumericLiteral(node) { - if (node.numericLiteralFlags & 32 /* Octal */ ) { - let diagnosticMessage; - if (languageVersion >= 1 /* ES5 */ ) diagnosticMessage = Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; - else if (isChildOfNodeWithKind(node, 198 /* LiteralType */ )) diagnosticMessage = Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; - else if (isChildOfNodeWithKind(node, 302 /* EnumMember */ )) diagnosticMessage = Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; - if (diagnosticMessage) { - const withMinus = isPrefixUnaryExpression(node.parent) && node.parent.operator === 40 /* MinusToken */ ; - const literal = (withMinus ? "-" : "") + "0o" + node.text; - return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); - } - } - checkNumericLiteralValueSize(node); - return false; - } - function checkNumericLiteralValueSize(node) { const isFractional = getTextOfNode(node).indexOf(".") !== -1; const isScientific = node.numericLiteralFlags & 16 /* Scientific */ ; if (isFractional || isScientific) return; @@ -72028,11 +72870,11 @@ ${lanes.join("\n")} } return false; } - function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { + function grammarErrorAfterFirstToken(node, message, ...args) { const sourceFile = getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { const span = getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(createFileDiagnostic(sourceFile, textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2)); + diagnostics.add(createFileDiagnostic(sourceFile, textSpanEnd(span), /*length*/ 0, message, ...args)); return true; } return false; @@ -72047,14 +72889,14 @@ ${lanes.join("\n")} return ambientModulesCache; } function checkGrammarImportClause(node) { - var _a2; + var _a; if (node.isTypeOnly && node.name && node.namedBindings) return grammarErrorOnNode(node, Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both); - if (node.isTypeOnly && ((_a2 = node.namedBindings) == null ? void 0 : _a2.kind) === 272 /* NamedImports */ ) return checkGrammarNamedImportsOrExports(node.namedBindings); + if (node.isTypeOnly && ((_a = node.namedBindings) == null ? void 0 : _a.kind) === 275 /* NamedImports */ ) return checkGrammarNamedImportsOrExports(node.namedBindings); return false; } function checkGrammarNamedImportsOrExports(namedBindings) { return !!forEach(namedBindings.elements, (specifier)=>{ - if (specifier.isTypeOnly) return grammarErrorOnFirstToken(specifier, specifier.kind === 273 /* ImportSpecifier */ ? Diagnostics.The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement : Diagnostics.The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement); + if (specifier.isTypeOnly) return grammarErrorOnFirstToken(specifier, specifier.kind === 276 /* ImportSpecifier */ ? Diagnostics.The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement : Diagnostics.The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement); }); } function checkGrammarImportCallExpression(node) { @@ -72116,37 +72958,60 @@ ${lanes.join("\n")} } function filterPrimitivesIfContainsNonPrimitive(type) { if (maybeTypeOfKind(type, 67108864 /* NonPrimitive */ )) { - const result = filterType(type, (t)=>!(t.flags & 134348796 /* Primitive */ )); + const result = filterType(type, (t)=>!(t.flags & 402784252 /* Primitive */ )); if (!(result.flags & 131072 /* Never */ )) return result; } return type; } - function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) { + function findMatchingDiscriminantType(source, target, isRelatedTo) { if (target.flags & 1048576 /* Union */ && source.flags & 2621440 /* Object */ ) { const match = getMatchingUnionConstituentForType(target, source); if (match) return match; const sourceProperties = getPropertiesOfType(source); if (sourceProperties) { const sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); - if (sourcePropertiesFiltered) return discriminateTypeByDiscriminableItems(target, map(sourcePropertiesFiltered, (p)=>[ - ()=>getTypeOfSymbol(p), - p.escapedName - ]), isRelatedTo, /*defaultValue*/ void 0, skipPartial); + if (sourcePropertiesFiltered) { + const discriminated = discriminateTypeByDiscriminableItems(target, map(sourcePropertiesFiltered, (p)=>[ + ()=>getTypeOfSymbol(p), + p.escapedName + ]), isRelatedTo); + if (discriminated !== target) return discriminated; + } } } return void 0; } + function getEffectivePropertyNameForPropertyNameNode(node) { + const name = getPropertyNameForPropertyNameNode(node); + return name ? name : isComputedPropertyName(node) && isEntityNameExpression(node.expression) ? tryGetNameFromEntityNameExpression(node.expression) : void 0; + } + function getCombinedModifierFlagsCached(node) { + if (lastGetCombinedModifierFlagsNode === node) return lastGetCombinedModifierFlagsResult; + lastGetCombinedModifierFlagsNode = node; + lastGetCombinedModifierFlagsResult = getCombinedModifierFlags(node); + return lastGetCombinedModifierFlagsResult; + } + function getCombinedNodeFlagsCached(node) { + if (lastGetCombinedNodeFlagsNode === node) return lastGetCombinedNodeFlagsResult; + lastGetCombinedNodeFlagsNode = node; + lastGetCombinedNodeFlagsResult = getCombinedNodeFlags(node); + return lastGetCombinedNodeFlagsResult; + } + function isVarConstLike(node) { + const blockScopeKind = getCombinedNodeFlagsCached(node) & 7 /* BlockScoped */ ; + return blockScopeKind === 2 /* Const */ || blockScopeKind === 4 /* Using */ || blockScopeKind === 6 /* AwaitUsing */ ; + } } function isNotAccessor(declaration) { return !isAccessor(declaration); } function isNotOverload(declaration) { - return declaration.kind !== 259 /* FunctionDeclaration */ && declaration.kind !== 171 /* MethodDeclaration */ || !!declaration.body; + return declaration.kind !== 262 /* FunctionDeclaration */ && declaration.kind !== 174 /* MethodDeclaration */ || !!declaration.body; } function isDeclarationNameOrImportPropertyName(name) { switch(name.parent.kind){ - case 273 /* ImportSpecifier */ : - case 278 /* ExportSpecifier */ : + case 276 /* ImportSpecifier */ : + case 281 /* ExportSpecifier */ : return isIdentifier(name); default: return isDeclarationName(name); @@ -72174,8 +73039,8 @@ ${lanes.join("\n")} getCurrentDirectory: ()=>host.getCurrentDirectory(), getSymlinkCache: maybeBind(host, host.getSymlinkCache), getPackageJsonInfoCache: ()=>{ - var _a2; - return (_a2 = host.getPackageJsonInfoCache) == null ? void 0 : _a2.call(host); + var _a; + return (_a = host.getPackageJsonInfoCache) == null ? void 0 : _a.call(host); }, useCaseSensitiveFileNames: maybeBind(host, host.useCaseSensitiveFileNames), redirectTargetsMap: host.redirectTargetsMap, @@ -72297,6 +73162,7 @@ ${lanes.join("\n")} CheckMode3[CheckMode3["IsForSignatureHelp"] = 16] = "IsForSignatureHelp"; CheckMode3[CheckMode3["IsForStringLiteralArgumentCompletions"] = 32] = "IsForStringLiteralArgumentCompletions"; CheckMode3[CheckMode3["RestBindingElement"] = 64] = "RestBindingElement"; + CheckMode3[CheckMode3["TypeOnly"] = 128] = "TypeOnly"; return CheckMode3; })(CheckMode || {}); SignatureCheckMode = /* @__PURE__ */ ((SignatureCheckMode3)=>{ @@ -72325,25 +73191,26 @@ ${lanes.join("\n")} JsxNames2.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; JsxNames2.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute"; JsxNames2.Element = "Element"; + JsxNames2.ElementType = "ElementType"; JsxNames2.IntrinsicAttributes = "IntrinsicAttributes"; JsxNames2.IntrinsicClassAttributes = "IntrinsicClassAttributes"; JsxNames2.LibraryManagedAttributes = "LibraryManagedAttributes"; })(JsxNames || (JsxNames = {})); - SymbolTrackerImpl = class { + SymbolTrackerImpl = class _SymbolTrackerImpl { constructor(context, tracker, moduleResolverHost){ this.moduleResolverHost = void 0; this.inner = void 0; this.disableTrackSymbol = false; - var _a2; - while(tracker instanceof SymbolTrackerImpl)tracker = tracker.inner; + var _a; + while(tracker instanceof _SymbolTrackerImpl)tracker = tracker.inner; this.inner = tracker; this.moduleResolverHost = moduleResolverHost; this.context = context; - this.canTrackSymbol = !!((_a2 = this.inner) == null ? void 0 : _a2.trackSymbol); + this.canTrackSymbol = !!((_a = this.inner) == null ? void 0 : _a.trackSymbol); } trackSymbol(symbol, enclosingDeclaration, meaning) { - var _a2; - if (((_a2 = this.inner) == null ? void 0 : _a2.trackSymbol) && !this.disableTrackSymbol) { + var _a; + if (((_a = this.inner) == null ? void 0 : _a.trackSymbol) && !this.disableTrackSymbol) { if (this.inner.trackSymbol(symbol, enclosingDeclaration, meaning)) { this.onDiagnosticReported(); return true; @@ -72352,78 +73219,78 @@ ${lanes.join("\n")} return false; } reportInaccessibleThisError() { - var _a2; - if ((_a2 = this.inner) == null ? void 0 : _a2.reportInaccessibleThisError) { + var _a; + if ((_a = this.inner) == null ? void 0 : _a.reportInaccessibleThisError) { this.onDiagnosticReported(); this.inner.reportInaccessibleThisError(); } } reportPrivateInBaseOfClassExpression(propertyName) { - var _a2; - if ((_a2 = this.inner) == null ? void 0 : _a2.reportPrivateInBaseOfClassExpression) { + var _a; + if ((_a = this.inner) == null ? void 0 : _a.reportPrivateInBaseOfClassExpression) { this.onDiagnosticReported(); this.inner.reportPrivateInBaseOfClassExpression(propertyName); } } reportInaccessibleUniqueSymbolError() { - var _a2; - if ((_a2 = this.inner) == null ? void 0 : _a2.reportInaccessibleUniqueSymbolError) { + var _a; + if ((_a = this.inner) == null ? void 0 : _a.reportInaccessibleUniqueSymbolError) { this.onDiagnosticReported(); this.inner.reportInaccessibleUniqueSymbolError(); } } reportCyclicStructureError() { - var _a2; - if ((_a2 = this.inner) == null ? void 0 : _a2.reportCyclicStructureError) { + var _a; + if ((_a = this.inner) == null ? void 0 : _a.reportCyclicStructureError) { this.onDiagnosticReported(); this.inner.reportCyclicStructureError(); } } reportLikelyUnsafeImportRequiredError(specifier) { - var _a2; - if ((_a2 = this.inner) == null ? void 0 : _a2.reportLikelyUnsafeImportRequiredError) { + var _a; + if ((_a = this.inner) == null ? void 0 : _a.reportLikelyUnsafeImportRequiredError) { this.onDiagnosticReported(); this.inner.reportLikelyUnsafeImportRequiredError(specifier); } } reportTruncationError() { - var _a2; - if ((_a2 = this.inner) == null ? void 0 : _a2.reportTruncationError) { + var _a; + if ((_a = this.inner) == null ? void 0 : _a.reportTruncationError) { this.onDiagnosticReported(); this.inner.reportTruncationError(); } } trackReferencedAmbientModule(decl, symbol) { - var _a2; - if ((_a2 = this.inner) == null ? void 0 : _a2.trackReferencedAmbientModule) { + var _a; + if ((_a = this.inner) == null ? void 0 : _a.trackReferencedAmbientModule) { this.onDiagnosticReported(); this.inner.trackReferencedAmbientModule(decl, symbol); } } trackExternalModuleSymbolOfImportTypeNode(symbol) { - var _a2; - if ((_a2 = this.inner) == null ? void 0 : _a2.trackExternalModuleSymbolOfImportTypeNode) { + var _a; + if ((_a = this.inner) == null ? void 0 : _a.trackExternalModuleSymbolOfImportTypeNode) { this.onDiagnosticReported(); this.inner.trackExternalModuleSymbolOfImportTypeNode(symbol); } } reportNonlocalAugmentation(containingFile, parentSymbol, augmentingSymbol) { - var _a2; - if ((_a2 = this.inner) == null ? void 0 : _a2.reportNonlocalAugmentation) { + var _a; + if ((_a = this.inner) == null ? void 0 : _a.reportNonlocalAugmentation) { this.onDiagnosticReported(); this.inner.reportNonlocalAugmentation(containingFile, parentSymbol, augmentingSymbol); } } reportNonSerializableProperty(propertyName) { - var _a2; - if ((_a2 = this.inner) == null ? void 0 : _a2.reportNonSerializableProperty) { + var _a; + if ((_a = this.inner) == null ? void 0 : _a.reportNonSerializableProperty) { this.onDiagnosticReported(); this.inner.reportNonSerializableProperty(propertyName); } } reportImportTypeNodeResolutionModeOverride() { - var _a2; - if ((_a2 = this.inner) == null ? void 0 : _a2.reportImportTypeNodeResolutionModeOverride) { + var _a; + if ((_a = this.inner) == null ? void 0 : _a.reportImportTypeNodeResolutionModeOverride) { this.onDiagnosticReported(); this.inner.reportImportTypeNodeResolutionModeOverride(); } @@ -72537,7 +73404,7 @@ ${lanes.join("\n")} return parameter.dotDotDotToken ? parameter : isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) : parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) : parameter; } function addDefaultValueAssignmentForBindingPattern(parameter, context) { - const { factory: factory2 } = context; + const { factory: factory2 } = context; context.addInitializationStatement(factory2.createVariableStatement(/*modifiers*/ void 0, factory2.createVariableDeclarationList([ factory2.createVariableDeclaration(parameter.name, /*exclamationToken*/ void 0, parameter.type, parameter.initializer ? factory2.createConditionalExpression(factory2.createStrictEquality(factory2.getGeneratedNameForNode(parameter), factory2.createVoidZero()), /*questionToken*/ void 0, parameter.initializer, /*colonToken*/ void 0, factory2.getGeneratedNameForNode(parameter)) : factory2.getGeneratedNameForNode(parameter)) ]))); @@ -72602,424 +73469,426 @@ ${lanes.join("\n")} "use strict"; init_ts2(); visitEachChildTable = { - [163 /* QualifiedName */ ]: function visitEachChildOfQualifiedName(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [166 /* QualifiedName */ ]: function visitEachChildOfQualifiedName(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateQualifiedName(node, Debug.checkDefined(nodeVisitor(node.left, visitor, isEntityName)), Debug.checkDefined(nodeVisitor(node.right, visitor, isIdentifier))); }, - [164 /* ComputedPropertyName */ ]: function visitEachChildOfComputedPropertyName(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [167 /* ComputedPropertyName */ ]: function visitEachChildOfComputedPropertyName(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateComputedPropertyName(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, // Signature elements - [165 /* TypeParameter */ ]: function visitEachChildOfTypeParameterDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [168 /* TypeParameter */ ]: function visitEachChildOfTypeParameterDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateTypeParameterDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifier), Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), nodeVisitor(node.constraint, visitor, isTypeNode), nodeVisitor(node.default, visitor, isTypeNode)); }, - [166 /* Parameter */ ]: function visitEachChildOfParameterDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + [169 /* Parameter */ ]: function visitEachChildOfParameterDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { return context.factory.updateParameterDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), tokenVisitor ? nodeVisitor(node.dotDotDotToken, tokenVisitor, isDotDotDotToken) : node.dotDotDotToken, Debug.checkDefined(nodeVisitor(node.name, visitor, isBindingName)), tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, nodeVisitor(node.type, visitor, isTypeNode), nodeVisitor(node.initializer, visitor, isExpression)); }, - [167 /* Decorator */ ]: function visitEachChildOfDecorator(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [170 /* Decorator */ ]: function visitEachChildOfDecorator(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateDecorator(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, // Type elements - [168 /* PropertySignature */ ]: function visitEachChildOfPropertySignature(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + [171 /* PropertySignature */ ]: function visitEachChildOfPropertySignature(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { return context.factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, isModifier), Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, nodeVisitor(node.type, visitor, isTypeNode)); }, - [169 /* PropertyDeclaration */ ]: function visitEachChildOfPropertyDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { - var _a2, _b; + [172 /* PropertyDeclaration */ ]: function visitEachChildOfPropertyDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { return context.factory.updatePropertyDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), // QuestionToken and ExclamationToken are mutually exclusive in PropertyDeclaration - tokenVisitor ? nodeVisitor((_a2 = node.questionToken) != null ? _a2 : node.exclamationToken, tokenVisitor, isQuestionOrExclamationToken) : (_b = node.questionToken) != null ? _b : node.exclamationToken, nodeVisitor(node.type, visitor, isTypeNode), nodeVisitor(node.initializer, visitor, isExpression)); + tokenVisitor ? nodeVisitor(node.questionToken ?? node.exclamationToken, tokenVisitor, isQuestionOrExclamationToken) : node.questionToken ?? node.exclamationToken, nodeVisitor(node.type, visitor, isTypeNode), nodeVisitor(node.initializer, visitor, isExpression)); }, - [170 /* MethodSignature */ ]: function visitEachChildOfMethodSignature(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + [173 /* MethodSignature */ ]: function visitEachChildOfMethodSignature(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { return context.factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, isModifier), Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, isParameter), nodeVisitor(node.type, visitor, isTypeNode)); }, - [171 /* MethodDeclaration */ ]: function visitEachChildOfMethodDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + [174 /* MethodDeclaration */ ]: function visitEachChildOfMethodDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { return context.factory.updateMethodDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken, Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); }, - [173 /* Constructor */ ]: function visitEachChildOfConstructorDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [176 /* Constructor */ ]: function visitEachChildOfConstructorDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateConstructorDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); }, - [174 /* GetAccessor */ ]: function visitEachChildOfGetAccessorDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [177 /* GetAccessor */ ]: function visitEachChildOfGetAccessorDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateGetAccessorDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); }, - [175 /* SetAccessor */ ]: function visitEachChildOfSetAccessorDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [178 /* SetAccessor */ ]: function visitEachChildOfSetAccessorDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateSetAccessorDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); }, - [172 /* ClassStaticBlockDeclaration */ ]: function visitEachChildOfClassStaticBlockDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [175 /* ClassStaticBlockDeclaration */ ]: function visitEachChildOfClassStaticBlockDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { context.startLexicalEnvironment(); context.suspendLexicalEnvironment(); return context.factory.updateClassStaticBlockDeclaration(node, visitFunctionBody(node.body, visitor, context, nodeVisitor)); }, - [176 /* CallSignature */ ]: function visitEachChildOfCallSignatureDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [179 /* CallSignature */ ]: function visitEachChildOfCallSignatureDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, isParameter), nodeVisitor(node.type, visitor, isTypeNode)); }, - [177 /* ConstructSignature */ ]: function visitEachChildOfConstructSignatureDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [180 /* ConstructSignature */ ]: function visitEachChildOfConstructSignatureDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, isParameter), nodeVisitor(node.type, visitor, isTypeNode)); }, - [178 /* IndexSignature */ ]: function visitEachChildOfIndexSignatureDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [181 /* IndexSignature */ ]: function visitEachChildOfIndexSignatureDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateIndexSignature(node, nodesVisitor(node.modifiers, visitor, isModifierLike), nodesVisitor(node.parameters, visitor, isParameter), Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); }, // Types - [179 /* TypePredicate */ ]: function visitEachChildOfTypePredicateNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [182 /* TypePredicate */ ]: function visitEachChildOfTypePredicateNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateTypePredicateNode(node, nodeVisitor(node.assertsModifier, visitor, isAssertsKeyword), Debug.checkDefined(nodeVisitor(node.parameterName, visitor, isIdentifierOrThisTypeNode)), nodeVisitor(node.type, visitor, isTypeNode)); }, - [180 /* TypeReference */ ]: function visitEachChildOfTypeReferenceNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [183 /* TypeReference */ ]: function visitEachChildOfTypeReferenceNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateTypeReferenceNode(node, Debug.checkDefined(nodeVisitor(node.typeName, visitor, isEntityName)), nodesVisitor(node.typeArguments, visitor, isTypeNode)); }, - [181 /* FunctionType */ ]: function visitEachChildOfFunctionTypeNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [184 /* FunctionType */ ]: function visitEachChildOfFunctionTypeNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, isParameter), Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); }, - [182 /* ConstructorType */ ]: function visitEachChildOfConstructorTypeNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [185 /* ConstructorType */ ]: function visitEachChildOfConstructorTypeNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateConstructorTypeNode(node, nodesVisitor(node.modifiers, visitor, isModifier), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, isParameter), Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); }, - [183 /* TypeQuery */ ]: function visitEachChildOfTypeQueryNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [186 /* TypeQuery */ ]: function visitEachChildOfTypeQueryNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateTypeQueryNode(node, Debug.checkDefined(nodeVisitor(node.exprName, visitor, isEntityName)), nodesVisitor(node.typeArguments, visitor, isTypeNode)); }, - [184 /* TypeLiteral */ ]: function visitEachChildOfTypeLiteralNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + [187 /* TypeLiteral */ ]: function visitEachChildOfTypeLiteralNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { return context.factory.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, isTypeElement)); }, - [185 /* ArrayType */ ]: function visitEachChildOfArrayTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [188 /* ArrayType */ ]: function visitEachChildOfArrayTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateArrayTypeNode(node, Debug.checkDefined(nodeVisitor(node.elementType, visitor, isTypeNode))); }, - [186 /* TupleType */ ]: function visitEachChildOfTupleTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + [189 /* TupleType */ ]: function visitEachChildOfTupleTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { return context.factory.updateTupleTypeNode(node, nodesVisitor(node.elements, visitor, isTypeNode)); }, - [187 /* OptionalType */ ]: function visitEachChildOfOptionalTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [190 /* OptionalType */ ]: function visitEachChildOfOptionalTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateOptionalTypeNode(node, Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); }, - [188 /* RestType */ ]: function visitEachChildOfRestTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [191 /* RestType */ ]: function visitEachChildOfRestTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateRestTypeNode(node, Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); }, - [189 /* UnionType */ ]: function visitEachChildOfUnionTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + [192 /* UnionType */ ]: function visitEachChildOfUnionTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { return context.factory.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, isTypeNode)); }, - [190 /* IntersectionType */ ]: function visitEachChildOfIntersectionTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + [193 /* IntersectionType */ ]: function visitEachChildOfIntersectionTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { return context.factory.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, isTypeNode)); }, - [191 /* ConditionalType */ ]: function visitEachChildOfConditionalTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [194 /* ConditionalType */ ]: function visitEachChildOfConditionalTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateConditionalTypeNode(node, Debug.checkDefined(nodeVisitor(node.checkType, visitor, isTypeNode)), Debug.checkDefined(nodeVisitor(node.extendsType, visitor, isTypeNode)), Debug.checkDefined(nodeVisitor(node.trueType, visitor, isTypeNode)), Debug.checkDefined(nodeVisitor(node.falseType, visitor, isTypeNode))); }, - [192 /* InferType */ ]: function visitEachChildOfInferTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [195 /* InferType */ ]: function visitEachChildOfInferTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateInferTypeNode(node, Debug.checkDefined(nodeVisitor(node.typeParameter, visitor, isTypeParameterDeclaration))); }, - [202 /* ImportType */ ]: function visitEachChildOfImportTypeNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [205 /* ImportType */ ]: function visitEachChildOfImportTypeNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateImportTypeNode(node, Debug.checkDefined(nodeVisitor(node.argument, visitor, isTypeNode)), nodeVisitor(node.assertions, visitor, isImportTypeAssertionContainer), nodeVisitor(node.qualifier, visitor, isEntityName), nodesVisitor(node.typeArguments, visitor, isTypeNode), node.isTypeOf); }, - [298 /* ImportTypeAssertionContainer */ ]: function visitEachChildOfImportTypeAssertionContainer(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [302 /* ImportTypeAssertionContainer */ ]: function visitEachChildOfImportTypeAssertionContainer(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateImportTypeAssertionContainer(node, Debug.checkDefined(nodeVisitor(node.assertClause, visitor, isAssertClause)), node.multiLine); }, - [199 /* NamedTupleMember */ ]: function visitEachChildOfNamedTupleMember(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + [202 /* NamedTupleMember */ ]: function visitEachChildOfNamedTupleMember(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { return context.factory.updateNamedTupleMember(node, tokenVisitor ? nodeVisitor(node.dotDotDotToken, tokenVisitor, isDotDotDotToken) : node.dotDotDotToken, Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); }, - [193 /* ParenthesizedType */ ]: function visitEachChildOfParenthesizedType(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [196 /* ParenthesizedType */ ]: function visitEachChildOfParenthesizedType(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateParenthesizedType(node, Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); }, - [195 /* TypeOperator */ ]: function visitEachChildOfTypeOperatorNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [198 /* TypeOperator */ ]: function visitEachChildOfTypeOperatorNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateTypeOperatorNode(node, Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); }, - [196 /* IndexedAccessType */ ]: function visitEachChildOfIndexedAccessType(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [199 /* IndexedAccessType */ ]: function visitEachChildOfIndexedAccessType(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateIndexedAccessTypeNode(node, Debug.checkDefined(nodeVisitor(node.objectType, visitor, isTypeNode)), Debug.checkDefined(nodeVisitor(node.indexType, visitor, isTypeNode))); }, - [197 /* MappedType */ ]: function visitEachChildOfMappedType(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + [200 /* MappedType */ ]: function visitEachChildOfMappedType(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { return context.factory.updateMappedTypeNode(node, tokenVisitor ? nodeVisitor(node.readonlyToken, tokenVisitor, isReadonlyKeywordOrPlusOrMinusToken) : node.readonlyToken, Debug.checkDefined(nodeVisitor(node.typeParameter, visitor, isTypeParameterDeclaration)), nodeVisitor(node.nameType, visitor, isTypeNode), tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionOrPlusOrMinusToken) : node.questionToken, nodeVisitor(node.type, visitor, isTypeNode), nodesVisitor(node.members, visitor, isTypeElement)); }, - [198 /* LiteralType */ ]: function visitEachChildOfLiteralTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [201 /* LiteralType */ ]: function visitEachChildOfLiteralTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateLiteralTypeNode(node, Debug.checkDefined(nodeVisitor(node.literal, visitor, isLiteralTypeLiteral))); }, - [200 /* TemplateLiteralType */ ]: function visitEachChildOfTemplateLiteralType(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [203 /* TemplateLiteralType */ ]: function visitEachChildOfTemplateLiteralType(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateTemplateLiteralType(node, Debug.checkDefined(nodeVisitor(node.head, visitor, isTemplateHead)), nodesVisitor(node.templateSpans, visitor, isTemplateLiteralTypeSpan)); }, - [201 /* TemplateLiteralTypeSpan */ ]: function visitEachChildOfTemplateLiteralTypeSpan(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [204 /* TemplateLiteralTypeSpan */ ]: function visitEachChildOfTemplateLiteralTypeSpan(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateTemplateLiteralTypeSpan(node, Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)), Debug.checkDefined(nodeVisitor(node.literal, visitor, isTemplateMiddleOrTemplateTail))); }, // Binding patterns - [203 /* ObjectBindingPattern */ ]: function visitEachChildOfObjectBindingPattern(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + [206 /* ObjectBindingPattern */ ]: function visitEachChildOfObjectBindingPattern(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { return context.factory.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, isBindingElement)); }, - [204 /* ArrayBindingPattern */ ]: function visitEachChildOfArrayBindingPattern(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + [207 /* ArrayBindingPattern */ ]: function visitEachChildOfArrayBindingPattern(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { return context.factory.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, isArrayBindingElement)); }, - [205 /* BindingElement */ ]: function visitEachChildOfBindingElement(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + [208 /* BindingElement */ ]: function visitEachChildOfBindingElement(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { return context.factory.updateBindingElement(node, tokenVisitor ? nodeVisitor(node.dotDotDotToken, tokenVisitor, isDotDotDotToken) : node.dotDotDotToken, nodeVisitor(node.propertyName, visitor, isPropertyName), Debug.checkDefined(nodeVisitor(node.name, visitor, isBindingName)), nodeVisitor(node.initializer, visitor, isExpression)); }, // Expression - [206 /* ArrayLiteralExpression */ ]: function visitEachChildOfArrayLiteralExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + [209 /* ArrayLiteralExpression */ ]: function visitEachChildOfArrayLiteralExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { return context.factory.updateArrayLiteralExpression(node, nodesVisitor(node.elements, visitor, isExpression)); }, - [207 /* ObjectLiteralExpression */ ]: function visitEachChildOfObjectLiteralExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + [210 /* ObjectLiteralExpression */ ]: function visitEachChildOfObjectLiteralExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { return context.factory.updateObjectLiteralExpression(node, nodesVisitor(node.properties, visitor, isObjectLiteralElementLike)); }, - [208 /* PropertyAccessExpression */ ]: function visitEachChildOfPropertyAccessExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + [211 /* PropertyAccessExpression */ ]: function visitEachChildOfPropertyAccessExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { return isPropertyAccessChain(node) ? context.factory.updatePropertyAccessChain(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), tokenVisitor ? nodeVisitor(node.questionDotToken, tokenVisitor, isQuestionDotToken) : node.questionDotToken, Debug.checkDefined(nodeVisitor(node.name, visitor, isMemberName))) : context.factory.updatePropertyAccessExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), Debug.checkDefined(nodeVisitor(node.name, visitor, isMemberName))); }, - [209 /* ElementAccessExpression */ ]: function visitEachChildOfElementAccessExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + [212 /* ElementAccessExpression */ ]: function visitEachChildOfElementAccessExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { return isElementAccessChain(node) ? context.factory.updateElementAccessChain(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), tokenVisitor ? nodeVisitor(node.questionDotToken, tokenVisitor, isQuestionDotToken) : node.questionDotToken, Debug.checkDefined(nodeVisitor(node.argumentExpression, visitor, isExpression))) : context.factory.updateElementAccessExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), Debug.checkDefined(nodeVisitor(node.argumentExpression, visitor, isExpression))); }, - [210 /* CallExpression */ ]: function visitEachChildOfCallExpression(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + [213 /* CallExpression */ ]: function visitEachChildOfCallExpression(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { return isCallChain(node) ? context.factory.updateCallChain(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), tokenVisitor ? nodeVisitor(node.questionDotToken, tokenVisitor, isQuestionDotToken) : node.questionDotToken, nodesVisitor(node.typeArguments, visitor, isTypeNode), nodesVisitor(node.arguments, visitor, isExpression)) : context.factory.updateCallExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), nodesVisitor(node.typeArguments, visitor, isTypeNode), nodesVisitor(node.arguments, visitor, isExpression)); }, - [211 /* NewExpression */ ]: function visitEachChildOfNewExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [214 /* NewExpression */ ]: function visitEachChildOfNewExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateNewExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), nodesVisitor(node.typeArguments, visitor, isTypeNode), nodesVisitor(node.arguments, visitor, isExpression)); }, - [212 /* TaggedTemplateExpression */ ]: function visitEachChildOfTaggedTemplateExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [215 /* TaggedTemplateExpression */ ]: function visitEachChildOfTaggedTemplateExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateTaggedTemplateExpression(node, Debug.checkDefined(nodeVisitor(node.tag, visitor, isExpression)), nodesVisitor(node.typeArguments, visitor, isTypeNode), Debug.checkDefined(nodeVisitor(node.template, visitor, isTemplateLiteral))); }, - [213 /* TypeAssertionExpression */ ]: function visitEachChildOfTypeAssertionExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [216 /* TypeAssertionExpression */ ]: function visitEachChildOfTypeAssertionExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateTypeAssertion(node, Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)), Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, - [214 /* ParenthesizedExpression */ ]: function visitEachChildOfParenthesizedExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [217 /* ParenthesizedExpression */ ]: function visitEachChildOfParenthesizedExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateParenthesizedExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, - [215 /* FunctionExpression */ ]: function visitEachChildOfFunctionExpression(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + [218 /* FunctionExpression */ ]: function visitEachChildOfFunctionExpression(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { return context.factory.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, isModifier), tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken, nodeVisitor(node.name, visitor, isIdentifier), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); }, - [216 /* ArrowFunction */ ]: function visitEachChildOfArrowFunction(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + [219 /* ArrowFunction */ ]: function visitEachChildOfArrowFunction(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { return context.factory.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, isModifier), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, isTypeNode), tokenVisitor ? Debug.checkDefined(nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, isEqualsGreaterThanToken)) : node.equalsGreaterThanToken, visitFunctionBody(node.body, visitor, context, nodeVisitor)); }, - [217 /* DeleteExpression */ ]: function visitEachChildOfDeleteExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [220 /* DeleteExpression */ ]: function visitEachChildOfDeleteExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateDeleteExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, - [218 /* TypeOfExpression */ ]: function visitEachChildOfTypeOfExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [221 /* TypeOfExpression */ ]: function visitEachChildOfTypeOfExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateTypeOfExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, - [219 /* VoidExpression */ ]: function visitEachChildOfVoidExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [222 /* VoidExpression */ ]: function visitEachChildOfVoidExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateVoidExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, - [220 /* AwaitExpression */ ]: function visitEachChildOfAwaitExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [223 /* AwaitExpression */ ]: function visitEachChildOfAwaitExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateAwaitExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, - [221 /* PrefixUnaryExpression */ ]: function visitEachChildOfPrefixUnaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [224 /* PrefixUnaryExpression */ ]: function visitEachChildOfPrefixUnaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updatePrefixUnaryExpression(node, Debug.checkDefined(nodeVisitor(node.operand, visitor, isExpression))); }, - [222 /* PostfixUnaryExpression */ ]: function visitEachChildOfPostfixUnaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [225 /* PostfixUnaryExpression */ ]: function visitEachChildOfPostfixUnaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updatePostfixUnaryExpression(node, Debug.checkDefined(nodeVisitor(node.operand, visitor, isExpression))); }, - [223 /* BinaryExpression */ ]: function visitEachChildOfBinaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + [226 /* BinaryExpression */ ]: function visitEachChildOfBinaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { return context.factory.updateBinaryExpression(node, Debug.checkDefined(nodeVisitor(node.left, visitor, isExpression)), tokenVisitor ? Debug.checkDefined(nodeVisitor(node.operatorToken, tokenVisitor, isBinaryOperatorToken)) : node.operatorToken, Debug.checkDefined(nodeVisitor(node.right, visitor, isExpression))); }, - [224 /* ConditionalExpression */ ]: function visitEachChildOfConditionalExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + [227 /* ConditionalExpression */ ]: function visitEachChildOfConditionalExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { return context.factory.updateConditionalExpression(node, Debug.checkDefined(nodeVisitor(node.condition, visitor, isExpression)), tokenVisitor ? Debug.checkDefined(nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken)) : node.questionToken, Debug.checkDefined(nodeVisitor(node.whenTrue, visitor, isExpression)), tokenVisitor ? Debug.checkDefined(nodeVisitor(node.colonToken, tokenVisitor, isColonToken)) : node.colonToken, Debug.checkDefined(nodeVisitor(node.whenFalse, visitor, isExpression))); }, - [225 /* TemplateExpression */ ]: function visitEachChildOfTemplateExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [228 /* TemplateExpression */ ]: function visitEachChildOfTemplateExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateTemplateExpression(node, Debug.checkDefined(nodeVisitor(node.head, visitor, isTemplateHead)), nodesVisitor(node.templateSpans, visitor, isTemplateSpan)); }, - [226 /* YieldExpression */ ]: function visitEachChildOfYieldExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + [229 /* YieldExpression */ ]: function visitEachChildOfYieldExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { return context.factory.updateYieldExpression(node, tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken, nodeVisitor(node.expression, visitor, isExpression)); }, - [227 /* SpreadElement */ ]: function visitEachChildOfSpreadElement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [230 /* SpreadElement */ ]: function visitEachChildOfSpreadElement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateSpreadElement(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, - [228 /* ClassExpression */ ]: function visitEachChildOfClassExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [231 /* ClassExpression */ ]: function visitEachChildOfClassExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, isModifierLike), nodeVisitor(node.name, visitor, isIdentifier), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, isHeritageClause), nodesVisitor(node.members, visitor, isClassElement)); }, - [230 /* ExpressionWithTypeArguments */ ]: function visitEachChildOfExpressionWithTypeArguments(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [233 /* ExpressionWithTypeArguments */ ]: function visitEachChildOfExpressionWithTypeArguments(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateExpressionWithTypeArguments(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), nodesVisitor(node.typeArguments, visitor, isTypeNode)); }, - [231 /* AsExpression */ ]: function visitEachChildOfAsExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [234 /* AsExpression */ ]: function visitEachChildOfAsExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateAsExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); }, - [235 /* SatisfiesExpression */ ]: function visitEachChildOfSatisfiesExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [238 /* SatisfiesExpression */ ]: function visitEachChildOfSatisfiesExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateSatisfiesExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); }, - [232 /* NonNullExpression */ ]: function visitEachChildOfNonNullExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [235 /* NonNullExpression */ ]: function visitEachChildOfNonNullExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return isOptionalChain(node) ? context.factory.updateNonNullChain(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))) : context.factory.updateNonNullExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, - [233 /* MetaProperty */ ]: function visitEachChildOfMetaProperty(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [236 /* MetaProperty */ ]: function visitEachChildOfMetaProperty(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateMetaProperty(node, Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))); }, // Misc - [236 /* TemplateSpan */ ]: function visitEachChildOfTemplateSpan(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [239 /* TemplateSpan */ ]: function visitEachChildOfTemplateSpan(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateTemplateSpan(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), Debug.checkDefined(nodeVisitor(node.literal, visitor, isTemplateMiddleOrTemplateTail))); }, // Element - [238 /* Block */ ]: function visitEachChildOfBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + [241 /* Block */ ]: function visitEachChildOfBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { return context.factory.updateBlock(node, nodesVisitor(node.statements, visitor, isStatement)); }, - [240 /* VariableStatement */ ]: function visitEachChildOfVariableStatement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [243 /* VariableStatement */ ]: function visitEachChildOfVariableStatement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.declarationList, visitor, isVariableDeclarationList))); }, - [241 /* ExpressionStatement */ ]: function visitEachChildOfExpressionStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [244 /* ExpressionStatement */ ]: function visitEachChildOfExpressionStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateExpressionStatement(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, - [242 /* IfStatement */ ]: function visitEachChildOfIfStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [245 /* IfStatement */ ]: function visitEachChildOfIfStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateIfStatement(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), Debug.checkDefined(nodeVisitor(node.thenStatement, visitor, isStatement, context.factory.liftToBlock)), nodeVisitor(node.elseStatement, visitor, isStatement, context.factory.liftToBlock)); }, - [243 /* DoStatement */ ]: function visitEachChildOfDoStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [246 /* DoStatement */ ]: function visitEachChildOfDoStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateDoStatement(node, visitIterationBody(node.statement, visitor, context, nodeVisitor), Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, - [244 /* WhileStatement */ ]: function visitEachChildOfWhileStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [247 /* WhileStatement */ ]: function visitEachChildOfWhileStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateWhileStatement(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), visitIterationBody(node.statement, visitor, context, nodeVisitor)); }, - [245 /* ForStatement */ ]: function visitEachChildOfForStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [248 /* ForStatement */ ]: function visitEachChildOfForStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateForStatement(node, nodeVisitor(node.initializer, visitor, isForInitializer), nodeVisitor(node.condition, visitor, isExpression), nodeVisitor(node.incrementor, visitor, isExpression), visitIterationBody(node.statement, visitor, context, nodeVisitor)); }, - [246 /* ForInStatement */ ]: function visitEachChildOfForInStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [249 /* ForInStatement */ ]: function visitEachChildOfForInStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateForInStatement(node, Debug.checkDefined(nodeVisitor(node.initializer, visitor, isForInitializer)), Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), visitIterationBody(node.statement, visitor, context, nodeVisitor)); }, - [247 /* ForOfStatement */ ]: function visitEachChildOfForOfStatement(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + [250 /* ForOfStatement */ ]: function visitEachChildOfForOfStatement(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { return context.factory.updateForOfStatement(node, tokenVisitor ? nodeVisitor(node.awaitModifier, tokenVisitor, isAwaitKeyword) : node.awaitModifier, Debug.checkDefined(nodeVisitor(node.initializer, visitor, isForInitializer)), Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), visitIterationBody(node.statement, visitor, context, nodeVisitor)); }, - [248 /* ContinueStatement */ ]: function visitEachChildOfContinueStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [251 /* ContinueStatement */ ]: function visitEachChildOfContinueStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateContinueStatement(node, nodeVisitor(node.label, visitor, isIdentifier)); }, - [249 /* BreakStatement */ ]: function visitEachChildOfBreakStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [252 /* BreakStatement */ ]: function visitEachChildOfBreakStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateBreakStatement(node, nodeVisitor(node.label, visitor, isIdentifier)); }, - [250 /* ReturnStatement */ ]: function visitEachChildOfReturnStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [253 /* ReturnStatement */ ]: function visitEachChildOfReturnStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateReturnStatement(node, nodeVisitor(node.expression, visitor, isExpression)); }, - [251 /* WithStatement */ ]: function visitEachChildOfWithStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [254 /* WithStatement */ ]: function visitEachChildOfWithStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateWithStatement(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), Debug.checkDefined(nodeVisitor(node.statement, visitor, isStatement, context.factory.liftToBlock))); }, - [252 /* SwitchStatement */ ]: function visitEachChildOfSwitchStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [255 /* SwitchStatement */ ]: function visitEachChildOfSwitchStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateSwitchStatement(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), Debug.checkDefined(nodeVisitor(node.caseBlock, visitor, isCaseBlock))); }, - [253 /* LabeledStatement */ ]: function visitEachChildOfLabeledStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [256 /* LabeledStatement */ ]: function visitEachChildOfLabeledStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateLabeledStatement(node, Debug.checkDefined(nodeVisitor(node.label, visitor, isIdentifier)), Debug.checkDefined(nodeVisitor(node.statement, visitor, isStatement, context.factory.liftToBlock))); }, - [254 /* ThrowStatement */ ]: function visitEachChildOfThrowStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [257 /* ThrowStatement */ ]: function visitEachChildOfThrowStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateThrowStatement(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, - [255 /* TryStatement */ ]: function visitEachChildOfTryStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [258 /* TryStatement */ ]: function visitEachChildOfTryStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateTryStatement(node, Debug.checkDefined(nodeVisitor(node.tryBlock, visitor, isBlock)), nodeVisitor(node.catchClause, visitor, isCatchClause), nodeVisitor(node.finallyBlock, visitor, isBlock)); }, - [257 /* VariableDeclaration */ ]: function visitEachChildOfVariableDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + [260 /* VariableDeclaration */ ]: function visitEachChildOfVariableDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { return context.factory.updateVariableDeclaration(node, Debug.checkDefined(nodeVisitor(node.name, visitor, isBindingName)), tokenVisitor ? nodeVisitor(node.exclamationToken, tokenVisitor, isExclamationToken) : node.exclamationToken, nodeVisitor(node.type, visitor, isTypeNode), nodeVisitor(node.initializer, visitor, isExpression)); }, - [258 /* VariableDeclarationList */ ]: function visitEachChildOfVariableDeclarationList(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + [261 /* VariableDeclarationList */ ]: function visitEachChildOfVariableDeclarationList(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { return context.factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, isVariableDeclaration)); }, - [259 /* FunctionDeclaration */ ]: function visitEachChildOfFunctionDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + [262 /* FunctionDeclaration */ ]: function visitEachChildOfFunctionDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { return context.factory.updateFunctionDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifier), tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken, nodeVisitor(node.name, visitor, isIdentifier), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); }, - [260 /* ClassDeclaration */ ]: function visitEachChildOfClassDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [263 /* ClassDeclaration */ ]: function visitEachChildOfClassDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateClassDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), nodeVisitor(node.name, visitor, isIdentifier), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, isHeritageClause), nodesVisitor(node.members, visitor, isClassElement)); }, - [261 /* InterfaceDeclaration */ ]: function visitEachChildOfInterfaceDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [264 /* InterfaceDeclaration */ ]: function visitEachChildOfInterfaceDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateInterfaceDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, isHeritageClause), nodesVisitor(node.members, visitor, isTypeElement)); }, - [262 /* TypeAliasDeclaration */ ]: function visitEachChildOfTypeAliasDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [265 /* TypeAliasDeclaration */ ]: function visitEachChildOfTypeAliasDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateTypeAliasDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); }, - [263 /* EnumDeclaration */ ]: function visitEachChildOfEnumDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [266 /* EnumDeclaration */ ]: function visitEachChildOfEnumDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateEnumDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), nodesVisitor(node.members, visitor, isEnumMember)); }, - [264 /* ModuleDeclaration */ ]: function visitEachChildOfModuleDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [267 /* ModuleDeclaration */ ]: function visitEachChildOfModuleDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateModuleDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.name, visitor, isModuleName)), nodeVisitor(node.body, visitor, isModuleBody)); }, - [265 /* ModuleBlock */ ]: function visitEachChildOfModuleBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + [268 /* ModuleBlock */ ]: function visitEachChildOfModuleBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { return context.factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, isStatement)); }, - [266 /* CaseBlock */ ]: function visitEachChildOfCaseBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + [269 /* CaseBlock */ ]: function visitEachChildOfCaseBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { return context.factory.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, isCaseOrDefaultClause)); }, - [267 /* NamespaceExportDeclaration */ ]: function visitEachChildOfNamespaceExportDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [270 /* NamespaceExportDeclaration */ ]: function visitEachChildOfNamespaceExportDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateNamespaceExportDeclaration(node, Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))); }, - [268 /* ImportEqualsDeclaration */ ]: function visitEachChildOfImportEqualsDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [271 /* ImportEqualsDeclaration */ ]: function visitEachChildOfImportEqualsDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateImportEqualsDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), node.isTypeOnly, Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), Debug.checkDefined(nodeVisitor(node.moduleReference, visitor, isModuleReference))); }, - [269 /* ImportDeclaration */ ]: function visitEachChildOfImportDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [272 /* ImportDeclaration */ ]: function visitEachChildOfImportDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateImportDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), nodeVisitor(node.importClause, visitor, isImportClause), Debug.checkDefined(nodeVisitor(node.moduleSpecifier, visitor, isExpression)), nodeVisitor(node.assertClause, visitor, isAssertClause)); }, - [296 /* AssertClause */ ]: function visitEachChildOfAssertClause(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + [300 /* AssertClause */ ]: function visitEachChildOfAssertClause(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { return context.factory.updateAssertClause(node, nodesVisitor(node.elements, visitor, isAssertEntry), node.multiLine); }, - [297 /* AssertEntry */ ]: function visitEachChildOfAssertEntry(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [301 /* AssertEntry */ ]: function visitEachChildOfAssertEntry(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateAssertEntry(node, Debug.checkDefined(nodeVisitor(node.name, visitor, isAssertionKey)), Debug.checkDefined(nodeVisitor(node.value, visitor, isExpression))); }, - [270 /* ImportClause */ ]: function visitEachChildOfImportClause(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [273 /* ImportClause */ ]: function visitEachChildOfImportClause(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateImportClause(node, node.isTypeOnly, nodeVisitor(node.name, visitor, isIdentifier), nodeVisitor(node.namedBindings, visitor, isNamedImportBindings)); }, - [271 /* NamespaceImport */ ]: function visitEachChildOfNamespaceImport(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [274 /* NamespaceImport */ ]: function visitEachChildOfNamespaceImport(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateNamespaceImport(node, Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))); }, - [277 /* NamespaceExport */ ]: function visitEachChildOfNamespaceExport(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [280 /* NamespaceExport */ ]: function visitEachChildOfNamespaceExport(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateNamespaceExport(node, Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))); }, - [272 /* NamedImports */ ]: function visitEachChildOfNamedImports(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + [275 /* NamedImports */ ]: function visitEachChildOfNamedImports(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { return context.factory.updateNamedImports(node, nodesVisitor(node.elements, visitor, isImportSpecifier)); }, - [273 /* ImportSpecifier */ ]: function visitEachChildOfImportSpecifier(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [276 /* ImportSpecifier */ ]: function visitEachChildOfImportSpecifier(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateImportSpecifier(node, node.isTypeOnly, nodeVisitor(node.propertyName, visitor, isIdentifier), Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))); }, - [274 /* ExportAssignment */ ]: function visitEachChildOfExportAssignment(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [277 /* ExportAssignment */ ]: function visitEachChildOfExportAssignment(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateExportAssignment(node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, - [275 /* ExportDeclaration */ ]: function visitEachChildOfExportDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [278 /* ExportDeclaration */ ]: function visitEachChildOfExportDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateExportDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, isExpression), nodeVisitor(node.assertClause, visitor, isAssertClause)); }, - [276 /* NamedExports */ ]: function visitEachChildOfNamedExports(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + [279 /* NamedExports */ ]: function visitEachChildOfNamedExports(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { return context.factory.updateNamedExports(node, nodesVisitor(node.elements, visitor, isExportSpecifier)); }, - [278 /* ExportSpecifier */ ]: function visitEachChildOfExportSpecifier(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [281 /* ExportSpecifier */ ]: function visitEachChildOfExportSpecifier(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateExportSpecifier(node, node.isTypeOnly, nodeVisitor(node.propertyName, visitor, isIdentifier), Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))); }, // Module references - [280 /* ExternalModuleReference */ ]: function visitEachChildOfExternalModuleReference(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [283 /* ExternalModuleReference */ ]: function visitEachChildOfExternalModuleReference(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateExternalModuleReference(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, // JSX - [281 /* JsxElement */ ]: function visitEachChildOfJsxElement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [284 /* JsxElement */ ]: function visitEachChildOfJsxElement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateJsxElement(node, Debug.checkDefined(nodeVisitor(node.openingElement, visitor, isJsxOpeningElement)), nodesVisitor(node.children, visitor, isJsxChild), Debug.checkDefined(nodeVisitor(node.closingElement, visitor, isJsxClosingElement))); }, - [282 /* JsxSelfClosingElement */ ]: function visitEachChildOfJsxSelfClosingElement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [285 /* JsxSelfClosingElement */ ]: function visitEachChildOfJsxSelfClosingElement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateJsxSelfClosingElement(node, Debug.checkDefined(nodeVisitor(node.tagName, visitor, isJsxTagNameExpression)), nodesVisitor(node.typeArguments, visitor, isTypeNode), Debug.checkDefined(nodeVisitor(node.attributes, visitor, isJsxAttributes))); }, - [283 /* JsxOpeningElement */ ]: function visitEachChildOfJsxOpeningElement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [286 /* JsxOpeningElement */ ]: function visitEachChildOfJsxOpeningElement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateJsxOpeningElement(node, Debug.checkDefined(nodeVisitor(node.tagName, visitor, isJsxTagNameExpression)), nodesVisitor(node.typeArguments, visitor, isTypeNode), Debug.checkDefined(nodeVisitor(node.attributes, visitor, isJsxAttributes))); }, - [284 /* JsxClosingElement */ ]: function visitEachChildOfJsxClosingElement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [287 /* JsxClosingElement */ ]: function visitEachChildOfJsxClosingElement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateJsxClosingElement(node, Debug.checkDefined(nodeVisitor(node.tagName, visitor, isJsxTagNameExpression))); }, - [285 /* JsxFragment */ ]: function visitEachChildOfJsxFragment(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [295 /* JsxNamespacedName */ ]: function forEachChildInJsxNamespacedName2(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateJsxNamespacedName(node, Debug.checkDefined(nodeVisitor(node.namespace, visitor, isIdentifier)), Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))); + }, + [288 /* JsxFragment */ ]: function visitEachChildOfJsxFragment(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateJsxFragment(node, Debug.checkDefined(nodeVisitor(node.openingFragment, visitor, isJsxOpeningFragment)), nodesVisitor(node.children, visitor, isJsxChild), Debug.checkDefined(nodeVisitor(node.closingFragment, visitor, isJsxClosingFragment))); }, - [288 /* JsxAttribute */ ]: function visitEachChildOfJsxAttribute(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateJsxAttribute(node, Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), nodeVisitor(node.initializer, visitor, isStringLiteralOrJsxExpression)); + [291 /* JsxAttribute */ ]: function visitEachChildOfJsxAttribute(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateJsxAttribute(node, Debug.checkDefined(nodeVisitor(node.name, visitor, isJsxAttributeName)), nodeVisitor(node.initializer, visitor, isStringLiteralOrJsxExpression)); }, - [289 /* JsxAttributes */ ]: function visitEachChildOfJsxAttributes(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + [292 /* JsxAttributes */ ]: function visitEachChildOfJsxAttributes(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { return context.factory.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, isJsxAttributeLike)); }, - [290 /* JsxSpreadAttribute */ ]: function visitEachChildOfJsxSpreadAttribute(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [293 /* JsxSpreadAttribute */ ]: function visitEachChildOfJsxSpreadAttribute(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateJsxSpreadAttribute(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, - [291 /* JsxExpression */ ]: function visitEachChildOfJsxExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [294 /* JsxExpression */ ]: function visitEachChildOfJsxExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateJsxExpression(node, nodeVisitor(node.expression, visitor, isExpression)); }, // Clauses - [292 /* CaseClause */ ]: function visitEachChildOfCaseClause(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + [296 /* CaseClause */ ]: function visitEachChildOfCaseClause(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateCaseClause(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), nodesVisitor(node.statements, visitor, isStatement)); }, - [293 /* DefaultClause */ ]: function visitEachChildOfDefaultClause(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + [297 /* DefaultClause */ ]: function visitEachChildOfDefaultClause(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { return context.factory.updateDefaultClause(node, nodesVisitor(node.statements, visitor, isStatement)); }, - [294 /* HeritageClause */ ]: function visitEachChildOfHeritageClause(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + [298 /* HeritageClause */ ]: function visitEachChildOfHeritageClause(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { return context.factory.updateHeritageClause(node, nodesVisitor(node.types, visitor, isExpressionWithTypeArguments)); }, - [295 /* CatchClause */ ]: function visitEachChildOfCatchClause(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [299 /* CatchClause */ ]: function visitEachChildOfCatchClause(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateCatchClause(node, nodeVisitor(node.variableDeclaration, visitor, isVariableDeclaration), Debug.checkDefined(nodeVisitor(node.block, visitor, isBlock))); }, // Property assignments - [299 /* PropertyAssignment */ ]: function visitEachChildOfPropertyAssignment(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [303 /* PropertyAssignment */ ]: function visitEachChildOfPropertyAssignment(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updatePropertyAssignment(node, Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), Debug.checkDefined(nodeVisitor(node.initializer, visitor, isExpression))); }, - [300 /* ShorthandPropertyAssignment */ ]: function visitEachChildOfShorthandPropertyAssignment(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [304 /* ShorthandPropertyAssignment */ ]: function visitEachChildOfShorthandPropertyAssignment(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateShorthandPropertyAssignment(node, Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), nodeVisitor(node.objectAssignmentInitializer, visitor, isExpression)); }, - [301 /* SpreadAssignment */ ]: function visitEachChildOfSpreadAssignment(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [305 /* SpreadAssignment */ ]: function visitEachChildOfSpreadAssignment(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateSpreadAssignment(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, // Enum - [302 /* EnumMember */ ]: function visitEachChildOfEnumMember(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [306 /* EnumMember */ ]: function visitEachChildOfEnumMember(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updateEnumMember(node, Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), nodeVisitor(node.initializer, visitor, isExpression)); }, // Top-level nodes - [308 /* SourceFile */ ]: function visitEachChildOfSourceFile(node, visitor, context, _nodesVisitor, _nodeVisitor, _tokenVisitor) { + [312 /* SourceFile */ ]: function visitEachChildOfSourceFile(node, visitor, context, _nodesVisitor, _nodeVisitor, _tokenVisitor) { return context.factory.updateSourceFile(node, visitLexicalEnvironment(node.statements, visitor, context)); }, // Transformation nodes - [356 /* PartiallyEmittedExpression */ ]: function visitEachChildOfPartiallyEmittedExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [360 /* PartiallyEmittedExpression */ ]: function visitEachChildOfPartiallyEmittedExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updatePartiallyEmittedExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, - [357 /* CommaListExpression */ ]: function visitEachChildOfCommaListExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + [361 /* CommaListExpression */ ]: function visitEachChildOfCommaListExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { return context.factory.updateCommaListExpression(node, nodesVisitor(node.elements, visitor, isExpression)); } }; @@ -73027,7 +73896,7 @@ ${lanes.join("\n")} }); // src/compiler/sourcemap.ts function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) { - var { enter: enter , exit: exit } = generatorOptions.extendedDiagnostics ? createTimer("Source Map", "beforeSourcemap", "afterSourcemap") : nullTimer; + var { enter: enter, exit: exit } = generatorOptions.extendedDiagnostics ? createTimer("Source Map", "beforeSourcemap", "afterSourcemap") : nullTimer; var rawSources = []; var sources = []; var sourceToSourceIndexMap = /* @__PURE__ */ new Map(); @@ -73259,7 +74128,7 @@ ${lanes.join("\n")} try { const parsed = JSON.parse(text); if (isRawSourceMap(parsed)) return parsed; - } catch (e) {} + } catch {} return void 0; } function decodeMappings(mappings) { @@ -73271,13 +74140,13 @@ ${lanes.join("\n")} let sourceLine = 0; let sourceCharacter = 0; let nameIndex = 0; - let error; + let error2; return { get pos () { return pos; }, get error () { - return error; + return error2; }, get state () { return captureMapping(/*hasSource*/ true, /*hasName*/ true); @@ -73350,14 +74219,14 @@ ${lanes.join("\n")} }; } function setError(message) { - if (error === void 0) error = message; + if (error2 === void 0) error2 = message; } function setErrorAndStopIterating(message) { setError(message); return stopIterating(); } function hasReportedError() { - return error !== void 0; + return error2 !== void 0; } function isSourceMappingSegmentEnd() { return pos === mappings.length || mappings.charCodeAt(pos) === 44 /* comma */ || mappings.charCodeAt(pos) === 59 /* semicolon */ ; @@ -73537,7 +74406,7 @@ ${lanes.join("\n")} function chainBundle(context, transformSourceFile) { return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - return node.kind === 308 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + return node.kind === 312 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); } function transformBundle(node) { return context.factory.createBundle(map(node.sourceFiles, transformSourceFile), node.prepends); @@ -73558,9 +74427,11 @@ ${lanes.join("\n")} function getImportNeedsImportDefaultHelper(node) { return !getImportNeedsImportStarHelper(node) && (isDefaultImport(node) || !!node.importClause && isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings)); } - function collectExternalModuleInfo(context, sourceFile, resolver, compilerOptions) { + function collectExternalModuleInfo(context, sourceFile) { + const resolver = context.getEmitResolver(); + const compilerOptions = context.getCompilerOptions(); const externalImports = []; - const exportSpecifiers = createMultiMap(); + const exportSpecifiers = new IdentifierNameMultiMap(); const exportedBindings = []; const uniqueExports = /* @__PURE__ */ new Map(); let exportedNames; @@ -73570,15 +74441,15 @@ ${lanes.join("\n")} let hasImportStar = false; let hasImportDefault = false; for (const node of sourceFile.statements)switch(node.kind){ - case 269 /* ImportDeclaration */ : + case 272 /* ImportDeclaration */ : externalImports.push(node); if (!hasImportStar && getImportNeedsImportStarHelper(node)) hasImportStar = true; if (!hasImportDefault && getImportNeedsImportDefaultHelper(node)) hasImportDefault = true; break; - case 268 /* ImportEqualsDeclaration */ : - if (node.moduleReference.kind === 280 /* ExternalModuleReference */ ) externalImports.push(node); + case 271 /* ImportEqualsDeclaration */ : + if (node.moduleReference.kind === 283 /* ExternalModuleReference */ ) externalImports.push(node); break; - case 275 /* ExportDeclaration */ : + case 278 /* ExportDeclaration */ : if (node.moduleSpecifier) { if (!node.exportClause) { externalImports.push(node); @@ -73598,13 +74469,13 @@ ${lanes.join("\n")} } } else addExportedNamesForExportDeclaration(node); break; - case 274 /* ExportAssignment */ : + case 277 /* ExportAssignment */ : if (node.isExportEquals && !exportEquals) exportEquals = node; break; - case 240 /* VariableStatement */ : - if (hasSyntacticModifier(node, 1 /* Export */ )) for (const decl of node.declarationList.declarations)exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); + case 243 /* VariableStatement */ : + if (hasSyntacticModifier(node, 1 /* Export */ )) for (const decl of node.declarationList.declarations)exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames, exportedBindings); break; - case 259 /* FunctionDeclaration */ : + case 262 /* FunctionDeclaration */ : if (hasSyntacticModifier(node, 1 /* Export */ )) { if (hasSyntacticModifier(node, 1024 /* Default */ )) { if (!hasExportDefault) { @@ -73621,7 +74492,7 @@ ${lanes.join("\n")} } } break; - case 260 /* ClassDeclaration */ : + case 263 /* ClassDeclaration */ : if (hasSyntacticModifier(node, 1 /* Export */ )) { if (hasSyntacticModifier(node, 1024 /* Default */ )) { if (!hasExportDefault) { @@ -73653,7 +74524,7 @@ ${lanes.join("\n")} function addExportedNamesForExportDeclaration(node) { for (const specifier of cast(node.exportClause, isNamedExports).elements)if (!uniqueExports.get(idText(specifier.name))) { const name = specifier.propertyName || specifier.name; - if (!node.moduleSpecifier) exportSpecifiers.add(idText(name), specifier); + if (!node.moduleSpecifier) exportSpecifiers.add(name, specifier); const decl = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name); if (decl) multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); uniqueExports.set(idText(specifier.name), true); @@ -73661,14 +74532,15 @@ ${lanes.join("\n")} } } } - function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { + function collectExportedVariableInfo(decl, uniqueExports, exportedNames, exportedBindings) { if (isBindingPattern(decl.name)) { - for (const element of decl.name.elements)if (!isOmittedExpression(element)) exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); + for (const element of decl.name.elements)if (!isOmittedExpression(element)) exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames, exportedBindings); } else if (!isGeneratedIdentifier(decl.name)) { const text = idText(decl.name); if (!uniqueExports.get(text)) { uniqueExports.set(text, true); exportedNames = append(exportedNames, decl.name); + if (isLocalName(decl.name)) multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), decl.name); } } return exportedNames; @@ -73682,46 +74554,46 @@ ${lanes.join("\n")} return values; } function isSimpleCopiableExpression(expression) { - return isStringLiteralLike(expression) || expression.kind === 8 /* NumericLiteral */ || isKeyword(expression.kind) || isIdentifier(expression); + return isStringLiteralLike(expression) || expression.kind === 9 /* NumericLiteral */ || isKeyword(expression.kind) || isIdentifier(expression); } function isSimpleInlineableExpression(expression) { return !isIdentifier(expression) && isSimpleCopiableExpression(expression); } function isCompoundAssignment(kind) { - return kind >= 64 /* FirstCompoundAssignment */ && kind <= 78 /* LastCompoundAssignment */ ; + return kind >= 65 /* FirstCompoundAssignment */ && kind <= 79 /* LastCompoundAssignment */ ; } function getNonAssignmentOperatorForCompoundAssignment(kind) { switch(kind){ - case 64 /* PlusEqualsToken */ : - return 39 /* PlusToken */ ; - case 65 /* MinusEqualsToken */ : - return 40 /* MinusToken */ ; - case 66 /* AsteriskEqualsToken */ : - return 41 /* AsteriskToken */ ; - case 67 /* AsteriskAsteriskEqualsToken */ : - return 42 /* AsteriskAsteriskToken */ ; - case 68 /* SlashEqualsToken */ : - return 43 /* SlashToken */ ; - case 69 /* PercentEqualsToken */ : - return 44 /* PercentToken */ ; - case 70 /* LessThanLessThanEqualsToken */ : - return 47 /* LessThanLessThanToken */ ; - case 71 /* GreaterThanGreaterThanEqualsToken */ : - return 48 /* GreaterThanGreaterThanToken */ ; - case 72 /* GreaterThanGreaterThanGreaterThanEqualsToken */ : - return 49 /* GreaterThanGreaterThanGreaterThanToken */ ; - case 73 /* AmpersandEqualsToken */ : - return 50 /* AmpersandToken */ ; - case 74 /* BarEqualsToken */ : - return 51 /* BarToken */ ; - case 78 /* CaretEqualsToken */ : - return 52 /* CaretToken */ ; - case 75 /* BarBarEqualsToken */ : - return 56 /* BarBarToken */ ; - case 76 /* AmpersandAmpersandEqualsToken */ : - return 55 /* AmpersandAmpersandToken */ ; - case 77 /* QuestionQuestionEqualsToken */ : - return 60 /* QuestionQuestionToken */ ; + case 65 /* PlusEqualsToken */ : + return 40 /* PlusToken */ ; + case 66 /* MinusEqualsToken */ : + return 41 /* MinusToken */ ; + case 67 /* AsteriskEqualsToken */ : + return 42 /* AsteriskToken */ ; + case 68 /* AsteriskAsteriskEqualsToken */ : + return 43 /* AsteriskAsteriskToken */ ; + case 69 /* SlashEqualsToken */ : + return 44 /* SlashToken */ ; + case 70 /* PercentEqualsToken */ : + return 45 /* PercentToken */ ; + case 71 /* LessThanLessThanEqualsToken */ : + return 48 /* LessThanLessThanToken */ ; + case 72 /* GreaterThanGreaterThanEqualsToken */ : + return 49 /* GreaterThanGreaterThanToken */ ; + case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */ : + return 50 /* GreaterThanGreaterThanGreaterThanToken */ ; + case 74 /* AmpersandEqualsToken */ : + return 51 /* AmpersandToken */ ; + case 75 /* BarEqualsToken */ : + return 52 /* BarToken */ ; + case 79 /* CaretEqualsToken */ : + return 53 /* CaretToken */ ; + case 76 /* BarBarEqualsToken */ : + return 57 /* BarBarToken */ ; + case 77 /* AmpersandAmpersandEqualsToken */ : + return 56 /* AmpersandAmpersandToken */ ; + case 78 /* QuestionQuestionEqualsToken */ : + return 61 /* QuestionQuestionToken */ ; } } function getSuperCallFromStatement(statement) { @@ -73729,12 +74601,23 @@ ${lanes.join("\n")} const expression = skipParentheses(statement.expression); return isSuperCall(expression) ? expression : void 0; } - function findSuperStatementIndex(statements, indexAfterLastPrologueStatement) { - for(let i = indexAfterLastPrologueStatement; i < statements.length; i += 1){ + function findSuperStatementIndexPathWorker(statements, start, indices) { + for(let i = start; i < statements.length; i += 1){ const statement = statements[i]; - if (getSuperCallFromStatement(statement)) return i; + if (getSuperCallFromStatement(statement)) { + indices.unshift(i); + return true; + } else if (isTryStatement(statement) && findSuperStatementIndexPathWorker(statement.tryBlock.statements, 0, indices)) { + indices.unshift(i); + return true; + } } - return -1; + return false; + } + function findSuperStatementIndexPath(statements, start) { + const indices = []; + findSuperStatementIndexPathWorker(statements, start, indices); + return indices; } function getProperties(node, requireInitializer, isStatic2) { return filter(node.members, (m)=>isInitializedOrStaticProperty(m, requireInitializer, isStatic2)); @@ -73752,7 +74635,7 @@ ${lanes.join("\n")} return isPropertyDeclaration(member) && hasStaticModifier(member); } function isInitializedProperty(member) { - return member.kind === 169 /* PropertyDeclaration */ && member.initializer !== void 0; + return member.kind === 172 /* PropertyDeclaration */ && member.initializer !== void 0; } function isNonStaticMethodOrAccessorWithPrivateName(member) { return !isStatic(member) && (isMethodOrAccessor(member) || isAutoAccessorPropertyDeclaration(member)) && isPrivateIdentifier(member.name); @@ -73785,13 +74668,13 @@ ${lanes.join("\n")} } function getAllDecoratorsOfClassElement(member, parent2, useLegacyDecorators) { switch(member.kind){ - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : if (!useLegacyDecorators) return getAllDecoratorsOfMethod(member); return getAllDecoratorsOfAccessors(member, parent2); - case 171 /* MethodDeclaration */ : + case 174 /* MethodDeclaration */ : return getAllDecoratorsOfMethod(member); - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : return getAllDecoratorsOfProperty(member); default: return void 0; @@ -73799,7 +74682,7 @@ ${lanes.join("\n")} } function getAllDecoratorsOfAccessors(accessor, parent2) { if (!accessor.body) return void 0; - const { firstAccessor: firstAccessor , secondAccessor: secondAccessor , getAccessor: getAccessor , setAccessor: setAccessor } = getAllAccessorDeclarations(parent2.members, accessor); + const { firstAccessor: firstAccessor, secondAccessor: secondAccessor, getAccessor: getAccessor, setAccessor: setAccessor } = getAllAccessorDeclarations(parent2.members, accessor); const firstAccessorWithDecorators = hasDecorators(firstAccessor) ? firstAccessor : secondAccessor && hasDecorators(secondAccessor) ? secondAccessor : void 0; if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) return void 0; const decorators = getDecorators(firstAccessorWithDecorators); @@ -73842,26 +74725,86 @@ ${lanes.join("\n")} }; } function getPrivateIdentifier(privateEnv, name) { - var _a2, _b; - return isGeneratedPrivateIdentifier(name) ? (_a2 = privateEnv == null ? void 0 : privateEnv.generatedIdentifiers) == null ? void 0 : _a2.get(getNodeForGeneratedName(name)) : (_b = privateEnv == null ? void 0 : privateEnv.identifiers) == null ? void 0 : _b.get(name.escapedText); + var _a, _b; + return isGeneratedPrivateIdentifier(name) ? (_a = privateEnv == null ? void 0 : privateEnv.generatedIdentifiers) == null ? void 0 : _a.get(getNodeForGeneratedName(name)) : (_b = privateEnv == null ? void 0 : privateEnv.identifiers) == null ? void 0 : _b.get(name.escapedText); } function setPrivateIdentifier(privateEnv, name, entry) { - var _a2, _b; if (isGeneratedPrivateIdentifier(name)) { - (_a2 = privateEnv.generatedIdentifiers) != null ? _a2 : privateEnv.generatedIdentifiers = /* @__PURE__ */ new Map(); + privateEnv.generatedIdentifiers ?? (privateEnv.generatedIdentifiers = /* @__PURE__ */ new Map()); privateEnv.generatedIdentifiers.set(getNodeForGeneratedName(name), entry); } else { - (_b = privateEnv.identifiers) != null ? _b : privateEnv.identifiers = /* @__PURE__ */ new Map(); + privateEnv.identifiers ?? (privateEnv.identifiers = /* @__PURE__ */ new Map()); privateEnv.identifiers.set(name.escapedText, entry); } } function accessPrivateIdentifier(env, name) { return walkUpLexicalEnvironments(env, (env2)=>getPrivateIdentifier(env2.privateEnv, name)); } + var IdentifierNameMap, IdentifierNameMultiMap; var init_utilities3 = __esm({ "src/compiler/transformers/utilities.ts" () { "use strict"; init_ts2(); + IdentifierNameMap = class _IdentifierNameMap { + constructor(){ + this._map = /* @__PURE__ */ new Map(); + } + get size() { + return this._map.size; + } + has(key) { + return this._map.has(_IdentifierNameMap.toKey(key)); + } + get(key) { + return this._map.get(_IdentifierNameMap.toKey(key)); + } + set(key, value1) { + this._map.set(_IdentifierNameMap.toKey(key), value1); + return this; + } + delete(key) { + var _a; + return ((_a = this._map) == null ? void 0 : _a.delete(_IdentifierNameMap.toKey(key))) ?? false; + } + clear() { + this._map.clear(); + } + values() { + return this._map.values(); + } + static toKey(name) { + if (isGeneratedPrivateIdentifier(name) || isGeneratedIdentifier(name)) { + const autoGenerate = name.emitNode.autoGenerate; + if ((autoGenerate.flags & 7 /* KindMask */ ) === 4 /* Node */ ) { + const node = getNodeForGeneratedName(name); + const baseName = isMemberName(node) && node !== name ? _IdentifierNameMap.toKey(node) : `(generated@${getNodeId(node)})`; + return formatGeneratedName(/*privateName*/ false, autoGenerate.prefix, baseName, autoGenerate.suffix, _IdentifierNameMap.toKey); + } else { + const baseName = `(auto@${autoGenerate.id})`; + return formatGeneratedName(/*privateName*/ false, autoGenerate.prefix, baseName, autoGenerate.suffix, _IdentifierNameMap.toKey); + } + } + if (isPrivateIdentifier(name)) return idText(name).slice(1); + return idText(name); + } + }; + IdentifierNameMultiMap = class extends IdentifierNameMap { + add(key, value1) { + let values = this.get(key); + if (values) values.push(value1); + else this.set(key, values = [ + value1 + ]); + return values; + } + remove(key, value1) { + const values = this.get(key); + if (values) { + unorderedRemoveItem(values, value1); + if (!values.length) this.delete(key); + } + } + }; } }); // src/compiler/transformers/destructuring.ts @@ -73973,7 +74916,7 @@ ${lanes.join("\n")} pendingDeclaration.value = temp; } } - for (const { pendingExpressions: pendingExpressions2 , name: name , value: value1 , location: location , original: original } of pendingDeclarations){ + for (const { pendingExpressions: pendingExpressions2, name: name, value: value1, location: location, original: original } of pendingDeclarations){ const variable = context.factory.createVariableDeclaration(name, /*exclamationToken*/ void 0, /*type*/ void 0, pendingExpressions2 ? context.factory.inlineExpressions(append(pendingExpressions2, value1)) : value1); variable.original = original; setTextRange(variable, location); @@ -74097,11 +75040,12 @@ ${lanes.join("\n")} return flattenContext.context.factory.createConditionalExpression(flattenContext.context.factory.createTypeCheck(value1, "undefined"), /*questionToken*/ void 0, defaultValue, /*colonToken*/ void 0, value1); } function createDestructuringPropertyAccess(flattenContext, value1, propertyName) { + const { factory: factory2 } = flattenContext.context; if (isComputedPropertyName(propertyName)) { const argumentExpression = ensureIdentifier(flattenContext, Debug.checkDefined(visitNode(propertyName.expression, flattenContext.visitor, isExpression)), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName); return flattenContext.context.factory.createElementAccessExpression(value1, argumentExpression); } else if (isStringOrNumericLiteralLike(propertyName)) { - const argumentExpression = factory.cloneNode(propertyName); + const argumentExpression = factory2.cloneNode(propertyName); return flattenContext.context.factory.createElementAccessExpression(value1, argumentExpression); } else { const name = flattenContext.context.factory.createIdentifier(idText(propertyName)); @@ -74153,6 +75097,208 @@ ${lanes.join("\n")} })(FlattenLevel || {}); } }); + // src/compiler/transformers/classThis.ts + function createClassThisAssignmentBlock(factory2, classThis, thisExpression = factory2.createThis()) { + const expression = factory2.createAssignment(classThis, thisExpression); + const statement = factory2.createExpressionStatement(expression); + const body = factory2.createBlock([ + statement + ], /*multiLine*/ false); + const block = factory2.createClassStaticBlockDeclaration(body); + getOrCreateEmitNode(block).classThis = classThis; + return block; + } + function isClassThisAssignmentBlock(node) { + var _a; + if (!isClassStaticBlockDeclaration(node) || node.body.statements.length !== 1) return false; + const statement = node.body.statements[0]; + return isExpressionStatement(statement) && isAssignmentExpression(statement.expression, /*excludeCompoundAssignment*/ true) && isIdentifier(statement.expression.left) && ((_a = node.emitNode) == null ? void 0 : _a.classThis) === statement.expression.left && statement.expression.right.kind === 110 /* ThisKeyword */ ; + } + function classHasClassThisAssignment(node) { + var _a; + return !!((_a = node.emitNode) == null ? void 0 : _a.classThis) && some(node.members, isClassThisAssignmentBlock); + } + function injectClassThisAssignmentIfMissing(factory2, node, classThis, thisExpression) { + if (classHasClassThisAssignment(node)) return node; + const staticBlock = createClassThisAssignmentBlock(factory2, classThis, thisExpression); + if (node.name) setSourceMapRange(staticBlock.body.statements[0], node.name); + const members = factory2.createNodeArray([ + staticBlock, + ...node.members + ]); + setTextRange(members, node.members); + const updatedNode = isClassDeclaration(node) ? factory2.updateClassDeclaration(node, node.modifiers, node.name, node.typeParameters, node.heritageClauses, members) : factory2.updateClassExpression(node, node.modifiers, node.name, node.typeParameters, node.heritageClauses, members); + getOrCreateEmitNode(updatedNode).classThis = classThis; + return updatedNode; + } + var init_classThis = __esm({ + "src/compiler/transformers/classThis.ts" () { + "use strict"; + init_ts2(); + } + }); + // src/compiler/transformers/namedEvaluation.ts + function getAssignedNameOfIdentifier(factory2, name, expression) { + const original = getOriginalNode(skipOuterExpressions(expression)); + if ((isClassDeclaration(original) || isFunctionDeclaration(original)) && !original.name && hasSyntacticModifier(original, 1024 /* Default */ )) return factory2.createStringLiteral("default"); + return factory2.createStringLiteralFromNode(name); + } + function getAssignedNameOfPropertyName(context, name, assignedNameText) { + const { factory: factory2 } = context; + if (assignedNameText !== void 0) { + const assignedName2 = factory2.createStringLiteral(assignedNameText); + return { + assignedName: assignedName2, + name: name + }; + } + if (isPropertyNameLiteral(name) || isPrivateIdentifier(name)) { + const assignedName2 = factory2.createStringLiteralFromNode(name); + return { + assignedName: assignedName2, + name: name + }; + } + if (isPropertyNameLiteral(name.expression) && !isIdentifier(name.expression)) { + const assignedName2 = factory2.createStringLiteralFromNode(name.expression); + return { + assignedName: assignedName2, + name: name + }; + } + const assignedName = factory2.getGeneratedNameForNode(name); + context.hoistVariableDeclaration(assignedName); + const key = context.getEmitHelperFactory().createPropKeyHelper(name.expression); + const assignment = factory2.createAssignment(assignedName, key); + const updatedName = factory2.updateComputedPropertyName(name, assignment); + return { + assignedName: assignedName, + name: updatedName + }; + } + function createClassNamedEvaluationHelperBlock(context, assignedName, thisExpression = context.factory.createThis()) { + const { factory: factory2 } = context; + const expression = context.getEmitHelperFactory().createSetFunctionNameHelper(thisExpression, assignedName); + const statement = factory2.createExpressionStatement(expression); + const body = factory2.createBlock([ + statement + ], /*multiLine*/ false); + const block = factory2.createClassStaticBlockDeclaration(body); + getOrCreateEmitNode(block).assignedName = assignedName; + return block; + } + function isClassNamedEvaluationHelperBlock(node) { + var _a; + if (!isClassStaticBlockDeclaration(node) || node.body.statements.length !== 1) return false; + const statement = node.body.statements[0]; + return isExpressionStatement(statement) && isCallToHelper(statement.expression, "___setFunctionName") && statement.expression.arguments.length >= 2 && statement.expression.arguments[1] === ((_a = node.emitNode) == null ? void 0 : _a.assignedName); + } + function classHasExplicitlyAssignedName(node) { + var _a; + return !!((_a = node.emitNode) == null ? void 0 : _a.assignedName) && some(node.members, isClassNamedEvaluationHelperBlock); + } + function classHasDeclaredOrExplicitlyAssignedName(node) { + return !!node.name || classHasExplicitlyAssignedName(node); + } + function injectClassNamedEvaluationHelperBlockIfMissing(context, node, assignedName, thisExpression) { + if (classHasExplicitlyAssignedName(node)) return node; + const { factory: factory2 } = context; + const namedEvaluationBlock = createClassNamedEvaluationHelperBlock(context, assignedName, thisExpression); + if (node.name) setSourceMapRange(namedEvaluationBlock.body.statements[0], node.name); + const insertionIndex = findIndex(node.members, isClassThisAssignmentBlock) + 1; + const leading = node.members.slice(0, insertionIndex); + const trailing = node.members.slice(insertionIndex); + const members = factory2.createNodeArray([ + ...leading, + namedEvaluationBlock, + ...trailing + ]); + setTextRange(members, node.members); + node = isClassDeclaration(node) ? factory2.updateClassDeclaration(node, node.modifiers, node.name, node.typeParameters, node.heritageClauses, members) : factory2.updateClassExpression(node, node.modifiers, node.name, node.typeParameters, node.heritageClauses, members); + getOrCreateEmitNode(node).assignedName = assignedName; + return node; + } + function finishTransformNamedEvaluation(context, expression, assignedName, ignoreEmptyStringLiteral) { + if (ignoreEmptyStringLiteral && isStringLiteral(assignedName) && isEmptyStringLiteral(assignedName)) return expression; + const { factory: factory2 } = context; + const innerExpression = skipOuterExpressions(expression); + const updatedExpression = isClassExpression(innerExpression) ? cast(injectClassNamedEvaluationHelperBlockIfMissing(context, innerExpression, assignedName), isClassExpression) : context.getEmitHelperFactory().createSetFunctionNameHelper(innerExpression, assignedName); + return factory2.restoreOuterExpressions(expression, updatedExpression); + } + function transformNamedEvaluationOfPropertyAssignment(context, node, ignoreEmptyStringLiteral, assignedNameText) { + const { factory: factory2 } = context; + const { assignedName: assignedName, name: name } = getAssignedNameOfPropertyName(context, node.name, assignedNameText); + const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); + return factory2.updatePropertyAssignment(node, name, initializer); + } + function transformNamedEvaluationOfShorthandAssignmentProperty(context, node, ignoreEmptyStringLiteral, assignedNameText) { + const { factory: factory2 } = context; + const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : getAssignedNameOfIdentifier(factory2, node.name, node.objectAssignmentInitializer); + const objectAssignmentInitializer = finishTransformNamedEvaluation(context, node.objectAssignmentInitializer, assignedName, ignoreEmptyStringLiteral); + return factory2.updateShorthandPropertyAssignment(node, node.name, objectAssignmentInitializer); + } + function transformNamedEvaluationOfVariableDeclaration(context, node, ignoreEmptyStringLiteral, assignedNameText) { + const { factory: factory2 } = context; + const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : getAssignedNameOfIdentifier(factory2, node.name, node.initializer); + const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); + return factory2.updateVariableDeclaration(node, node.name, node.exclamationToken, node.type, initializer); + } + function transformNamedEvaluationOfParameterDeclaration(context, node, ignoreEmptyStringLiteral, assignedNameText) { + const { factory: factory2 } = context; + const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : getAssignedNameOfIdentifier(factory2, node.name, node.initializer); + const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); + return factory2.updateParameterDeclaration(node, node.modifiers, node.dotDotDotToken, node.name, node.questionToken, node.type, initializer); + } + function transformNamedEvaluationOfBindingElement(context, node, ignoreEmptyStringLiteral, assignedNameText) { + const { factory: factory2 } = context; + const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : getAssignedNameOfIdentifier(factory2, node.name, node.initializer); + const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); + return factory2.updateBindingElement(node, node.dotDotDotToken, node.propertyName, node.name, initializer); + } + function transformNamedEvaluationOfPropertyDeclaration(context, node, ignoreEmptyStringLiteral, assignedNameText) { + const { factory: factory2 } = context; + const { assignedName: assignedName, name: name } = getAssignedNameOfPropertyName(context, node.name, assignedNameText); + const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); + return factory2.updatePropertyDeclaration(node, node.modifiers, name, node.questionToken ?? node.exclamationToken, node.type, initializer); + } + function transformNamedEvaluationOfAssignmentExpression(context, node, ignoreEmptyStringLiteral, assignedNameText) { + const { factory: factory2 } = context; + const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : getAssignedNameOfIdentifier(factory2, node.left, node.right); + const right = finishTransformNamedEvaluation(context, node.right, assignedName, ignoreEmptyStringLiteral); + return factory2.updateBinaryExpression(node, node.left, node.operatorToken, right); + } + function transformNamedEvaluationOfExportAssignment(context, node, ignoreEmptyStringLiteral, assignedNameText) { + const { factory: factory2 } = context; + const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : factory2.createStringLiteral(node.isExportEquals ? "" : "default"); + const expression = finishTransformNamedEvaluation(context, node.expression, assignedName, ignoreEmptyStringLiteral); + return factory2.updateExportAssignment(node, node.modifiers, expression); + } + function transformNamedEvaluation(context, node, ignoreEmptyStringLiteral, assignedName) { + switch(node.kind){ + case 303 /* PropertyAssignment */ : + return transformNamedEvaluationOfPropertyAssignment(context, node, ignoreEmptyStringLiteral, assignedName); + case 304 /* ShorthandPropertyAssignment */ : + return transformNamedEvaluationOfShorthandAssignmentProperty(context, node, ignoreEmptyStringLiteral, assignedName); + case 260 /* VariableDeclaration */ : + return transformNamedEvaluationOfVariableDeclaration(context, node, ignoreEmptyStringLiteral, assignedName); + case 169 /* Parameter */ : + return transformNamedEvaluationOfParameterDeclaration(context, node, ignoreEmptyStringLiteral, assignedName); + case 208 /* BindingElement */ : + return transformNamedEvaluationOfBindingElement(context, node, ignoreEmptyStringLiteral, assignedName); + case 172 /* PropertyDeclaration */ : + return transformNamedEvaluationOfPropertyDeclaration(context, node, ignoreEmptyStringLiteral, assignedName); + case 226 /* BinaryExpression */ : + return transformNamedEvaluationOfAssignmentExpression(context, node, ignoreEmptyStringLiteral, assignedName); + case 277 /* ExportAssignment */ : + return transformNamedEvaluationOfExportAssignment(context, node, ignoreEmptyStringLiteral, assignedName); + } + } + var init_namedEvaluation = __esm({ + "src/compiler/transformers/namedEvaluation.ts" () { + "use strict"; + init_ts2(); + } + }); // src/compiler/transformers/taggedTemplate.ts function processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, level) { const tag = visitNode(node.tag, visitor, isExpression); @@ -74164,39 +75310,40 @@ ${lanes.join("\n")} const rawStrings = []; const template = node.template; if (level === 0 /* LiftRestriction */ && !hasInvalidEscape(template)) return visitEachChild(node, visitor, context); + const { factory: factory2 } = context; if (isNoSubstitutionTemplateLiteral(template)) { - cookedStrings.push(createTemplateCooked(template)); - rawStrings.push(getRawLiteral(template, currentSourceFile)); + cookedStrings.push(createTemplateCooked(factory2, template)); + rawStrings.push(getRawLiteral(factory2, template, currentSourceFile)); } else { - cookedStrings.push(createTemplateCooked(template.head)); - rawStrings.push(getRawLiteral(template.head, currentSourceFile)); + cookedStrings.push(createTemplateCooked(factory2, template.head)); + rawStrings.push(getRawLiteral(factory2, template.head, currentSourceFile)); for (const templateSpan of template.templateSpans){ - cookedStrings.push(createTemplateCooked(templateSpan.literal)); - rawStrings.push(getRawLiteral(templateSpan.literal, currentSourceFile)); + cookedStrings.push(createTemplateCooked(factory2, templateSpan.literal)); + rawStrings.push(getRawLiteral(factory2, templateSpan.literal, currentSourceFile)); templateArguments.push(Debug.checkDefined(visitNode(templateSpan.expression, visitor, isExpression))); } } - const helperCall = context.getEmitHelperFactory().createTemplateObjectHelper(factory.createArrayLiteralExpression(cookedStrings), factory.createArrayLiteralExpression(rawStrings)); + const helperCall = context.getEmitHelperFactory().createTemplateObjectHelper(factory2.createArrayLiteralExpression(cookedStrings), factory2.createArrayLiteralExpression(rawStrings)); if (isExternalModule(currentSourceFile)) { - const tempVar = factory.createUniqueName("templateObject"); + const tempVar = factory2.createUniqueName("templateObject"); recordTaggedTemplateString(tempVar); - templateArguments[0] = factory.createLogicalOr(tempVar, factory.createAssignment(tempVar, helperCall)); + templateArguments[0] = factory2.createLogicalOr(tempVar, factory2.createAssignment(tempVar, helperCall)); } else templateArguments[0] = helperCall; - return factory.createCallExpression(tag, /*typeArguments*/ void 0, templateArguments); + return factory2.createCallExpression(tag, /*typeArguments*/ void 0, templateArguments); } - function createTemplateCooked(template) { - return template.templateFlags ? factory.createVoidZero() : factory.createStringLiteral(template.text); + function createTemplateCooked(factory2, template) { + return template.templateFlags & 26656 /* IsInvalid */ ? factory2.createVoidZero() : factory2.createStringLiteral(template.text); } - function getRawLiteral(node, currentSourceFile) { + function getRawLiteral(factory2, node, currentSourceFile) { let text = node.rawText; if (text === void 0) { Debug.assertIsDefined(currentSourceFile, "Template literal node is missing 'rawText' and does not have a source file. Possibly bad transform."); text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node); - const isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */ ; + const isLast = node.kind === 15 /* NoSubstitutionTemplateLiteral */ || node.kind === 18 /* TemplateTail */ ; text = text.substring(1, text.length - (isLast ? 1 : 2)); } text = text.replace(/\r\n?/g, "\n"); - return setTextRange(factory.createStringLiteral(text), node); + return setTextRange(factory2.createStringLiteral(text), node); } var ProcessLevel; var init_taggedTemplate = __esm({ @@ -74212,7 +75359,7 @@ ${lanes.join("\n")} }); // src/compiler/transformers/ts.ts function transformTypeScript(context) { - const { factory: factory2 , getEmitHelperFactory: emitHelpers , startLexicalEnvironment: startLexicalEnvironment , resumeLexicalEnvironment: resumeLexicalEnvironment , endLexicalEnvironment: endLexicalEnvironment , hoistVariableDeclaration: hoistVariableDeclaration } = context; + const { factory: factory2, getEmitHelperFactory: emitHelpers, startLexicalEnvironment: startLexicalEnvironment, resumeLexicalEnvironment: resumeLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, hoistVariableDeclaration: hoistVariableDeclaration } = context; const resolver = context.getEmitResolver(); const compilerOptions = context.getCompilerOptions(); const languageVersion = getEmitScriptTarget(compilerOptions); @@ -74223,8 +75370,8 @@ ${lanes.join("\n")} const previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(208 /* PropertyAccessExpression */ ); - context.enableSubstitution(209 /* ElementAccessExpression */ ); + context.enableSubstitution(211 /* PropertyAccessExpression */ ); + context.enableSubstitution(212 /* ElementAccessExpression */ ); let currentSourceFile; let currentNamespace; let currentNamespaceContainerName; @@ -74235,12 +75382,12 @@ ${lanes.join("\n")} let applicableSubstitutions; return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - if (node.kind === 309 /* Bundle */ ) return transformBundle(node); + if (node.kind === 313 /* Bundle */ ) return transformBundle(node); return transformSourceFile(node); } function transformBundle(node) { return factory2.createBundle(node.sourceFiles.map(transformSourceFile), mapDefined(node.prepends, (prepend)=>{ - if (prepend.kind === 311 /* InputFiles */ ) return createUnparsedSourceFile(prepend, "js"); + if (prepend.kind === 315 /* InputFiles */ ) return createUnparsedSourceFile(prepend, "js"); return prepend; })); } @@ -74265,18 +75412,18 @@ ${lanes.join("\n")} } function onBeforeVisitNode(node) { switch(node.kind){ - case 308 /* SourceFile */ : - case 266 /* CaseBlock */ : - case 265 /* ModuleBlock */ : - case 238 /* Block */ : + case 312 /* SourceFile */ : + case 269 /* CaseBlock */ : + case 268 /* ModuleBlock */ : + case 241 /* Block */ : currentLexicalScope = node; currentScopeFirstDeclarationsOfName = void 0; break; - case 260 /* ClassDeclaration */ : - case 259 /* FunctionDeclaration */ : + case 263 /* ClassDeclaration */ : + case 262 /* FunctionDeclaration */ : if (hasSyntacticModifier(node, 2 /* Ambient */ )) break; if (node.name) recordEmittedDeclarationInScope(node); - else Debug.assert(node.kind === 260 /* ClassDeclaration */ || hasSyntacticModifier(node, 1024 /* Default */ )); + else Debug.assert(node.kind === 263 /* ClassDeclaration */ || hasSyntacticModifier(node, 1024 /* Default */ )); break; } } @@ -74292,10 +75439,10 @@ ${lanes.join("\n")} } function sourceElementVisitorWorker(node) { switch(node.kind){ - case 269 /* ImportDeclaration */ : - case 268 /* ImportEqualsDeclaration */ : - case 274 /* ExportAssignment */ : - case 275 /* ExportDeclaration */ : + case 272 /* ImportDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : + case 277 /* ExportAssignment */ : + case 278 /* ExportDeclaration */ : return visitElidableStatement(node); default: return visitorWorker(node); @@ -74308,13 +75455,13 @@ ${lanes.join("\n")} return node; } switch(node.kind){ - case 269 /* ImportDeclaration */ : + case 272 /* ImportDeclaration */ : return visitImportDeclaration(node); - case 268 /* ImportEqualsDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : return visitImportEqualsDeclaration(node); - case 274 /* ExportAssignment */ : + case 277 /* ExportAssignment */ : return visitExportAssignment(node); - case 275 /* ExportDeclaration */ : + case 278 /* ExportDeclaration */ : return visitExportDeclaration(node); default: Debug.fail("Unhandled ellided statement"); @@ -74324,7 +75471,7 @@ ${lanes.join("\n")} return saveStateAndInvoke(node, namespaceElementVisitorWorker); } function namespaceElementVisitorWorker(node) { - if (node.kind === 275 /* ExportDeclaration */ || node.kind === 269 /* ImportDeclaration */ || node.kind === 270 /* ImportClause */ || node.kind === 268 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 280 /* ExternalModuleReference */ ) return void 0; + if (node.kind === 278 /* ExportDeclaration */ || node.kind === 272 /* ImportDeclaration */ || node.kind === 273 /* ImportClause */ || node.kind === 271 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 283 /* ExternalModuleReference */ ) return void 0; else if (node.transformFlags & 1 /* ContainsTypeScript */ || hasSyntacticModifier(node, 1 /* Export */ )) return visitTypeScript(node); return node; } @@ -74333,21 +75480,21 @@ ${lanes.join("\n")} } function classElementVisitorWorker(node, parent2) { switch(node.kind){ - case 173 /* Constructor */ : + case 176 /* Constructor */ : return visitConstructor(node); - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : return visitPropertyDeclaration(node, parent2); - case 174 /* GetAccessor */ : + case 177 /* GetAccessor */ : return visitGetAccessor(node, parent2); - case 175 /* SetAccessor */ : + case 178 /* SetAccessor */ : return visitSetAccessor(node, parent2); - case 171 /* MethodDeclaration */ : + case 174 /* MethodDeclaration */ : return visitMethodDeclaration(node, parent2); - case 172 /* ClassStaticBlockDeclaration */ : + case 175 /* ClassStaticBlockDeclaration */ : return visitEachChild(node, visitor, context); - case 237 /* SemicolonClassElement */ : + case 240 /* SemicolonClassElement */ : return node; - case 178 /* IndexSignature */ : + case 181 /* IndexSignature */ : return; default: return Debug.failBadSyntaxKind(node); @@ -74358,15 +75505,15 @@ ${lanes.join("\n")} } function objectLiteralElementVisitorWorker(node, parent2) { switch(node.kind){ - case 299 /* PropertyAssignment */ : - case 300 /* ShorthandPropertyAssignment */ : - case 301 /* SpreadAssignment */ : + case 303 /* PropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : + case 305 /* SpreadAssignment */ : return visitor(node); - case 174 /* GetAccessor */ : + case 177 /* GetAccessor */ : return visitGetAccessor(node, parent2); - case 175 /* SetAccessor */ : + case 178 /* SetAccessor */ : return visitSetAccessor(node, parent2); - case 171 /* MethodDeclaration */ : + case 174 /* MethodDeclaration */ : return visitMethodDeclaration(node, parent2); default: return Debug.failBadSyntaxKind(node); @@ -74381,114 +75528,114 @@ ${lanes.join("\n")} function modifierVisitor(node) { if (isDecorator(node)) return void 0; if (modifierToFlag(node.kind) & 117086 /* TypeScriptModifier */ ) return void 0; - else if (currentNamespace && node.kind === 93 /* ExportKeyword */ ) return void 0; + else if (currentNamespace && node.kind === 95 /* ExportKeyword */ ) return void 0; return node; } function visitTypeScript(node) { if (isStatement(node) && hasSyntacticModifier(node, 2 /* Ambient */ )) return factory2.createNotEmittedStatement(node); switch(node.kind){ - case 93 /* ExportKeyword */ : - case 88 /* DefaultKeyword */ : + case 95 /* ExportKeyword */ : + case 90 /* DefaultKeyword */ : return currentNamespace ? void 0 : node; - case 123 /* PublicKeyword */ : - case 121 /* PrivateKeyword */ : - case 122 /* ProtectedKeyword */ : - case 126 /* AbstractKeyword */ : - case 161 /* OverrideKeyword */ : - case 85 /* ConstKeyword */ : - case 136 /* DeclareKeyword */ : - case 146 /* ReadonlyKeyword */ : - case 101 /* InKeyword */ : - case 145 /* OutKeyword */ : - case 185 /* ArrayType */ : - case 186 /* TupleType */ : - case 187 /* OptionalType */ : - case 188 /* RestType */ : - case 184 /* TypeLiteral */ : - case 179 /* TypePredicate */ : - case 165 /* TypeParameter */ : - case 131 /* AnyKeyword */ : - case 157 /* UnknownKeyword */ : - case 134 /* BooleanKeyword */ : - case 152 /* StringKeyword */ : - case 148 /* NumberKeyword */ : - case 144 /* NeverKeyword */ : - case 114 /* VoidKeyword */ : - case 153 /* SymbolKeyword */ : - case 182 /* ConstructorType */ : - case 181 /* FunctionType */ : - case 183 /* TypeQuery */ : - case 180 /* TypeReference */ : - case 189 /* UnionType */ : - case 190 /* IntersectionType */ : - case 191 /* ConditionalType */ : - case 193 /* ParenthesizedType */ : - case 194 /* ThisType */ : - case 195 /* TypeOperator */ : - case 196 /* IndexedAccessType */ : - case 197 /* MappedType */ : - case 198 /* LiteralType */ : - case 178 /* IndexSignature */ : + case 125 /* PublicKeyword */ : + case 123 /* PrivateKeyword */ : + case 124 /* ProtectedKeyword */ : + case 128 /* AbstractKeyword */ : + case 164 /* OverrideKeyword */ : + case 87 /* ConstKeyword */ : + case 138 /* DeclareKeyword */ : + case 148 /* ReadonlyKeyword */ : + case 103 /* InKeyword */ : + case 147 /* OutKeyword */ : + case 188 /* ArrayType */ : + case 189 /* TupleType */ : + case 190 /* OptionalType */ : + case 191 /* RestType */ : + case 187 /* TypeLiteral */ : + case 182 /* TypePredicate */ : + case 168 /* TypeParameter */ : + case 133 /* AnyKeyword */ : + case 159 /* UnknownKeyword */ : + case 136 /* BooleanKeyword */ : + case 154 /* StringKeyword */ : + case 150 /* NumberKeyword */ : + case 146 /* NeverKeyword */ : + case 116 /* VoidKeyword */ : + case 155 /* SymbolKeyword */ : + case 185 /* ConstructorType */ : + case 184 /* FunctionType */ : + case 186 /* TypeQuery */ : + case 183 /* TypeReference */ : + case 192 /* UnionType */ : + case 193 /* IntersectionType */ : + case 194 /* ConditionalType */ : + case 196 /* ParenthesizedType */ : + case 197 /* ThisType */ : + case 198 /* TypeOperator */ : + case 199 /* IndexedAccessType */ : + case 200 /* MappedType */ : + case 201 /* LiteralType */ : + case 181 /* IndexSignature */ : return void 0; - case 262 /* TypeAliasDeclaration */ : + case 265 /* TypeAliasDeclaration */ : return factory2.createNotEmittedStatement(node); - case 267 /* NamespaceExportDeclaration */ : + case 270 /* NamespaceExportDeclaration */ : return void 0; - case 261 /* InterfaceDeclaration */ : + case 264 /* InterfaceDeclaration */ : return factory2.createNotEmittedStatement(node); - case 260 /* ClassDeclaration */ : + case 263 /* ClassDeclaration */ : return visitClassDeclaration(node); - case 228 /* ClassExpression */ : + case 231 /* ClassExpression */ : return visitClassExpression(node); - case 294 /* HeritageClause */ : + case 298 /* HeritageClause */ : return visitHeritageClause(node); - case 230 /* ExpressionWithTypeArguments */ : + case 233 /* ExpressionWithTypeArguments */ : return visitExpressionWithTypeArguments(node); - case 207 /* ObjectLiteralExpression */ : + case 210 /* ObjectLiteralExpression */ : return visitObjectLiteralExpression(node); - case 173 /* Constructor */ : - case 169 /* PropertyDeclaration */ : - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 172 /* ClassStaticBlockDeclaration */ : + case 176 /* Constructor */ : + case 172 /* PropertyDeclaration */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 175 /* ClassStaticBlockDeclaration */ : return Debug.fail("Class and object literal elements must be visited with their respective visitors"); - case 259 /* FunctionDeclaration */ : + case 262 /* FunctionDeclaration */ : return visitFunctionDeclaration(node); - case 215 /* FunctionExpression */ : + case 218 /* FunctionExpression */ : return visitFunctionExpression(node); - case 216 /* ArrowFunction */ : + case 219 /* ArrowFunction */ : return visitArrowFunction(node); - case 166 /* Parameter */ : + case 169 /* Parameter */ : return visitParameter(node); - case 214 /* ParenthesizedExpression */ : + case 217 /* ParenthesizedExpression */ : return visitParenthesizedExpression(node); - case 213 /* TypeAssertionExpression */ : - case 231 /* AsExpression */ : + case 216 /* TypeAssertionExpression */ : + case 234 /* AsExpression */ : return visitAssertionExpression(node); - case 235 /* SatisfiesExpression */ : + case 238 /* SatisfiesExpression */ : return visitSatisfiesExpression(node); - case 210 /* CallExpression */ : + case 213 /* CallExpression */ : return visitCallExpression(node); - case 211 /* NewExpression */ : + case 214 /* NewExpression */ : return visitNewExpression(node); - case 212 /* TaggedTemplateExpression */ : + case 215 /* TaggedTemplateExpression */ : return visitTaggedTemplateExpression(node); - case 232 /* NonNullExpression */ : + case 235 /* NonNullExpression */ : return visitNonNullExpression(node); - case 263 /* EnumDeclaration */ : + case 266 /* EnumDeclaration */ : return visitEnumDeclaration(node); - case 240 /* VariableStatement */ : + case 243 /* VariableStatement */ : return visitVariableStatement(node); - case 257 /* VariableDeclaration */ : + case 260 /* VariableDeclaration */ : return visitVariableDeclaration(node); - case 264 /* ModuleDeclaration */ : + case 267 /* ModuleDeclaration */ : return visitModuleDeclaration(node); - case 268 /* ImportEqualsDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : return visitImportEqualsDeclaration(node); - case 282 /* JsxSelfClosingElement */ : + case 285 /* JsxSelfClosingElement */ : return visitJsxSelfClosingElement(node); - case 283 /* JsxOpeningElement */ : + case 286 /* JsxOpeningElement */ : return visitJsxJsxOpeningElement(node); default: return visitEachChild(node, visitor, context); @@ -74503,9 +75650,9 @@ ${lanes.join("\n")} } function getClassFacts(node) { let facts = 0 /* None */ ; - if (some(getProperties(node, /*requireInitialized*/ true, /*isStatic*/ true))) facts |= 1 /* HasStaticInitializedProperties */ ; + if (some(getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true))) facts |= 1 /* HasStaticInitializedProperties */ ; const extendsClauseElement = getEffectiveBaseTypeNode(node); - if (extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 104 /* NullKeyword */ ) facts |= 64 /* IsDerivedClass */ ; + if (extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 106 /* NullKeyword */ ) facts |= 64 /* IsDerivedClass */ ; if (classOrConstructorParameterIsDecorated(legacyDecorators, node)) facts |= 2 /* HasClassOrConstructorParameterDecorators */ ; if (childIsDecorated(legacyDecorators, node)) facts |= 4 /* HasMemberDecorators */ ; if (isExportOfNamespace(node)) facts |= 8 /* IsExportOfNamespace */ ; @@ -74520,16 +75667,15 @@ ${lanes.join("\n")} return hasDecorators(node) || some(node.typeParameters) || some(node.heritageClauses, hasTypeScriptClassSyntax) || some(node.members, hasTypeScriptClassSyntax); } function visitClassDeclaration(node) { - var _a2; const facts = getClassFacts(node); const promoteToIIFE = languageVersion <= 1 /* ES5 */ && !!(facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */ ); if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !classOrConstructorParameterIsDecorated(legacyDecorators, node) && !isExportOfNamespace(node)) return factory2.updateClassDeclaration(node, visitNodes2(node.modifiers, modifierVisitor, isModifier), node.name, /*typeParameters*/ void 0, visitNodes2(node.heritageClauses, visitor, isHeritageClause), visitNodes2(node.members, getClassElementVisitor(node), isClassElement)); if (promoteToIIFE) context.startLexicalEnvironment(); - const moveModifiers = promoteToIIFE || facts & 8 /* IsExportOfNamespace */ || facts & 2 /* HasClassOrConstructorParameterDecorators */ && legacyDecorators || facts & 1 /* HasStaticInitializedProperties */ ; + const moveModifiers = promoteToIIFE || facts & 8 /* IsExportOfNamespace */ ; let modifiers = moveModifiers ? visitNodes2(node.modifiers, modifierElidingVisitor, isModifierLike) : visitNodes2(node.modifiers, visitor, isModifierLike); if (facts & 2 /* HasClassOrConstructorParameterDecorators */ ) modifiers = injectClassTypeMetadata(modifiers, node); const needsName = moveModifiers && !node.name || facts & 4 /* HasMemberDecorators */ || facts & 1 /* HasStaticInitializedProperties */ ; - const name = needsName ? (_a2 = node.name) != null ? _a2 : factory2.getGeneratedNameForNode(node) : node.name; + const name = needsName ? node.name ?? factory2.getGeneratedNameForNode(node) : node.name; const classDeclaration = factory2.updateClassDeclaration(node, modifiers, name, /*typeParameters*/ void 0, visitNodes2(node.heritageClauses, visitor, isHeritageClause), transformClassMembers(node)); let emitFlags = getEmitFlags(node); if (facts & 1 /* HasStaticInitializedProperties */ ) emitFlags |= 64 /* NoTrailingSourceMap */ ; @@ -74539,7 +75685,7 @@ ${lanes.join("\n")} const statements = [ classDeclaration ]; - const closingBraceLocation = createTokenRange(skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */ ); + const closingBraceLocation = createTokenRange(skipTrivia(currentSourceFile.text, node.members.end), 20 /* CloseBraceToken */ ); const localName = factory2.getInternalName(node); const outer = factory2.createPartiallyEmittedExpression(localName); setTextRangeEnd(outer, closingBraceLocation.end); @@ -74551,9 +75697,10 @@ ${lanes.join("\n")} insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment()); const iife = factory2.createImmediatelyInvokedArrowFunction(statements); setInternalEmitFlags(iife, 1 /* TypeScriptClassWrapper */ ); - const modifiers2 = facts & 16 /* IsNamedExternalExport */ ? factory2.createModifiersFromModifierFlags(1 /* Export */ ) : void 0; - const varStatement = factory2.createVariableStatement(modifiers2, factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration(factory2.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), /*exclamationToken*/ void 0, /*type*/ void 0, iife) + const varDecl = factory2.createVariableDeclaration(factory2.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), /*exclamationToken*/ void 0, /*type*/ void 0, iife); + setOriginalNode(varDecl, node); + const varStatement = factory2.createVariableStatement(/*modifiers*/ void 0, factory2.createVariableDeclarationList([ + varDecl ], 1 /* Let */ )); setOriginalNode(varStatement, node); setCommentRange(varStatement, node); @@ -74562,20 +75709,21 @@ ${lanes.join("\n")} statement = varStatement; } else statement = classDeclaration; if (moveModifiers) { - if (facts & 8 /* IsExportOfNamespace */ ) return demarcateMultiStatementExport(statement, createExportMemberAssignmentStatement(node)); - if (facts & 32 /* IsDefaultExternalExport */ ) return demarcateMultiStatementExport(statement, factory2.createExportDefault(factory2.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); - if (facts & 16 /* IsNamedExternalExport */ && !promoteToIIFE) return demarcateMultiStatementExport(statement, factory2.createExternalModuleExport(factory2.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); + if (facts & 8 /* IsExportOfNamespace */ ) return [ + statement, + createExportMemberAssignmentStatement(node) + ]; + if (facts & 32 /* IsDefaultExternalExport */ ) return [ + statement, + factory2.createExportDefault(factory2.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) + ]; + if (facts & 16 /* IsNamedExternalExport */ ) return [ + statement, + factory2.createExternalModuleExport(factory2.getDeclarationName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) + ]; } return statement; } - function demarcateMultiStatementExport(declarationStatement, exportStatement) { - addEmitFlags(declarationStatement, 8388608 /* HasEndOfDeclarationMarker */ ); - return [ - declarationStatement, - exportStatement, - factory2.createEndOfDeclarationMarker(declarationStatement) - ]; - } function visitClassExpression(node) { let modifiers = visitNodes2(node.modifiers, modifierElidingVisitor, isModifierLike); if (classOrConstructorParameterIsDecorated(legacyDecorators, node)) modifiers = injectClassTypeMetadata(modifiers, node); @@ -74657,21 +75805,21 @@ ${lanes.join("\n")} if (typeSerializer) { let properties; if (shouldAddTypeMetadata(node)) { - const typeProperty = factory2.createPropertyAssignment("type", factory2.createArrowFunction(/*modifiers*/ void 0, /*typeParameters*/ void 0, [], /*type*/ void 0, factory2.createToken(38 /* EqualsGreaterThanToken */ ), typeSerializer.serializeTypeOfNode({ + const typeProperty = factory2.createPropertyAssignment("type", factory2.createArrowFunction(/*modifiers*/ void 0, /*typeParameters*/ void 0, [], /*type*/ void 0, factory2.createToken(39 /* EqualsGreaterThanToken */ ), typeSerializer.serializeTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node))); properties = append(properties, typeProperty); } if (shouldAddParamTypesMetadata(node)) { - const paramTypeProperty = factory2.createPropertyAssignment("paramTypes", factory2.createArrowFunction(/*modifiers*/ void 0, /*typeParameters*/ void 0, [], /*type*/ void 0, factory2.createToken(38 /* EqualsGreaterThanToken */ ), typeSerializer.serializeParameterTypesOfNode({ + const paramTypeProperty = factory2.createPropertyAssignment("paramTypes", factory2.createArrowFunction(/*modifiers*/ void 0, /*typeParameters*/ void 0, [], /*type*/ void 0, factory2.createToken(39 /* EqualsGreaterThanToken */ ), typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node, container))); properties = append(properties, paramTypeProperty); } if (shouldAddReturnTypeMetadata(node)) { - const returnTypeProperty = factory2.createPropertyAssignment("returnType", factory2.createArrowFunction(/*modifiers*/ void 0, /*typeParameters*/ void 0, [], /*type*/ void 0, factory2.createToken(38 /* EqualsGreaterThanToken */ ), typeSerializer.serializeReturnTypeOfNode({ + const returnTypeProperty = factory2.createPropertyAssignment("returnType", factory2.createArrowFunction(/*modifiers*/ void 0, /*typeParameters*/ void 0, [], /*type*/ void 0, factory2.createToken(39 /* EqualsGreaterThanToken */ ), typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node))); @@ -74687,19 +75835,19 @@ ${lanes.join("\n")} } function shouldAddTypeMetadata(node) { const kind = node.kind; - return kind === 171 /* MethodDeclaration */ || kind === 174 /* GetAccessor */ || kind === 175 /* SetAccessor */ || kind === 169 /* PropertyDeclaration */ ; + return kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ || kind === 172 /* PropertyDeclaration */ ; } function shouldAddReturnTypeMetadata(node) { - return node.kind === 171 /* MethodDeclaration */ ; + return node.kind === 174 /* MethodDeclaration */ ; } function shouldAddParamTypesMetadata(node) { switch(node.kind){ - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : return getFirstConstructorWithBody(node) !== void 0; - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : return true; } return false; @@ -74726,7 +75874,7 @@ ${lanes.join("\n")} return Debug.checkDefined(visitNode(name, visitor, isPropertyName)); } function visitHeritageClause(node) { - if (node.token === 117 /* ImplementsKeyword */ ) return void 0; + if (node.token === 119 /* ImplementsKeyword */ ) return void 0; return visitEachChild(node, visitor, context); } function visitExpressionWithTypeArguments(node) { @@ -74736,7 +75884,7 @@ ${lanes.join("\n")} return !nodeIsMissing(node.body); } function visitPropertyDeclaration(node, parent2) { - const isAmbient = node.flags & 16777216 /* Ambient */ || hasSyntacticModifier(node, 256 /* Abstract */ ); + const isAmbient = node.flags & 33554432 /* Ambient */ || hasSyntacticModifier(node, 256 /* Abstract */ ); if (isAmbient && !(legacyDecorators && hasDecorators(node))) return void 0; let modifiers = isClassLike(parent2) ? !isAmbient ? visitNodes2(node.modifiers, visitor, isModifierLike) : visitNodes2(node.modifiers, modifierElidingVisitor, isModifierLike) : visitNodes2(node.modifiers, decoratorElidingVisitor, isModifierLike); modifiers = injectClassElementTypeMetadata(modifiers, node, parent2); @@ -74747,23 +75895,35 @@ ${lanes.join("\n")} if (!shouldEmitFunctionLikeDeclaration(node)) return void 0; return factory2.updateConstructorDeclaration(node, /*modifiers*/ void 0, visitParameterList(node.parameters, visitor, context), transformConstructorBody(node.body, node)); } + function transformConstructorBodyWorker(statementsOut, statementsIn, statementOffset, superPath, superPathDepth, initializerStatements) { + const superStatementIndex = superPath[superPathDepth]; + const superStatement = statementsIn[superStatementIndex]; + addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, statementOffset, superStatementIndex - statementOffset)); + if (isTryStatement(superStatement)) { + const tryBlockStatements = []; + transformConstructorBodyWorker(tryBlockStatements, superStatement.tryBlock.statements, /*statementOffset*/ 0, superPath, superPathDepth + 1, initializerStatements); + const tryBlockStatementsArray = factory2.createNodeArray(tryBlockStatements); + setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); + statementsOut.push(factory2.updateTryStatement(superStatement, factory2.updateBlock(superStatement.tryBlock, tryBlockStatements), visitNode(superStatement.catchClause, visitor, isCatchClause), visitNode(superStatement.finallyBlock, visitor, isBlock))); + } else { + addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, superStatementIndex, 1)); + addRange(statementsOut, initializerStatements); + } + addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, superStatementIndex + 1)); + } function transformConstructorBody(body, constructor) { const parametersWithPropertyAssignments = constructor && filter(constructor.parameters, (p)=>isParameterPropertyDeclaration(p, constructor)); if (!some(parametersWithPropertyAssignments)) return visitFunctionBody(body, visitor, context); let statements = []; resumeLexicalEnvironment(); const prologueStatementCount = factory2.copyPrologue(body.statements, statements, /*ensureUseStrict*/ false, visitor); - const superStatementIndex = findSuperStatementIndex(body.statements, prologueStatementCount); - if (superStatementIndex >= 0) addRange(statements, visitNodes2(body.statements, visitor, isStatement, prologueStatementCount, superStatementIndex + 1 - prologueStatementCount)); + const superPath = findSuperStatementIndexPath(body.statements, prologueStatementCount); const parameterPropertyAssignments = mapDefined(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment); - if (superStatementIndex >= 0) addRange(statements, parameterPropertyAssignments); - else statements = [ - ...statements.slice(0, prologueStatementCount), - ...parameterPropertyAssignments, - ...statements.slice(prologueStatementCount) - ]; - const start = superStatementIndex >= 0 ? superStatementIndex + 1 : prologueStatementCount; - addRange(statements, visitNodes2(body.statements, visitor, isStatement, start)); + if (superPath.length) transformConstructorBodyWorker(statements, body.statements, prologueStatementCount, superPath, /*superPathDepth*/ 0, parameterPropertyAssignments); + else { + addRange(statements, parameterPropertyAssignments); + addRange(statements, visitNodes2(body.statements, visitor, isStatement, prologueStatementCount)); + } statements = factory2.mergeLexicalEnvironment(statements, endLexicalEnvironment()); const block = factory2.createBlock(setTextRange(factory2.createNodeArray(statements), body.statements), /*multiLine*/ true); setTextRange(block, /*location*/ body); @@ -74904,9 +76064,9 @@ ${lanes.join("\n")} } const parameterName = getNamespaceParameterName(node); const containerName = getNamespaceContainerName(node); - const exportName = hasSyntacticModifier(node, 1 /* Export */ ) ? factory2.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true) : factory2.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + const exportName = isExportOfNamespace(node) ? factory2.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true) : factory2.getDeclarationName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); let moduleArg = factory2.createLogicalOr(exportName, factory2.createAssignment(exportName, factory2.createObjectLiteralExpression())); - if (hasNamespaceQualifiedExportName(node)) { + if (isExportOfNamespace(node)) { const localName = factory2.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); moduleArg = factory2.createAssignment(localName, moduleArg); } @@ -74923,7 +76083,6 @@ ${lanes.join("\n")} setTextRange(enumStatement, node); addEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); - statements.push(factory2.createEndOfDeclarationMarker(node)); return statements; } function transformEnumBody(node, localName) { @@ -74941,7 +76100,7 @@ ${lanes.join("\n")} const name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false); const valueExpression = transformEnumMemberDeclarationValue(member); const innerAssignment = factory2.createAssignment(factory2.createElementAccessExpression(currentNamespaceContainerName, name), valueExpression); - const outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ? innerAssignment : factory2.createAssignment(factory2.createElementAccessExpression(currentNamespaceContainerName, innerAssignment), name); + const outerAssignment = valueExpression.kind === 11 /* StringLiteral */ ? innerAssignment : factory2.createAssignment(factory2.createElementAccessExpression(currentNamespaceContainerName, innerAssignment), name); return setTextRange(factory2.createExpressionStatement(setTextRange(outerAssignment, member)), member); } function transformEnumMemberDeclarationValue(member) { @@ -74958,9 +76117,6 @@ ${lanes.join("\n")} if (!node) return true; return isInstantiatedModule(node, shouldPreserveConstEnums(compilerOptions)); } - function hasNamespaceQualifiedExportName(node) { - return isExportOfNamespace(node) || isExternalModuleExport(node) && moduleKind !== 5 /* ES2015 */ && moduleKind !== 6 /* ES2020 */ && moduleKind !== 7 /* ES2022 */ && moduleKind !== 99 /* ESNext */ && moduleKind !== 4 /* System */ ; - } function recordEmittedDeclarationInScope(node) { if (!currentScopeFirstDeclarationsOfName) currentScopeFirstDeclarationsOfName = /* @__PURE__ */ new Map(); const name = declaredNameInScope(node); @@ -74978,24 +76134,25 @@ ${lanes.join("\n")} return node.name.escapedText; } function addVarForEnumOrModuleDeclaration(statements, node) { + const varDecl = factory2.createVariableDeclaration(factory2.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)); + const varFlags = currentLexicalScope.kind === 312 /* SourceFile */ ? 0 /* None */ : 1 /* Let */ ; const statement = factory2.createVariableStatement(visitNodes2(node.modifiers, modifierVisitor, isModifier), factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration(factory2.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ], currentLexicalScope.kind === 308 /* SourceFile */ ? 0 /* None */ : 1 /* Let */ )); + varDecl + ], varFlags)); + setOriginalNode(varDecl, node); + setSyntheticLeadingComments(varDecl, void 0); + setSyntheticTrailingComments(varDecl, void 0); setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { - if (node.kind === 263 /* EnumDeclaration */ ) setSourceMapRange(statement.declarationList, node); + if (node.kind === 266 /* EnumDeclaration */ ) setSourceMapRange(statement.declarationList, node); else setSourceMapRange(statement, node); setCommentRange(statement, node); - addEmitFlags(statement, 8390656 /* HasEndOfDeclarationMarker */ ); + addEmitFlags(statement, 2048 /* NoTrailingComments */ ); statements.push(statement); return true; - } else { - const mergeMarker = factory2.createMergeDeclarationMarker(statement); - setEmitFlags(mergeMarker, 8391680 /* HasEndOfDeclarationMarker */ ); - statements.push(mergeMarker); - return false; } + return false; } function visitModuleDeclaration(node) { if (!shouldEmitModuleDeclaration(node)) return factory2.createNotEmittedStatement(node); @@ -75009,9 +76166,9 @@ ${lanes.join("\n")} } const parameterName = getNamespaceParameterName(node); const containerName = getNamespaceContainerName(node); - const exportName = hasSyntacticModifier(node, 1 /* Export */ ) ? factory2.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true) : factory2.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + const exportName = isExportOfNamespace(node) ? factory2.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true) : factory2.getDeclarationName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); let moduleArg = factory2.createLogicalOr(exportName, factory2.createAssignment(exportName, factory2.createObjectLiteralExpression())); - if (hasNamespaceQualifiedExportName(node)) { + if (isExportOfNamespace(node)) { const localName = factory2.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); moduleArg = factory2.createAssignment(localName, moduleArg); } @@ -75028,7 +76185,6 @@ ${lanes.join("\n")} setTextRange(moduleStatement, node); addEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); - statements.push(factory2.createEndOfDeclarationMarker(node)); return statements; } function transformModuleBody(node, namespaceLocalName) { @@ -75043,7 +76199,7 @@ ${lanes.join("\n")} let statementsLocation; let blockLocation; if (node.body) { - if (node.body.kind === 265 /* ModuleBlock */ ) { + if (node.body.kind === 268 /* ModuleBlock */ ) { saveStateAndInvoke(node.body, (body)=>addRange(statements, visitNodes2(body.statements, namespaceElementVisitor, isStatement))); statementsLocation = node.body.statements; blockLocation = node.body; @@ -75063,11 +76219,11 @@ ${lanes.join("\n")} currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; const block = factory2.createBlock(setTextRange(factory2.createNodeArray(statements), /*location*/ statementsLocation), /*multiLine*/ true); setTextRange(block, blockLocation); - if (!node.body || node.body.kind !== 265 /* ModuleBlock */ ) setEmitFlags(block, getEmitFlags(block) | 3072 /* NoComments */ ); + if (!node.body || node.body.kind !== 268 /* ModuleBlock */ ) setEmitFlags(block, getEmitFlags(block) | 3072 /* NoComments */ ); return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 264 /* ModuleDeclaration */ ) { + if (moduleDeclaration.body.kind === 267 /* ModuleDeclaration */ ) { const recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -75085,7 +76241,7 @@ ${lanes.join("\n")} return name || namedBindings ? factory2.updateImportClause(node, /*isTypeOnly*/ false, name, namedBindings) : void 0; } function visitNamedImportBindings(node) { - if (node.kind === 271 /* NamespaceImport */ ) return shouldEmitAliasDeclaration(node) ? node : void 0; + if (node.kind === 274 /* NamespaceImport */ ) return shouldEmitAliasDeclaration(node) ? node : void 0; else { const allowEmpty = compilerOptions.verbatimModuleSyntax || compilerOptions.preserveValueImports && (compilerOptions.importsNotUsedAsValues === 1 /* Preserve */ || compilerOptions.importsNotUsedAsValues === 2 /* Error */ ); const elements = visitNodes2(node.elements, visitImportSpecifier, isImportSpecifier); @@ -75178,22 +76334,22 @@ ${lanes.join("\n")} function enableSubstitutionForNonQualifiedEnumMembers() { if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ ) === 0) { enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */ ; - context.enableSubstitution(79 /* Identifier */ ); + context.enableSubstitution(80 /* Identifier */ ); } } function enableSubstitutionForNamespaceExports() { if ((enabledSubstitutions & 2 /* NamespaceExports */ ) === 0) { enabledSubstitutions |= 2 /* NamespaceExports */ ; - context.enableSubstitution(79 /* Identifier */ ); - context.enableSubstitution(300 /* ShorthandPropertyAssignment */ ); - context.enableEmitNotification(264 /* ModuleDeclaration */ ); + context.enableSubstitution(80 /* Identifier */ ); + context.enableSubstitution(304 /* ShorthandPropertyAssignment */ ); + context.enableEmitNotification(267 /* ModuleDeclaration */ ); } } function isTransformedModuleDeclaration(node) { - return getOriginalNode(node).kind === 264 /* ModuleDeclaration */ ; + return getOriginalNode(node).kind === 267 /* ModuleDeclaration */ ; } function isTransformedEnumDeclaration(node) { - return getOriginalNode(node).kind === 263 /* EnumDeclaration */ ; + return getOriginalNode(node).kind === 266 /* EnumDeclaration */ ; } function onEmitNode(hint, node, emitCallback) { const savedApplicableSubstitutions = applicableSubstitutions; @@ -75227,11 +76383,11 @@ ${lanes.join("\n")} } function substituteExpression(node) { switch(node.kind){ - case 79 /* Identifier */ : + case 80 /* Identifier */ : return substituteExpressionIdentifier(node); - case 208 /* PropertyAccessExpression */ : + case 211 /* PropertyAccessExpression */ : return substitutePropertyAccessExpression(node); - case 209 /* ElementAccessExpression */ : + case 212 /* ElementAccessExpression */ : return substituteElementAccessExpression(node); } return node; @@ -75242,8 +76398,8 @@ ${lanes.join("\n")} function trySubstituteNamespaceExportedName(node) { if (enabledSubstitutions & applicableSubstitutions && !isGeneratedIdentifier(node) && !isLocalName(node)) { const container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); - if (container && container.kind !== 308 /* SourceFile */ ) { - const substitute = applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 264 /* ModuleDeclaration */ || applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 263 /* EnumDeclaration */ ; + if (container && container.kind !== 312 /* SourceFile */ ) { + const substitute = applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 267 /* ModuleDeclaration */ || applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 266 /* EnumDeclaration */ ; if (substitute) return setTextRange(factory2.createPropertyAccessExpression(factory2.getGeneratedNameForNode(container), node), /*location*/ node); } } @@ -75262,7 +76418,7 @@ ${lanes.join("\n")} const constantValue = tryGetConstEnumValue(node); if (constantValue !== void 0) { setConstantValue(node, constantValue); - const substitute = typeof constantValue === "string" ? factory2.createStringLiteral(constantValue) : factory2.createNumericLiteral(constantValue); + const substitute = typeof constantValue === "string" ? factory2.createStringLiteral(constantValue) : constantValue < 0 ? factory2.createPrefixUnaryExpression(41 /* MinusToken */ , factory2.createNumericLiteral(Math.abs(constantValue))) : factory2.createNumericLiteral(constantValue); if (!compilerOptions.removeComments) { const originalNode = getOriginalNode(node, isAccessExpression); addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */ , ` ${safeMultiLineComment(getTextOfNode(originalNode))} `); @@ -75289,7 +76445,7 @@ ${lanes.join("\n")} }); // src/compiler/transformers/classFields.ts function transformClassFields(context) { - const { factory: factory2 , getEmitHelperFactory: emitHelpers , hoistVariableDeclaration: hoistVariableDeclaration , endLexicalEnvironment: endLexicalEnvironment , startLexicalEnvironment: startLexicalEnvironment , resumeLexicalEnvironment: resumeLexicalEnvironment , addBlockScopedVariable: addBlockScopedVariable } = context; + const { factory: factory2, getEmitHelperFactory: emitHelpers, hoistVariableDeclaration: hoistVariableDeclaration, endLexicalEnvironment: endLexicalEnvironment, startLexicalEnvironment: startLexicalEnvironment, resumeLexicalEnvironment: resumeLexicalEnvironment, addBlockScopedVariable: addBlockScopedVariable } = context; const resolver = context.getEmitResolver(); const compilerOptions = context.getCompilerOptions(); const languageVersion = getEmitScriptTarget(compilerOptions); @@ -75314,8 +76470,9 @@ ${lanes.join("\n")} let pendingStatements; let lexicalEnvironment; const lexicalEnvironmentMap = /* @__PURE__ */ new Map(); + const noSubstitution = /* @__PURE__ */ new Set(); let currentClassContainer; - let currentStaticPropertyDeclarationOrStaticBlock; + let currentClassElement; let shouldSubstituteThisWithClassThis = false; let previousShouldSubstituteThisWithClassThis = false; return chainBundle(context, transformSourceFile); @@ -75330,7 +76487,7 @@ ${lanes.join("\n")} } function modifierVisitor(node) { switch(node.kind){ - case 127 /* AccessorKeyword */ : + case 129 /* AccessorKeyword */ : return shouldTransformAutoAccessorsInCurrentClass() ? void 0 : node; default: return tryCast(node, isModifier); @@ -75339,55 +76496,58 @@ ${lanes.join("\n")} function visitor(node) { if (!(node.transformFlags & 16777216 /* ContainsClassFields */ ) && !(node.transformFlags & 134234112 /* ContainsLexicalThisOrSuper */ )) return node; switch(node.kind){ - case 127 /* AccessorKeyword */ : + case 129 /* AccessorKeyword */ : return Debug.fail("Use `modifierVisitor` instead."); - case 260 /* ClassDeclaration */ : + case 263 /* ClassDeclaration */ : return visitClassDeclaration(node); - case 228 /* ClassExpression */ : - return visitClassExpression(node, /*referencedName*/ void 0); - case 172 /* ClassStaticBlockDeclaration */ : - case 169 /* PropertyDeclaration */ : + case 231 /* ClassExpression */ : + return visitClassExpression(node); + case 175 /* ClassStaticBlockDeclaration */ : + case 172 /* PropertyDeclaration */ : return Debug.fail("Use `classElementVisitor` instead."); - case 299 /* PropertyAssignment */ : + case 303 /* PropertyAssignment */ : return visitPropertyAssignment(node); - case 240 /* VariableStatement */ : + case 243 /* VariableStatement */ : return visitVariableStatement(node); - case 257 /* VariableDeclaration */ : + case 260 /* VariableDeclaration */ : return visitVariableDeclaration(node); - case 166 /* Parameter */ : + case 169 /* Parameter */ : return visitParameterDeclaration(node); - case 205 /* BindingElement */ : + case 208 /* BindingElement */ : return visitBindingElement(node); - case 274 /* ExportAssignment */ : + case 277 /* ExportAssignment */ : return visitExportAssignment(node); - case 80 /* PrivateIdentifier */ : + case 81 /* PrivateIdentifier */ : return visitPrivateIdentifier(node); - case 208 /* PropertyAccessExpression */ : + case 211 /* PropertyAccessExpression */ : return visitPropertyAccessExpression(node); - case 209 /* ElementAccessExpression */ : + case 212 /* ElementAccessExpression */ : return visitElementAccessExpression(node); - case 221 /* PrefixUnaryExpression */ : - case 222 /* PostfixUnaryExpression */ : + case 224 /* PrefixUnaryExpression */ : + case 225 /* PostfixUnaryExpression */ : return visitPreOrPostfixUnaryExpression(node, /*discarded*/ false); - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : return visitBinaryExpression(node, /*discarded*/ false); - case 214 /* ParenthesizedExpression */ : - return visitParenthesizedExpression(node, /*discarded*/ false, /*referencedName*/ void 0); - case 210 /* CallExpression */ : + case 217 /* ParenthesizedExpression */ : + return visitParenthesizedExpression(node, /*discarded*/ false); + case 213 /* CallExpression */ : return visitCallExpression(node); - case 241 /* ExpressionStatement */ : + case 244 /* ExpressionStatement */ : return visitExpressionStatement(node); - case 212 /* TaggedTemplateExpression */ : + case 215 /* TaggedTemplateExpression */ : return visitTaggedTemplateExpression(node); - case 245 /* ForStatement */ : + case 248 /* ForStatement */ : return visitForStatement(node); - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 173 /* Constructor */ : - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - return setCurrentStaticPropertyDeclarationOrStaticBlockAnd(/*current*/ void 0, fallbackVisitor, node); + case 110 /* ThisKeyword */ : + return visitThisExpression(node); + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + return setCurrentClassElementAnd(/*classElement*/ void 0, fallbackVisitor, node); + case 176 /* Constructor */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + return setCurrentClassElementAnd(node, fallbackVisitor, node); default: return fallbackVisitor(node); } @@ -75395,38 +76555,26 @@ ${lanes.join("\n")} function fallbackVisitor(node) { return visitEachChild(node, visitor, context); } - function namedEvaluationVisitor(node, referencedName) { - switch(node.kind){ - case 356 /* PartiallyEmittedExpression */ : - return visitPartiallyEmittedExpression(node, /*discarded*/ false, referencedName); - case 214 /* ParenthesizedExpression */ : - return visitParenthesizedExpression(node, /*discarded*/ false, referencedName); - case 228 /* ClassExpression */ : - return visitClassExpression(node, referencedName); - default: - return visitor(node); - } - } function discardedValueVisitor(node) { switch(node.kind){ - case 221 /* PrefixUnaryExpression */ : - case 222 /* PostfixUnaryExpression */ : + case 224 /* PrefixUnaryExpression */ : + case 225 /* PostfixUnaryExpression */ : return visitPreOrPostfixUnaryExpression(node, /*discarded*/ true); - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : return visitBinaryExpression(node, /*discarded*/ true); - case 357 /* CommaListExpression */ : + case 361 /* CommaListExpression */ : return visitCommaListExpression(node, /*discarded*/ true); - case 214 /* ParenthesizedExpression */ : - return visitParenthesizedExpression(node, /*discarded*/ true, /*referencedName*/ void 0); + case 217 /* ParenthesizedExpression */ : + return visitParenthesizedExpression(node, /*discarded*/ true); default: return visitor(node); } } function heritageClauseVisitor(node) { switch(node.kind){ - case 294 /* HeritageClause */ : + case 298 /* HeritageClause */ : return visitEachChild(node, heritageClauseVisitor, context); - case 230 /* ExpressionWithTypeArguments */ : + case 233 /* ExpressionWithTypeArguments */ : return visitExpressionWithTypeArgumentsInHeritageClause(node); default: return visitor(node); @@ -75434,8 +76582,8 @@ ${lanes.join("\n")} } function assignmentTargetVisitor(node) { switch(node.kind){ - case 207 /* ObjectLiteralExpression */ : - case 206 /* ArrayLiteralExpression */ : + case 210 /* ObjectLiteralExpression */ : + case 209 /* ArrayLiteralExpression */ : return visitAssignmentPattern(node); default: return visitor(node); @@ -75443,19 +76591,19 @@ ${lanes.join("\n")} } function classElementVisitor(node) { switch(node.kind){ - case 173 /* Constructor */ : - return visitConstructorDeclaration(node); - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 171 /* MethodDeclaration */ : - return setCurrentStaticPropertyDeclarationOrStaticBlockAnd(/*current*/ void 0, visitMethodOrAccessorDeclaration, node); - case 169 /* PropertyDeclaration */ : - return setCurrentStaticPropertyDeclarationOrStaticBlockAnd(/*current*/ void 0, visitPropertyDeclaration, node); - case 172 /* ClassStaticBlockDeclaration */ : - return visitClassStaticBlockDeclaration(node); - case 164 /* ComputedPropertyName */ : + case 176 /* Constructor */ : + return setCurrentClassElementAnd(node, visitConstructorDeclaration, node); + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 174 /* MethodDeclaration */ : + return setCurrentClassElementAnd(node, visitMethodOrAccessorDeclaration, node); + case 172 /* PropertyDeclaration */ : + return setCurrentClassElementAnd(node, visitPropertyDeclaration, node); + case 175 /* ClassStaticBlockDeclaration */ : + return setCurrentClassElementAnd(node, visitClassStaticBlockDeclaration, node); + case 167 /* ComputedPropertyName */ : return visitComputedPropertyName(node); - case 237 /* SemicolonClassElement */ : + case 240 /* SemicolonClassElement */ : return node; default: return isModifierLike(node) ? modifierVisitor(node) : visitor(node); @@ -75463,7 +76611,7 @@ ${lanes.join("\n")} } function propertyNameVisitor(node) { switch(node.kind){ - case 164 /* ComputedPropertyName */ : + case 167 /* ComputedPropertyName */ : return visitComputedPropertyName(node); default: return visitor(node); @@ -75471,10 +76619,10 @@ ${lanes.join("\n")} } function accessorFieldResultVisitor(node) { switch(node.kind){ - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : return transformFieldInitializer(node); - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : return classElementVisitor(node); default: Debug.assertMissingNode(node, "Expected node to either be a PropertyDeclaration, GetAccessorDeclaration, or SetAccessorDeclaration"); @@ -75495,11 +76643,7 @@ ${lanes.join("\n")} return visitEachChild(node, visitor, context); } function visitPropertyAssignment(node) { - if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - const { referencedName: referencedName , name: name } = visitReferencedPropertyName(node.name); - const initializer = visitNode(node.initializer, (node2)=>namedEvaluationVisitor(node2, referencedName), isExpression); - return factory2.updatePropertyAssignment(node, name, initializer); - } + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) node = transformNamedEvaluation(context, node); return visitEachChild(node, visitor, context); } function visitVariableStatement(node) { @@ -75513,45 +76657,20 @@ ${lanes.join("\n")} pendingStatements = savedPendingStatements; return statement; } - function getAssignedNameOfIdentifier(name, initializer) { - const originalClass = getOriginalNode(initializer, isClassLike); - return originalClass && !originalClass.name && hasSyntacticModifier(originalClass, 1024 /* Default */ ) ? factory2.createStringLiteral("default") : factory2.createStringLiteralFromNode(name); - } function visitVariableDeclaration(node) { - if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer); - const name = visitNode(node.name, visitor, isBindingName); - const initializer = visitNode(node.initializer, (node2)=>namedEvaluationVisitor(node2, assignedName), isExpression); - return factory2.updateVariableDeclaration(node, name, /*exclamationToken*/ void 0, /*type*/ void 0, initializer); - } + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) node = transformNamedEvaluation(context, node); return visitEachChild(node, visitor, context); } function visitParameterDeclaration(node) { - if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer); - const name = visitNode(node.name, visitor, isBindingName); - const initializer = visitNode(node.initializer, (node2)=>namedEvaluationVisitor(node2, assignedName), isExpression); - return factory2.updateParameterDeclaration(node, /*modifiers*/ void 0, /*dotDotDotToken*/ void 0, name, /*questionToken*/ void 0, /*type*/ void 0, initializer); - } + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) node = transformNamedEvaluation(context, node); return visitEachChild(node, visitor, context); } function visitBindingElement(node) { - if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer); - const propertyName = visitNode(node.propertyName, visitor, isPropertyName); - const name = visitNode(node.name, visitor, isBindingName); - const initializer = visitNode(node.initializer, (node2)=>namedEvaluationVisitor(node2, assignedName), isExpression); - return factory2.updateBindingElement(node, /*dotDotDotToken*/ void 0, propertyName, name, initializer); - } + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) node = transformNamedEvaluation(context, node); return visitEachChild(node, visitor, context); } function visitExportAssignment(node) { - if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - const assignedName = factory2.createStringLiteral(node.isExportEquals ? "" : "default"); - const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); - const expression = visitNode(node.expression, (node2)=>namedEvaluationVisitor(node2, assignedName), isExpression); - return factory2.updateExportAssignment(node, modifiers, expression); - } + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) node = transformNamedEvaluation(context, node, /*ignoreEmptyStringLiteral*/ true, node.isExportEquals ? "" : "default"); return visitEachChild(node, visitor, context); } function injectPendingExpressions(expression) { @@ -75587,15 +76706,18 @@ ${lanes.join("\n")} Debug.assert(info, "Undeclared private name for property declaration."); if (!info.isValid) return node; const functionName = getHoistedFunctionName(node); - if (functionName) getPendingExpressions().push(factory2.createAssignment(functionName, factory2.createFunctionExpression(filter(node.modifiers, (m)=>isModifier(m) && !isStaticModifier(m) && !isAccessorModifier(m)), node.asteriskToken, functionName, /* typeParameters */ void 0, visitParameterList(node.parameters, visitor, context), /* type */ void 0, visitFunctionBody(node.body, visitor, context)))); + if (functionName) getPendingExpressions().push(factory2.createAssignment(functionName, factory2.createFunctionExpression(filter(node.modifiers, (m)=>isModifier(m) && !isStaticModifier(m) && !isAccessorModifier(m)), node.asteriskToken, functionName, /*typeParameters*/ void 0, visitParameterList(node.parameters, visitor, context), /*type*/ void 0, visitFunctionBody(node.body, visitor, context)))); return void 0; } - function setCurrentStaticPropertyDeclarationOrStaticBlockAnd(current, visitor2, arg) { - const savedCurrentStaticPropertyDeclarationOrStaticBlock = currentStaticPropertyDeclarationOrStaticBlock; - currentStaticPropertyDeclarationOrStaticBlock = current; - const result = visitor2(arg); - currentStaticPropertyDeclarationOrStaticBlock = savedCurrentStaticPropertyDeclarationOrStaticBlock; - return result; + function setCurrentClassElementAnd(classElement, visitor2, arg) { + if (classElement !== currentClassElement) { + const savedCurrentClassElement = currentClassElement; + currentClassElement = classElement; + const result = visitor2(arg); + currentClassElement = savedCurrentClassElement; + return result; + } + return visitor2(arg); } function getHoistedFunctionName(node) { Debug.assert(isPrivateIdentifier(node.name)); @@ -75607,6 +76729,11 @@ ${lanes.join("\n")} if (isSetAccessor(node)) return info.setterName; } } + function getClassThis() { + const lex = getClassLexicalEnvironment(); + const classThis = lex.classThis ?? lex.classConstructor ?? (currentClassContainer == null ? void 0 : currentClassContainer.name); + return Debug.checkDefined(classThis); + } function transformAutoAccessor(node) { const commentRange = getCommentRange(node); const sourceMapRange = getSourceMapRange(node); @@ -75633,11 +76760,13 @@ ${lanes.join("\n")} setOriginalNode(backingField, node); setEmitFlags(backingField, 3072 /* NoComments */ ); setSourceMapRange(backingField, sourceMapRange); - const getter = createAccessorPropertyGetRedirector(factory2, node, modifiers, getterName); + const receiver = isStatic(node) ? getClassThis() : factory2.createThis(); + const getter = createAccessorPropertyGetRedirector(factory2, node, modifiers, getterName, receiver); setOriginalNode(getter, node); setCommentRange(getter, commentRange); setSourceMapRange(getter, sourceMapRange); - const setter = createAccessorPropertySetRedirector(factory2, node, modifiers, setterName); + const setterModifiers = factory2.createModifiersFromModifierFlags(modifiersToFlags(modifiers)); + const setter = createAccessorPropertySetRedirector(factory2, node, setterModifiers, setterName, receiver); setOriginalNode(setter, node); setEmitFlags(setter, 3072 /* NoComments */ ); setSourceMapRange(setter, sourceMapRange); @@ -75661,15 +76790,12 @@ ${lanes.join("\n")} return void 0; } if (shouldTransformInitializersUsingSet && !isStatic(node) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) && lexicalEnvironment.data.facts & 16 /* WillHoistInitializersToConstructor */ ) return factory2.updatePropertyDeclaration(node, visitNodes2(node.modifiers, visitor, isModifierLike), node.name, /*questionOrExclamationToken*/ void 0, /*type*/ void 0, /*initializer*/ void 0); - if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - const { referencedName: referencedName , name: name } = visitReferencedPropertyName(node.name); - return factory2.updatePropertyDeclaration(node, visitNodes2(node.modifiers, modifierVisitor, isModifier), name, /*questionOrExclamationToken*/ void 0, /*type*/ void 0, visitNode(node.initializer, (child)=>namedEvaluationVisitor(child, referencedName), isExpression)); - } + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) node = transformNamedEvaluation(context, node); return factory2.updatePropertyDeclaration(node, visitNodes2(node.modifiers, modifierVisitor, isModifier), visitNode(node.name, propertyNameVisitor, isPropertyName), /*questionOrExclamationToken*/ void 0, /*type*/ void 0, visitNode(node.initializer, visitor, isExpression)); } function transformPublicFieldInitializer(node) { if (shouldTransformInitializers && !isAutoAccessorPropertyDeclaration(node)) { - const expr = getPropertyNameExpressionIfNeeded(node.name, /*shouldHoist*/ !!node.initializer || useDefineForClassFields, /*captureReferencedName*/ isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)); + const expr = getPropertyNameExpressionIfNeeded(node.name, /*shouldHoist*/ !!node.initializer || useDefineForClassFields); if (expr) getPendingExpressions().push(...flattenCommaList(expr)); if (isStatic(node) && !shouldTransformPrivateElementsOrClassStaticBlocks) { const initializerStatement = transformPropertyOrClassStaticBlock(node, factory2.createThis()); @@ -75703,8 +76829,19 @@ ${lanes.join("\n")} if (isAutoAccessorPropertyDeclaration(node) && (shouldTransformAutoAccessorsInCurrentClass() || hasStaticModifier(node) && getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */ )) return transformAutoAccessor(node); return transformFieldInitializer(node); } + function shouldForceDynamicThis() { + return !!currentClassElement && hasStaticModifier(currentClassElement) && isAccessor(currentClassElement) && isAutoAccessorPropertyDeclaration(getOriginalNode(currentClassElement)); + } + function ensureDynamicThisIfNeeded(node) { + if (shouldForceDynamicThis()) { + const innerExpression = skipOuterExpressions(node); + if (innerExpression.kind === 110 /* ThisKeyword */ ) noSubstitution.add(innerExpression); + } + } function createPrivateIdentifierAccess(info, receiver) { - return createPrivateIdentifierAccessHelper(info, visitNode(receiver, visitor, isExpression)); + receiver = visitNode(receiver, visitor, isExpression); + ensureDynamicThisIfNeeded(receiver); + return createPrivateIdentifierAccessHelper(info, receiver); } function createPrivateIdentifierAccessHelper(info, receiver) { setCommentRange(receiver, moveRangePos(receiver, -1)); @@ -75726,8 +76863,8 @@ ${lanes.join("\n")} const privateIdentifierInfo = accessPrivateIdentifier2(node.name); if (privateIdentifierInfo) return setTextRange(setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node), node); } - if (shouldTransformSuperInStaticInitializers && isSuperProperty(node) && isIdentifier(node.name) && currentStaticPropertyDeclarationOrStaticBlock && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { - const { classConstructor: classConstructor , superClassReference: superClassReference , facts: facts } = lexicalEnvironment.data; + if (shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node) && isIdentifier(node.name) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { + const { classConstructor: classConstructor, superClassReference: superClassReference, facts: facts } = lexicalEnvironment.data; if (facts & 1 /* ClassWasDecorated */ ) return visitInvalidSuperProperty(node); if (classConstructor && superClassReference) { const superProperty = factory2.createReflectGetCall(superClassReference, factory2.createStringLiteralFromNode(node.name), classConstructor); @@ -75739,8 +76876,8 @@ ${lanes.join("\n")} return visitEachChild(node, visitor, context); } function visitElementAccessExpression(node) { - if (shouldTransformSuperInStaticInitializers && isSuperProperty(node) && currentStaticPropertyDeclarationOrStaticBlock && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { - const { classConstructor: classConstructor , superClassReference: superClassReference , facts: facts } = lexicalEnvironment.data; + if (shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { + const { classConstructor: classConstructor, superClassReference: superClassReference, facts: facts } = lexicalEnvironment.data; if (facts & 1 /* ClassWasDecorated */ ) return visitInvalidSuperProperty(node); if (classConstructor && superClassReference) { const superProperty = factory2.createReflectGetCall(superClassReference, visitNode(node.argumentExpression, visitor, isExpression), classConstructor); @@ -75752,17 +76889,18 @@ ${lanes.join("\n")} return visitEachChild(node, visitor, context); } function visitPreOrPostfixUnaryExpression(node, discarded) { - if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */ ) { + if (node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */ ) { const operand = skipParentheses(node.operand); if (isPrivateIdentifierPropertyAccessExpression(operand)) { let info; if (info = accessPrivateIdentifier2(operand.name)) { const receiver = visitNode(operand.expression, visitor, isExpression); - const { readExpression: readExpression , initializeExpression: initializeExpression } = createCopiableReceiverExpr(receiver); + ensureDynamicThisIfNeeded(receiver); + const { readExpression: readExpression, initializeExpression: initializeExpression } = createCopiableReceiverExpr(receiver); let expression = createPrivateIdentifierAccess(info, readExpression); const temp = isPrefixUnaryExpression(node) || discarded ? void 0 : factory2.createTempVariable(hoistVariableDeclaration); expression = expandPreOrPostfixIncrementOrDecrementExpression(factory2, node, expression, hoistVariableDeclaration, temp); - expression = createPrivateIdentifierAssignment(info, initializeExpression || readExpression, expression, 63 /* EqualsToken */ ); + expression = createPrivateIdentifierAssignment(info, initializeExpression || readExpression, expression, 64 /* EqualsToken */ ); setOriginalNode(expression, node); setTextRange(expression, node); if (temp) { @@ -75771,8 +76909,8 @@ ${lanes.join("\n")} } return expression; } - } else if (shouldTransformSuperInStaticInitializers && isSuperProperty(operand) && currentStaticPropertyDeclarationOrStaticBlock && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { - const { classConstructor: classConstructor , superClassReference: superClassReference , facts: facts } = lexicalEnvironment.data; + } else if (shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(operand) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { + const { classConstructor: classConstructor, superClassReference: superClassReference, facts: facts } = lexicalEnvironment.data; if (facts & 1 /* ClassWasDecorated */ ) { const expression = visitInvalidSuperProperty(operand); return isPrefixUnaryExpression(node) ? factory2.updatePrefixUnaryExpression(node, expression) : factory2.updatePostfixUnaryExpression(node, expression); @@ -75814,6 +76952,7 @@ ${lanes.join("\n")} } function createCopiableReceiverExpr(receiver) { const clone2 = nodeIsSynthesized(receiver) ? receiver : factory2.cloneNode(receiver); + if (receiver.kind === 110 /* ThisKeyword */ && noSubstitution.has(receiver)) noSubstitution.add(clone2); if (isSimpleInlineableExpression(receiver)) return { readExpression: clone2, initializeExpression: void 0 @@ -75826,9 +76965,9 @@ ${lanes.join("\n")} }; } function visitCallExpression(node) { - var _a2; + var _a; if (isPrivateIdentifierPropertyAccessExpression(node.expression) && accessPrivateIdentifier2(node.expression.name)) { - const { thisArg: thisArg , target: target } = factory2.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion); + const { thisArg: thisArg, target: target } = factory2.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion); if (isCallChain(node)) return factory2.updateCallChain(node, factory2.createPropertyAccessChain(visitNode(target, visitor, isExpression), node.questionDotToken, "call"), /*questionDotToken*/ void 0, /*typeArguments*/ void 0, [ visitNode(thisArg, visitor, isExpression), ...visitNodes2(node.arguments, visitor, isExpression) @@ -75838,7 +76977,7 @@ ${lanes.join("\n")} ...visitNodes2(node.arguments, visitor, isExpression) ]); } - if (shouldTransformSuperInStaticInitializers && isSuperProperty(node.expression) && currentStaticPropertyDeclarationOrStaticBlock && ((_a2 = lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) == null ? void 0 : _a2.classConstructor)) { + if (shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node.expression) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && ((_a = lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) == null ? void 0 : _a.classConstructor)) { const invocation = factory2.createFunctionCallCall(visitNode(node.expression, visitor, isExpression), lexicalEnvironment.data.classConstructor, visitNodes2(node.arguments, visitor, isExpression)); setOriginalNode(invocation, node); setTextRange(invocation, node); @@ -75847,14 +76986,14 @@ ${lanes.join("\n")} return visitEachChild(node, visitor, context); } function visitTaggedTemplateExpression(node) { - var _a2; + var _a; if (isPrivateIdentifierPropertyAccessExpression(node.tag) && accessPrivateIdentifier2(node.tag.name)) { - const { thisArg: thisArg , target: target } = factory2.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion); + const { thisArg: thisArg, target: target } = factory2.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion); return factory2.updateTaggedTemplateExpression(node, factory2.createCallExpression(factory2.createPropertyAccessExpression(visitNode(target, visitor, isExpression), "bind"), /*typeArguments*/ void 0, [ visitNode(thisArg, visitor, isExpression) ]), /*typeArguments*/ void 0, visitNode(node.template, visitor, isTemplateLiteral)); } - if (shouldTransformSuperInStaticInitializers && isSuperProperty(node.tag) && currentStaticPropertyDeclarationOrStaticBlock && ((_a2 = lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) == null ? void 0 : _a2.classConstructor)) { + if (shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node.tag) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && ((_a = lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) == null ? void 0 : _a.classConstructor)) { const invocation = factory2.createFunctionBindCall(visitNode(node.tag, visitor, isExpression), lexicalEnvironment.data.classConstructor, []); setOriginalNode(invocation, node); setTextRange(invocation, node); @@ -75865,23 +77004,27 @@ ${lanes.join("\n")} function transformClassStaticBlockDeclaration(node) { if (lexicalEnvironment) lexicalEnvironmentMap.set(getOriginalNode(node), lexicalEnvironment); if (shouldTransformPrivateElementsOrClassStaticBlocks) { + if (isClassThisAssignmentBlock(node)) { + const result = visitNode(node.body.statements[0].expression, visitor, isExpression); + if (isAssignmentExpression(result, /*excludeCompoundAssignment*/ true) && result.left === result.right) return void 0; + return result; + } + if (isClassNamedEvaluationHelperBlock(node)) return visitNode(node.body.statements[0].expression, visitor, isExpression); startLexicalEnvironment(); - let statements = setCurrentStaticPropertyDeclarationOrStaticBlockAnd(node, (statements2)=>visitNodes2(statements2, visitor, isStatement), node.body.statements); + let statements = setCurrentClassElementAnd(node, (statements2)=>visitNodes2(statements2, visitor, isStatement), node.body.statements); statements = factory2.mergeLexicalEnvironment(statements, endLexicalEnvironment()); const iife = factory2.createImmediatelyInvokedArrowFunction(statements); + setOriginalNode(skipParentheses(iife.expression), node); + addEmitFlags(skipParentheses(iife.expression), 4 /* AdviseOnEmitNode */ ); setOriginalNode(iife, node); setTextRange(iife, node); - addEmitFlags(iife, 4 /* AdviseOnEmitNode */ ); return iife; } } function isAnonymousClassNeedingAssignedName(node) { if (isClassExpression(node) && !node.name) { const staticPropertiesOrClassStaticBlocks = getStaticPropertiesAndClassStaticBlock(node); - const classStaticBlock = find(staticPropertiesOrClassStaticBlocks, isClassStaticBlockDeclaration); - if (classStaticBlock) for (const statement of classStaticBlock.body.statements){ - if (isExpressionStatement(statement) && isCallToHelper(statement.expression, "___setFunctionName")) return false; - } + if (some(staticPropertiesOrClassStaticBlocks, isClassNamedEvaluationHelperBlock)) return false; const hasTransformableStatics = (shouldTransformPrivateElementsOrClassStaticBlocks || !!(getInternalEmitFlags(node) && 32 /* TransformPrivateStaticElements */ )) && some(staticPropertiesOrClassStaticBlocks, (node2)=>isClassStaticBlockDeclaration(node2) || isPrivateIdentifierClassElementDeclaration(node2) || shouldTransformInitializers && isInitializedProperty(node2)); return hasTransformableStatics; } @@ -75901,16 +77044,15 @@ ${lanes.join("\n")} } if (isAssignmentExpression(node)) { if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - const assignedName = getAssignedNameOfIdentifier(node.left, node.right); - const left = visitNode(node.left, visitor, isExpression); - const right = visitNode(node.right, (node2)=>namedEvaluationVisitor(node2, assignedName), isExpression); - return factory2.updateBinaryExpression(node, left, node.operatorToken, right); - } - if (isPrivateIdentifierPropertyAccessExpression(node.left)) { - const info = accessPrivateIdentifier2(node.left.name); - if (info) return setTextRange(setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node), node); - } else if (shouldTransformSuperInStaticInitializers && isSuperProperty(node.left) && currentStaticPropertyDeclarationOrStaticBlock && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { - const { classConstructor: classConstructor , superClassReference: superClassReference , facts: facts } = lexicalEnvironment.data; + node = transformNamedEvaluation(context, node); + Debug.assertNode(node, isAssignmentExpression); + } + const left = skipOuterExpressions(node.left, 9 /* Parentheses */ ); + if (isPrivateIdentifierPropertyAccessExpression(left)) { + const info = accessPrivateIdentifier2(left.name); + if (info) return setTextRange(setOriginalNode(createPrivateIdentifierAssignment(info, left.expression, node.right, node.operatorToken.kind), node), node); + } else if (shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node.left) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { + const { classConstructor: classConstructor, superClassReference: superClassReference, facts: facts } = lexicalEnvironment.data; if (facts & 1 /* ClassWasDecorated */ ) return factory2.updateBinaryExpression(node, visitInvalidSuperProperty(node.left), node.operatorToken, visitNode(node.right, visitor, isExpression)); if (classConstructor && superClassReference) { let setterName = isElementAccessExpression(node.left) ? visitNode(node.left.argumentExpression, visitor, isExpression) : isIdentifier(node.left.name) ? factory2.createStringLiteralFromNode(node.left.name) : void 0; @@ -75952,47 +77094,17 @@ ${lanes.join("\n")} const elements = discarded ? visitCommaListElements(node.elements, discardedValueVisitor) : visitCommaListElements(node.elements, visitor, discardedValueVisitor); return factory2.updateCommaListExpression(node, elements); } - function visitParenthesizedExpression(node, discarded, referencedName) { - const visitorFunc = discarded ? discardedValueVisitor : referencedName ? (node2)=>namedEvaluationVisitor(node2, referencedName) : visitor; + function visitParenthesizedExpression(node, discarded) { + const visitorFunc = discarded ? discardedValueVisitor : visitor; const expression = visitNode(node.expression, visitorFunc, isExpression); return factory2.updateParenthesizedExpression(node, expression); } - function visitPartiallyEmittedExpression(node, discarded, referencedName) { - const visitorFunc = discarded ? discardedValueVisitor : referencedName ? (node2)=>namedEvaluationVisitor(node2, referencedName) : visitor; - const expression = visitNode(node.expression, visitorFunc, isExpression); - return factory2.updatePartiallyEmittedExpression(node, expression); - } - function visitReferencedPropertyName(node) { - if (isPropertyNameLiteral(node) || isPrivateIdentifier(node)) { - const referencedName2 = factory2.createStringLiteralFromNode(node); - const name2 = visitNode(node, visitor, isPropertyName); - return { - referencedName: referencedName2, - name: name2 - }; - } - if (isPropertyNameLiteral(node.expression) && !isIdentifier(node.expression)) { - const referencedName2 = factory2.createStringLiteralFromNode(node.expression); - const name2 = visitNode(node, visitor, isPropertyName); - return { - referencedName: referencedName2, - name: name2 - }; - } - const referencedName = factory2.createTempVariable(hoistVariableDeclaration); - const key = emitHelpers().createPropKeyHelper(visitNode(node.expression, visitor, isExpression)); - const assignment = factory2.createAssignment(referencedName, key); - const name = factory2.updateComputedPropertyName(node, injectPendingExpressions(assignment)); - return { - referencedName: referencedName, - name: name - }; - } function createPrivateIdentifierAssignment(info, receiver, right, operator) { receiver = visitNode(receiver, visitor, isExpression); right = visitNode(right, visitor, isExpression); + ensureDynamicThisIfNeeded(receiver); if (isCompoundAssignment(operator)) { - const { readExpression: readExpression , initializeExpression: initializeExpression } = createCopiableReceiverExpr(receiver); + const { readExpression: readExpression, initializeExpression: initializeExpression } = createCopiableReceiverExpr(receiver); receiver = initializeExpression || readExpression; right = factory2.createBinaryExpression(createPrivateIdentifierAccessHelper(info, readExpression), getNonAssignmentOperatorForCompoundAssignment(operator), right); } @@ -76001,7 +77113,7 @@ ${lanes.join("\n")} case "a" /* Accessor */ : return emitHelpers().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, info.setterName); case "m" /* Method */ : - return emitHelpers().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, /* f */ void 0); + return emitHelpers().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, /*f*/ void 0); case "f" /* Field */ : return emitHelpers().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, info.isStatic ? info.variableName : void 0); case "untransformed": @@ -76014,9 +77126,11 @@ ${lanes.join("\n")} return filter(node.members, isNonStaticMethodOrAccessorWithPrivateName); } function getClassFacts(node) { + var _a; let facts = 0 /* None */ ; const original = getOriginalNode(node); if (isClassDeclaration(original) && classOrConstructorParameterIsDecorated(legacyDecorators, original)) facts |= 1 /* ClassWasDecorated */ ; + if (shouldTransformPrivateElementsOrClassStaticBlocks && (classHasClassThisAssignment(node) || classHasExplicitlyAssignedName(node))) facts |= 2 /* NeedsClassConstructorReference */ ; let containsPublicInstanceFields = false; let containsInitializedPublicInstanceFields = false; let containsInstancePrivateElements = false; @@ -76024,6 +77138,7 @@ ${lanes.join("\n")} for (const member of node.members){ if (isStatic(member)) { if (member.name && (isPrivateIdentifier(member.name) || isAutoAccessorPropertyDeclaration(member)) && shouldTransformPrivateElementsOrClassStaticBlocks) facts |= 2 /* NeedsClassConstructorReference */ ; + else if (isAutoAccessorPropertyDeclaration(member) && shouldTransformAutoAccessors === -1 /* True */ && !node.name && !((_a = node.emitNode) == null ? void 0 : _a.classThis)) facts |= 2 /* NeedsClassConstructorReference */ ; if (isPropertyDeclaration(member) || isClassStaticBlockDeclaration(member)) { if (shouldTransformThisInStaticInitializers && member.transformFlags & 16384 /* ContainsLexicalThis */ ) { facts |= 8 /* NeedsSubstitutionForThisInClassStaticField */ ; @@ -76037,8 +77152,10 @@ ${lanes.join("\n")} if (isAutoAccessorPropertyDeclaration(member)) { containsInstanceAutoAccessors = true; containsInstancePrivateElements || (containsInstancePrivateElements = isPrivateIdentifierClassElementDeclaration(member)); - } else if (isPrivateIdentifierClassElementDeclaration(member)) containsInstancePrivateElements = true; - else if (isPropertyDeclaration(member)) { + } else if (isPrivateIdentifierClassElementDeclaration(member)) { + containsInstancePrivateElements = true; + if (resolver.getNodeCheckFlags(member) & 262144 /* ContainsConstructorReference */ ) facts |= 2 /* NeedsClassConstructorReference */ ; + } else if (isPropertyDeclaration(member)) { containsPublicInstanceFields = true; containsInitializedPublicInstanceFields || (containsInitializedPublicInstanceFields = !!member.initializer); } @@ -76049,16 +77166,17 @@ ${lanes.join("\n")} return facts; } function visitExpressionWithTypeArgumentsInHeritageClause(node) { - var _a2; - const facts = ((_a2 = lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) == null ? void 0 : _a2.facts) || 0 /* None */ ; + var _a; + const facts = ((_a = lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) == null ? void 0 : _a.facts) || 0 /* None */ ; if (facts & 4 /* NeedsClassSuperReference */ ) { - const temp = factory2.createTempVariable(hoistVariableDeclaration, /*reserveInNestedScopes*/ true); + const temp = factory2.createTempVariable(hoistVariableDeclaration, /*reservedInNestedScopes*/ true); getClassLexicalEnvironment().superClassReference = temp; return factory2.updateExpressionWithTypeArguments(node, factory2.createAssignment(temp, visitNode(node.expression, visitor, isExpression)), /*typeArguments*/ void 0); } return visitEachChild(node, visitor, context); } - function visitInNewClassLexicalEnvironment(node, referencedName, visitor2) { + function visitInNewClassLexicalEnvironment(node, visitor2) { + var _a; const savedCurrentClassContainer = currentClassContainer; const savedPendingExpressions = pendingExpressions; const savedLexicalEnvironment = lexicalEnvironment; @@ -76069,6 +77187,15 @@ ${lanes.join("\n")} if (shouldTransformPrivateElementsOrClassStaticBlocks || shouldAlwaysTransformPrivateStaticElements) { const name = getNameOfDeclaration(node); if (name && isIdentifier(name)) getPrivateIdentifierEnvironment().data.className = name; + else if ((_a = node.emitNode) == null ? void 0 : _a.assignedName) { + if (isStringLiteral(node.emitNode.assignedName)) { + if (node.emitNode.assignedName.textSourceNode && isIdentifier(node.emitNode.assignedName.textSourceNode)) getPrivateIdentifierEnvironment().data.className = node.emitNode.assignedName.textSourceNode; + else if (isIdentifierText(node.emitNode.assignedName.text, languageVersion)) { + const prefixName = factory2.createIdentifier(node.emitNode.assignedName.text); + getPrivateIdentifierEnvironment().data.className = prefixName; + } + } + } } if (shouldTransformPrivateElementsOrClassStaticBlocks) { const privateInstanceMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); @@ -76077,7 +77204,7 @@ ${lanes.join("\n")} const facts = getClassFacts(node); if (facts) getClassLexicalEnvironment().facts = facts; if (facts & 8 /* NeedsSubstitutionForThisInClassStaticField */ ) enableSubstitutionForClassStaticThisOrSuperReference(); - const result = visitor2(node, facts, referencedName); + const result = visitor2(node, facts); endClassLexicalEnvironment(); Debug.assert(lexicalEnvironment === savedLexicalEnvironment); currentClassContainer = savedCurrentClassContainer; @@ -76085,13 +77212,13 @@ ${lanes.join("\n")} return result; } function visitClassDeclaration(node) { - return visitInNewClassLexicalEnvironment(node, /*referencedName*/ void 0, visitClassDeclarationInNewClassLexicalEnvironment); + return visitInNewClassLexicalEnvironment(node, visitClassDeclarationInNewClassLexicalEnvironment); } function visitClassDeclarationInNewClassLexicalEnvironment(node, facts) { - var _a2, _b; + var _a, _b; let pendingClassReferenceAssignment; if (facts & 2 /* NeedsClassConstructorReference */ ) { - if (shouldTransformPrivateElementsOrClassStaticBlocks && ((_a2 = node.emitNode) == null ? void 0 : _a2.classThis)) { + if (shouldTransformPrivateElementsOrClassStaticBlocks && ((_a = node.emitNode) == null ? void 0 : _a.classThis)) { getClassLexicalEnvironment().classConstructor = node.emitNode.classThis; pendingClassReferenceAssignment = factory2.createAssignment(node.emitNode.classThis, factory2.getInternalName(node)); } else { @@ -76099,75 +77226,72 @@ ${lanes.join("\n")} getClassLexicalEnvironment().classConstructor = factory2.cloneNode(temp); pendingClassReferenceAssignment = factory2.createAssignment(temp, factory2.getInternalName(node)); } - if ((_b = node.emitNode) == null ? void 0 : _b.classThis) getClassLexicalEnvironment().classThis = node.emitNode.classThis; } - const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); + if ((_b = node.emitNode) == null ? void 0 : _b.classThis) getClassLexicalEnvironment().classThis = node.emitNode.classThis; + const isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 262144 /* ContainsConstructorReference */ ; + const isExport = hasSyntacticModifier(node, 1 /* Export */ ); + const isDefault = hasSyntacticModifier(node, 1024 /* Default */ ); + let modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); const heritageClauses = visitNodes2(node.heritageClauses, heritageClauseVisitor, isHeritageClause); - const { members: members , prologue: prologue } = transformClassMembers(node); - const classDecl = factory2.updateClassDeclaration(node, modifiers, node.name, /*typeParameters*/ void 0, heritageClauses, members); + const { members: members, prologue: prologue } = transformClassMembers(node); const statements = []; - if (prologue) statements.push(factory2.createExpressionStatement(prologue)); - statements.push(classDecl); if (pendingClassReferenceAssignment) getPendingExpressions().unshift(pendingClassReferenceAssignment); if (some(pendingExpressions)) statements.push(factory2.createExpressionStatement(factory2.inlineExpressions(pendingExpressions))); if (shouldTransformInitializersUsingSet || shouldTransformPrivateElementsOrClassStaticBlocks || getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */ ) { const staticProperties = getStaticPropertiesAndClassStaticBlock(node); if (some(staticProperties)) addPropertyOrClassStaticBlockStatements(statements, staticProperties, factory2.getInternalName(node)); } + if (statements.length > 0 && isExport && isDefault) { + modifiers = visitNodes2(modifiers, (node2)=>isExportOrDefaultModifier(node2) ? void 0 : node2, isModifier); + statements.push(factory2.createExportAssignment(/*modifiers*/ void 0, /*isExportEquals*/ false, factory2.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); + } + const alias = getClassLexicalEnvironment().classConstructor; + if (isClassWithConstructorReference && alias) { + enableSubstitutionForClassAliases(); + classAliases[getOriginalNodeId(node)] = alias; + } + const classDecl = factory2.updateClassDeclaration(node, modifiers, node.name, /*typeParameters*/ void 0, heritageClauses, members); + statements.unshift(classDecl); + if (prologue) statements.unshift(factory2.createExpressionStatement(prologue)); return statements; } - function visitClassExpression(node, referencedName) { - return visitInNewClassLexicalEnvironment(node, referencedName, visitClassExpressionInNewClassLexicalEnvironment); + function visitClassExpression(node) { + return visitInNewClassLexicalEnvironment(node, visitClassExpressionInNewClassLexicalEnvironment); } - function visitClassExpressionInNewClassLexicalEnvironment(node, facts, referencedName) { - var _a2, _b, _c, _d, _e, _f; + function visitClassExpressionInNewClassLexicalEnvironment(node, facts) { + var _a, _b, _c; const isDecoratedClassDeclaration = !!(facts & 1 /* ClassWasDecorated */ ); const staticPropertiesOrClassStaticBlocks = getStaticPropertiesAndClassStaticBlock(node); - const isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 1048576 /* ClassWithConstructorReference */ ; + const classCheckFlags = resolver.getNodeCheckFlags(node); + const isClassWithConstructorReference = classCheckFlags & 262144 /* ContainsConstructorReference */ ; let temp; function createClassTempVar() { - var _a3; - if (shouldTransformPrivateElementsOrClassStaticBlocks && ((_a3 = node.emitNode) == null ? void 0 : _a3.classThis)) return getClassLexicalEnvironment().classConstructor = node.emitNode.classThis; - const classCheckFlags = resolver.getNodeCheckFlags(node); - const isClassWithConstructorReference2 = classCheckFlags & 1048576 /* ClassWithConstructorReference */ ; + var _a2; + if (shouldTransformPrivateElementsOrClassStaticBlocks && ((_a2 = node.emitNode) == null ? void 0 : _a2.classThis)) return getClassLexicalEnvironment().classConstructor = node.emitNode.classThis; const requiresBlockScopedVar = classCheckFlags & 32768 /* BlockScopedBindingInLoop */ ; - const temp2 = factory2.createTempVariable(requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, !!isClassWithConstructorReference2); + const temp2 = factory2.createTempVariable(requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, /*reservedInNestedScopes*/ true); getClassLexicalEnvironment().classConstructor = factory2.cloneNode(temp2); return temp2; } - if ((_a2 = node.emitNode) == null ? void 0 : _a2.classThis) getClassLexicalEnvironment().classThis = node.emitNode.classThis; - if (facts & 2 /* NeedsClassConstructorReference */ ) temp != null ? temp : temp = createClassTempVar(); + if ((_a = node.emitNode) == null ? void 0 : _a.classThis) getClassLexicalEnvironment().classThis = node.emitNode.classThis; + if (facts & 2 /* NeedsClassConstructorReference */ ) temp ?? (temp = createClassTempVar()); const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); const heritageClauses = visitNodes2(node.heritageClauses, heritageClauseVisitor, isHeritageClause); - const { members: members , prologue: prologue } = transformClassMembers(node); - let classExpression = factory2.updateClassExpression(node, modifiers, node.name, /*typeParameters*/ void 0, heritageClauses, members); + const { members: members, prologue: prologue } = transformClassMembers(node); + const classExpression = factory2.updateClassExpression(node, modifiers, node.name, /*typeParameters*/ void 0, heritageClauses, members); const expressions = []; if (prologue) expressions.push(prologue); const hasTransformableStatics = (shouldTransformPrivateElementsOrClassStaticBlocks || getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */ ) && some(staticPropertiesOrClassStaticBlocks, (node2)=>isClassStaticBlockDeclaration(node2) || isPrivateIdentifierClassElementDeclaration(node2) || shouldTransformInitializers && isInitializedProperty(node2)); - if (hasTransformableStatics || some(pendingExpressions) || referencedName) { + if (hasTransformableStatics || some(pendingExpressions)) { if (isDecoratedClassDeclaration) { Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration."); if (some(pendingExpressions)) addRange(pendingStatements, map(pendingExpressions, factory2.createExpressionStatement)); - if (referencedName) { - if (shouldTransformPrivateElementsOrClassStaticBlocks) { - const setNameExpression = emitHelpers().createSetFunctionNameHelper((_c = temp != null ? temp : (_b = node.emitNode) == null ? void 0 : _b.classThis) != null ? _c : factory2.getInternalName(node), referencedName); - pendingStatements.push(factory2.createExpressionStatement(setNameExpression)); - } else { - const setNameExpression = emitHelpers().createSetFunctionNameHelper(factory2.createThis(), referencedName); - classExpression = factory2.updateClassExpression(classExpression, classExpression.modifiers, classExpression.name, classExpression.typeParameters, classExpression.heritageClauses, [ - factory2.createClassStaticBlockDeclaration(factory2.createBlock([ - factory2.createExpressionStatement(setNameExpression) - ])), - ...classExpression.members - ]); - } - } - if (some(staticPropertiesOrClassStaticBlocks)) addPropertyOrClassStaticBlockStatements(pendingStatements, staticPropertiesOrClassStaticBlocks, (_e = (_d = node.emitNode) == null ? void 0 : _d.classThis) != null ? _e : factory2.getInternalName(node)); + if (some(staticPropertiesOrClassStaticBlocks)) addPropertyOrClassStaticBlockStatements(pendingStatements, staticPropertiesOrClassStaticBlocks, ((_b = node.emitNode) == null ? void 0 : _b.classThis) ?? factory2.getInternalName(node)); if (temp) expressions.push(factory2.createAssignment(temp, classExpression)); - else if (shouldTransformPrivateElementsOrClassStaticBlocks && ((_f = node.emitNode) == null ? void 0 : _f.classThis)) expressions.push(factory2.createAssignment(node.emitNode.classThis, classExpression)); + else if (shouldTransformPrivateElementsOrClassStaticBlocks && ((_c = node.emitNode) == null ? void 0 : _c.classThis)) expressions.push(factory2.createAssignment(node.emitNode.classThis, classExpression)); else expressions.push(classExpression); } else { - temp != null ? temp : temp = createClassTempVar(); + temp ?? (temp = createClassTempVar()); if (isClassWithConstructorReference) { enableSubstitutionForClassAliases(); const alias = factory2.cloneNode(temp); @@ -76176,7 +77300,6 @@ ${lanes.join("\n")} } expressions.push(factory2.createAssignment(temp, classExpression)); addRange(expressions, pendingExpressions); - if (referencedName) expressions.push(emitHelpers().createSetFunctionNameHelper(temp, referencedName)); addRange(expressions, generateInitializedPropertyExpressionsOrClassStaticBlock(staticPropertiesOrClassStaticBlocks, temp)); expressions.push(factory2.cloneNode(temp)); } @@ -76191,6 +77314,13 @@ ${lanes.join("\n")} if (!shouldTransformPrivateElementsOrClassStaticBlocks) return visitEachChild(node, visitor, context); return void 0; } + function visitThisExpression(node) { + if (shouldTransformThisInStaticInitializers && currentClassElement && isClassStaticBlockDeclaration(currentClassElement) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { + const { classThis: classThis, classConstructor: classConstructor } = lexicalEnvironment.data; + return classThis ?? classConstructor ?? node; + } + return node; + } function transformClassMembers(node) { const shouldTransformPrivateStaticElementsInClass = !!(getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */ ); if (shouldTransformPrivateElementsOrClassStaticBlocks || shouldTransformPrivateStaticElementsInFile) { @@ -76242,9 +77372,14 @@ ${lanes.join("\n")} } if (syntheticConstructor || syntheticStaticBlock) { let membersArray; + const classThisAssignmentBlock = find(members, isClassThisAssignmentBlock); + const classNamedEvaluationHelperBlock = find(members, isClassNamedEvaluationHelperBlock); + membersArray = append(membersArray, classThisAssignmentBlock); + membersArray = append(membersArray, classNamedEvaluationHelperBlock); membersArray = append(membersArray, syntheticConstructor); membersArray = append(membersArray, syntheticStaticBlock); - membersArray = addRange(membersArray, members); + const remainingMembers = classThisAssignmentBlock || classNamedEvaluationHelperBlock ? filter(members, (member)=>member !== classThisAssignmentBlock && member !== classNamedEvaluationHelperBlock) : members; + membersArray = addRange(membersArray, remainingMembers); members = setTextRange(factory2.createNodeArray(membersArray), /*location*/ node.members); } return { @@ -76253,7 +77388,7 @@ ${lanes.join("\n")} }; } function createBrandCheckWeakSetForPrivateMethods() { - const { weakSetName: weakSetName } = getPrivateIdentifierEnvironment().data; + const { weakSetName: weakSetName } = getPrivateIdentifierEnvironment().data; Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); getPendingExpressions().push(factory2.createAssignment(weakSetName, factory2.createNewExpression(factory2.createIdentifier("WeakSet"), /*typeArguments*/ void 0, []))); } @@ -76261,7 +77396,7 @@ ${lanes.join("\n")} constructor = visitNode(constructor, visitor, isConstructorDeclaration); if (!(lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) || !(lexicalEnvironment.data.facts & 16 /* WillHoistInitializersToConstructor */ )) return constructor; const extendsClauseElement = getEffectiveBaseTypeNode(container); - const isDerivedClass = !!(extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 104 /* NullKeyword */ ); + const isDerivedClass = !!(extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 106 /* NullKeyword */ ); const parameters = visitParameterList(constructor ? constructor.parameters : void 0, visitor, context); const body = transformConstructorBody(container, constructor, isDerivedClass); if (!body) return constructor; @@ -76269,10 +77404,31 @@ ${lanes.join("\n")} Debug.assert(parameters); return factory2.updateConstructorDeclaration(constructor, /*modifiers*/ void 0, parameters, body); } - return startOnNewLine(setOriginalNode(setTextRange(factory2.createConstructorDeclaration(/*modifiers*/ void 0, parameters != null ? parameters : [], body), constructor || container), constructor)); + return startOnNewLine(setOriginalNode(setTextRange(factory2.createConstructorDeclaration(/*modifiers*/ void 0, parameters ?? [], body), constructor || container), constructor)); + } + function transformConstructorBodyWorker(statementsOut, statementsIn, statementOffset, superPath, superPathDepth, initializerStatements, constructor) { + const superStatementIndex = superPath[superPathDepth]; + const superStatement = statementsIn[superStatementIndex]; + addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, statementOffset, superStatementIndex - statementOffset)); + statementOffset = superStatementIndex + 1; + if (isTryStatement(superStatement)) { + const tryBlockStatements = []; + transformConstructorBodyWorker(tryBlockStatements, superStatement.tryBlock.statements, /*statementOffset*/ 0, superPath, superPathDepth + 1, initializerStatements, constructor); + const tryBlockStatementsArray = factory2.createNodeArray(tryBlockStatements); + setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); + statementsOut.push(factory2.updateTryStatement(superStatement, factory2.updateBlock(superStatement.tryBlock, tryBlockStatements), visitNode(superStatement.catchClause, visitor, isCatchClause), visitNode(superStatement.finallyBlock, visitor, isBlock))); + } else { + addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, superStatementIndex, 1)); + while(statementOffset < statementsIn.length){ + const statement = statementsIn[statementOffset]; + if (isParameterPropertyDeclaration(getOriginalNode(statement), constructor)) statementOffset++; + else break; + } + addRange(statementsOut, initializerStatements); + } + addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, statementOffset)); } function transformConstructorBody(node, constructor, isDerivedClass) { - var _a2, _b; const instanceProperties = getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false); let properties = instanceProperties; if (!useDefineForClassFields) properties = filter(properties, (property)=>!!property.initializer || isPrivateIdentifier(property.name) || hasAccessorModifier(property)); @@ -76281,46 +77437,39 @@ ${lanes.join("\n")} if (!constructor && !needsConstructorBody) return visitFunctionBody(/*node*/ void 0, visitor, context); resumeLexicalEnvironment(); const needsSyntheticConstructor = !constructor && isDerivedClass; - let indexOfFirstStatementAfterSuperAndPrologue = 0; - let prologueStatementCount = 0; - let superStatementIndex = -1; + let statementOffset = 0; let statements = []; - if ((_a2 = constructor == null ? void 0 : constructor.body) == null ? void 0 : _a2.statements) { - prologueStatementCount = factory2.copyPrologue(constructor.body.statements, statements, /*ensureUseStrict*/ false, visitor); - superStatementIndex = findSuperStatementIndex(constructor.body.statements, prologueStatementCount); - if (superStatementIndex >= 0) { - indexOfFirstStatementAfterSuperAndPrologue = superStatementIndex + 1; - statements = [ - ...statements.slice(0, prologueStatementCount), - ...visitNodes2(constructor.body.statements, visitor, isStatement, prologueStatementCount, indexOfFirstStatementAfterSuperAndPrologue - prologueStatementCount), - ...statements.slice(prologueStatementCount) - ]; - } else if (prologueStatementCount >= 0) indexOfFirstStatementAfterSuperAndPrologue = prologueStatementCount; - } - if (needsSyntheticConstructor) statements.push(factory2.createExpressionStatement(factory2.createCallExpression(factory2.createSuper(), /*typeArguments*/ void 0, [ - factory2.createSpreadElement(factory2.createIdentifier("arguments")) - ]))); - let parameterPropertyDeclarationCount = 0; - if (constructor == null ? void 0 : constructor.body) { - for(let i = indexOfFirstStatementAfterSuperAndPrologue; i < constructor.body.statements.length; i++){ - const statement = constructor.body.statements[i]; - if (isParameterPropertyDeclaration(getOriginalNode(statement), constructor)) parameterPropertyDeclarationCount++; - else break; - } - if (parameterPropertyDeclarationCount > 0) indexOfFirstStatementAfterSuperAndPrologue += parameterPropertyDeclarationCount; - } + const initializerStatements = []; const receiver = factory2.createThis(); - addInstanceMethodStatements(statements, privateMethodsAndAccessors, receiver); + addInstanceMethodStatements(initializerStatements, privateMethodsAndAccessors, receiver); if (constructor) { const parameterProperties = filter(instanceProperties, (prop)=>isParameterPropertyDeclaration(getOriginalNode(prop), constructor)); const nonParameterProperties = filter(properties, (prop)=>!isParameterPropertyDeclaration(getOriginalNode(prop), constructor)); - addPropertyOrClassStaticBlockStatements(statements, parameterProperties, receiver); - addPropertyOrClassStaticBlockStatements(statements, nonParameterProperties, receiver); - } else addPropertyOrClassStaticBlockStatements(statements, properties, receiver); - if (constructor) addRange(statements, visitNodes2(constructor.body.statements, visitor, isStatement, indexOfFirstStatementAfterSuperAndPrologue)); + addPropertyOrClassStaticBlockStatements(initializerStatements, parameterProperties, receiver); + addPropertyOrClassStaticBlockStatements(initializerStatements, nonParameterProperties, receiver); + } else addPropertyOrClassStaticBlockStatements(initializerStatements, properties, receiver); + if (constructor == null ? void 0 : constructor.body) { + statementOffset = factory2.copyPrologue(constructor.body.statements, statements, /*ensureUseStrict*/ false, visitor); + const superStatementIndices = findSuperStatementIndexPath(constructor.body.statements, statementOffset); + if (superStatementIndices.length) transformConstructorBodyWorker(statements, constructor.body.statements, statementOffset, superStatementIndices, /*superPathDepth*/ 0, initializerStatements, constructor); + else { + while(statementOffset < constructor.body.statements.length){ + const statement = constructor.body.statements[statementOffset]; + if (isParameterPropertyDeclaration(getOriginalNode(statement), constructor)) statementOffset++; + else break; + } + addRange(statements, initializerStatements); + addRange(statements, visitNodes2(constructor.body.statements, visitor, isStatement, statementOffset)); + } + } else { + if (needsSyntheticConstructor) statements.push(factory2.createExpressionStatement(factory2.createCallExpression(factory2.createSuper(), /*typeArguments*/ void 0, [ + factory2.createSpreadElement(factory2.createIdentifier("arguments")) + ]))); + addRange(statements, initializerStatements); + } statements = factory2.mergeLexicalEnvironment(statements, endLexicalEnvironment()); if (statements.length === 0 && !constructor) return void 0; - const multiLine = (constructor == null ? void 0 : constructor.body) && constructor.body.statements.length >= statements.length ? (_b = constructor.body.multiLine) != null ? _b : statements.length > 0 : statements.length > 0; + const multiLine = (constructor == null ? void 0 : constructor.body) && constructor.body.statements.length >= statements.length ? constructor.body.multiLine ?? statements.length > 0 : statements.length > 0; return setTextRange(factory2.createBlock(setTextRange(factory2.createNodeArray(statements), /*location*/ constructor ? constructor.body.statements : node.members), multiLine), /*location*/ constructor ? constructor.body : void 0); } function addPropertyOrClassStaticBlockStatements(statements, properties, receiver) { @@ -76332,7 +77481,7 @@ ${lanes.join("\n")} } } function transformPropertyOrClassStaticBlock(property, receiver) { - const expression = isClassStaticBlockDeclaration(property) ? transformClassStaticBlockDeclaration(property) : transformProperty(property, receiver); + const expression = isClassStaticBlockDeclaration(property) ? setCurrentClassElementAnd(property, transformClassStaticBlockDeclaration, property) : transformProperty(property, receiver); if (!expression) return void 0; const statement = factory2.createExpressionStatement(expression); setOriginalNode(statement, property); @@ -76351,7 +77500,7 @@ ${lanes.join("\n")} function generateInitializedPropertyExpressionsOrClassStaticBlock(propertiesOrClassStaticBlocks, receiver) { const expressions = []; for (const property of propertiesOrClassStaticBlocks){ - const expression = isClassStaticBlockDeclaration(property) ? transformClassStaticBlockDeclaration(property) : transformProperty(property, receiver); + const expression = isClassStaticBlockDeclaration(property) ? setCurrentClassElementAnd(property, transformClassStaticBlockDeclaration, property) : setCurrentClassElementAnd(property, ()=>transformProperty(property, receiver), /*arg*/ void 0); if (!expression) continue; startOnNewLine(expression); setOriginalNode(expression, property); @@ -76363,42 +77512,36 @@ ${lanes.join("\n")} return expressions; } function transformProperty(property, receiver) { - var _a2; - const savedCurrentStaticPropertyDeclarationOrStaticBlock = currentStaticPropertyDeclarationOrStaticBlock; + var _a; + const savedCurrentClassElement = currentClassElement; const transformed = transformPropertyWorker(property, receiver); - if (transformed && hasStaticModifier(property) && ((_a2 = lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) == null ? void 0 : _a2.facts)) { + if (transformed && hasStaticModifier(property) && ((_a = lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) == null ? void 0 : _a.facts)) { setOriginalNode(transformed, property); addEmitFlags(transformed, 4 /* AdviseOnEmitNode */ ); setSourceMapRange(transformed, getSourceMapRange(property.name)); lexicalEnvironmentMap.set(getOriginalNode(property), lexicalEnvironment); } - currentStaticPropertyDeclarationOrStaticBlock = savedCurrentStaticPropertyDeclarationOrStaticBlock; + currentClassElement = savedCurrentClassElement; return transformed; } function transformPropertyWorker(property, receiver) { const emitAssignment = !useDefineForClassFields; - let referencedName; - if (isNamedEvaluation(property, isAnonymousClassNeedingAssignedName)) { - if (isPropertyNameLiteral(property.name) || isPrivateIdentifier(property.name)) referencedName = factory2.createStringLiteralFromNode(property.name); - else if (isPropertyNameLiteral(property.name.expression) && !isIdentifier(property.name.expression)) referencedName = factory2.createStringLiteralFromNode(property.name.expression); - else referencedName = factory2.getGeneratedNameForNode(property.name); - } + if (isNamedEvaluation(property, isAnonymousClassNeedingAssignedName)) property = transformNamedEvaluation(context, property); const propertyName = hasAccessorModifier(property) ? factory2.getGeneratedPrivateNameForNode(property.name) : isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) ? factory2.updateComputedPropertyName(property.name, factory2.getGeneratedNameForNode(property.name)) : property.name; - if (hasStaticModifier(property)) currentStaticPropertyDeclarationOrStaticBlock = property; - const initializerVisitor = referencedName ? (child)=>namedEvaluationVisitor(child, referencedName) : visitor; + if (hasStaticModifier(property)) currentClassElement = property; if (isPrivateIdentifier(propertyName) && shouldTransformClassElementToWeakMap(property)) { const privateIdentifierInfo = accessPrivateIdentifier2(propertyName); if (privateIdentifierInfo) { if (privateIdentifierInfo.kind === "f" /* Field */ ) { - if (!privateIdentifierInfo.isStatic) return createPrivateInstanceFieldInitializer(receiver, visitNode(property.initializer, initializerVisitor, isExpression), privateIdentifierInfo.brandCheckIdentifier); - else return createPrivateStaticFieldInitializer(privateIdentifierInfo.variableName, visitNode(property.initializer, initializerVisitor, isExpression)); + if (!privateIdentifierInfo.isStatic) return createPrivateInstanceFieldInitializer(factory2, receiver, visitNode(property.initializer, visitor, isExpression), privateIdentifierInfo.brandCheckIdentifier); + else return createPrivateStaticFieldInitializer(factory2, privateIdentifierInfo.variableName, visitNode(property.initializer, visitor, isExpression)); } else return void 0; } else Debug.fail("Undeclared private name for property declaration."); } if ((isPrivateIdentifier(propertyName) || hasStaticModifier(property)) && !property.initializer) return void 0; const propertyOriginalNode = getOriginalNode(property); if (hasSyntacticModifier(propertyOriginalNode, 256 /* Abstract */ )) return void 0; - let initializer = visitNode(property.initializer, initializerVisitor, isExpression); + let initializer = visitNode(property.initializer, visitor, isExpression); if (isParameterPropertyDeclaration(propertyOriginalNode, propertyOriginalNode.parent) && isIdentifier(propertyName)) { const localName = factory2.cloneNode(propertyName); if (initializer) { @@ -76411,7 +77554,7 @@ ${lanes.join("\n")} setEmitFlags(propertyName, 3168 /* NoSourceMap */ ); setSourceMapRange(localName, propertyOriginalNode.name); setEmitFlags(localName, 3072 /* NoComments */ ); - } else initializer != null ? initializer : initializer = factory2.createVoidZero(); + } else initializer ?? (initializer = factory2.createVoidZero()); if (emitAssignment || isPrivateIdentifier(propertyName)) { const memberAccess = createMemberAccessForPropertyName(factory2, receiver, propertyName, /*location*/ propertyName); addEmitFlags(memberAccess, 1024 /* NoLeadingComments */ ); @@ -76431,37 +77574,37 @@ ${lanes.join("\n")} function enableSubstitutionForClassAliases() { if ((enabledSubstitutions & 1 /* ClassAliases */ ) === 0) { enabledSubstitutions |= 1 /* ClassAliases */ ; - context.enableSubstitution(79 /* Identifier */ ); + context.enableSubstitution(80 /* Identifier */ ); classAliases = []; } } function enableSubstitutionForClassStaticThisOrSuperReference() { if ((enabledSubstitutions & 2 /* ClassStaticThisOrSuperReference */ ) === 0) { enabledSubstitutions |= 2 /* ClassStaticThisOrSuperReference */ ; - context.enableSubstitution(108 /* ThisKeyword */ ); - context.enableEmitNotification(259 /* FunctionDeclaration */ ); - context.enableEmitNotification(215 /* FunctionExpression */ ); - context.enableEmitNotification(173 /* Constructor */ ); - context.enableEmitNotification(174 /* GetAccessor */ ); - context.enableEmitNotification(175 /* SetAccessor */ ); - context.enableEmitNotification(171 /* MethodDeclaration */ ); - context.enableEmitNotification(169 /* PropertyDeclaration */ ); - context.enableEmitNotification(164 /* ComputedPropertyName */ ); + context.enableSubstitution(110 /* ThisKeyword */ ); + context.enableEmitNotification(262 /* FunctionDeclaration */ ); + context.enableEmitNotification(218 /* FunctionExpression */ ); + context.enableEmitNotification(176 /* Constructor */ ); + context.enableEmitNotification(177 /* GetAccessor */ ); + context.enableEmitNotification(178 /* SetAccessor */ ); + context.enableEmitNotification(174 /* MethodDeclaration */ ); + context.enableEmitNotification(172 /* PropertyDeclaration */ ); + context.enableEmitNotification(167 /* ComputedPropertyName */ ); } } function addInstanceMethodStatements(statements, methods, receiver) { if (!shouldTransformPrivateElementsOrClassStaticBlocks || !some(methods)) return; - const { weakSetName: weakSetName } = getPrivateIdentifierEnvironment().data; + const { weakSetName: weakSetName } = getPrivateIdentifierEnvironment().data; Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); - statements.push(factory2.createExpressionStatement(createPrivateInstanceMethodInitializer(receiver, weakSetName))); + statements.push(factory2.createExpressionStatement(createPrivateInstanceMethodInitializer(factory2, receiver, weakSetName))); } function visitInvalidSuperProperty(node) { return isPropertyAccessExpression(node) ? factory2.updatePropertyAccessExpression(node, factory2.createVoidZero(), node.name) : factory2.updateElementAccessExpression(node, factory2.createVoidZero(), visitNode(node.argumentExpression, visitor, isExpression)); } - function getPropertyNameExpressionIfNeeded(name, shouldHoist, captureReferencedName) { + function getPropertyNameExpressionIfNeeded(name, shouldHoist) { if (isComputedPropertyName(name)) { const cacheAssignment = findComputedPropertyNameCacheAssignment(name); - let expression = visitNode(name.expression, visitor, isExpression); + const expression = visitNode(name.expression, visitor, isExpression); const innerExpression = skipPartiallyEmittedExpressions(expression); const inlinable = isSimpleInlineableExpression(innerExpression); const alreadyTransformed = !!cacheAssignment || isAssignmentExpression(innerExpression) && isGeneratedIdentifier(innerExpression.left); @@ -76469,7 +77612,6 @@ ${lanes.join("\n")} const generatedName = factory2.getGeneratedNameForNode(name); if (resolver.getNodeCheckFlags(name) & 32768 /* BlockScopedBindingInLoop */ ) addBlockScopedVariable(generatedName); else hoistVariableDeclaration(generatedName); - if (captureReferencedName) expression = emitHelpers().createPropKeyHelper(expression); return factory2.createAssignment(generatedName, expression); } return inlinable || isIdentifier(innerExpression) ? void 0 : expression; @@ -76485,25 +77627,23 @@ ${lanes.join("\n")} lexicalEnvironment = lexicalEnvironment == null ? void 0 : lexicalEnvironment.previous; } function getClassLexicalEnvironment() { - var _a2; Debug.assert(lexicalEnvironment); - return (_a2 = lexicalEnvironment.data) != null ? _a2 : lexicalEnvironment.data = { + return lexicalEnvironment.data ?? (lexicalEnvironment.data = { facts: 0 /* None */ , classConstructor: void 0, classThis: void 0, superClassReference: void 0 - }; + }); } function getPrivateIdentifierEnvironment() { - var _a2; Debug.assert(lexicalEnvironment); - return (_a2 = lexicalEnvironment.privateEnv) != null ? _a2 : lexicalEnvironment.privateEnv = newPrivateEnvironment({ + return lexicalEnvironment.privateEnv ?? (lexicalEnvironment.privateEnv = newPrivateEnvironment({ className: void 0, weakSetName: void 0 - }); + })); } function getPendingExpressions() { - return pendingExpressions != null ? pendingExpressions : pendingExpressions = []; + return pendingExpressions ?? (pendingExpressions = []); } function addPrivateIdentifierClassElementToEnvironment(node, name, lex, privateEnv, isStatic2, isValid, previousInfo) { if (isAutoAccessorPropertyDeclaration(node)) addPrivateIdentifierAutoAccessorPropertyDeclarationToEnvironment(node, name, lex, privateEnv, isStatic2, isValid, previousInfo); @@ -76513,9 +77653,8 @@ ${lanes.join("\n")} else if (isSetAccessorDeclaration(node)) addPrivateIdentifierSetAccessorDeclarationToEnvironment(node, name, lex, privateEnv, isStatic2, isValid, previousInfo); } function addPrivateIdentifierPropertyDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic2, isValid, _previousInfo) { - var _a2; if (isStatic2) { - const brandCheckIdentifier = Debug.checkDefined((_a2 = lex.classThis) != null ? _a2 : lex.classConstructor, "classConstructor should be set in private identifier environment"); + const brandCheckIdentifier = Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment"); const variableName = createHoistedVariableForPrivateName(name); setPrivateIdentifier(privateEnv, name, { kind: "f" /* Field */ , @@ -76536,9 +77675,8 @@ ${lanes.join("\n")} } } function addPrivateIdentifierMethodDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic2, isValid, _previousInfo) { - var _a2; const methodName = createHoistedVariableForPrivateName(name); - const brandCheckIdentifier = isStatic2 ? Debug.checkDefined((_a2 = lex.classThis) != null ? _a2 : lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); + const brandCheckIdentifier = isStatic2 ? Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); setPrivateIdentifier(privateEnv, name, { kind: "m" /* Method */ , methodName: methodName, @@ -76548,9 +77686,8 @@ ${lanes.join("\n")} }); } function addPrivateIdentifierGetAccessorDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic2, isValid, previousInfo) { - var _a2; const getterName = createHoistedVariableForPrivateName(name, "_get"); - const brandCheckIdentifier = isStatic2 ? Debug.checkDefined((_a2 = lex.classThis) != null ? _a2 : lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); + const brandCheckIdentifier = isStatic2 ? Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); if ((previousInfo == null ? void 0 : previousInfo.kind) === "a" /* Accessor */ && previousInfo.isStatic === isStatic2 && !previousInfo.getterName) previousInfo.getterName = getterName; else setPrivateIdentifier(privateEnv, name, { kind: "a" /* Accessor */ , @@ -76562,9 +77699,8 @@ ${lanes.join("\n")} }); } function addPrivateIdentifierSetAccessorDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic2, isValid, previousInfo) { - var _a2; const setterName = createHoistedVariableForPrivateName(name, "_set"); - const brandCheckIdentifier = isStatic2 ? Debug.checkDefined((_a2 = lex.classThis) != null ? _a2 : lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); + const brandCheckIdentifier = isStatic2 ? Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); if ((previousInfo == null ? void 0 : previousInfo.kind) === "a" /* Accessor */ && previousInfo.isStatic === isStatic2 && !previousInfo.setterName) previousInfo.setterName = setterName; else setPrivateIdentifier(privateEnv, name, { kind: "a" /* Accessor */ , @@ -76576,10 +77712,9 @@ ${lanes.join("\n")} }); } function addPrivateIdentifierAutoAccessorPropertyDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic2, isValid, _previousInfo) { - var _a2; const getterName = createHoistedVariableForPrivateName(name, "_get"); const setterName = createHoistedVariableForPrivateName(name, "_set"); - const brandCheckIdentifier = isStatic2 ? Debug.checkDefined((_a2 = lex.classThis) != null ? _a2 : lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); + const brandCheckIdentifier = isStatic2 ? Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); setPrivateIdentifier(privateEnv, name, { kind: "a" /* Accessor */ , getterName: getterName, @@ -76598,21 +77733,20 @@ ${lanes.join("\n")} addDeclaration(node, name, lex, privateEnv, isStatic2, isValid, previousInfo); } function createHoistedVariableForClass(name, node, suffix) { - const { className: className } = getPrivateIdentifierEnvironment().data; + const { className: className } = getPrivateIdentifierEnvironment().data; const prefix = className ? { prefix: "_", node: className, suffix: "_" } : "_"; - const identifier = typeof name === "object" ? factory2.getGeneratedNameForNode(name, 24 /* ReservedInNestedScopes */ , prefix, suffix) : typeof name === "string" ? factory2.createUniqueName(name, 16 /* Optimistic */ , prefix, suffix) : factory2.createTempVariable(/*recordTempVariable*/ void 0, /*reserveInNestedScopes*/ true, prefix, suffix); + const identifier = typeof name === "object" ? factory2.getGeneratedNameForNode(name, 24 /* ReservedInNestedScopes */ , prefix, suffix) : typeof name === "string" ? factory2.createUniqueName(name, 16 /* Optimistic */ , prefix, suffix) : factory2.createTempVariable(/*recordTempVariable*/ void 0, /*reservedInNestedScopes*/ true, prefix, suffix); if (resolver.getNodeCheckFlags(node) & 32768 /* BlockScopedBindingInLoop */ ) addBlockScopedVariable(identifier); else hoistVariableDeclaration(identifier); return identifier; } function createHoistedVariableForPrivateName(name, suffix) { - var _a2; const text = tryGetTextOfPropertyName(name); - return createHoistedVariableForClass((_a2 = text == null ? void 0 : text.substring(1)) != null ? _a2 : name, name, suffix); + return createHoistedVariableForClass((text == null ? void 0 : text.substring(1)) ?? name, name, suffix); } function accessPrivateIdentifier2(name) { const info = accessPrivateIdentifier(lexicalEnvironment, name); @@ -76625,15 +77759,15 @@ ${lanes.join("\n")} let receiver = node.expression; if (isThisProperty(node) || isSuperProperty(node) || !isSimpleCopiableExpression(node.expression)) { receiver = factory2.createTempVariable(hoistVariableDeclaration, /*reservedInNestedScopes*/ true); - getPendingExpressions().push(factory2.createBinaryExpression(receiver, 63 /* EqualsToken */ , visitNode(node.expression, visitor, isExpression))); + getPendingExpressions().push(factory2.createBinaryExpression(receiver, 64 /* EqualsToken */ , visitNode(node.expression, visitor, isExpression))); } - return factory2.createAssignmentTargetWrapper(parameter, createPrivateIdentifierAssignment(info, receiver, parameter, 63 /* EqualsToken */ )); + return factory2.createAssignmentTargetWrapper(parameter, createPrivateIdentifierAssignment(info, receiver, parameter, 64 /* EqualsToken */ )); } function visitDestructuringAssignmentTarget(node) { if (isObjectLiteralExpression(node) || isArrayLiteralExpression(node)) return visitAssignmentPattern(node); if (isPrivateIdentifierPropertyAccessExpression(node)) return wrapPrivateIdentifierForDestructuringTarget(node); - else if (shouldTransformSuperInStaticInitializers && isSuperProperty(node) && currentStaticPropertyDeclarationOrStaticBlock && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { - const { classConstructor: classConstructor , superClassReference: superClassReference , facts: facts } = lexicalEnvironment.data; + else if (shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { + const { classConstructor: classConstructor, superClassReference: superClassReference, facts: facts } = lexicalEnvironment.data; if (facts & 1 /* ClassWasDecorated */ ) return visitInvalidSuperProperty(node); else if (classConstructor && superClassReference) { const name = isElementAccessExpression(node) ? visitNode(node.argumentExpression, visitor, isExpression) : isIdentifier(node.name) ? factory2.createStringLiteralFromNode(node.name) : void 0; @@ -76646,12 +77780,7 @@ ${lanes.join("\n")} return visitEachChild(node, visitor, context); } function visitAssignmentElement(node) { - if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - const left = visitDestructuringAssignmentTarget(node.left); - const assignedName = getAssignedNameOfIdentifier(node.left, node.right); - const right = visitNode(node.right, (node2)=>namedEvaluationVisitor(node2, assignedName), isExpression); - return factory2.updateBinaryExpression(node, left, node.operatorToken, right); - } + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) node = transformNamedEvaluation(context, node); if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { const left = visitDestructuringAssignmentTarget(node.left); const right = visitNode(node.right, visitor, isExpression); @@ -76686,11 +77815,7 @@ ${lanes.join("\n")} return visitEachChild(node, visitor, context); } function visitShorthandAssignmentProperty(node) { - if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - const assignedName = getAssignedNameOfIdentifier(node.name, node.objectAssignmentInitializer); - const objectAssignmentInitializer = visitNode(node.objectAssignmentInitializer, (node2)=>namedEvaluationVisitor(node2, assignedName), isExpression); - return factory2.updateShorthandPropertyAssignment(node, node.name, objectAssignmentInitializer); - } + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) node = transformNamedEvaluation(context, node); return visitEachChild(node, visitor, context); } function visitAssignmentRestProperty(node) { @@ -76727,14 +77852,14 @@ ${lanes.join("\n")} return; } switch(node.kind){ - case 215 /* FunctionExpression */ : + case 218 /* FunctionExpression */ : if (isArrowFunction(original) || getEmitFlags(node) & 524288 /* AsyncFunctionBody */ ) break; - case 259 /* FunctionDeclaration */ : - case 173 /* Constructor */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 171 /* MethodDeclaration */ : - case 169 /* PropertyDeclaration */ : + case 262 /* FunctionDeclaration */ : + case 176 /* Constructor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 174 /* MethodDeclaration */ : + case 172 /* PropertyDeclaration */ : { const savedLexicalEnvironment = lexicalEnvironment; const savedPreviousShouldSubstituteThisWithClassThis = previousShouldSubstituteThisWithClassThis; @@ -76747,7 +77872,7 @@ ${lanes.join("\n")} lexicalEnvironment = savedLexicalEnvironment; return; } - case 164 /* ComputedPropertyName */ : + case 167 /* ComputedPropertyName */ : { const savedLexicalEnvironment = lexicalEnvironment; const savedShouldSubstituteThisWithClassThis = shouldSubstituteThisWithClassThis; @@ -76768,19 +77893,19 @@ ${lanes.join("\n")} } function substituteExpression(node) { switch(node.kind){ - case 79 /* Identifier */ : + case 80 /* Identifier */ : return substituteExpressionIdentifier(node); - case 108 /* ThisKeyword */ : + case 110 /* ThisKeyword */ : return substituteThisExpression(node); } return node; } function substituteThisExpression(node) { - if (enabledSubstitutions & 2 /* ClassStaticThisOrSuperReference */ && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { - const { facts: facts , classConstructor: classConstructor , classThis: classThis } = lexicalEnvironment.data; - if (facts & 1 /* ClassWasDecorated */ && legacyDecorators) return factory2.createParenthesizedExpression(factory2.createVoidZero()); - const substituteThis = shouldSubstituteThisWithClassThis ? classThis != null ? classThis : classConstructor : classConstructor; + if (enabledSubstitutions & 2 /* ClassStaticThisOrSuperReference */ && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) && !noSubstitution.has(node)) { + const { facts: facts, classConstructor: classConstructor, classThis: classThis } = lexicalEnvironment.data; + const substituteThis = shouldSubstituteThisWithClassThis ? classThis ?? classConstructor : classConstructor; if (substituteThis) return setTextRange(setOriginalNode(factory2.cloneNode(substituteThis), node), node); + if (facts & 1 /* ClassWasDecorated */ && legacyDecorators) return factory2.createParenthesizedExpression(factory2.createVoidZero()); } return node; } @@ -76789,7 +77914,7 @@ ${lanes.join("\n")} } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1 /* ClassAliases */ ) { - if (resolver.getNodeCheckFlags(node) & 2097152 /* ConstructorReferenceInClass */ ) { + if (resolver.getNodeCheckFlags(node) & 536870912 /* ConstructorReference */ ) { const declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { const classAlias = classAliases[declaration.id]; @@ -76805,19 +77930,19 @@ ${lanes.join("\n")} return void 0; } } - function createPrivateStaticFieldInitializer(variableName, initializer) { - return factory.createAssignment(variableName, factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("value", initializer || factory.createVoidZero()) + function createPrivateStaticFieldInitializer(factory2, variableName, initializer) { + return factory2.createAssignment(variableName, factory2.createObjectLiteralExpression([ + factory2.createPropertyAssignment("value", initializer || factory2.createVoidZero()) ])); } - function createPrivateInstanceFieldInitializer(receiver, initializer, weakMapName) { - return factory.createCallExpression(factory.createPropertyAccessExpression(weakMapName, "set"), /*typeArguments*/ void 0, [ + function createPrivateInstanceFieldInitializer(factory2, receiver, initializer, weakMapName) { + return factory2.createCallExpression(factory2.createPropertyAccessExpression(weakMapName, "set"), /*typeArguments*/ void 0, [ receiver, - initializer || factory.createVoidZero() + initializer || factory2.createVoidZero() ]); } - function createPrivateInstanceMethodInitializer(receiver, weakSetName) { - return factory.createCallExpression(factory.createPropertyAccessExpression(weakSetName, "add"), /*typeArguments*/ void 0, [ + function createPrivateInstanceMethodInitializer(factory2, receiver, weakSetName) { + return factory2.createCallExpression(factory2.createPropertyAccessExpression(weakSetName, "add"), /*typeArguments*/ void 0, [ receiver ]); } @@ -76825,7 +77950,13 @@ ${lanes.join("\n")} return !isGeneratedPrivateIdentifier(node) && node.escapedText === "#constructor"; } function isPrivateIdentifierInExpression(node) { - return isPrivateIdentifier(node.left) && node.operatorToken.kind === 101 /* InKeyword */ ; + return isPrivateIdentifier(node.left) && node.operatorToken.kind === 103 /* InKeyword */ ; + } + function isStaticPropertyDeclaration2(node) { + return isPropertyDeclaration(node) && hasStaticModifier(node); + } + function isStaticPropertyDeclarationOrClassStaticBlock(node) { + return isClassStaticBlockDeclaration(node) || isStaticPropertyDeclaration2(node); } var init_classFields = __esm({ "src/compiler/transformers/classFields.ts" () { @@ -76835,7 +77966,7 @@ ${lanes.join("\n")} }); // src/compiler/transformers/typeSerializer.ts function createRuntimeTypeSerializer(context) { - const { hoistVariableDeclaration: hoistVariableDeclaration } = context; + const { factory: factory2, hoistVariableDeclaration: hoistVariableDeclaration } = context; const resolver = context.getEmitResolver(); const compilerOptions = context.getCompilerOptions(); const languageVersion = getEmitScriptTarget(compilerOptions); @@ -76864,18 +77995,18 @@ ${lanes.join("\n")} } function serializeTypeOfNode(node) { switch(node.kind){ - case 169 /* PropertyDeclaration */ : - case 166 /* Parameter */ : + case 172 /* PropertyDeclaration */ : + case 169 /* Parameter */ : return serializeTypeNode(node.type); - case 175 /* SetAccessor */ : - case 174 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 177 /* GetAccessor */ : return serializeTypeNode(getAccessorTypeNode(node)); - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : - case 171 /* MethodDeclaration */ : - return factory.createIdentifier("Function"); + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 174 /* MethodDeclaration */ : + return factory2.createIdentifier("Function"); default: - return factory.createVoidZero(); + return factory2.createVoidZero(); } } function serializeParameterTypesOfNode(node, container) { @@ -76891,114 +78022,114 @@ ${lanes.join("\n")} else expressions.push(serializeTypeOfNode(parameter)); } } - return factory.createArrayLiteralExpression(expressions); + return factory2.createArrayLiteralExpression(expressions); } function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 174 /* GetAccessor */ ) { - const { setAccessor: setAccessor } = getAllAccessorDeclarations(container.members, node); + if (container && node.kind === 177 /* GetAccessor */ ) { + const { setAccessor: setAccessor } = getAllAccessorDeclarations(container.members, node); if (setAccessor) return setAccessor.parameters; } return node.parameters; } function serializeReturnTypeOfNode(node) { if (isFunctionLike(node) && node.type) return serializeTypeNode(node.type); - else if (isAsyncFunction(node)) return factory.createIdentifier("Promise"); - return factory.createVoidZero(); + else if (isAsyncFunction(node)) return factory2.createIdentifier("Promise"); + return factory2.createVoidZero(); } function serializeTypeNode(node) { - if (node === void 0) return factory.createIdentifier("Object"); + if (node === void 0) return factory2.createIdentifier("Object"); node = skipTypeParentheses(node); switch(node.kind){ - case 114 /* VoidKeyword */ : - case 155 /* UndefinedKeyword */ : - case 144 /* NeverKeyword */ : - return factory.createVoidZero(); - case 181 /* FunctionType */ : - case 182 /* ConstructorType */ : - return factory.createIdentifier("Function"); - case 185 /* ArrayType */ : - case 186 /* TupleType */ : - return factory.createIdentifier("Array"); - case 179 /* TypePredicate */ : - return node.assertsModifier ? factory.createVoidZero() : factory.createIdentifier("Boolean"); - case 134 /* BooleanKeyword */ : - return factory.createIdentifier("Boolean"); - case 200 /* TemplateLiteralType */ : - case 152 /* StringKeyword */ : - return factory.createIdentifier("String"); - case 149 /* ObjectKeyword */ : - return factory.createIdentifier("Object"); - case 198 /* LiteralType */ : + case 116 /* VoidKeyword */ : + case 157 /* UndefinedKeyword */ : + case 146 /* NeverKeyword */ : + return factory2.createVoidZero(); + case 184 /* FunctionType */ : + case 185 /* ConstructorType */ : + return factory2.createIdentifier("Function"); + case 188 /* ArrayType */ : + case 189 /* TupleType */ : + return factory2.createIdentifier("Array"); + case 182 /* TypePredicate */ : + return node.assertsModifier ? factory2.createVoidZero() : factory2.createIdentifier("Boolean"); + case 136 /* BooleanKeyword */ : + return factory2.createIdentifier("Boolean"); + case 203 /* TemplateLiteralType */ : + case 154 /* StringKeyword */ : + return factory2.createIdentifier("String"); + case 151 /* ObjectKeyword */ : + return factory2.createIdentifier("Object"); + case 201 /* LiteralType */ : return serializeLiteralOfLiteralTypeNode(node.literal); - case 148 /* NumberKeyword */ : - return factory.createIdentifier("Number"); - case 160 /* BigIntKeyword */ : + case 150 /* NumberKeyword */ : + return factory2.createIdentifier("Number"); + case 163 /* BigIntKeyword */ : return getGlobalConstructor("BigInt", 7 /* ES2020 */ ); - case 153 /* SymbolKeyword */ : + case 155 /* SymbolKeyword */ : return getGlobalConstructor("Symbol", 2 /* ES2015 */ ); - case 180 /* TypeReference */ : + case 183 /* TypeReference */ : return serializeTypeReferenceNode(node); - case 190 /* IntersectionType */ : + case 193 /* IntersectionType */ : return serializeUnionOrIntersectionConstituents(node.types, /*isIntersection*/ true); - case 189 /* UnionType */ : + case 192 /* UnionType */ : return serializeUnionOrIntersectionConstituents(node.types, /*isIntersection*/ false); - case 191 /* ConditionalType */ : + case 194 /* ConditionalType */ : return serializeUnionOrIntersectionConstituents([ node.trueType, node.falseType ], /*isIntersection*/ false); - case 195 /* TypeOperator */ : - if (node.operator === 146 /* ReadonlyKeyword */ ) return serializeTypeNode(node.type); + case 198 /* TypeOperator */ : + if (node.operator === 148 /* ReadonlyKeyword */ ) return serializeTypeNode(node.type); break; - case 183 /* TypeQuery */ : - case 196 /* IndexedAccessType */ : - case 197 /* MappedType */ : - case 184 /* TypeLiteral */ : - case 131 /* AnyKeyword */ : - case 157 /* UnknownKeyword */ : - case 194 /* ThisType */ : - case 202 /* ImportType */ : + case 186 /* TypeQuery */ : + case 199 /* IndexedAccessType */ : + case 200 /* MappedType */ : + case 187 /* TypeLiteral */ : + case 133 /* AnyKeyword */ : + case 159 /* UnknownKeyword */ : + case 197 /* ThisType */ : + case 205 /* ImportType */ : break; - case 315 /* JSDocAllType */ : - case 316 /* JSDocUnknownType */ : - case 320 /* JSDocFunctionType */ : - case 321 /* JSDocVariadicType */ : - case 322 /* JSDocNamepathType */ : + case 319 /* JSDocAllType */ : + case 320 /* JSDocUnknownType */ : + case 324 /* JSDocFunctionType */ : + case 325 /* JSDocVariadicType */ : + case 326 /* JSDocNamepathType */ : break; - case 317 /* JSDocNullableType */ : - case 318 /* JSDocNonNullableType */ : - case 319 /* JSDocOptionalType */ : + case 321 /* JSDocNullableType */ : + case 322 /* JSDocNonNullableType */ : + case 323 /* JSDocOptionalType */ : return serializeTypeNode(node.type); default: return Debug.failBadSyntaxKind(node); } - return factory.createIdentifier("Object"); + return factory2.createIdentifier("Object"); } function serializeLiteralOfLiteralTypeNode(node) { switch(node.kind){ - case 10 /* StringLiteral */ : - case 14 /* NoSubstitutionTemplateLiteral */ : - return factory.createIdentifier("String"); - case 221 /* PrefixUnaryExpression */ : + case 11 /* StringLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + return factory2.createIdentifier("String"); + case 224 /* PrefixUnaryExpression */ : { const operand = node.operand; switch(operand.kind){ - case 8 /* NumericLiteral */ : - case 9 /* BigIntLiteral */ : + case 9 /* NumericLiteral */ : + case 10 /* BigIntLiteral */ : return serializeLiteralOfLiteralTypeNode(operand); default: return Debug.failBadSyntaxKind(operand); } } - case 8 /* NumericLiteral */ : - return factory.createIdentifier("Number"); - case 9 /* BigIntLiteral */ : + case 9 /* NumericLiteral */ : + return factory2.createIdentifier("Number"); + case 10 /* BigIntLiteral */ : return getGlobalConstructor("BigInt", 7 /* ES2020 */ ); - case 110 /* TrueKeyword */ : - case 95 /* FalseKeyword */ : - return factory.createIdentifier("Boolean"); - case 104 /* NullKeyword */ : - return factory.createVoidZero(); + case 112 /* TrueKeyword */ : + case 97 /* FalseKeyword */ : + return factory2.createIdentifier("Boolean"); + case 106 /* NullKeyword */ : + return factory2.createVoidZero(); default: return Debug.failBadSyntaxKind(node); } @@ -77007,23 +78138,23 @@ ${lanes.join("\n")} let serializedType; for (let typeNode of types){ typeNode = skipTypeParentheses(typeNode); - if (typeNode.kind === 144 /* NeverKeyword */ ) { - if (isIntersection) return factory.createVoidZero(); + if (typeNode.kind === 146 /* NeverKeyword */ ) { + if (isIntersection) return factory2.createVoidZero(); continue; } - if (typeNode.kind === 157 /* UnknownKeyword */ ) { - if (!isIntersection) return factory.createIdentifier("Object"); + if (typeNode.kind === 159 /* UnknownKeyword */ ) { + if (!isIntersection) return factory2.createIdentifier("Object"); continue; } - if (typeNode.kind === 131 /* AnyKeyword */ ) return factory.createIdentifier("Object"); - if (!strictNullChecks && (isLiteralTypeNode(typeNode) && typeNode.literal.kind === 104 /* NullKeyword */ || typeNode.kind === 155 /* UndefinedKeyword */ )) continue; + if (typeNode.kind === 133 /* AnyKeyword */ ) return factory2.createIdentifier("Object"); + if (!strictNullChecks && (isLiteralTypeNode(typeNode) && typeNode.literal.kind === 106 /* NullKeyword */ || typeNode.kind === 157 /* UndefinedKeyword */ )) continue; const serializedConstituent = serializeTypeNode(typeNode); if (isIdentifier(serializedConstituent) && serializedConstituent.escapedText === "Object") return serializedConstituent; if (serializedType) { - if (!equateSerializedTypeNodes(serializedType, serializedConstituent)) return factory.createIdentifier("Object"); + if (!equateSerializedTypeNodes(serializedType, serializedConstituent)) return factory2.createIdentifier("Object"); } else serializedType = serializedConstituent; } - return serializedType != null ? serializedType : factory.createVoidZero(); + return serializedType ?? factory2.createVoidZero(); } function equateSerializedTypeNodes(left, right) { return(// temp vars used in fallback @@ -77037,71 +78168,71 @@ ${lanes.join("\n")} isBinaryExpression(left) ? isBinaryExpression(right) && left.operatorToken.kind === right.operatorToken.kind && equateSerializedTypeNodes(left.left, right.left) && equateSerializedTypeNodes(left.right, right.right) : false); } function serializeTypeReferenceNode(node) { - const kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope != null ? currentNameScope : currentLexicalScope); + const kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope ?? currentLexicalScope); switch(kind){ case 0 /* Unknown */ : - if (findAncestor(node, (n)=>n.parent && isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n))) return factory.createIdentifier("Object"); + if (findAncestor(node, (n)=>n.parent && isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n))) return factory2.createIdentifier("Object"); const serialized = serializeEntityNameAsExpressionFallback(node.typeName); - const temp = factory.createTempVariable(hoistVariableDeclaration); - return factory.createConditionalExpression(factory.createTypeCheck(factory.createAssignment(temp, serialized), "function"), /*questionToken*/ void 0, temp, /*colonToken*/ void 0, factory.createIdentifier("Object")); + const temp = factory2.createTempVariable(hoistVariableDeclaration); + return factory2.createConditionalExpression(factory2.createTypeCheck(factory2.createAssignment(temp, serialized), "function"), /*questionToken*/ void 0, temp, /*colonToken*/ void 0, factory2.createIdentifier("Object")); case 1 /* TypeWithConstructSignatureAndValue */ : return serializeEntityNameAsExpression(node.typeName); case 2 /* VoidNullableOrNeverType */ : - return factory.createVoidZero(); + return factory2.createVoidZero(); case 4 /* BigIntLikeType */ : return getGlobalConstructor("BigInt", 7 /* ES2020 */ ); case 6 /* BooleanType */ : - return factory.createIdentifier("Boolean"); + return factory2.createIdentifier("Boolean"); case 3 /* NumberLikeType */ : - return factory.createIdentifier("Number"); + return factory2.createIdentifier("Number"); case 5 /* StringLikeType */ : - return factory.createIdentifier("String"); + return factory2.createIdentifier("String"); case 7 /* ArrayLikeType */ : - return factory.createIdentifier("Array"); + return factory2.createIdentifier("Array"); case 8 /* ESSymbolType */ : return getGlobalConstructor("Symbol", 2 /* ES2015 */ ); case 10 /* TypeWithCallSignature */ : - return factory.createIdentifier("Function"); + return factory2.createIdentifier("Function"); case 9 /* Promise */ : - return factory.createIdentifier("Promise"); + return factory2.createIdentifier("Promise"); case 11 /* ObjectType */ : - return factory.createIdentifier("Object"); + return factory2.createIdentifier("Object"); default: return Debug.assertNever(kind); } } function createCheckedValue(left, right) { - return factory.createLogicalAnd(factory.createStrictInequality(factory.createTypeOfExpression(left), factory.createStringLiteral("undefined")), right); + return factory2.createLogicalAnd(factory2.createStrictInequality(factory2.createTypeOfExpression(left), factory2.createStringLiteral("undefined")), right); } function serializeEntityNameAsExpressionFallback(node) { - if (node.kind === 79 /* Identifier */ ) { + if (node.kind === 80 /* Identifier */ ) { const copied = serializeEntityNameAsExpression(node); return createCheckedValue(copied, copied); } - if (node.left.kind === 79 /* Identifier */ ) return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + if (node.left.kind === 80 /* Identifier */ ) return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); const left = serializeEntityNameAsExpressionFallback(node.left); - const temp = factory.createTempVariable(hoistVariableDeclaration); - return factory.createLogicalAnd(factory.createLogicalAnd(left.left, factory.createStrictInequality(factory.createAssignment(temp, left.right), factory.createVoidZero())), factory.createPropertyAccessExpression(temp, node.right)); + const temp = factory2.createTempVariable(hoistVariableDeclaration); + return factory2.createLogicalAnd(factory2.createLogicalAnd(left.left, factory2.createStrictInequality(factory2.createAssignment(temp, left.right), factory2.createVoidZero())), factory2.createPropertyAccessExpression(temp, node.right)); } function serializeEntityNameAsExpression(node) { switch(node.kind){ - case 79 /* Identifier */ : + case 80 /* Identifier */ : const name = setParent(setTextRange(parseNodeFactory.cloneNode(node), node), node.parent); name.original = void 0; setParent(name, getParseTreeNode(currentLexicalScope)); return name; - case 163 /* QualifiedName */ : + case 166 /* QualifiedName */ : return serializeQualifiedNameAsExpression(node); } } function serializeQualifiedNameAsExpression(node) { - return factory.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right); + return factory2.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right); } function getGlobalConstructorWithFallback(name) { - return factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier(name), "function"), /*questionToken*/ void 0, factory.createIdentifier(name), /*colonToken*/ void 0, factory.createIdentifier("Object")); + return factory2.createConditionalExpression(factory2.createTypeCheck(factory2.createIdentifier(name), "function"), /*questionToken*/ void 0, factory2.createIdentifier(name), /*colonToken*/ void 0, factory2.createIdentifier("Object")); } function getGlobalConstructor(name, minLanguageVersion) { - return languageVersion < minLanguageVersion ? getGlobalConstructorWithFallback(name) : factory.createIdentifier(name); + return languageVersion < minLanguageVersion ? getGlobalConstructorWithFallback(name) : factory2.createIdentifier(name); } } var init_typeSerializer = __esm({ @@ -77112,7 +78243,7 @@ ${lanes.join("\n")} }); // src/compiler/transformers/legacyDecorators.ts function transformLegacyDecorators(context) { - const { factory: factory2 , getEmitHelperFactory: emitHelpers , hoistVariableDeclaration: hoistVariableDeclaration } = context; + const { factory: factory2, getEmitHelperFactory: emitHelpers, hoistVariableDeclaration: hoistVariableDeclaration } = context; const resolver = context.getEmitResolver(); const compilerOptions = context.getCompilerOptions(); const languageVersion = getEmitScriptTarget(compilerOptions); @@ -77131,35 +78262,31 @@ ${lanes.join("\n")} function visitor(node) { if (!(node.transformFlags & 33554432 /* ContainsDecorators */ )) return node; switch(node.kind){ - case 167 /* Decorator */ : + case 170 /* Decorator */ : return void 0; - case 260 /* ClassDeclaration */ : + case 263 /* ClassDeclaration */ : return visitClassDeclaration(node); - case 228 /* ClassExpression */ : + case 231 /* ClassExpression */ : return visitClassExpression(node); - case 173 /* Constructor */ : + case 176 /* Constructor */ : return visitConstructorDeclaration(node); - case 171 /* MethodDeclaration */ : + case 174 /* MethodDeclaration */ : return visitMethodDeclaration(node); - case 175 /* SetAccessor */ : + case 178 /* SetAccessor */ : return visitSetAccessorDeclaration(node); - case 174 /* GetAccessor */ : + case 177 /* GetAccessor */ : return visitGetAccessorDeclaration(node); - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : return visitPropertyDeclaration(node); - case 166 /* Parameter */ : + case 169 /* Parameter */ : return visitParameterDeclaration(node); default: return visitEachChild(node, visitor, context); } } function visitClassDeclaration(node) { - if (!(classOrConstructorParameterIsDecorated(/*legacyDecorators*/ true, node) || childIsDecorated(/*legacyDecorators*/ true, node))) return visitEachChild(node, visitor, context); + if (!(classOrConstructorParameterIsDecorated(/*useLegacyDecorators*/ true, node) || childIsDecorated(/*useLegacyDecorators*/ true, node))) return visitEachChild(node, visitor, context); const statements = classOrConstructorParameterIsDecorated(/*useLegacyDecorators*/ true, node) ? transformClassDeclarationWithClassDecorators(node, node.name) : transformClassDeclarationWithoutClassDecorators(node, node.name); - if (statements.length > 1) { - statements.push(factory2.createEndOfDeclarationMarker(node)); - setEmitFlags(statements[0], getEmitFlags(statements[0]) | 8388608 /* HasEndOfDeclarationMarker */ ); - } return singleOrMany(statements); } function decoratorContainsPrivateIdentifierInExpression(decorator) { @@ -77198,34 +78325,57 @@ ${lanes.join("\n")} const heritageClauses = visitNodes2(node.heritageClauses, visitor, isHeritageClause); let members = visitNodes2(node.members, visitor, isClassElement); let decorationStatements = []; - ({ members: members , decorationStatements: decorationStatements } = transformDecoratorsOfClassElements(node, members)); + ({ members: members, decorationStatements: decorationStatements } = transformDecoratorsOfClassElements(node, members)); const updated = factory2.updateClassDeclaration(node, modifiers, name, /*typeParameters*/ void 0, heritageClauses, members); return addRange([ updated ], decorationStatements); } function transformClassDeclarationWithClassDecorators(node, name) { + const isExport = hasSyntacticModifier(node, 1 /* Export */ ); + const isDefault = hasSyntacticModifier(node, 1024 /* Default */ ); + const modifiers = visitNodes2(node.modifiers, (node2)=>isExportOrDefaultModifier(node2) || isDecorator(node2) ? void 0 : node2, isModifierLike); const location = moveRangePastModifiers(node); const classAlias = getClassAliasIfNeeded(node); - const declName = languageVersion <= 2 /* ES2015 */ ? factory2.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : factory2.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + const declName = languageVersion < 2 /* ES2015 */ ? factory2.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : factory2.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); const heritageClauses = visitNodes2(node.heritageClauses, visitor, isHeritageClause); let members = visitNodes2(node.members, visitor, isClassElement); let decorationStatements = []; - ({ members: members , decorationStatements: decorationStatements } = transformDecoratorsOfClassElements(node, members)); - const classExpression = factory2.createClassExpression(/*modifiers*/ void 0, name && isGeneratedIdentifier(name) ? void 0 : name, /*typeParameters*/ void 0, heritageClauses, members); + ({ members: members, decorationStatements: decorationStatements } = transformDecoratorsOfClassElements(node, members)); + const assignClassAliasInStaticBlock = languageVersion >= 9 /* ES2022 */ && !!classAlias && some(members, (member)=>isPropertyDeclaration(member) && hasSyntacticModifier(member, 32 /* Static */ ) || isClassStaticBlockDeclaration(member)); + if (assignClassAliasInStaticBlock) members = setTextRange(factory2.createNodeArray([ + factory2.createClassStaticBlockDeclaration(factory2.createBlock([ + factory2.createExpressionStatement(factory2.createAssignment(classAlias, factory2.createThis())) + ])), + ...members + ]), members); + const classExpression = factory2.createClassExpression(modifiers, name && isGeneratedIdentifier(name) ? void 0 : name, /*typeParameters*/ void 0, heritageClauses, members); setOriginalNode(classExpression, node); setTextRange(classExpression, location); - const statement = factory2.createVariableStatement(/*modifiers*/ void 0, factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration(declName, /*exclamationToken*/ void 0, /*type*/ void 0, classAlias ? factory2.createAssignment(classAlias, classExpression) : classExpression) - ], 1 /* Let */ )); - setOriginalNode(statement, node); - setTextRange(statement, location); - setCommentRange(statement, node); + const varInitializer = classAlias && !assignClassAliasInStaticBlock ? factory2.createAssignment(classAlias, classExpression) : classExpression; + const varDecl = factory2.createVariableDeclaration(declName, /*exclamationToken*/ void 0, /*type*/ void 0, varInitializer); + setOriginalNode(varDecl, node); + const varDeclList = factory2.createVariableDeclarationList([ + varDecl + ], 1 /* Let */ ); + const varStatement = factory2.createVariableStatement(/*modifiers*/ void 0, varDeclList); + setOriginalNode(varStatement, node); + setTextRange(varStatement, location); + setCommentRange(varStatement, node); const statements = [ - statement + varStatement ]; addRange(statements, decorationStatements); addConstructorDecorationStatement(statements, node); + if (isExport) { + if (isDefault) { + const exportStatement = factory2.createExportDefault(declName); + statements.push(exportStatement); + } else { + const exportStatement = factory2.createExternalModuleExport(factory2.getDeclarationName(node)); + statements.push(exportStatement); + } + } return statements; } function visitClassExpression(node) { @@ -77251,7 +78401,7 @@ ${lanes.join("\n")} return finishClassElement(factory2.updateSetAccessorDeclaration(node, visitNodes2(node.modifiers, modifierVisitor, isModifier), Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), visitNodes2(node.parameters, visitor, isParameter), visitNode(node.body, visitor, isBlock)), node); } function visitPropertyDeclaration(node) { - if (node.flags & 16777216 /* Ambient */ || hasSyntacticModifier(node, 2 /* Ambient */ )) return void 0; + if (node.flags & 33554432 /* Ambient */ || hasSyntacticModifier(node, 2 /* Ambient */ )) return void 0; return finishClassElement(factory2.updatePropertyDeclaration(node, visitNodes2(node.modifiers, modifierVisitor, isModifier), Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), /*questionOrExclamationToken*/ void 0, /*type*/ void 0, visitNode(node.initializer, visitor, isExpression)), node); } function visitParameterDeclaration(node) { @@ -77269,7 +78419,7 @@ ${lanes.join("\n")} } function transformAllDecoratorsOfDeclaration(allDecorators) { if (!allDecorators) return void 0; - const { false: decorators , true: metadata } = groupBy(allDecorators.decorators, isSyntheticMetadataDecorator); + const { false: decorators, true: metadata } = groupBy(allDecorators.decorators, isSyntheticMetadataDecorator); const decoratorExpressions = []; addRange(decoratorExpressions, map(decorators, transformDecorator)); addRange(decoratorExpressions, flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); @@ -77280,7 +78430,7 @@ ${lanes.join("\n")} addRange(statements, map(generateClassElementDecorationExpressions(node, isStatic2), (expr)=>factory2.createExpressionStatement(expr))); } function isDecoratedClassElement(member, isStaticElement, parent2) { - return nodeOrChildIsDecorated(/*legacyDecorators*/ true, member, parent2) && isStaticElement === isStatic(member); + return nodeOrChildIsDecorated(/*useLegacyDecorators*/ true, member, parent2) && isStaticElement === isStatic(member); } function getDecoratedClassElements(node, isStatic2) { return filter(node.members, (m)=>isDecoratedClassElement(m, isStatic2, node)); @@ -77312,7 +78462,7 @@ ${lanes.join("\n")} const decoratorExpressions = transformAllDecoratorsOfDeclaration(allDecorators); if (!decoratorExpressions) return void 0; const classAlias = classAliases && classAliases[getOriginalNodeId(node)]; - const localName = languageVersion <= 2 /* ES2015 */ ? factory2.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : factory2.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + const localName = languageVersion < 2 /* ES2015 */ ? factory2.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : factory2.getDeclarationName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); const decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName); const expression = factory2.createAssignment(localName, classAlias ? factory2.createAssignment(classAlias, decorate) : decorate); setEmitFlags(expression, 3072 /* NoComments */ ); @@ -77344,12 +78494,12 @@ ${lanes.join("\n")} } function enableSubstitutionForClassAliases() { if (!classAliases) { - context.enableSubstitution(79 /* Identifier */ ); + context.enableSubstitution(80 /* Identifier */ ); classAliases = []; } } function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 1048576 /* ClassWithConstructorReference */ ) { + if (resolver.getNodeCheckFlags(node) & 262144 /* ContainsConstructorReference */ ) { enableSubstitutionForClassAliases(); const classAlias = factory2.createUniqueName(node.name && !isGeneratedIdentifier(node.name) ? idText(node.name) : "default"); classAliases[getOriginalNodeId(node)] = classAlias; @@ -77370,18 +78520,17 @@ ${lanes.join("\n")} } function substituteExpression(node) { switch(node.kind){ - case 79 /* Identifier */ : + case 80 /* Identifier */ : return substituteExpressionIdentifier(node); } return node; } function substituteExpressionIdentifier(node) { - var _a2; - return (_a2 = trySubstituteClassAlias(node)) != null ? _a2 : node; + return trySubstituteClassAlias(node) ?? node; } function trySubstituteClassAlias(node) { if (classAliases) { - if (resolver.getNodeCheckFlags(node) & 2097152 /* ConstructorReferenceInClass */ ) { + if (resolver.getNodeCheckFlags(node) & 536870912 /* ConstructorReference */ ) { const declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { const classAlias = classAliases[declaration.id]; @@ -77405,7 +78554,8 @@ ${lanes.join("\n")} }); // src/compiler/transformers/esDecorators.ts function transformESDecorators(context) { - const { factory: factory2 , getEmitHelperFactory: emitHelpers , startLexicalEnvironment: startLexicalEnvironment , endLexicalEnvironment: endLexicalEnvironment , hoistVariableDeclaration: hoistVariableDeclaration } = context; + const { factory: factory2, getEmitHelperFactory: emitHelpers, startLexicalEnvironment: startLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, hoistVariableDeclaration: hoistVariableDeclaration } = context; + const languageVersion = getEmitScriptTarget(context.getCompilerOptions()); let top; let classInfo; let classThis; @@ -77464,24 +78614,24 @@ ${lanes.join("\n")} updateState(); } function enterClassElement(node) { - var _a2, _b; + var _a, _b; Debug.assert((top == null ? void 0 : top.kind) === "class", "Incorrect value for top.kind.", ()=>`Expected top.kind to be 'class' but got '${top == null ? void 0 : top.kind}' instead.`); top = { kind: "class-element", next: top }; if (isClassStaticBlockDeclaration(node) || isPropertyDeclaration(node) && hasStaticModifier(node)) { - top.classThis = (_a2 = top.next.classInfo) == null ? void 0 : _a2.classThis; + top.classThis = (_a = top.next.classInfo) == null ? void 0 : _a.classThis; top.classSuper = (_b = top.next.classInfo) == null ? void 0 : _b.classSuper; } updateState(); } function exitClassElement() { - var _a2; + var _a; Debug.assert((top == null ? void 0 : top.kind) === "class-element", "Incorrect value for top.kind.", ()=>`Expected top.kind to be 'class-element' but got '${top == null ? void 0 : top.kind}' instead.`); - Debug.assert(((_a2 = top.next) == null ? void 0 : _a2.kind) === "class", "Incorrect value for top.next.kind.", ()=>{ - var _a3; - return `Expected top.next.kind to be 'class' but got '${(_a3 = top.next) == null ? void 0 : _a3.kind}' instead.`; + Debug.assert(((_a = top.next) == null ? void 0 : _a.kind) === "class", "Incorrect value for top.next.kind.", ()=>{ + var _a2; + return `Expected top.next.kind to be 'class' but got '${(_a2 = top.next) == null ? void 0 : _a2.kind}' instead.`; }); top = top.next; updateState(); @@ -77531,58 +78681,58 @@ ${lanes.join("\n")} function visitor(node) { if (!shouldVisitNode(node)) return node; switch(node.kind){ - case 167 /* Decorator */ : + case 170 /* Decorator */ : return Debug.fail("Use `modifierVisitor` instead."); - case 260 /* ClassDeclaration */ : + case 263 /* ClassDeclaration */ : return visitClassDeclaration(node); - case 228 /* ClassExpression */ : - return visitClassExpression(node, /*referencedName*/ void 0); - case 173 /* Constructor */ : - case 169 /* PropertyDeclaration */ : - case 172 /* ClassStaticBlockDeclaration */ : + case 231 /* ClassExpression */ : + return visitClassExpression(node); + case 176 /* Constructor */ : + case 172 /* PropertyDeclaration */ : + case 175 /* ClassStaticBlockDeclaration */ : return Debug.fail("Not supported outside of a class. Use 'classElementVisitor' instead."); - case 166 /* Parameter */ : + case 169 /* Parameter */ : return visitParameterDeclaration(node); - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : return visitBinaryExpression(node, /*discarded*/ false); - case 299 /* PropertyAssignment */ : + case 303 /* PropertyAssignment */ : return visitPropertyAssignment(node); - case 257 /* VariableDeclaration */ : + case 260 /* VariableDeclaration */ : return visitVariableDeclaration(node); - case 205 /* BindingElement */ : + case 208 /* BindingElement */ : return visitBindingElement(node); - case 274 /* ExportAssignment */ : + case 277 /* ExportAssignment */ : return visitExportAssignment(node); - case 108 /* ThisKeyword */ : + case 110 /* ThisKeyword */ : return visitThisExpression(node); - case 245 /* ForStatement */ : + case 248 /* ForStatement */ : return visitForStatement(node); - case 241 /* ExpressionStatement */ : + case 244 /* ExpressionStatement */ : return visitExpressionStatement(node); - case 357 /* CommaListExpression */ : + case 361 /* CommaListExpression */ : return visitCommaListExpression(node, /*discarded*/ false); - case 214 /* ParenthesizedExpression */ : - return visitParenthesizedExpression(node, /*discarded*/ false, /*referencedName*/ void 0); - case 356 /* PartiallyEmittedExpression */ : - return visitPartiallyEmittedExpression(node, /*discarded*/ false, /*referencedName*/ void 0); - case 210 /* CallExpression */ : + case 217 /* ParenthesizedExpression */ : + return visitParenthesizedExpression(node, /*discarded*/ false); + case 360 /* PartiallyEmittedExpression */ : + return visitPartiallyEmittedExpression(node, /*discarded*/ false); + case 213 /* CallExpression */ : return visitCallExpression(node); - case 212 /* TaggedTemplateExpression */ : + case 215 /* TaggedTemplateExpression */ : return visitTaggedTemplateExpression(node); - case 221 /* PrefixUnaryExpression */ : - case 222 /* PostfixUnaryExpression */ : - return visitPreOrPostfixUnaryExpression(node, /*discard*/ false); - case 208 /* PropertyAccessExpression */ : + case 224 /* PrefixUnaryExpression */ : + case 225 /* PostfixUnaryExpression */ : + return visitPreOrPostfixUnaryExpression(node, /*discarded*/ false); + case 211 /* PropertyAccessExpression */ : return visitPropertyAccessExpression(node); - case 209 /* ElementAccessExpression */ : + case 212 /* ElementAccessExpression */ : return visitElementAccessExpression(node); - case 164 /* ComputedPropertyName */ : + case 167 /* ComputedPropertyName */ : return visitComputedPropertyName(node); - case 171 /* MethodDeclaration */ : - case 175 /* SetAccessor */ : - case 174 /* GetAccessor */ : - case 215 /* FunctionExpression */ : - case 259 /* FunctionDeclaration */ : + case 174 /* MethodDeclaration */ : + case 178 /* SetAccessor */ : + case 177 /* GetAccessor */ : + case 218 /* FunctionExpression */ : + case 262 /* FunctionDeclaration */ : { enterOther(); const result = visitEachChild(node, fallbackVisitor, context); @@ -77595,7 +78745,7 @@ ${lanes.join("\n")} } function fallbackVisitor(node) { switch(node.kind){ - case 167 /* Decorator */ : + case 170 /* Decorator */ : return void 0; default: return visitor(node); @@ -77603,7 +78753,7 @@ ${lanes.join("\n")} } function modifierVisitor(node) { switch(node.kind){ - case 167 /* Decorator */ : + case 170 /* Decorator */ : return void 0; default: return node; @@ -77611,45 +78761,33 @@ ${lanes.join("\n")} } function classElementVisitor(node) { switch(node.kind){ - case 173 /* Constructor */ : + case 176 /* Constructor */ : return visitConstructorDeclaration(node); - case 171 /* MethodDeclaration */ : + case 174 /* MethodDeclaration */ : return visitMethodDeclaration(node); - case 174 /* GetAccessor */ : + case 177 /* GetAccessor */ : return visitGetAccessorDeclaration(node); - case 175 /* SetAccessor */ : + case 178 /* SetAccessor */ : return visitSetAccessorDeclaration(node); - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : return visitPropertyDeclaration(node); - case 172 /* ClassStaticBlockDeclaration */ : + case 175 /* ClassStaticBlockDeclaration */ : return visitClassStaticBlockDeclaration(node); default: return visitor(node); } } - function namedEvaluationVisitor(node, referencedName) { - switch(node.kind){ - case 356 /* PartiallyEmittedExpression */ : - return visitPartiallyEmittedExpression(node, /*discarded*/ false, referencedName); - case 214 /* ParenthesizedExpression */ : - return visitParenthesizedExpression(node, /*discarded*/ false, referencedName); - case 228 /* ClassExpression */ : - return visitClassExpression(node, referencedName); - default: - return visitor(node); - } - } function discardedValueVisitor(node) { switch(node.kind){ - case 221 /* PrefixUnaryExpression */ : - case 222 /* PostfixUnaryExpression */ : + case 224 /* PrefixUnaryExpression */ : + case 225 /* PostfixUnaryExpression */ : return visitPreOrPostfixUnaryExpression(node, /*discarded*/ true); - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : return visitBinaryExpression(node, /*discarded*/ true); - case 357 /* CommaListExpression */ : + case 361 /* CommaListExpression */ : return visitCommaListExpression(node, /*discarded*/ true); - case 214 /* ParenthesizedExpression */ : - return visitParenthesizedExpression(node, /*discarded*/ true, /*referencedName*/ void 0); + case 217 /* ParenthesizedExpression */ : + return visitParenthesizedExpression(node, /*discarded*/ true); default: return visitor(node); } @@ -77671,18 +78809,20 @@ ${lanes.join("\n")} ], 1 /* Let */ )); } function createClassInfo(node) { + const metadataReference = factory2.createUniqueName("_metadata", 48 /* FileLevel */ ); let instanceExtraInitializersName; let staticExtraInitializersName; let hasStaticInitializers = false; let hasNonAmbientInstanceFields = false; let hasStaticPrivateClassElements = false; for (const member of node.members){ - if (isNamedClassElement(member) && nodeOrChildIsDecorated(/*legacyDecorators*/ false, member, node)) { - if (hasStaticModifier(member)) staticExtraInitializersName != null ? staticExtraInitializersName : staticExtraInitializersName = factory2.createUniqueName("_staticExtraInitializers", 16 /* Optimistic */ ); - else instanceExtraInitializersName != null ? instanceExtraInitializersName : instanceExtraInitializersName = factory2.createUniqueName("_instanceExtraInitializers", 16 /* Optimistic */ ); + if (isNamedClassElement(member) && nodeOrChildIsDecorated(/*useLegacyDecorators*/ false, member, node)) { + if (hasStaticModifier(member)) staticExtraInitializersName ?? (staticExtraInitializersName = factory2.createUniqueName("_staticExtraInitializers", 48 /* FileLevel */ )); + else instanceExtraInitializersName ?? (instanceExtraInitializersName = factory2.createUniqueName("_instanceExtraInitializers", 48 /* FileLevel */ )); } - if (isClassStaticBlockDeclaration(member)) hasStaticInitializers = true; - else if (isPropertyDeclaration(member)) { + if (isClassStaticBlockDeclaration(member)) { + if (!isClassNamedEvaluationHelperBlock(member)) hasStaticInitializers = true; + } else if (isPropertyDeclaration(member)) { if (hasStaticModifier(member)) hasStaticInitializers || (hasStaticInitializers = !!member.initializer || hasDecorators(member)); else hasNonAmbientInstanceFields || (hasNonAmbientInstanceFields = !isAmbientPropertyDeclaration(member)); } @@ -77691,6 +78831,7 @@ ${lanes.join("\n")} } return { class: node, + metadataReference: metadataReference, instanceExtraInitializersName: instanceExtraInitializersName, staticExtraInitializersName: staticExtraInitializersName, hasStaticInitializers: hasStaticInitializers, @@ -77698,16 +78839,10 @@ ${lanes.join("\n")} hasStaticPrivateClassElements: hasStaticPrivateClassElements }; } - function containsLexicalSuperInStaticInitializer(node) { - for (const member of node.members)if (isClassStaticBlockDeclaration(member) || isPropertyDeclaration(member) && hasStaticModifier(member)) { - if (member.transformFlags & 134217728 /* ContainsLexicalSuper */ ) return true; - } - return false; - } - function transformClassLike(node, className) { - var _a2, _b, _c, _d, _e; + function transformClassLike(node) { startLexicalEnvironment(); - const classReference = (_a2 = node.name) != null ? _a2 : factory2.getGeneratedNameForNode(node); + if (!classHasDeclaredOrExplicitlyAssignedName(node) && classOrConstructorParameterIsDecorated(/*useLegacyDecorators*/ false, node)) node = injectClassNamedEvaluationHelperBlockIfMissing(context, node, factory2.createStringLiteral("")); + const classReference = factory2.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false, /*ignoreAssignedName*/ true); const classInfo2 = createClassInfo(node); const classDefinitionStatements = []; let leadingBlockStatements; @@ -77717,41 +78852,36 @@ ${lanes.join("\n")} let shouldTransformPrivateStaticElementsInClass = false; const classDecorators = transformAllDecoratorsOfDeclaration(getAllDecoratorsOfClass(node)); if (classDecorators) { - classInfo2.classDecoratorsName = factory2.createUniqueName("_classDecorators", 16 /* Optimistic */ ); - classInfo2.classDescriptorName = factory2.createUniqueName("_classDescriptor", 16 /* Optimistic */ ); - classInfo2.classExtraInitializersName = factory2.createUniqueName("_classExtraInitializers", 16 /* Optimistic */ ); - classInfo2.classThis = factory2.createUniqueName("_classThis", 16 /* Optimistic */ ); + classInfo2.classDecoratorsName = factory2.createUniqueName("_classDecorators", 48 /* FileLevel */ ); + classInfo2.classDescriptorName = factory2.createUniqueName("_classDescriptor", 48 /* FileLevel */ ); + classInfo2.classExtraInitializersName = factory2.createUniqueName("_classExtraInitializers", 48 /* FileLevel */ ); + const needsUniqueClassThis = some(node.members, (member)=>(isPrivateIdentifierClassElementDeclaration(member) || isAutoAccessorPropertyDeclaration(member)) && hasStaticModifier(member)); + classInfo2.classThis = factory2.createUniqueName("_classThis", needsUniqueClassThis ? 24 /* ReservedInNestedScopes */ : 48 /* FileLevel */ ); classDefinitionStatements.push(createLet(classInfo2.classDecoratorsName, factory2.createArrayLiteralExpression(classDecorators)), createLet(classInfo2.classDescriptorName), createLet(classInfo2.classExtraInitializersName, factory2.createArrayLiteralExpression()), createLet(classInfo2.classThis)); if (classInfo2.hasStaticPrivateClassElements) { shouldTransformPrivateStaticElementsInClass = true; shouldTransformPrivateStaticElementsInFile = true; } } - if (classDecorators && containsLexicalSuperInStaticInitializer(node)) { - const extendsClause = getHeritageClause(node.heritageClauses, 94 /* ExtendsKeyword */ ); - const extendsElement = extendsClause && firstOrUndefined(extendsClause.types); - const extendsExpression = extendsElement && visitNode(extendsElement.expression, visitor, isExpression); - if (extendsExpression) { - classInfo2.classSuper = factory2.createUniqueName("_classSuper", 16 /* Optimistic */ ); - const unwrapped = skipOuterExpressions(extendsExpression); - const safeExtendsExpression = isClassExpression(unwrapped) && !unwrapped.name || isFunctionExpression(unwrapped) && !unwrapped.name || isArrowFunction(unwrapped) ? factory2.createComma(factory2.createNumericLiteral(0), extendsExpression) : extendsExpression; - classDefinitionStatements.push(createLet(classInfo2.classSuper, safeExtendsExpression)); - const updatedExtendsElement = factory2.updateExpressionWithTypeArguments(extendsElement, classInfo2.classSuper, /*typeArguments*/ void 0); - const updatedExtendsClause = factory2.updateHeritageClause(extendsClause, [ - updatedExtendsElement - ]); - heritageClauses = factory2.createNodeArray([ - updatedExtendsClause - ]); - } - } else heritageClauses = visitNodes2(node.heritageClauses, visitor, isHeritageClause); - const renamedClassThis = (_b = classInfo2.classThis) != null ? _b : factory2.createThis(); - const needsSetNameHelper = !((_c = getOriginalNode(node, isClassLike)) == null ? void 0 : _c.name) && (classDecorators || !isStringLiteral(className) || !isEmptyStringLiteral(className)); - if (needsSetNameHelper) { - const setNameExpr = emitHelpers().createSetFunctionNameHelper(factory2.createThis(), className); - leadingBlockStatements = append(leadingBlockStatements, factory2.createExpressionStatement(setNameExpr)); + const extendsClause = getHeritageClause(node.heritageClauses, 96 /* ExtendsKeyword */ ); + const extendsElement = extendsClause && firstOrUndefined(extendsClause.types); + const extendsExpression = extendsElement && visitNode(extendsElement.expression, visitor, isExpression); + if (extendsExpression) { + classInfo2.classSuper = factory2.createUniqueName("_classSuper", 48 /* FileLevel */ ); + const unwrapped = skipOuterExpressions(extendsExpression); + const safeExtendsExpression = isClassExpression(unwrapped) && !unwrapped.name || isFunctionExpression(unwrapped) && !unwrapped.name || isArrowFunction(unwrapped) ? factory2.createComma(factory2.createNumericLiteral(0), extendsExpression) : extendsExpression; + classDefinitionStatements.push(createLet(classInfo2.classSuper, safeExtendsExpression)); + const updatedExtendsElement = factory2.updateExpressionWithTypeArguments(extendsElement, classInfo2.classSuper, /*typeArguments*/ void 0); + const updatedExtendsClause = factory2.updateHeritageClause(extendsClause, [ + updatedExtendsElement + ]); + heritageClauses = factory2.createNodeArray([ + updatedExtendsClause + ]); } + const renamedClassThis = classInfo2.classThis ?? factory2.createThis(); enterClass(classInfo2); + leadingBlockStatements = append(leadingBlockStatements, createMetadata(classInfo2.metadataReference, classInfo2.classSuper)); let members = visitNodes2(node.members, classElementVisitor, isClassElement); if (pendingExpressions) { let outerThis; @@ -77759,7 +78889,7 @@ ${lanes.join("\n")} expression = visitNode(expression, function thisVisitor(node2) { if (!(node2.transformFlags & 16384 /* ContainsLexicalThis */ )) return node2; switch(node2.kind){ - case 108 /* ThisKeyword */ : + case 110 /* ThisKeyword */ : if (!outerThis) { outerThis = factory2.createUniqueName("_outerThis", 16 /* Optimistic */ ); classDefinitionStatements.unshift(createLet(outerThis, factory2.createThis())); @@ -77779,7 +78909,7 @@ ${lanes.join("\n")} const initializerStatements = prepareConstructor(node, classInfo2); if (initializerStatements) { const extendsClauseElement = getEffectiveBaseTypeNode(node); - const isDerivedClass = !!(extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 104 /* NullKeyword */ ); + const isDerivedClass = !!(extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 106 /* NullKeyword */ ); const constructorStatements = []; if (isDerivedClass) { const spreadArguments = factory2.createSpreadElement(factory2.createIdentifier("arguments")); @@ -77814,16 +78944,17 @@ ${lanes.join("\n")} leadingBlockStatements = addRange(leadingBlockStatements, classInfo2.staticFieldDecorationStatements); leadingBlockStatements = addRange(leadingBlockStatements, classInfo2.nonStaticFieldDecorationStatements); if (classInfo2.classDescriptorName && classInfo2.classDecoratorsName && classInfo2.classExtraInitializersName && classInfo2.classThis) { - leadingBlockStatements != null ? leadingBlockStatements : leadingBlockStatements = []; - const valueProperty = factory2.createPropertyAssignment("value", factory2.createThis()); + leadingBlockStatements ?? (leadingBlockStatements = []); + const valueProperty = factory2.createPropertyAssignment("value", renamedClassThis); const classDescriptor = factory2.createObjectLiteralExpression([ valueProperty ]); const classDescriptorAssignment = factory2.createAssignment(classInfo2.classDescriptorName, classDescriptor); - const classNameReference = factory2.createPropertyAccessExpression(factory2.createThis(), "name"); + const classNameReference = factory2.createPropertyAccessExpression(renamedClassThis, "name"); const esDecorateHelper2 = emitHelpers().createESDecorateHelper(factory2.createNull(), classDescriptorAssignment, classInfo2.classDecoratorsName, { kind: "class", - name: classNameReference + name: classNameReference, + metadata: classInfo2.metadataReference }, factory2.createNull(), classInfo2.classExtraInitializersName); const esDecorateStatement = factory2.createExpressionStatement(esDecorateHelper2); setSourceMapRange(esDecorateStatement, moveRangePastDecorators(node)); @@ -77833,49 +78964,43 @@ ${lanes.join("\n")} const classReferenceAssignment = factory2.createAssignment(classReference, classThisAssignment); leadingBlockStatements.push(factory2.createExpressionStatement(classReferenceAssignment)); } + leadingBlockStatements.push(createSymbolMetadata(renamedClassThis, classInfo2.metadataReference)); if (classInfo2.staticExtraInitializersName) { const runStaticInitializersHelper = emitHelpers().createRunInitializersHelper(renamedClassThis, classInfo2.staticExtraInitializersName); const runStaticInitializersStatement = factory2.createExpressionStatement(runStaticInitializersHelper); - setSourceMapRange(runStaticInitializersStatement, (_d = node.name) != null ? _d : moveRangePastDecorators(node)); + setSourceMapRange(runStaticInitializersStatement, node.name ?? moveRangePastDecorators(node)); leadingBlockStatements = append(leadingBlockStatements, runStaticInitializersStatement); } if (classInfo2.classExtraInitializersName) { const runClassInitializersHelper = emitHelpers().createRunInitializersHelper(renamedClassThis, classInfo2.classExtraInitializersName); const runClassInitializersStatement = factory2.createExpressionStatement(runClassInitializersHelper); - setSourceMapRange(runClassInitializersStatement, (_e = node.name) != null ? _e : moveRangePastDecorators(node)); + setSourceMapRange(runClassInitializersStatement, node.name ?? moveRangePastDecorators(node)); trailingBlockStatements = append(trailingBlockStatements, runClassInitializersStatement); } if (leadingBlockStatements && trailingBlockStatements && !classInfo2.hasStaticInitializers) { addRange(leadingBlockStatements, trailingBlockStatements); trailingBlockStatements = void 0; } - let newMembers = members; - if (leadingBlockStatements) { - const leadingStaticBlockBody = factory2.createBlock(leadingBlockStatements, /*multiline*/ true); - const leadingStaticBlock = factory2.createClassStaticBlockDeclaration(leadingStaticBlockBody); - if (shouldTransformPrivateStaticElementsInClass) setInternalEmitFlags(leadingStaticBlock, 32 /* TransformPrivateStaticElements */ ); - newMembers = [ - leadingStaticBlock, - ...newMembers - ]; - } - if (syntheticConstructor) newMembers = [ - ...newMembers, - syntheticConstructor - ]; - if (trailingBlockStatements) { - const trailingStaticBlockBody = factory2.createBlock(trailingBlockStatements, /*multiline*/ true); - const trailingStaticBlock = factory2.createClassStaticBlockDeclaration(trailingStaticBlockBody); - newMembers = [ - ...newMembers, - trailingStaticBlock - ]; + const leadingStaticBlock = leadingBlockStatements && factory2.createClassStaticBlockDeclaration(factory2.createBlock(leadingBlockStatements, /*multiLine*/ true)); + if (leadingStaticBlock && shouldTransformPrivateStaticElementsInClass) setInternalEmitFlags(leadingStaticBlock, 32 /* TransformPrivateStaticElements */ ); + const trailingStaticBlock = trailingBlockStatements && factory2.createClassStaticBlockDeclaration(factory2.createBlock(trailingBlockStatements, /*multiLine*/ true)); + if (leadingStaticBlock || syntheticConstructor || trailingStaticBlock) { + const newMembers = []; + const existingNamedEvaluationHelperBlockIndex = members.findIndex(isClassNamedEvaluationHelperBlock); + if (leadingStaticBlock) { + addRange(newMembers, members, 0, existingNamedEvaluationHelperBlockIndex + 1); + newMembers.push(leadingStaticBlock); + addRange(newMembers, members, existingNamedEvaluationHelperBlockIndex + 1); + } else addRange(newMembers, members); + if (syntheticConstructor) newMembers.push(syntheticConstructor); + if (trailingStaticBlock) newMembers.push(trailingStaticBlock); + members = setTextRange(factory2.createNodeArray(newMembers), members); } - if (newMembers !== members) members = setTextRange(factory2.createNodeArray(newMembers), members); const lexicalEnvironment = endLexicalEnvironment(); let classExpression; if (classDecorators) { classExpression = factory2.createClassExpression(/*modifiers*/ void 0, /*name*/ void 0, /*typeParameters*/ void 0, heritageClauses, members); + if (classInfo2.classThis) classExpression = injectClassThisAssignmentIfMissing(factory2, classExpression, classInfo2.classThis); const classReferenceDeclaration = factory2.createVariableDeclaration(classReference, /*exclamationToken*/ void 0, /*type*/ void 0, classExpression); const classReferenceVarDeclList = factory2.createVariableDeclarationList([ classReferenceDeclaration @@ -77891,37 +79016,63 @@ ${lanes.join("\n")} for (const member of classExpression.members)if ((isPrivateIdentifierClassElementDeclaration(member) || isAutoAccessorPropertyDeclaration(member)) && hasStaticModifier(member)) addInternalEmitFlags(member, 32 /* TransformPrivateStaticElements */ ); } setOriginalNode(classExpression, node); - getOrCreateEmitNode(classExpression).classThis = classInfo2.classThis; return factory2.createImmediatelyInvokedArrowFunction(factory2.mergeLexicalEnvironment(classDefinitionStatements, lexicalEnvironment)); } function isDecoratedClassLike(node) { - return classOrConstructorParameterIsDecorated(/*legacyDecorators*/ false, node) || childIsDecorated(/*legacyDecorators*/ false, node); + return classOrConstructorParameterIsDecorated(/*useLegacyDecorators*/ false, node) || childIsDecorated(/*useLegacyDecorators*/ false, node); } function visitClassDeclaration(node) { - var _a2; if (isDecoratedClassLike(node)) { - if (hasSyntacticModifier(node, 1 /* Export */ ) && hasSyntacticModifier(node, 1024 /* Default */ )) { - const originalClass = (_a2 = getOriginalNode(node, isClassLike)) != null ? _a2 : node; - const className = originalClass.name ? factory2.createStringLiteralFromNode(originalClass.name) : factory2.createStringLiteral("default"); - const iife = transformClassLike(node, className); - const statement = factory2.createExportDefault(iife); - setOriginalNode(statement, node); - setCommentRange(statement, getCommentRange(node)); - setSourceMapRange(statement, moveRangePastDecorators(node)); - return statement; + const statements = []; + const originalClass = getOriginalNode(node, isClassLike) ?? node; + const className = originalClass.name ? factory2.createStringLiteralFromNode(originalClass.name) : factory2.createStringLiteral("default"); + const isExport = hasSyntacticModifier(node, 1 /* Export */ ); + const isDefault = hasSyntacticModifier(node, 1024 /* Default */ ); + if (!node.name) node = injectClassNamedEvaluationHelperBlockIfMissing(context, node, className); + if (isExport && isDefault) { + const iife = transformClassLike(node); + if (node.name) { + const varDecl = factory2.createVariableDeclaration(factory2.getLocalName(node), /*exclamationToken*/ void 0, /*type*/ void 0, iife); + setOriginalNode(varDecl, node); + const varDecls = factory2.createVariableDeclarationList([ + varDecl + ], 1 /* Let */ ); + const varStatement = factory2.createVariableStatement(/*modifiers*/ void 0, varDecls); + statements.push(varStatement); + const exportStatement = factory2.createExportDefault(factory2.getDeclarationName(node)); + setOriginalNode(exportStatement, node); + setCommentRange(exportStatement, getCommentRange(node)); + setSourceMapRange(exportStatement, moveRangePastDecorators(node)); + statements.push(exportStatement); + } else { + const exportStatement = factory2.createExportDefault(iife); + setOriginalNode(exportStatement, node); + setCommentRange(exportStatement, getCommentRange(node)); + setSourceMapRange(exportStatement, moveRangePastDecorators(node)); + statements.push(exportStatement); + } } else { Debug.assertIsDefined(node.name, "A class declaration that is not a default export must have a name."); - const iife = transformClassLike(node, factory2.createStringLiteralFromNode(node.name)); - const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); - const varDecl = factory2.createVariableDeclaration(node.name, /*exclamationToken*/ void 0, /*type*/ void 0, iife); + const iife = transformClassLike(node); + const modifierVisitorNoExport = isExport ? (node2)=>isExportModifier(node2) ? void 0 : modifierVisitor(node2) : modifierVisitor; + const modifiers = visitNodes2(node.modifiers, modifierVisitorNoExport, isModifier); + const declName = factory2.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + const varDecl = factory2.createVariableDeclaration(declName, /*exclamationToken*/ void 0, /*type*/ void 0, iife); + setOriginalNode(varDecl, node); const varDecls = factory2.createVariableDeclarationList([ varDecl ], 1 /* Let */ ); - const statement = factory2.createVariableStatement(modifiers, varDecls); - setOriginalNode(statement, node); - setCommentRange(statement, getCommentRange(node)); - return statement; + const varStatement = factory2.createVariableStatement(modifiers, varDecls); + setOriginalNode(varStatement, node); + setCommentRange(varStatement, getCommentRange(node)); + statements.push(varStatement); + if (isExport) { + const exportStatement = factory2.createExternalModuleExport(declName); + setOriginalNode(exportStatement, node); + statements.push(exportStatement); + } } + return singleOrMany(statements); } else { const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); const heritageClauses = visitNodes2(node.heritageClauses, visitor, isHeritageClause); @@ -77931,10 +79082,9 @@ ${lanes.join("\n")} return factory2.updateClassDeclaration(node, modifiers, node.name, /*typeParameters*/ void 0, heritageClauses, members); } } - function visitClassExpression(node, referencedName) { + function visitClassExpression(node) { if (isDecoratedClassLike(node)) { - const className = node.name ? factory2.createStringLiteralFromNode(node.name) : referencedName != null ? referencedName : factory2.createStringLiteral(""); - const iife = transformClassLike(node, className); + const iife = transformClassLike(node); setOriginalNode(iife, node); return iife; } else { @@ -77953,6 +79103,22 @@ ${lanes.join("\n")} return statements; } } + function transformConstructorBodyWorker(statementsOut, statementsIn, statementOffset, superPath, superPathDepth, initializerStatements) { + const superStatementIndex = superPath[superPathDepth]; + const superStatement = statementsIn[superStatementIndex]; + addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, statementOffset, superStatementIndex - statementOffset)); + if (isTryStatement(superStatement)) { + const tryBlockStatements = []; + transformConstructorBodyWorker(tryBlockStatements, superStatement.tryBlock.statements, /*statementOffset*/ 0, superPath, superPathDepth + 1, initializerStatements); + const tryBlockStatementsArray = factory2.createNodeArray(tryBlockStatements); + setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); + statementsOut.push(factory2.updateTryStatement(superStatement, factory2.updateBlock(superStatement.tryBlock, tryBlockStatements), visitNode(superStatement.catchClause, visitor, isCatchClause), visitNode(superStatement.finallyBlock, visitor, isBlock))); + } else { + addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, superStatementIndex, 1)); + addRange(statementsOut, initializerStatements); + } + addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, superStatementIndex + 1)); + } function visitConstructorDeclaration(node) { enterClassElement(node); const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); @@ -77963,12 +79129,9 @@ ${lanes.join("\n")} if (initializerStatements) { const statements = []; const nonPrologueStart = factory2.copyPrologue(node.body.statements, statements, /*ensureUseStrict*/ false, visitor); - const superStatementIndex = findSuperStatementIndex(node.body.statements, nonPrologueStart); - if (superStatementIndex >= 0) { - addRange(statements, visitNodes2(node.body.statements, visitor, isStatement, nonPrologueStart, superStatementIndex + 1 - nonPrologueStart)); - addRange(statements, initializerStatements); - addRange(statements, visitNodes2(node.body.statements, visitor, isStatement, superStatementIndex + 1)); - } else { + const superStatementIndices = findSuperStatementIndexPath(node.body.statements, nonPrologueStart); + if (superStatementIndices.length > 0) transformConstructorBodyWorker(statements, node.body.statements, nonPrologueStart, superStatementIndices, 0, initializerStatements); + else { addRange(statements, initializerStatements); addRange(statements, visitNodes2(node.body.statements, visitor, isStatement)); } @@ -77977,7 +79140,7 @@ ${lanes.join("\n")} setTextRange(body, node.body); } } - body != null ? body : body = visitNode(node.body, visitor, isBlock); + body ?? (body = visitNode(node.body, visitor, isBlock)); exitClassElement(); return factory2.updateConstructorDeclaration(node, modifiers, parameters, body); } @@ -77988,8 +79151,7 @@ ${lanes.join("\n")} } return updated; } - function partialTransformClassElement(member, useNamedEvaluation, classInfo2, createDescriptor) { - var _a2, _b, _c, _d, _e, _f, _g, _h; + function partialTransformClassElement(member, classInfo2, createDescriptor) { let referencedName; let name; let initializersName; @@ -77998,8 +79160,7 @@ ${lanes.join("\n")} if (!classInfo2) { const modifiers2 = visitNodes2(member.modifiers, modifierVisitor, isModifier); enterName(); - if (useNamedEvaluation) ({ referencedName: referencedName , name: name } = visitReferencedPropertyName(member.name)); - else name = visitPropertyName(member.name); + name = visitPropertyName(member.name); exitName(); return { modifiers: modifiers2, @@ -78019,11 +79180,11 @@ ${lanes.join("\n")} const memberInfo = { memberDecoratorsName: memberDecoratorsName }; - (_a2 = classInfo2.memberInfos) != null ? _a2 : classInfo2.memberInfos = /* @__PURE__ */ new Map(); + classInfo2.memberInfos ?? (classInfo2.memberInfos = /* @__PURE__ */ new Map()); classInfo2.memberInfos.set(member, memberInfo); - pendingExpressions != null ? pendingExpressions : pendingExpressions = []; + pendingExpressions ?? (pendingExpressions = []); pendingExpressions.push(memberDecoratorsAssignment); - const statements = isMethodOrAccessor(member) || isAutoAccessorPropertyDeclaration(member) ? isStatic(member) ? (_b = classInfo2.staticNonFieldDecorationStatements) != null ? _b : classInfo2.staticNonFieldDecorationStatements = [] : (_c = classInfo2.nonStaticNonFieldDecorationStatements) != null ? _c : classInfo2.nonStaticNonFieldDecorationStatements = [] : isPropertyDeclaration(member) && !isAutoAccessorPropertyDeclaration(member) ? isStatic(member) ? (_d = classInfo2.staticFieldDecorationStatements) != null ? _d : classInfo2.staticFieldDecorationStatements = [] : (_e = classInfo2.nonStaticFieldDecorationStatements) != null ? _e : classInfo2.nonStaticFieldDecorationStatements = [] : Debug.fail(); + const statements = isMethodOrAccessor(member) || isAutoAccessorPropertyDeclaration(member) ? isStatic(member) ? classInfo2.staticNonFieldDecorationStatements ?? (classInfo2.staticNonFieldDecorationStatements = []) : classInfo2.nonStaticNonFieldDecorationStatements ?? (classInfo2.nonStaticNonFieldDecorationStatements = []) : isPropertyDeclaration(member) && !isAutoAccessorPropertyDeclaration(member) ? isStatic(member) ? classInfo2.staticFieldDecorationStatements ?? (classInfo2.staticFieldDecorationStatements = []) : classInfo2.nonStaticFieldDecorationStatements ?? (classInfo2.nonStaticFieldDecorationStatements = []) : Debug.fail(); const kind = isGetAccessorDeclaration(member) ? "getter" : isSetAccessorDeclaration(member) ? "setter" : isMethodDeclaration(member) ? "method" : isAutoAccessorPropertyDeclaration(member) ? "accessor" : isPropertyDeclaration(member) ? "field" : Debug.fail(); let propertyName; if (isIdentifier(member.name) || isPrivateIdentifier(member.name)) propertyName = { @@ -78042,7 +79203,7 @@ ${lanes.join("\n")} }; else { enterName(); - ({ referencedName: referencedName , name: name } = visitReferencedPropertyName(member.name)); + ({ referencedName: referencedName, name: name } = visitReferencedPropertyName(member.name)); propertyName = { computed: true, name: referencedName @@ -78061,9 +79222,10 @@ ${lanes.join("\n")} get: isPropertyDeclaration(member) || isGetAccessorDeclaration(member) || isMethodDeclaration(member), // 3. If _kind_ is ~field~, ~accessor~, or ~setter~, then ... set: isPropertyDeclaration(member) || isSetAccessorDeclaration(member) - } + }, + metadata: classInfo2.metadataReference }; - const extraInitializers = isStatic(member) ? (_f = classInfo2.staticExtraInitializersName) != null ? _f : classInfo2.staticExtraInitializersName = factory2.createUniqueName("_staticExtraInitializers", 16 /* Optimistic */ ) : (_g = classInfo2.instanceExtraInitializersName) != null ? _g : classInfo2.instanceExtraInitializersName = factory2.createUniqueName("_instanceExtraInitializers", 16 /* Optimistic */ ); + const extraInitializers = isStatic(member) ? classInfo2.staticExtraInitializersName ?? (classInfo2.staticExtraInitializersName = factory2.createUniqueName("_staticExtraInitializers", 48 /* FileLevel */ )) : classInfo2.instanceExtraInitializersName ?? (classInfo2.instanceExtraInitializersName = factory2.createUniqueName("_instanceExtraInitializers", 48 /* FileLevel */ )); if (isMethodOrAccessor(member)) { let descriptor; if (isPrivateIdentifierClassElementDeclaration(member) && createDescriptor) { @@ -78071,12 +79233,12 @@ ${lanes.join("\n")} memberInfo.memberDescriptorName = descriptorName = createHelperVariable(member, "descriptor"); descriptor = factory2.createAssignment(descriptorName, descriptor); } - const esDecorateExpression = emitHelpers().createESDecorateHelper(factory2.createThis(), descriptor != null ? descriptor : factory2.createNull(), memberDecoratorsName, context2, factory2.createNull(), extraInitializers); + const esDecorateExpression = emitHelpers().createESDecorateHelper(factory2.createThis(), descriptor ?? factory2.createNull(), memberDecoratorsName, context2, factory2.createNull(), extraInitializers); const esDecorateStatement = factory2.createExpressionStatement(esDecorateExpression); setSourceMapRange(esDecorateStatement, moveRangePastDecorators(member)); statements.push(esDecorateStatement); } else if (isPropertyDeclaration(member)) { - initializersName = (_h = memberInfo.memberInitializersName) != null ? _h : memberInfo.memberInitializersName = createHelperVariable(member, "initializers"); + initializersName = memberInfo.memberInitializersName ?? (memberInfo.memberInitializersName = createHelperVariable(member, "initializers")); if (isStatic(member)) thisArg = classInfo2.classThis; let descriptor; if (isPrivateIdentifierClassElementDeclaration(member) && hasAccessorModifier(member) && createDescriptor) { @@ -78084,7 +79246,7 @@ ${lanes.join("\n")} memberInfo.memberDescriptorName = descriptorName = createHelperVariable(member, "descriptor"); descriptor = factory2.createAssignment(descriptorName, descriptor); } - const esDecorateExpression = emitHelpers().createESDecorateHelper(isAutoAccessorPropertyDeclaration(member) ? factory2.createThis() : factory2.createNull(), descriptor != null ? descriptor : factory2.createNull(), memberDecoratorsName, context2, initializersName, extraInitializers); + const esDecorateExpression = emitHelpers().createESDecorateHelper(isAutoAccessorPropertyDeclaration(member) ? factory2.createThis() : factory2.createNull(), descriptor ?? factory2.createNull(), memberDecoratorsName, context2, initializersName, extraInitializers); const esDecorateStatement = factory2.createExpressionStatement(esDecorateExpression); setSourceMapRange(esDecorateStatement, moveRangePastDecorators(member)); statements.push(esDecorateStatement); @@ -78092,8 +79254,7 @@ ${lanes.join("\n")} } if (name === void 0) { enterName(); - if (useNamedEvaluation) ({ referencedName: referencedName , name: name } = visitReferencedPropertyName(member.name)); - else name = visitPropertyName(member.name); + name = visitPropertyName(member.name); exitName(); } if (!some(modifiers) && (isMethodDeclaration(member) || isPropertyDeclaration(member))) setEmitFlags(name, 1024 /* NoLeadingComments */ ); @@ -78108,7 +79269,7 @@ ${lanes.join("\n")} } function visitMethodDeclaration(node) { enterClassElement(node); - const { modifiers: modifiers , name: name , descriptorName: descriptorName } = partialTransformClassElement(node, /*useNamedEvaluation*/ false, classInfo, createMethodDescriptorObject); + const { modifiers: modifiers, name: name, descriptorName: descriptorName } = partialTransformClassElement(node, classInfo, createMethodDescriptorObject); if (descriptorName) { exitClassElement(); return finishClassElement(createMethodDescriptorForwarder(modifiers, name, descriptorName), node); @@ -78121,7 +79282,7 @@ ${lanes.join("\n")} } function visitGetAccessorDeclaration(node) { enterClassElement(node); - const { modifiers: modifiers , name: name , descriptorName: descriptorName } = partialTransformClassElement(node, /*useNamedEvaluation*/ false, classInfo, createGetAccessorDescriptorObject); + const { modifiers: modifiers, name: name, descriptorName: descriptorName } = partialTransformClassElement(node, classInfo, createGetAccessorDescriptorObject); if (descriptorName) { exitClassElement(); return finishClassElement(createGetAccessorDescriptorForwarder(modifiers, name, descriptorName), node); @@ -78134,7 +79295,7 @@ ${lanes.join("\n")} } function visitSetAccessorDeclaration(node) { enterClassElement(node); - const { modifiers: modifiers , name: name , descriptorName: descriptorName } = partialTransformClassElement(node, /*useNamedEvaluation*/ false, classInfo, createSetAccessorDescriptorObject); + const { modifiers: modifiers, name: name, descriptorName: descriptorName } = partialTransformClassElement(node, classInfo, createSetAccessorDescriptorObject); if (descriptorName) { exitClassElement(); return finishClassElement(createSetAccessorDescriptorForwarder(modifiers, name, descriptorName), node); @@ -78147,22 +79308,31 @@ ${lanes.join("\n")} } function visitClassStaticBlockDeclaration(node) { enterClassElement(node); - if (classInfo) classInfo.hasStaticInitializers = true; - const result = visitEachChild(node, visitor, context); + let result; + if (isClassNamedEvaluationHelperBlock(node)) result = visitEachChild(node, visitor, context); + else if (isClassThisAssignmentBlock(node)) { + const savedClassThis = classThis; + classThis = void 0; + result = visitEachChild(node, visitor, context); + classThis = savedClassThis; + } else { + if (classInfo) classInfo.hasStaticInitializers = true; + result = visitEachChild(node, visitor, context); + } exitClassElement(); return result; } function visitPropertyDeclaration(node) { + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); enterClassElement(node); Debug.assert(!isAmbientPropertyDeclaration(node), "Not yet implemented."); - const useNamedEvaluation = isNamedEvaluation(node, isAnonymousClassNeedingAssignedName); - const { modifiers: modifiers , name: name , referencedName: referencedName , initializersName: initializersName , descriptorName: descriptorName , thisArg: thisArg } = partialTransformClassElement(node, useNamedEvaluation, classInfo, hasAccessorModifier(node) ? createAccessorPropertyDescriptorObject : void 0); + const { modifiers: modifiers, name: name, initializersName: initializersName, descriptorName: descriptorName, thisArg: thisArg } = partialTransformClassElement(node, classInfo, hasAccessorModifier(node) ? createAccessorPropertyDescriptorObject : void 0); startLexicalEnvironment(); - let initializer = referencedName ? visitNode(node.initializer, (node2)=>namedEvaluationVisitor(node2, referencedName), isExpression) : visitNode(node.initializer, visitor, isExpression); - if (initializersName) initializer = emitHelpers().createRunInitializersHelper(thisArg != null ? thisArg : factory2.createThis(), initializersName, initializer != null ? initializer : factory2.createVoidZero()); + let initializer = visitNode(node.initializer, visitor, isExpression); + if (initializersName) initializer = emitHelpers().createRunInitializersHelper(thisArg ?? factory2.createThis(), initializersName, initializer ?? factory2.createVoidZero()); if (!isStatic(node) && (classInfo == null ? void 0 : classInfo.instanceExtraInitializersName) && !(classInfo == null ? void 0 : classInfo.hasInjectedInstanceInitializers)) { classInfo.hasInjectedInstanceInitializers = true; - initializer != null ? initializer : initializer = factory2.createVoidZero(); + initializer ?? (initializer = factory2.createVoidZero()); initializer = factory2.createParenthesizedExpression(factory2.createComma(emitHelpers().createRunInitializersHelper(factory2.createThis(), classInfo.instanceExtraInitializersName), initializer)); } if (isStatic(node) && classInfo && initializer) classInfo.hasStaticInitializers = true; @@ -78193,7 +79363,7 @@ ${lanes.join("\n")} setterName = factory2.updateComputedPropertyName(name2, temp); } } - const modifiersWithoutAccessor = visitNodes2(modifiers, (node2)=>node2.kind !== 127 /* AccessorKeyword */ ? node2 : void 0, isModifier); + const modifiersWithoutAccessor = visitNodes2(modifiers, (node2)=>node2.kind !== 129 /* AccessorKeyword */ ? node2 : void 0, isModifier); const backingField = createAccessorPropertyBackingField(factory2, node, modifiersWithoutAccessor, initializer); setOriginalNode(backingField, node); setEmitFlags(backingField, 3072 /* NoComments */ ); @@ -78216,7 +79386,7 @@ ${lanes.join("\n")} return finishClassElement(factory2.updatePropertyDeclaration(node, modifiers, name, /*questionOrExclamationToken*/ void 0, /*type*/ void 0, initializer), node); } function visitThisExpression(node) { - return classThis != null ? classThis : node; + return classThis ?? node; } function visitCallExpression(node) { if (isSuperProperty(node.expression) && classThis) { @@ -78261,13 +79431,8 @@ ${lanes.join("\n")} return visitEachChild(node, visitor, context); } function visitParameterDeclaration(node) { - let updated; - if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer); - const name = visitNode(node.name, visitor, isBindingName); - const initializer = visitNode(node.initializer, (node2)=>namedEvaluationVisitor(node2, assignedName), isExpression); - updated = factory2.updateParameterDeclaration(node, /*modifiers*/ void 0, /*dotDotDotToken*/ void 0, name, /*questionToken*/ void 0, /*type*/ void 0, initializer); - } else updated = factory2.updateParameterDeclaration(node, /*modifiers*/ void 0, node.dotDotDotToken, visitNode(node.name, visitor, isBindingName), /*questionToken*/ void 0, /*type*/ void 0, visitNode(node.initializer, visitor, isExpression)); + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); + const updated = factory2.updateParameterDeclaration(node, /*modifiers*/ void 0, node.dotDotDotToken, visitNode(node.name, visitor, isBindingName), /*questionToken*/ void 0, /*type*/ void 0, visitNode(node.initializer, visitor, isExpression)); if (updated !== node) { setCommentRange(updated, node); setTextRange(updated, moveRangePastModifiers(node)); @@ -78279,6 +79444,10 @@ ${lanes.join("\n")} function isAnonymousClassNeedingAssignedName(node) { return isClassExpression(node) && !node.name && isDecoratedClassLike(node); } + function canIgnoreEmptyStringLiteralInAssignedName(node) { + const innerExpression = skipOuterExpressions(node); + return isClassExpression(innerExpression) && !innerExpression.name && !classOrConstructorParameterIsDecorated(/*useLegacyDecorators*/ false, innerExpression); + } function visitForStatement(node) { return factory2.updateForStatement(node, visitNode(node.initializer, discardedValueVisitor, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, discardedValueVisitor, isExpression), visitIterationBody(node.statement, visitor, context)); } @@ -78293,10 +79462,8 @@ ${lanes.join("\n")} } if (isAssignmentExpression(node)) { if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - const assignedName = getAssignedNameOfIdentifier(node.left, node.right); - const left = visitNode(node.left, visitor, isExpression); - const right = visitNode(node.right, (node2)=>namedEvaluationVisitor(node2, assignedName), isExpression); - return factory2.updateBinaryExpression(node, left, node.operatorToken, right); + node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.right)); + return visitEachChild(node, visitor, context); } if (isSuperProperty(node.left) && classThis && classSuper) { let setterName = isElementAccessExpression(node.left) ? visitNode(node.left.argumentExpression, visitor, isExpression) : isIdentifier(node.left.name) ? factory2.createStringLiteralFromNode(node.left.name) : void 0; @@ -78330,7 +79497,7 @@ ${lanes.join("\n")} } } } - if (node.operatorToken.kind === 27 /* CommaToken */ ) { + if (node.operatorToken.kind === 28 /* CommaToken */ ) { const left = visitNode(node.left, discardedValueVisitor, isExpression); const right = visitNode(node.right, discarded ? discardedValueVisitor : visitor, isExpression); return factory2.updateBinaryExpression(node, left, node.operatorToken, right); @@ -78338,7 +79505,7 @@ ${lanes.join("\n")} return visitEachChild(node, visitor, context); } function visitPreOrPostfixUnaryExpression(node, discarded) { - if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */ ) { + if (node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */ ) { const operand = skipParentheses(node.operand); if (isSuperProperty(operand) && classThis && classSuper) { let setterName = isElementAccessExpression(operand) ? visitNode(operand.argumentExpression, visitor, isExpression) : isIdentifier(operand.name) ? factory2.createStringLiteralFromNode(operand.name) : void 0; @@ -78407,30 +79574,15 @@ ${lanes.join("\n")} return factory2.updateComputedPropertyName(node, expression); } function visitPropertyAssignment(node) { - if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - const { referencedName: referencedName , name: name } = visitReferencedPropertyName(node.name); - const initializer = visitNode(node.initializer, (node2)=>namedEvaluationVisitor(node2, referencedName), isExpression); - return factory2.updatePropertyAssignment(node, name, initializer); - } + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); return visitEachChild(node, visitor, context); } function visitVariableDeclaration(node) { - if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer); - const name = visitNode(node.name, visitor, isBindingName); - const initializer = visitNode(node.initializer, (node2)=>namedEvaluationVisitor(node2, assignedName), isExpression); - return factory2.updateVariableDeclaration(node, name, /*exclamationToken*/ void 0, /*type*/ void 0, initializer); - } + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); return visitEachChild(node, visitor, context); } function visitBindingElement(node) { - if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer); - const propertyName = visitNode(node.propertyName, visitor, isPropertyName); - const name = visitNode(node.name, visitor, isBindingName); - const initializer = visitNode(node.initializer, (node2)=>namedEvaluationVisitor(node2, assignedName), isExpression); - return factory2.updateBindingElement(node, /*dotDotDotToken*/ void 0, propertyName, name, initializer); - } + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); return visitEachChild(node, visitor, context); } function visitDestructuringAssignmentTarget(node) { @@ -78449,12 +79601,9 @@ ${lanes.join("\n")} } function visitAssignmentElement(node) { if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.right)); const assignmentTarget = visitDestructuringAssignmentTarget(node.left); - let initializer; - if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - const assignedName = getAssignedNameOfIdentifier(node.left, node.right); - initializer = visitNode(node.right, (node2)=>namedEvaluationVisitor(node2, assignedName), isExpression); - } else initializer = visitNode(node.right, visitor, isExpression); + const initializer = visitNode(node.right, visitor, isExpression); return factory2.updateBinaryExpression(node, assignmentTarget, node.operatorToken, initializer); } else return visitDestructuringAssignmentTarget(node); } @@ -78484,12 +79633,7 @@ ${lanes.join("\n")} return visitEachChild(node, visitor, context); } function visitShorthandAssignmentProperty(node) { - if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - const assignedName = getAssignedNameOfIdentifier(node.name, node.objectAssignmentInitializer); - const name = visitNode(node.name, visitor, isIdentifier); - const objectAssignmentInitializer = visitNode(node.objectAssignmentInitializer, (node2)=>namedEvaluationVisitor(node2, assignedName), isExpression); - return factory2.updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer); - } + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.objectAssignmentInitializer)); return visitEachChild(node, visitor, context); } function visitAssignmentRestProperty(node) { @@ -78516,21 +79660,16 @@ ${lanes.join("\n")} } } function visitExportAssignment(node) { - if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - const referencedName = factory2.createStringLiteral(node.isExportEquals ? "" : "default"); - const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); - const expression = visitNode(node.expression, (node2)=>namedEvaluationVisitor(node2, referencedName), isExpression); - return factory2.updateExportAssignment(node, modifiers, expression); - } + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.expression)); return visitEachChild(node, visitor, context); } - function visitParenthesizedExpression(node, discarded, referencedName) { - const visitorFunc = discarded ? discardedValueVisitor : referencedName ? (node2)=>namedEvaluationVisitor(node2, referencedName) : visitor; + function visitParenthesizedExpression(node, discarded) { + const visitorFunc = discarded ? discardedValueVisitor : visitor; const expression = visitNode(node.expression, visitorFunc, isExpression); return factory2.updateParenthesizedExpression(node, expression); } - function visitPartiallyEmittedExpression(node, discarded, referencedName) { - const visitorFunc = discarded ? discardedValueVisitor : referencedName ? (node2)=>namedEvaluationVisitor(node2, referencedName) : visitor; + function visitPartiallyEmittedExpression(node, discarded) { + const visitorFunc = discarded ? discardedValueVisitor : visitor; const expression = visitNode(node.expression, visitorFunc, isExpression); return factory2.updatePartiallyEmittedExpression(node, expression); } @@ -78556,10 +79695,15 @@ ${lanes.join("\n")} function transformDecorator(decorator) { const expression = visitNode(decorator.expression, visitor, isExpression); setEmitFlags(expression, 3072 /* NoComments */ ); + const innerExpression = skipOuterExpressions(expression); + if (isAccessExpression(innerExpression)) { + const { target: target, thisArg: thisArg } = factory2.createCallBinding(expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true); + return factory2.restoreOuterExpressions(expression, factory2.createFunctionBindCall(target, thisArg, [])); + } return expression; } function createDescriptorMethod(original, name, modifiers, asteriskToken, kind, parameters, body) { - const func = factory2.createFunctionExpression(modifiers, asteriskToken, /*name*/ void 0, /*typeParameters*/ void 0, parameters, /*type*/ void 0, body != null ? body : factory2.createBlock([])); + const func = factory2.createFunctionExpression(modifiers, asteriskToken, /*name*/ void 0, /*typeParameters*/ void 0, parameters, /*type*/ void 0, body ?? factory2.createBlock([])); setOriginalNode(func, original); setSourceMapRange(func, moveRangePastDecorators(original)); setEmitFlags(func, 3072 /* NoComments */ ); @@ -78621,9 +79765,25 @@ ${lanes.join("\n")} ])) ])); } - function getAssignedNameOfIdentifier(name, initializer) { - const originalClass = getOriginalNode(initializer, isClassLike); - return originalClass && !originalClass.name && hasSyntacticModifier(originalClass, 1024 /* Default */ ) ? factory2.createStringLiteral("default") : factory2.createStringLiteralFromNode(name); + function createMetadata(name, classSuper2) { + const varDecl = factory2.createVariableDeclaration(name, /*exclamationToken*/ void 0, /*type*/ void 0, factory2.createConditionalExpression(factory2.createLogicalAnd(factory2.createTypeCheck(factory2.createIdentifier("Symbol"), "function"), factory2.createPropertyAccessExpression(factory2.createIdentifier("Symbol"), "metadata")), factory2.createToken(58 /* QuestionToken */ ), factory2.createCallExpression(factory2.createPropertyAccessExpression(factory2.createIdentifier("Object"), "create"), /*typeArguments*/ void 0, [ + classSuper2 ? createSymbolMetadataReference(classSuper2) : factory2.createNull() + ]), factory2.createToken(59 /* ColonToken */ ), factory2.createVoidZero())); + return factory2.createVariableStatement(/*modifiers*/ void 0, factory2.createVariableDeclarationList([ + varDecl + ], 2 /* Const */ )); + } + function createSymbolMetadata(target, value1) { + const defineProperty = factory2.createObjectDefinePropertyCall(target, factory2.createPropertyAccessExpression(factory2.createIdentifier("Symbol"), "metadata"), factory2.createPropertyDescriptor({ + configurable: true, + writable: true, + enumerable: true, + value: value1 + }, /*singleLine*/ true)); + return setEmitFlags(factory2.createIfStatement(value1, factory2.createExpressionStatement(defineProperty)), 1 /* SingleLine */ ); + } + function createSymbolMetadataReference(classSuper2) { + return factory2.createBinaryExpression(factory2.createElementAccessExpression(classSuper2, factory2.createPropertyAccessExpression(factory2.createIdentifier("Symbol"), "metadata")), 61 /* QuestionQuestionToken */ , factory2.createNull()); } } var init_esDecorators = __esm({ @@ -78634,7 +79794,7 @@ ${lanes.join("\n")} }); // src/compiler/transformers/es2017.ts function transformES2017(context) { - const { factory: factory2 , getEmitHelperFactory: emitHelpers , resumeLexicalEnvironment: resumeLexicalEnvironment , endLexicalEnvironment: endLexicalEnvironment , hoistVariableDeclaration: hoistVariableDeclaration } = context; + const { factory: factory2, getEmitHelperFactory: emitHelpers, resumeLexicalEnvironment: resumeLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, hoistVariableDeclaration: hoistVariableDeclaration } = context; const resolver = context.getEmitResolver(); const compilerOptions = context.getCompilerOptions(); const languageVersion = getEmitScriptTarget(compilerOptions); @@ -78686,32 +79846,32 @@ ${lanes.join("\n")} function visitor(node) { if ((node.transformFlags & 256 /* ContainsES2017 */ ) === 0) return node; switch(node.kind){ - case 132 /* AsyncKeyword */ : + case 134 /* AsyncKeyword */ : return void 0; - case 220 /* AwaitExpression */ : + case 223 /* AwaitExpression */ : return visitAwaitExpression(node); - case 171 /* MethodDeclaration */ : + case 174 /* MethodDeclaration */ : return doWithContext(3 /* HasLexicalThis */ , visitMethodDeclaration, node); - case 259 /* FunctionDeclaration */ : + case 262 /* FunctionDeclaration */ : return doWithContext(3 /* HasLexicalThis */ , visitFunctionDeclaration, node); - case 215 /* FunctionExpression */ : + case 218 /* FunctionExpression */ : return doWithContext(3 /* HasLexicalThis */ , visitFunctionExpression, node); - case 216 /* ArrowFunction */ : + case 219 /* ArrowFunction */ : return doWithContext(1 /* NonTopLevel */ , visitArrowFunction, node); - case 208 /* PropertyAccessExpression */ : - if (capturedSuperProperties && isPropertyAccessExpression(node) && node.expression.kind === 106 /* SuperKeyword */ ) capturedSuperProperties.add(node.name.escapedText); + case 211 /* PropertyAccessExpression */ : + if (capturedSuperProperties && isPropertyAccessExpression(node) && node.expression.kind === 108 /* SuperKeyword */ ) capturedSuperProperties.add(node.name.escapedText); return visitEachChild(node, visitor, context); - case 209 /* ElementAccessExpression */ : - if (capturedSuperProperties && node.expression.kind === 106 /* SuperKeyword */ ) hasSuperElementAccess = true; + case 212 /* ElementAccessExpression */ : + if (capturedSuperProperties && node.expression.kind === 108 /* SuperKeyword */ ) hasSuperElementAccess = true; return visitEachChild(node, visitor, context); - case 174 /* GetAccessor */ : + case 177 /* GetAccessor */ : return doWithContext(3 /* HasLexicalThis */ , visitGetAccessorDeclaration, node); - case 175 /* SetAccessor */ : + case 178 /* SetAccessor */ : return doWithContext(3 /* HasLexicalThis */ , visitSetAccessorDeclaration, node); - case 173 /* Constructor */ : + case 176 /* Constructor */ : return doWithContext(3 /* HasLexicalThis */ , visitConstructorDeclaration, node); - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : return doWithContext(3 /* HasLexicalThis */ , visitDefault, node); default: return visitEachChild(node, visitor, context); @@ -78719,27 +79879,27 @@ ${lanes.join("\n")} } function asyncBodyVisitor(node) { if (isNodeWithPossibleHoistedDeclaration(node)) switch(node.kind){ - case 240 /* VariableStatement */ : + case 243 /* VariableStatement */ : return visitVariableStatementInAsyncBody(node); - case 245 /* ForStatement */ : + case 248 /* ForStatement */ : return visitForStatementInAsyncBody(node); - case 246 /* ForInStatement */ : + case 249 /* ForInStatement */ : return visitForInStatementInAsyncBody(node); - case 247 /* ForOfStatement */ : + case 250 /* ForOfStatement */ : return visitForOfStatementInAsyncBody(node); - case 295 /* CatchClause */ : + case 299 /* CatchClause */ : return visitCatchClauseInAsyncBody(node); - case 238 /* Block */ : - case 252 /* SwitchStatement */ : - case 266 /* CaseBlock */ : - case 292 /* CaseClause */ : - case 293 /* DefaultClause */ : - case 255 /* TryStatement */ : - case 243 /* DoStatement */ : - case 244 /* WhileStatement */ : - case 242 /* IfStatement */ : - case 251 /* WithStatement */ : - case 253 /* LabeledStatement */ : + case 241 /* Block */ : + case 255 /* SwitchStatement */ : + case 269 /* CaseBlock */ : + case 296 /* CaseClause */ : + case 297 /* DefaultClause */ : + case 258 /* TryStatement */ : + case 246 /* DoStatement */ : + case 247 /* WhileStatement */ : + case 245 /* IfStatement */ : + case 254 /* WithStatement */ : + case 256 /* LabeledStatement */ : return visitEachChild(node, asyncBodyVisitor, context); default: return Debug.assertNever(node, "Unhandled node."); @@ -78806,14 +79966,14 @@ ${lanes.join("\n")} function visitArrowFunction(node) { return factory2.updateArrowFunction(node, visitNodes2(node.modifiers, visitor, isModifier), /*typeParameters*/ void 0, visitParameterList(node.parameters, visitor, context), /*type*/ void 0, node.equalsGreaterThanToken, getFunctionFlags(node) & 2 /* Async */ ? transformAsyncFunctionBody(node) : visitFunctionBody(node.body, visitor, context)); } - function recordDeclarationName({ name: name }, names) { + function recordDeclarationName({ name: name }, names) { if (isIdentifier(name)) names.add(name.escapedText); else { for (const element of name.elements)if (!isOmittedExpression(element)) recordDeclarationName(element, names); } } function isVariableDeclarationListWithCollidingName(node) { - return !!node && isVariableDeclarationList(node) && !(node.flags & 3 /* BlockScoped */ ) && node.declarations.some(collidesWithParameterName); + return !!node && isVariableDeclarationList(node) && !(node.flags & 7 /* BlockScoped */ ) && node.declarations.some(collidesWithParameterName); } function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { hoistVariableDeclarationList(node); @@ -78827,7 +79987,7 @@ ${lanes.join("\n")} function hoistVariableDeclarationList(node) { forEach(node.declarations, hoistVariable); } - function hoistVariable({ name: name }) { + function hoistVariable({ name: name }) { if (isIdentifier(name)) hoistVariableDeclaration(name); else { for (const element of name.elements)if (!isOmittedExpression(element)) hoistVariable(element); @@ -78837,7 +79997,7 @@ ${lanes.join("\n")} const converted = setSourceMapRange(factory2.createAssignment(factory2.converters.convertToAssignmentElementTarget(node.name), node.initializer), node); return Debug.checkDefined(visitNode(converted, visitor, isExpression)); } - function collidesWithParameterName({ name: name }) { + function collidesWithParameterName({ name: name }) { if (isIdentifier(name)) return enclosingFunctionParameterNames.has(name.escapedText); else for (const element of name.elements){ if (!isOmittedExpression(element) && collidesWithParameterName(element)) return true; @@ -78878,7 +80038,7 @@ ${lanes.join("\n")} const original = getOriginalNode(node, isFunctionLike); const nodeType = original.type; const promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : void 0; - const isArrowFunction2 = node.kind === 216 /* ArrowFunction */ ; + const isArrowFunction2 = node.kind === 219 /* ArrowFunction */ ; const hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 512 /* CaptureArguments */ ) !== 0; const savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; enclosingFunctionParameterNames = /* @__PURE__ */ new Set(); @@ -78943,15 +80103,15 @@ ${lanes.join("\n")} function enableSubstitutionForAsyncMethodsWithSuper() { if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ ) === 0) { enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */ ; - context.enableSubstitution(210 /* CallExpression */ ); - context.enableSubstitution(208 /* PropertyAccessExpression */ ); - context.enableSubstitution(209 /* ElementAccessExpression */ ); - context.enableEmitNotification(260 /* ClassDeclaration */ ); - context.enableEmitNotification(171 /* MethodDeclaration */ ); - context.enableEmitNotification(174 /* GetAccessor */ ); - context.enableEmitNotification(175 /* SetAccessor */ ); - context.enableEmitNotification(173 /* Constructor */ ); - context.enableEmitNotification(240 /* VariableStatement */ ); + context.enableSubstitution(213 /* CallExpression */ ); + context.enableSubstitution(211 /* PropertyAccessExpression */ ); + context.enableSubstitution(212 /* ElementAccessExpression */ ); + context.enableEmitNotification(263 /* ClassDeclaration */ ); + context.enableEmitNotification(174 /* MethodDeclaration */ ); + context.enableEmitNotification(177 /* GetAccessor */ ); + context.enableEmitNotification(178 /* SetAccessor */ ); + context.enableEmitNotification(176 /* Constructor */ ); + context.enableEmitNotification(243 /* VariableStatement */ ); } } function onEmitNode(hint, node, emitCallback) { @@ -78980,21 +80140,21 @@ ${lanes.join("\n")} } function substituteExpression(node) { switch(node.kind){ - case 208 /* PropertyAccessExpression */ : + case 211 /* PropertyAccessExpression */ : return substitutePropertyAccessExpression(node); - case 209 /* ElementAccessExpression */ : + case 212 /* ElementAccessExpression */ : return substituteElementAccessExpression(node); - case 210 /* CallExpression */ : + case 213 /* CallExpression */ : return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 106 /* SuperKeyword */ ) return setTextRange(factory2.createPropertyAccessExpression(factory2.createUniqueName("_super", 48 /* FileLevel */ ), node.name), node); + if (node.expression.kind === 108 /* SuperKeyword */ ) return setTextRange(factory2.createPropertyAccessExpression(factory2.createUniqueName("_super", 48 /* FileLevel */ ), node.name), node); return node; } function substituteElementAccessExpression(node) { - if (node.expression.kind === 106 /* SuperKeyword */ ) return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); + if (node.expression.kind === 108 /* SuperKeyword */ ) return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); return node; } function substituteCallExpression(node) { @@ -79010,7 +80170,7 @@ ${lanes.join("\n")} } function isSuperContainer(node) { const kind = node.kind; - return kind === 260 /* ClassDeclaration */ || kind === 173 /* Constructor */ || kind === 171 /* MethodDeclaration */ || kind === 174 /* GetAccessor */ || kind === 175 /* SetAccessor */ ; + return kind === 263 /* ClassDeclaration */ || kind === 176 /* Constructor */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ ; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 256 /* MethodWithSuperPropertyAssignmentInAsync */ ) return setTextRange(factory2.createPropertyAccessExpression(factory2.createCallExpression(factory2.createUniqueName("_superIndex", 48 /* FileLevel */ ), /*typeArguments*/ void 0, [ @@ -79027,16 +80187,16 @@ ${lanes.join("\n")} names.forEach((_, key)=>{ const name = unescapeLeadingUnderscores(key); const getterAndSetter = []; - getterAndSetter.push(factory2.createPropertyAssignment("get", factory2.createArrowFunction(/* modifiers */ void 0, /* typeParameters */ void 0, /* parameters */ [], /* type */ void 0, /* equalsGreaterThanToken */ void 0, setEmitFlags(factory2.createPropertyAccessExpression(setEmitFlags(factory2.createSuper(), 8 /* NoSubstitution */ ), name), 8 /* NoSubstitution */ )))); - if (hasBinding) getterAndSetter.push(factory2.createPropertyAssignment("set", factory2.createArrowFunction(/* modifiers */ void 0, /* typeParameters */ void 0, /* parameters */ [ - factory2.createParameterDeclaration(/* modifiers */ void 0, /* dotDotDotToken */ void 0, "v", /* questionToken */ void 0, /* type */ void 0, /* initializer */ void 0) - ], /* type */ void 0, /* equalsGreaterThanToken */ void 0, factory2.createAssignment(setEmitFlags(factory2.createPropertyAccessExpression(setEmitFlags(factory2.createSuper(), 8 /* NoSubstitution */ ), name), 8 /* NoSubstitution */ ), factory2.createIdentifier("v"))))); + getterAndSetter.push(factory2.createPropertyAssignment("get", factory2.createArrowFunction(/*modifiers*/ void 0, /*typeParameters*/ void 0, /* parameters */ [], /*type*/ void 0, /*equalsGreaterThanToken*/ void 0, setEmitFlags(factory2.createPropertyAccessExpression(setEmitFlags(factory2.createSuper(), 8 /* NoSubstitution */ ), name), 8 /* NoSubstitution */ )))); + if (hasBinding) getterAndSetter.push(factory2.createPropertyAssignment("set", factory2.createArrowFunction(/*modifiers*/ void 0, /*typeParameters*/ void 0, /* parameters */ [ + factory2.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, "v", /*questionToken*/ void 0, /*type*/ void 0, /*initializer*/ void 0) + ], /*type*/ void 0, /*equalsGreaterThanToken*/ void 0, factory2.createAssignment(setEmitFlags(factory2.createPropertyAccessExpression(setEmitFlags(factory2.createSuper(), 8 /* NoSubstitution */ ), name), 8 /* NoSubstitution */ ), factory2.createIdentifier("v"))))); accessors.push(factory2.createPropertyAssignment(name, factory2.createObjectLiteralExpression(getterAndSetter))); }); - return factory2.createVariableStatement(/* modifiers */ void 0, factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration(factory2.createUniqueName("_super", 48 /* FileLevel */ ), /*exclamationToken*/ void 0, /* type */ void 0, factory2.createCallExpression(factory2.createPropertyAccessExpression(factory2.createIdentifier("Object"), "create"), /* typeArguments */ void 0, [ + return factory2.createVariableStatement(/*modifiers*/ void 0, factory2.createVariableDeclarationList([ + factory2.createVariableDeclaration(factory2.createUniqueName("_super", 48 /* FileLevel */ ), /*exclamationToken*/ void 0, /*type*/ void 0, factory2.createCallExpression(factory2.createPropertyAccessExpression(factory2.createIdentifier("Object"), "create"), /*typeArguments*/ void 0, [ factory2.createNull(), - factory2.createObjectLiteralExpression(accessors, /* multiline */ true) + factory2.createObjectLiteralExpression(accessors, /*multiLine*/ true) ])) ], 2 /* Const */ )); } @@ -79048,7 +80208,7 @@ ${lanes.join("\n")} }); // src/compiler/transformers/es2018.ts function transformES2018(context) { - const { factory: factory2 , getEmitHelperFactory: emitHelpers , resumeLexicalEnvironment: resumeLexicalEnvironment , endLexicalEnvironment: endLexicalEnvironment , hoistVariableDeclaration: hoistVariableDeclaration } = context; + const { factory: factory2, getEmitHelperFactory: emitHelpers, resumeLexicalEnvironment: resumeLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, hoistVariableDeclaration: hoistVariableDeclaration } = context; const resolver = context.getEmitResolver(); const compilerOptions = context.getCompilerOptions(); const languageVersion = getEmitScriptTarget(compilerOptions); @@ -79098,7 +80258,7 @@ ${lanes.join("\n")} return visitorWorker(node, /*expressionResultIsUnused*/ true); } function visitorNoAsyncModifier(node) { - if (node.kind === 132 /* AsyncKeyword */ ) return void 0; + if (node.kind === 134 /* AsyncKeyword */ ) return void 0; return node; } function doWithHierarchyFacts(cb, value1, excludeFacts, includeFacts) { @@ -79116,66 +80276,66 @@ ${lanes.join("\n")} function visitorWorker(node, expressionResultIsUnused2) { if ((node.transformFlags & 128 /* ContainsES2018 */ ) === 0) return node; switch(node.kind){ - case 220 /* AwaitExpression */ : + case 223 /* AwaitExpression */ : return visitAwaitExpression(node); - case 226 /* YieldExpression */ : + case 229 /* YieldExpression */ : return visitYieldExpression(node); - case 250 /* ReturnStatement */ : + case 253 /* ReturnStatement */ : return visitReturnStatement(node); - case 253 /* LabeledStatement */ : + case 256 /* LabeledStatement */ : return visitLabeledStatement(node); - case 207 /* ObjectLiteralExpression */ : + case 210 /* ObjectLiteralExpression */ : return visitObjectLiteralExpression(node); - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : return visitBinaryExpression(node, expressionResultIsUnused2); - case 357 /* CommaListExpression */ : + case 361 /* CommaListExpression */ : return visitCommaListExpression(node, expressionResultIsUnused2); - case 295 /* CatchClause */ : + case 299 /* CatchClause */ : return visitCatchClause(node); - case 240 /* VariableStatement */ : + case 243 /* VariableStatement */ : return visitVariableStatement(node); - case 257 /* VariableDeclaration */ : + case 260 /* VariableDeclaration */ : return visitVariableDeclaration(node); - case 243 /* DoStatement */ : - case 244 /* WhileStatement */ : - case 246 /* ForInStatement */ : + case 246 /* DoStatement */ : + case 247 /* WhileStatement */ : + case 249 /* ForInStatement */ : return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */ , 2 /* IterationStatementIncludes */ ); - case 247 /* ForOfStatement */ : + case 250 /* ForOfStatement */ : return visitForOfStatement(node, /*outermostLabeledStatement*/ void 0); - case 245 /* ForStatement */ : + case 248 /* ForStatement */ : return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */ , 2 /* IterationStatementIncludes */ ); - case 219 /* VoidExpression */ : + case 222 /* VoidExpression */ : return visitVoidExpression(node); - case 173 /* Constructor */ : + case 176 /* Constructor */ : return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */ , 1 /* ClassOrFunctionIncludes */ ); - case 171 /* MethodDeclaration */ : + case 174 /* MethodDeclaration */ : return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */ , 1 /* ClassOrFunctionIncludes */ ); - case 174 /* GetAccessor */ : + case 177 /* GetAccessor */ : return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */ , 1 /* ClassOrFunctionIncludes */ ); - case 175 /* SetAccessor */ : + case 178 /* SetAccessor */ : return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */ , 1 /* ClassOrFunctionIncludes */ ); - case 259 /* FunctionDeclaration */ : + case 262 /* FunctionDeclaration */ : return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */ , 1 /* ClassOrFunctionIncludes */ ); - case 215 /* FunctionExpression */ : + case 218 /* FunctionExpression */ : return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */ , 1 /* ClassOrFunctionIncludes */ ); - case 216 /* ArrowFunction */ : + case 219 /* ArrowFunction */ : return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */ , 0 /* ArrowFunctionIncludes */ ); - case 166 /* Parameter */ : + case 169 /* Parameter */ : return visitParameter(node); - case 241 /* ExpressionStatement */ : + case 244 /* ExpressionStatement */ : return visitExpressionStatement(node); - case 214 /* ParenthesizedExpression */ : + case 217 /* ParenthesizedExpression */ : return visitParenthesizedExpression(node, expressionResultIsUnused2); - case 212 /* TaggedTemplateExpression */ : + case 215 /* TaggedTemplateExpression */ : return visitTaggedTemplateExpression(node); - case 208 /* PropertyAccessExpression */ : - if (capturedSuperProperties && isPropertyAccessExpression(node) && node.expression.kind === 106 /* SuperKeyword */ ) capturedSuperProperties.add(node.name.escapedText); + case 211 /* PropertyAccessExpression */ : + if (capturedSuperProperties && isPropertyAccessExpression(node) && node.expression.kind === 108 /* SuperKeyword */ ) capturedSuperProperties.add(node.name.escapedText); return visitEachChild(node, visitor, context); - case 209 /* ElementAccessExpression */ : - if (capturedSuperProperties && node.expression.kind === 106 /* SuperKeyword */ ) hasSuperElementAccess = true; + case 212 /* ElementAccessExpression */ : + if (capturedSuperProperties && node.expression.kind === 108 /* SuperKeyword */ ) hasSuperElementAccess = true; return visitEachChild(node, visitor, context); - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */ , 1 /* ClassOrFunctionIncludes */ ); default: return visitEachChild(node, visitor, context); @@ -79202,7 +80362,7 @@ ${lanes.join("\n")} function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2 /* Async */ ) { const statement = unwrapInnermostStatementOfLabel(node); - if (statement.kind === 247 /* ForOfStatement */ && statement.awaitModifier) return visitForOfStatement(statement, node); + if (statement.kind === 250 /* ForOfStatement */ && statement.awaitModifier) return visitForOfStatement(statement, node); return factory2.restoreEnclosingLabel(visitNode(statement, visitor, isStatement, factory2.liftToBlock), node); } return visitEachChild(node, visitor, context); @@ -79210,21 +80370,21 @@ ${lanes.join("\n")} function chunkObjectLiteralElements(elements) { let chunkObject; const objects = []; - for (const e of elements)if (e.kind === 301 /* SpreadAssignment */ ) { + for (const e of elements)if (e.kind === 305 /* SpreadAssignment */ ) { if (chunkObject) { objects.push(factory2.createObjectLiteralExpression(chunkObject)); chunkObject = void 0; } const target = e.expression; objects.push(visitNode(target, visitor, isExpression)); - } else chunkObject = append(chunkObject, e.kind === 299 /* PropertyAssignment */ ? factory2.createPropertyAssignment(e.name, visitNode(e.initializer, visitor, isExpression)) : visitNode(e, visitor, isObjectLiteralElementLike)); + } else chunkObject = append(chunkObject, e.kind === 303 /* PropertyAssignment */ ? factory2.createPropertyAssignment(e.name, visitNode(e.initializer, visitor, isExpression)) : visitNode(e, visitor, isObjectLiteralElementLike)); if (chunkObject) objects.push(factory2.createObjectLiteralExpression(chunkObject)); return objects; } function visitObjectLiteralExpression(node) { if (node.transformFlags & 65536 /* ContainsObjectRestOrSpread */ ) { const objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== 207 /* ObjectLiteralExpression */ ) objects.unshift(factory2.createObjectLiteralExpression()); + if (objects.length && objects[0].kind !== 210 /* ObjectLiteralExpression */ ) objects.unshift(factory2.createObjectLiteralExpression()); let expression = objects[0]; if (objects.length > 1) { for(let i = 1; i < objects.length; i++)expression = emitHelpers().createAssignHelper([ @@ -79258,7 +80418,7 @@ ${lanes.join("\n")} } function visitBinaryExpression(node, expressionResultIsUnused2) { if (isDestructuringAssignment(node) && containsObjectRestOrSpread(node.left)) return flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */ , !expressionResultIsUnused2); - if (node.operatorToken.kind === 27 /* CommaToken */ ) return factory2.updateBinaryExpression(node, visitNode(node.left, visitorWithUnusedExpressionResult, isExpression), node.operatorToken, visitNode(node.right, expressionResultIsUnused2 ? visitorWithUnusedExpressionResult : visitor, isExpression)); + if (node.operatorToken.kind === 28 /* CommaToken */ ) return factory2.updateBinaryExpression(node, visitNode(node.left, visitorWithUnusedExpressionResult, isExpression), node.operatorToken, visitNode(node.right, expressionResultIsUnused2 ? visitorWithUnusedExpressionResult : visitor, isExpression)); return visitEachChild(node, visitor, context); } function visitCommaListExpression(node, expressionResultIsUnused2) { @@ -79358,10 +80518,10 @@ ${lanes.join("\n")} const exitNonUserCodeExpression = factory2.createAssignment(nonUserCode, factory2.createFalse()); const exitNonUserCodeStatement = factory2.createExpressionStatement(exitNonUserCodeExpression); setSourceMapRange(exitNonUserCodeStatement, node.expression); - const enterNonUserCodeExpression = factory2.createAssignment(nonUserCode, factory2.createTrue()); - const enterNonUserCodeStatement = factory2.createExpressionStatement(enterNonUserCodeExpression); - setSourceMapRange(exitNonUserCodeStatement, node.expression); - const statements = []; + const statements = [ + iteratorValueStatement, + exitNonUserCodeStatement + ]; const binding = createForOfBindingStatement(factory2, node.initializer, value1); statements.push(visitNode(binding, visitor, isStatement)); let bodyLocation; @@ -79372,14 +80532,7 @@ ${lanes.join("\n")} bodyLocation = statement; statementsLocation = statement.statements; } else statements.push(statement); - const body = setEmitFlags(setTextRange(factory2.createBlock(setTextRange(factory2.createNodeArray(statements), statementsLocation), /*multiLine*/ true), bodyLocation), 864 /* NoTokenSourceMaps */ ); - return factory2.createBlock([ - iteratorValueStatement, - exitNonUserCodeStatement, - factory2.createTryStatement(body, /*catchClause*/ void 0, factory2.createBlock([ - enterNonUserCodeStatement - ])) - ]); + return setTextRange(factory2.createBlock(setTextRange(factory2.createNodeArray(statements), statementsLocation), /*multiLine*/ true), bodyLocation); } function createDownlevelAwait(expression) { return enclosingFunctionFlags & 1 /* Generator */ ? factory2.createYieldExpression(/*asteriskToken*/ void 0, emitHelpers().createAwaitHelper(expression)) : factory2.createAwaitExpression(expression); @@ -79412,7 +80565,7 @@ ${lanes.join("\n")} factory2.createAssignment(result, createDownlevelAwait(callNext)), factory2.createAssignment(done, getDone), factory2.createLogicalNot(done) - ]), /*incrementor*/ void 0, /*statement*/ convertForOfStatementHead(node, getValue, nonUserCode)), /*location*/ node), 512 /* NoTokenTrailingSourceMaps */ ); + ]), /*incrementor*/ factory2.createAssignment(nonUserCode, factory2.createTrue()), /*statement*/ convertForOfStatementHead(node, getValue, nonUserCode)), /*location*/ node), 512 /* NoTokenTrailingSourceMaps */ ); setOriginalNode(forStatement, node); return factory2.createTryStatement(factory2.createBlock([ factory2.restoreEnclosingLabel(forStatement, outermostLabeledStatement) @@ -79480,7 +80633,7 @@ ${lanes.join("\n")} const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - const updated = factory2.updateMethodDeclaration(node, enclosingFunctionFlags & 1 /* Generator */ ? visitNodes2(node.modifiers, visitorNoAsyncModifier, isModifierLike) : node.modifiers, enclosingFunctionFlags & 2 /* Async */ ? void 0 : node.asteriskToken, visitNode(node.name, visitor, isPropertyName), visitNode(/*questionToken*/ void 0, visitor, isQuestionToken), /*typeParameters*/ void 0, visitParameterList(node.parameters, parameterVisitor, context), /*type*/ void 0, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody2(node)); + const updated = factory2.updateMethodDeclaration(node, enclosingFunctionFlags & 1 /* Generator */ ? visitNodes2(node.modifiers, visitorNoAsyncModifier, isModifierLike) : node.modifiers, enclosingFunctionFlags & 2 /* Async */ ? void 0 : node.asteriskToken, visitNode(node.name, visitor, isPropertyName), visitNode(/*node*/ void 0, visitor, isQuestionToken), /*typeParameters*/ void 0, visitParameterList(node.parameters, parameterVisitor, context), /*type*/ void 0, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody2(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -79524,7 +80677,7 @@ ${lanes.join("\n")} const savedHasSuperElementAccess = hasSuperElementAccess; capturedSuperProperties = /* @__PURE__ */ new Set(); hasSuperElementAccess = false; - const returnStatement = factory2.createReturnStatement(emitHelpers().createAsyncGeneratorHelper(factory2.createFunctionExpression(/*modifiers*/ void 0, factory2.createToken(41 /* AsteriskToken */ ), node.name && factory2.getGeneratedNameForNode(node.name), /*typeParameters*/ void 0, /*parameters*/ [], /*type*/ void 0, factory2.updateBlock(node.body, visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HasLexicalThis */ ))); + const returnStatement = factory2.createReturnStatement(emitHelpers().createAsyncGeneratorHelper(factory2.createFunctionExpression(/*modifiers*/ void 0, factory2.createToken(42 /* AsteriskToken */ ), node.name && factory2.getGeneratedNameForNode(node.name), /*typeParameters*/ void 0, /*parameters*/ [], /*type*/ void 0, factory2.updateBlock(node.body, visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HasLexicalThis */ ))); const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & 384 /* MethodWithSuperPropertyAccessInAsync */ ; if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); @@ -79546,11 +80699,10 @@ ${lanes.join("\n")} return block; } function transformFunctionBody2(node) { - var _a2; resumeLexicalEnvironment(); let statementOffset = 0; const statements = []; - const body = (_a2 = visitNode(node.body, visitor, isConciseBody)) != null ? _a2 : factory2.createBlock([]); + const body = visitNode(node.body, visitor, isConciseBody) ?? factory2.createBlock([]); if (isBlock(body)) statementOffset = factory2.copyPrologue(body.statements, statements, /*ensureUseStrict*/ false, visitor); addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ void 0, node)); const leadingStatements = endLexicalEnvironment(); @@ -79606,7 +80758,7 @@ ${lanes.join("\n")} } } else if (parameter.transformFlags & 65536 /* ContainsObjectRestOrSpread */ ) { containsPrecedingObjectRestOrSpread = true; - const declarations = flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */ , factory2.getGeneratedNameForNode(parameter), /*doNotRecordTempVariablesInLine*/ false, /*skipInitializer*/ true); + const declarations = flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */ , factory2.getGeneratedNameForNode(parameter), /*hoistTempVariables*/ false, /*skipInitializer*/ true); if (some(declarations)) { const declarationList = factory2.createVariableDeclarationList(declarations); const statement = factory2.createVariableStatement(/*modifiers*/ void 0, declarationList); @@ -79620,15 +80772,15 @@ ${lanes.join("\n")} function enableSubstitutionForAsyncMethodsWithSuper() { if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ ) === 0) { enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */ ; - context.enableSubstitution(210 /* CallExpression */ ); - context.enableSubstitution(208 /* PropertyAccessExpression */ ); - context.enableSubstitution(209 /* ElementAccessExpression */ ); - context.enableEmitNotification(260 /* ClassDeclaration */ ); - context.enableEmitNotification(171 /* MethodDeclaration */ ); - context.enableEmitNotification(174 /* GetAccessor */ ); - context.enableEmitNotification(175 /* SetAccessor */ ); - context.enableEmitNotification(173 /* Constructor */ ); - context.enableEmitNotification(240 /* VariableStatement */ ); + context.enableSubstitution(213 /* CallExpression */ ); + context.enableSubstitution(211 /* PropertyAccessExpression */ ); + context.enableSubstitution(212 /* ElementAccessExpression */ ); + context.enableEmitNotification(263 /* ClassDeclaration */ ); + context.enableEmitNotification(174 /* MethodDeclaration */ ); + context.enableEmitNotification(177 /* GetAccessor */ ); + context.enableEmitNotification(178 /* SetAccessor */ ); + context.enableEmitNotification(176 /* Constructor */ ); + context.enableEmitNotification(243 /* VariableStatement */ ); } } function onEmitNode(hint, node, emitCallback) { @@ -79657,21 +80809,21 @@ ${lanes.join("\n")} } function substituteExpression(node) { switch(node.kind){ - case 208 /* PropertyAccessExpression */ : + case 211 /* PropertyAccessExpression */ : return substitutePropertyAccessExpression(node); - case 209 /* ElementAccessExpression */ : + case 212 /* ElementAccessExpression */ : return substituteElementAccessExpression(node); - case 210 /* CallExpression */ : + case 213 /* CallExpression */ : return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 106 /* SuperKeyword */ ) return setTextRange(factory2.createPropertyAccessExpression(factory2.createUniqueName("_super", 48 /* FileLevel */ ), node.name), node); + if (node.expression.kind === 108 /* SuperKeyword */ ) return setTextRange(factory2.createPropertyAccessExpression(factory2.createUniqueName("_super", 48 /* FileLevel */ ), node.name), node); return node; } function substituteElementAccessExpression(node) { - if (node.expression.kind === 106 /* SuperKeyword */ ) return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); + if (node.expression.kind === 108 /* SuperKeyword */ ) return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); return node; } function substituteCallExpression(node) { @@ -79687,7 +80839,7 @@ ${lanes.join("\n")} } function isSuperContainer(node) { const kind = node.kind; - return kind === 260 /* ClassDeclaration */ || kind === 173 /* Constructor */ || kind === 171 /* MethodDeclaration */ || kind === 174 /* GetAccessor */ || kind === 175 /* SetAccessor */ ; + return kind === 263 /* ClassDeclaration */ || kind === 176 /* Constructor */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ ; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 256 /* MethodWithSuperPropertyAssignmentInAsync */ ) return setTextRange(factory2.createPropertyAccessExpression(factory2.createCallExpression(factory2.createIdentifier("_superIndex"), /*typeArguments*/ void 0, [ @@ -79715,7 +80867,7 @@ ${lanes.join("\n")} function visitor(node) { if ((node.transformFlags & 64 /* ContainsES2019 */ ) === 0) return node; switch(node.kind){ - case 295 /* CatchClause */ : + case 299 /* CatchClause */ : return visitCatchClause(node); default: return visitEachChild(node, visitor, context); @@ -79734,7 +80886,7 @@ ${lanes.join("\n")} }); // src/compiler/transformers/es2020.ts function transformES2020(context) { - const { factory: factory2 , hoistVariableDeclaration: hoistVariableDeclaration } = context; + const { factory: factory2, hoistVariableDeclaration: hoistVariableDeclaration } = context; return chainBundle(context, transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) return node; @@ -79743,24 +80895,24 @@ ${lanes.join("\n")} function visitor(node) { if ((node.transformFlags & 32 /* ContainsES2020 */ ) === 0) return node; switch(node.kind){ - case 210 /* CallExpression */ : + case 213 /* CallExpression */ : { const updated = visitNonOptionalCallExpression(node, /*captureThisArg*/ false); Debug.assertNotNode(updated, isSyntheticReference); return updated; } - case 208 /* PropertyAccessExpression */ : - case 209 /* ElementAccessExpression */ : + case 211 /* PropertyAccessExpression */ : + case 212 /* ElementAccessExpression */ : if (isOptionalChain(node)) { const updated = visitOptionalExpression(node, /*captureThisArg*/ false, /*isDelete*/ false); Debug.assertNotNode(updated, isSyntheticReference); return updated; } return visitEachChild(node, visitor, context); - case 223 /* BinaryExpression */ : - if (node.operatorToken.kind === 60 /* QuestionQuestionToken */ ) return transformNullishCoalescingExpression(node); + case 226 /* BinaryExpression */ : + if (node.operatorToken.kind === 61 /* QuestionQuestionToken */ ) return transformNullishCoalescingExpression(node); return visitEachChild(node, visitor, context); - case 217 /* DeleteExpression */ : + case 220 /* DeleteExpression */ : return visitDeleteExpression(node); default: return visitEachChild(node, visitor, context); @@ -79797,7 +80949,7 @@ ${lanes.join("\n")} expression = factory2.createAssignment(thisArg, expression); } else thisArg = expression; } - expression = node.kind === 208 /* PropertyAccessExpression */ ? factory2.updatePropertyAccessExpression(node, expression, visitNode(node.name, visitor, isIdentifier)) : factory2.updateElementAccessExpression(node, expression, visitNode(node.argumentExpression, visitor, isExpression)); + expression = node.kind === 211 /* PropertyAccessExpression */ ? factory2.updatePropertyAccessExpression(node, expression, visitNode(node.name, visitor, isIdentifier)) : factory2.updateElementAccessExpression(node, expression, visitNode(node.argumentExpression, visitor, isExpression)); return thisArg ? factory2.createSyntheticReferenceExpression(expression, thisArg) : expression; } function visitNonOptionalCallExpression(node, captureThisArg) { @@ -79812,19 +80964,19 @@ ${lanes.join("\n")} } function visitNonOptionalExpression(node, captureThisArg, isDelete) { switch(node.kind){ - case 214 /* ParenthesizedExpression */ : + case 217 /* ParenthesizedExpression */ : return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete); - case 208 /* PropertyAccessExpression */ : - case 209 /* ElementAccessExpression */ : + case 211 /* PropertyAccessExpression */ : + case 212 /* ElementAccessExpression */ : return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete); - case 210 /* CallExpression */ : + case 213 /* CallExpression */ : return visitNonOptionalCallExpression(node, captureThisArg); default: return visitNode(node, visitor, isExpression); } } function visitOptionalExpression(node, captureThisArg, isDelete) { - const { expression: expression , chain: chain } = flattenChain(node); + const { expression: expression, chain: chain } = flattenChain(node); const left = visitNonOptionalExpression(skipPartiallyEmittedExpressions(expression), isCallChain(chain[0]), /*isDelete*/ false); let leftThisArg = isSyntheticReference(left) ? left.thisArg : void 0; let capturedLeft = isSyntheticReference(left) ? left.expression : left; @@ -79838,23 +80990,23 @@ ${lanes.join("\n")} for(let i = 0; i < chain.length; i++){ const segment = chain[i]; switch(segment.kind){ - case 208 /* PropertyAccessExpression */ : - case 209 /* ElementAccessExpression */ : + case 211 /* PropertyAccessExpression */ : + case 212 /* ElementAccessExpression */ : if (i === chain.length - 1 && captureThisArg) { if (!isSimpleCopiableExpression(rightExpression)) { thisArg = factory2.createTempVariable(hoistVariableDeclaration); rightExpression = factory2.createAssignment(thisArg, rightExpression); } else thisArg = rightExpression; } - rightExpression = segment.kind === 208 /* PropertyAccessExpression */ ? factory2.createPropertyAccessExpression(rightExpression, visitNode(segment.name, visitor, isIdentifier)) : factory2.createElementAccessExpression(rightExpression, visitNode(segment.argumentExpression, visitor, isExpression)); + rightExpression = segment.kind === 211 /* PropertyAccessExpression */ ? factory2.createPropertyAccessExpression(rightExpression, visitNode(segment.name, visitor, isIdentifier)) : factory2.createElementAccessExpression(rightExpression, visitNode(segment.argumentExpression, visitor, isExpression)); break; - case 210 /* CallExpression */ : + case 213 /* CallExpression */ : if (i === 0 && leftThisArg) { if (!isGeneratedIdentifier(leftThisArg)) { leftThisArg = factory2.cloneNode(leftThisArg); addEmitFlags(leftThisArg, 3072 /* NoComments */ ); } - rightExpression = factory2.createFunctionCallCall(rightExpression, leftThisArg.kind === 106 /* SuperKeyword */ ? factory2.createThis() : leftThisArg, visitNodes2(segment.arguments, visitor, isExpression)); + rightExpression = factory2.createFunctionCallCall(rightExpression, leftThisArg.kind === 108 /* SuperKeyword */ ? factory2.createThis() : leftThisArg, visitNodes2(segment.arguments, visitor, isExpression)); } else rightExpression = factory2.createCallExpression(rightExpression, /*typeArguments*/ void 0, visitNodes2(segment.arguments, visitor, isExpression)); break; } @@ -79865,7 +81017,7 @@ ${lanes.join("\n")} return thisArg ? factory2.createSyntheticReferenceExpression(target, thisArg) : target; } function createNotNullCondition(left, right, invert) { - return factory2.createBinaryExpression(factory2.createBinaryExpression(left, factory2.createToken(invert ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */ ), factory2.createNull()), factory2.createToken(invert ? 56 /* BarBarToken */ : 55 /* AmpersandAmpersandToken */ ), factory2.createBinaryExpression(right, factory2.createToken(invert ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */ ), factory2.createVoidZero())); + return factory2.createBinaryExpression(factory2.createBinaryExpression(left, factory2.createToken(invert ? 37 /* EqualsEqualsEqualsToken */ : 38 /* ExclamationEqualsEqualsToken */ ), factory2.createNull()), factory2.createToken(invert ? 57 /* BarBarToken */ : 56 /* AmpersandAmpersandToken */ ), factory2.createBinaryExpression(right, factory2.createToken(invert ? 37 /* EqualsEqualsEqualsToken */ : 38 /* ExclamationEqualsEqualsToken */ ), factory2.createVoidZero())); } function transformNullishCoalescingExpression(node) { let left = visitNode(node.left, visitor, isExpression); @@ -79888,7 +81040,7 @@ ${lanes.join("\n")} }); // src/compiler/transformers/es2021.ts function transformES2021(context) { - const { hoistVariableDeclaration: hoistVariableDeclaration , factory: factory2 } = context; + const { hoistVariableDeclaration: hoistVariableDeclaration, factory: factory2 } = context; return chainBundle(context, transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) return node; @@ -79930,16 +81082,356 @@ ${lanes.join("\n")} }); // src/compiler/transformers/esnext.ts function transformESNext(context) { + const { factory: factory2, getEmitHelperFactory: emitHelpers, hoistVariableDeclaration: hoistVariableDeclaration, startLexicalEnvironment: startLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment } = context; + let exportBindings; + let exportVars; + let defaultExportBinding; + let exportEqualsBinding; return chainBundle(context, transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) return node; - return visitEachChild(node, visitor, context); + const visited = visitNode(node, visitor, isSourceFile); + addEmitHelpers(visited, context.readEmitHelpers()); + exportVars = void 0; + exportBindings = void 0; + defaultExportBinding = void 0; + return visited; } function visitor(node) { if ((node.transformFlags & 4 /* ContainsESNext */ ) === 0) return node; - node.kind; + switch(node.kind){ + case 312 /* SourceFile */ : + return visitSourceFile(node); + case 241 /* Block */ : + return visitBlock(node); + case 248 /* ForStatement */ : + return visitForStatement(node); + case 250 /* ForOfStatement */ : + return visitForOfStatement(node); + case 255 /* SwitchStatement */ : + return visitSwitchStatement(node); + default: + return visitEachChild(node, visitor, context); + } + } + function visitSourceFile(node) { + const usingKind = getUsingKindOfStatements(node.statements); + if (usingKind) { + startLexicalEnvironment(); + exportBindings = new IdentifierNameMap(); + exportVars = []; + const prologueCount = countPrologueStatements(node.statements); + const topLevelStatements = []; + addRange(topLevelStatements, visitArray(node.statements, visitor, isStatement, 0, prologueCount)); + let pos = prologueCount; + while(pos < node.statements.length){ + const statement = node.statements[pos]; + if (getUsingKind(statement) !== 0 /* None */ ) { + if (pos > prologueCount) addRange(topLevelStatements, visitNodes2(node.statements, visitor, isStatement, prologueCount, pos - prologueCount)); + break; + } + pos++; + } + Debug.assert(pos < node.statements.length, "Should have encountered at least one 'using' statement."); + const envBinding = createEnvBinding(); + const bodyStatements = transformUsingDeclarations(node.statements, pos, node.statements.length, envBinding, topLevelStatements); + if (exportBindings.size) append(topLevelStatements, factory2.createExportDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, factory2.createNamedExports(arrayFrom(exportBindings.values())))); + addRange(topLevelStatements, endLexicalEnvironment()); + if (exportVars.length) topLevelStatements.push(factory2.createVariableStatement(factory2.createModifiersFromModifierFlags(1 /* Export */ ), factory2.createVariableDeclarationList(exportVars, 1 /* Let */ ))); + addRange(topLevelStatements, createDownlevelUsingStatements(bodyStatements, envBinding, usingKind === 2 /* Async */ )); + if (exportEqualsBinding) topLevelStatements.push(factory2.createExportAssignment(/*modifiers*/ void 0, /*isExportEquals*/ true, exportEqualsBinding)); + return factory2.updateSourceFile(node, topLevelStatements); + } return visitEachChild(node, visitor, context); } + function visitBlock(node) { + const usingKind = getUsingKindOfStatements(node.statements); + if (usingKind) { + const prologueCount = countPrologueStatements(node.statements); + const envBinding = createEnvBinding(); + return factory2.updateBlock(node, [ + ...visitArray(node.statements, visitor, isStatement, 0, prologueCount), + ...createDownlevelUsingStatements(transformUsingDeclarations(node.statements, prologueCount, node.statements.length, envBinding, /*topLevelStatements*/ void 0), envBinding, usingKind === 2 /* Async */ ) + ]); + } + return visitEachChild(node, visitor, context); + } + function visitForStatement(node) { + if (node.initializer && isUsingVariableDeclarationList(node.initializer)) return visitNode(factory2.createBlock([ + factory2.createVariableStatement(/*modifiers*/ void 0, node.initializer), + factory2.updateForStatement(node, /*initializer*/ void 0, node.condition, node.incrementor, node.statement) + ]), visitor, isStatement); + return visitEachChild(node, visitor, context); + } + function visitForOfStatement(node) { + if (isUsingVariableDeclarationList(node.initializer)) { + const forInitializer = node.initializer; + Debug.assertNode(forInitializer, isUsingVariableDeclarationList); + Debug.assert(forInitializer.declarations.length === 1, "ForInitializer may only have one declaration"); + const forDecl = forInitializer.declarations[0]; + Debug.assert(!forDecl.initializer, "ForInitializer may not have an initializer"); + const isAwaitUsing = getUsingKindOfVariableDeclarationList(forInitializer) === 2 /* Async */ ; + const temp = factory2.getGeneratedNameForNode(forDecl.name); + const usingVar = factory2.updateVariableDeclaration(forDecl, forDecl.name, /*exclamationToken*/ void 0, /*type*/ void 0, temp); + const usingVarList = factory2.createVariableDeclarationList([ + usingVar + ], isAwaitUsing ? 6 /* AwaitUsing */ : 4 /* Using */ ); + const usingVarStatement = factory2.createVariableStatement(/*modifiers*/ void 0, usingVarList); + return visitNode(factory2.updateForOfStatement(node, node.awaitModifier, factory2.createVariableDeclarationList([ + factory2.createVariableDeclaration(temp) + ], 2 /* Const */ ), node.expression, isBlock(node.statement) ? factory2.updateBlock(node.statement, [ + usingVarStatement, + ...node.statement.statements + ]) : factory2.createBlock([ + usingVarStatement, + node.statement + ], /*multiLine*/ true)), visitor, isStatement); + } + return visitEachChild(node, visitor, context); + } + function visitCaseOrDefaultClause(node, envBinding) { + if (getUsingKindOfStatements(node.statements) !== 0 /* None */ ) { + if (isCaseClause(node)) return factory2.updateCaseClause(node, visitNode(node.expression, visitor, isExpression), transformUsingDeclarations(node.statements, /*start*/ 0, node.statements.length, envBinding, /*topLevelStatements*/ void 0)); + else return factory2.updateDefaultClause(node, transformUsingDeclarations(node.statements, /*start*/ 0, node.statements.length, envBinding, /*topLevelStatements*/ void 0)); + } + return visitEachChild(node, visitor, context); + } + function visitSwitchStatement(node) { + const usingKind = getUsingKindOfCaseOrDefaultClauses(node.caseBlock.clauses); + if (usingKind) { + const envBinding = createEnvBinding(); + return createDownlevelUsingStatements([ + factory2.updateSwitchStatement(node, visitNode(node.expression, visitor, isExpression), factory2.updateCaseBlock(node.caseBlock, node.caseBlock.clauses.map((clause)=>visitCaseOrDefaultClause(clause, envBinding)))) + ], envBinding, usingKind === 2 /* Async */ ); + } + return visitEachChild(node, visitor, context); + } + function transformUsingDeclarations(statementsIn, start, end, envBinding, topLevelStatements) { + const statements = []; + for(let i = start; i < end; i++){ + const statement = statementsIn[i]; + const usingKind = getUsingKind(statement); + if (usingKind) { + Debug.assertNode(statement, isVariableStatement); + const declarations = []; + for (let declaration of statement.declarationList.declarations){ + if (!isIdentifier(declaration.name)) { + declarations.length = 0; + break; + } + if (isNamedEvaluation(declaration)) declaration = transformNamedEvaluation(context, declaration); + const initializer = visitNode(declaration.initializer, visitor, isExpression) ?? factory2.createVoidZero(); + declarations.push(factory2.updateVariableDeclaration(declaration, declaration.name, /*exclamationToken*/ void 0, /*type*/ void 0, emitHelpers().createAddDisposableResourceHelper(envBinding, initializer, usingKind === 2 /* Async */ ))); + } + if (declarations.length) { + const varList = factory2.createVariableDeclarationList(declarations, 2 /* Const */ ); + setOriginalNode(varList, statement.declarationList); + setTextRange(varList, statement.declarationList); + hoistOrAppendNode(factory2.updateVariableStatement(statement, /*modifiers*/ void 0, varList)); + continue; + } + } + const result = visitor(statement); + if (isArray(result)) result.forEach(hoistOrAppendNode); + else if (result) hoistOrAppendNode(result); + } + return statements; + function hoistOrAppendNode(node) { + Debug.assertNode(node, isStatement); + append(statements, hoist(node)); + } + function hoist(node) { + if (!topLevelStatements) return node; + switch(node.kind){ + case 272 /* ImportDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : + case 278 /* ExportDeclaration */ : + case 262 /* FunctionDeclaration */ : + return hoistImportOrExportOrHoistedDeclaration(node, topLevelStatements); + case 277 /* ExportAssignment */ : + return hoistExportAssignment(node); + case 263 /* ClassDeclaration */ : + return hoistClassDeclaration(node); + case 243 /* VariableStatement */ : + return hoistVariableStatement(node); + } + return node; + } + } + function hoistImportOrExportOrHoistedDeclaration(node, topLevelStatements) { + topLevelStatements.push(node); + return void 0; + } + function hoistExportAssignment(node) { + return node.isExportEquals ? hoistExportEquals(node) : hoistExportDefault(node); + } + function hoistExportDefault(node) { + if (defaultExportBinding) return node; + defaultExportBinding = factory2.createUniqueName("_default", 56 /* Optimistic */ ); + hoistBindingIdentifier(defaultExportBinding, /*isExport*/ true, "default", node); + let expression = node.expression; + let innerExpression = skipOuterExpressions(expression); + if (isNamedEvaluation(innerExpression)) { + innerExpression = transformNamedEvaluation(context, innerExpression, /*ignoreEmptyStringLiteral*/ false, "default"); + expression = factory2.restoreOuterExpressions(expression, innerExpression); + } + const assignment = factory2.createAssignment(defaultExportBinding, expression); + return factory2.createExpressionStatement(assignment); + } + function hoistExportEquals(node) { + if (exportEqualsBinding) return node; + exportEqualsBinding = factory2.createUniqueName("_default", 56 /* Optimistic */ ); + hoistVariableDeclaration(exportEqualsBinding); + const assignment = factory2.createAssignment(exportEqualsBinding, node.expression); + return factory2.createExpressionStatement(assignment); + } + function hoistClassDeclaration(node) { + if (!node.name && defaultExportBinding) return node; + const isExported2 = hasSyntacticModifier(node, 1 /* Export */ ); + const isDefault = hasSyntacticModifier(node, 1024 /* Default */ ); + let expression = factory2.converters.convertToClassExpression(node); + if (node.name) { + hoistBindingIdentifier(factory2.getLocalName(node), isExported2 && !isDefault, /*exportAlias*/ void 0, node); + expression = factory2.createAssignment(factory2.getDeclarationName(node), expression); + if (isNamedEvaluation(expression)) expression = transformNamedEvaluation(context, expression, /*ignoreEmptyStringLiteral*/ false); + setOriginalNode(expression, node); + setSourceMapRange(expression, node); + setCommentRange(expression, node); + } + if (isDefault && !defaultExportBinding) { + defaultExportBinding = factory2.createUniqueName("_default", 56 /* Optimistic */ ); + hoistBindingIdentifier(defaultExportBinding, /*isExport*/ true, "default", node); + expression = factory2.createAssignment(defaultExportBinding, expression); + if (isNamedEvaluation(expression)) expression = transformNamedEvaluation(context, expression, /*ignoreEmptyStringLiteral*/ false, "default"); + setOriginalNode(expression, node); + } + return factory2.createExpressionStatement(expression); + } + function hoistVariableStatement(node) { + let expressions; + const isExported2 = hasSyntacticModifier(node, 1 /* Export */ ); + for (const variable of node.declarationList.declarations){ + hoistBindingElement(variable, isExported2, variable); + if (variable.initializer) expressions = append(expressions, hoistInitializedVariable(variable)); + } + if (expressions) { + const statement = factory2.createExpressionStatement(factory2.inlineExpressions(expressions)); + setOriginalNode(statement, node); + setCommentRange(statement, node); + setSourceMapRange(statement, node); + return statement; + } + return void 0; + } + function hoistInitializedVariable(node) { + Debug.assertIsDefined(node.initializer); + let target; + if (isIdentifier(node.name)) { + target = factory2.cloneNode(node.name); + setEmitFlags(target, getEmitFlags(target) & -114689); + } else target = factory2.converters.convertToAssignmentPattern(node.name); + const assignment = factory2.createAssignment(target, node.initializer); + setOriginalNode(assignment, node); + setCommentRange(assignment, node); + setSourceMapRange(assignment, node); + return assignment; + } + function hoistBindingElement(node, isExportedDeclaration, original) { + if (isBindingPattern(node.name)) { + for (const element of node.name.elements)if (!isOmittedExpression(element)) hoistBindingElement(element, isExportedDeclaration, original); + } else hoistBindingIdentifier(node.name, isExportedDeclaration, /*exportAlias*/ void 0, original); + } + function hoistBindingIdentifier(node, isExport, exportAlias, original) { + const name = isGeneratedIdentifier(node) ? node : factory2.cloneNode(node); + if (isExport) { + if (exportAlias === void 0 && !isLocalName(name)) { + const varDecl = factory2.createVariableDeclaration(name); + if (original) setOriginalNode(varDecl, original); + exportVars.push(varDecl); + return; + } + const localName = exportAlias !== void 0 ? name : void 0; + const exportName = exportAlias !== void 0 ? exportAlias : name; + const specifier = factory2.createExportSpecifier(/*isTypeOnly*/ false, localName, exportName); + if (original) setOriginalNode(specifier, original); + exportBindings.set(name, specifier); + } + hoistVariableDeclaration(name); + } + function createEnvBinding() { + return factory2.createUniqueName("env"); + } + function createDownlevelUsingStatements(bodyStatements, envBinding, async) { + const statements = []; + const envObject = factory2.createObjectLiteralExpression([ + factory2.createPropertyAssignment("stack", factory2.createArrayLiteralExpression()), + factory2.createPropertyAssignment("error", factory2.createVoidZero()), + factory2.createPropertyAssignment("hasError", factory2.createFalse()) + ]); + const envVar = factory2.createVariableDeclaration(envBinding, /*exclamationToken*/ void 0, /*type*/ void 0, envObject); + const envVarList = factory2.createVariableDeclarationList([ + envVar + ], 2 /* Const */ ); + const envVarStatement = factory2.createVariableStatement(/*modifiers*/ void 0, envVarList); + statements.push(envVarStatement); + const tryBlock = factory2.createBlock(bodyStatements, /*multiLine*/ true); + const bodyCatchBinding = factory2.createUniqueName("e"); + const catchClause = factory2.createCatchClause(bodyCatchBinding, factory2.createBlock([ + factory2.createExpressionStatement(factory2.createAssignment(factory2.createPropertyAccessExpression(envBinding, "error"), bodyCatchBinding)), + factory2.createExpressionStatement(factory2.createAssignment(factory2.createPropertyAccessExpression(envBinding, "hasError"), factory2.createTrue())) + ], /*multiLine*/ true)); + let finallyBlock; + if (async) { + const result = factory2.createUniqueName("result"); + finallyBlock = factory2.createBlock([ + factory2.createVariableStatement(/*modifiers*/ void 0, factory2.createVariableDeclarationList([ + factory2.createVariableDeclaration(result, /*exclamationToken*/ void 0, /*type*/ void 0, emitHelpers().createDisposeResourcesHelper(envBinding)) + ], 2 /* Const */ )), + factory2.createIfStatement(result, factory2.createExpressionStatement(factory2.createAwaitExpression(result))) + ], /*multiLine*/ true); + } else finallyBlock = factory2.createBlock([ + factory2.createExpressionStatement(emitHelpers().createDisposeResourcesHelper(envBinding)) + ], /*multiLine*/ true); + const tryStatement = factory2.createTryStatement(tryBlock, catchClause, finallyBlock); + statements.push(tryStatement); + return statements; + } + } + function countPrologueStatements(statements) { + for(let i = 0; i < statements.length; i++){ + if (!isPrologueDirective(statements[i]) && !isCustomPrologue(statements[i])) return i; + } + return 0; + } + function isUsingVariableDeclarationList(node) { + return isVariableDeclarationList(node) && getUsingKindOfVariableDeclarationList(node) !== 0 /* None */ ; + } + function getUsingKindOfVariableDeclarationList(node) { + return (node.flags & 7 /* BlockScoped */ ) === 6 /* AwaitUsing */ ? 2 /* Async */ : (node.flags & 7 /* BlockScoped */ ) === 4 /* Using */ ? 1 /* Sync */ : 0 /* None */ ; + } + function getUsingKindOfVariableStatement(node) { + return getUsingKindOfVariableDeclarationList(node.declarationList); + } + function getUsingKind(statement) { + return isVariableStatement(statement) ? getUsingKindOfVariableStatement(statement) : 0 /* None */ ; + } + function getUsingKindOfStatements(statements) { + let result = 0 /* None */ ; + for (const statement of statements){ + const usingKind = getUsingKind(statement); + if (usingKind === 2 /* Async */ ) return 2 /* Async */ ; + if (usingKind > result) result = usingKind; + } + return result; + } + function getUsingKindOfCaseOrDefaultClauses(clauses) { + let result = 0 /* None */ ; + for (const clause of clauses){ + const usingKind = getUsingKindOfStatements(clause.statements); + if (usingKind === 2 /* Async */ ) return 2 /* Async */ ; + if (usingKind > result) result = usingKind; + } + return result; } var init_esnext = __esm({ "src/compiler/transformers/esnext.ts" () { @@ -79949,14 +81441,14 @@ ${lanes.join("\n")} }); // src/compiler/transformers/jsx.ts function transformJsx(context) { - const { factory: factory2 , getEmitHelperFactory: emitHelpers } = context; + const { factory: factory2, getEmitHelperFactory: emitHelpers } = context; const compilerOptions = context.getCompilerOptions(); let currentSourceFile; let currentFileState; return chainBundle(context, transformSourceFile); function getCurrentFileNameExpression() { if (currentFileState.filenameDeclaration) return currentFileState.filenameDeclaration.name; - const declaration = factory2.createVariableDeclaration(factory2.createUniqueName("_jsxFileName", 48 /* FileLevel */ ), /*exclaimationToken*/ void 0, /*type*/ void 0, factory2.createStringLiteral(currentSourceFile.fileName)); + const declaration = factory2.createVariableDeclaration(factory2.createUniqueName("_jsxFileName", 48 /* FileLevel */ ), /*exclamationToken*/ void 0, /*type*/ void 0, factory2.createStringLiteral(currentSourceFile.fileName)); currentFileState.filenameDeclaration = declaration; return currentFileState.filenameDeclaration.name; } @@ -79971,9 +81463,9 @@ ${lanes.join("\n")} return getImplicitImportForName("Fragment"); } function getImplicitImportForName(name) { - var _a2, _b; + var _a, _b; const importSource = name === "createElement" ? currentFileState.importSpecifier : getJSXRuntimeImport(currentFileState.importSpecifier, compilerOptions); - const existing = (_b = (_a2 = currentFileState.utilizedImplicitRuntimeImports) == null ? void 0 : _a2.get(importSource)) == null ? void 0 : _b.get(name); + const existing = (_b = (_a = currentFileState.utilizedImplicitRuntimeImports) == null ? void 0 : _a.get(importSource)) == null ? void 0 : _b.get(name); if (existing) return existing.name; if (!currentFileState.utilizedImplicitRuntimeImports) currentFileState.utilizedImplicitRuntimeImports = /* @__PURE__ */ new Map(); let specifierSourceImports = currentFileState.utilizedImplicitRuntimeImports.get(importSource); @@ -80000,12 +81492,12 @@ ${lanes.join("\n")} ], 2 /* Const */ ))); if (currentFileState.utilizedImplicitRuntimeImports) for (const [importSource, importSpecifiersMap] of arrayFrom(currentFileState.utilizedImplicitRuntimeImports.entries())){ if (isExternalModule(node)) { - const importStatement = factory2.createImportDeclaration(/*modifiers*/ void 0, factory2.createImportClause(/*typeOnly*/ false, /*name*/ void 0, factory2.createNamedImports(arrayFrom(importSpecifiersMap.values()))), factory2.createStringLiteral(importSource), /*assertClause*/ void 0); + const importStatement = factory2.createImportDeclaration(/*modifiers*/ void 0, factory2.createImportClause(/*isTypeOnly*/ false, /*name*/ void 0, factory2.createNamedImports(arrayFrom(importSpecifiersMap.values()))), factory2.createStringLiteral(importSource), /*assertClause*/ void 0); setParentRecursive(importStatement, /*incremental*/ false); statements = insertStatementAfterCustomPrologue(statements.slice(), importStatement); } else if (isExternalOrCommonJsModule(node)) { const requireStatement = factory2.createVariableStatement(/*modifiers*/ void 0, factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration(factory2.createObjectBindingPattern(arrayFrom(importSpecifiersMap.values(), (s)=>factory2.createBindingElement(/*dotdotdot*/ void 0, s.propertyName, s.name))), /*exclaimationToken*/ void 0, /*type*/ void 0, factory2.createCallExpression(factory2.createIdentifier("require"), /*typeArguments*/ void 0, [ + factory2.createVariableDeclaration(factory2.createObjectBindingPattern(arrayFrom(importSpecifiersMap.values(), (s)=>factory2.createBindingElement(/*dotDotDotToken*/ void 0, s.propertyName, s.name))), /*exclamationToken*/ void 0, /*type*/ void 0, factory2.createCallExpression(factory2.createIdentifier("require"), /*typeArguments*/ void 0, [ factory2.createStringLiteral(importSource) ])) ], 2 /* Const */ )); @@ -80023,13 +81515,13 @@ ${lanes.join("\n")} } function visitorWorker(node) { switch(node.kind){ - case 281 /* JsxElement */ : + case 284 /* JsxElement */ : return visitJsxElement(node, /*isChild*/ false); - case 282 /* JsxSelfClosingElement */ : + case 285 /* JsxSelfClosingElement */ : return visitJsxSelfClosingElement(node, /*isChild*/ false); - case 285 /* JsxFragment */ : + case 288 /* JsxFragment */ : return visitJsxFragment(node, /*isChild*/ false); - case 291 /* JsxExpression */ : + case 294 /* JsxExpression */ : return visitJsxExpression(node); default: return visitEachChild(node, visitor, context); @@ -80037,25 +81529,28 @@ ${lanes.join("\n")} } function transformJsxChildToExpression(node) { switch(node.kind){ - case 11 /* JsxText */ : + case 12 /* JsxText */ : return visitJsxText(node); - case 291 /* JsxExpression */ : + case 294 /* JsxExpression */ : return visitJsxExpression(node); - case 281 /* JsxElement */ : + case 284 /* JsxElement */ : return visitJsxElement(node, /*isChild*/ true); - case 282 /* JsxSelfClosingElement */ : + case 285 /* JsxSelfClosingElement */ : return visitJsxSelfClosingElement(node, /*isChild*/ true); - case 285 /* JsxFragment */ : + case 288 /* JsxFragment */ : return visitJsxFragment(node, /*isChild*/ true); default: return Debug.failBadSyntaxKind(node); } } + function hasProto(obj) { + return obj.properties.some((p)=>isPropertyAssignment(p) && (isIdentifier(p.name) && idText(p.name) === "__proto__" || isStringLiteral(p.name) && p.name.text === "__proto__")); + } function hasKeyAfterPropsSpread(node) { let spread = false; for (const elem of node.attributes.properties){ - if (isJsxSpreadAttribute(elem)) spread = true; - else if (spread && isJsxAttribute(elem) && elem.name.escapedText === "key") return true; + if (isJsxSpreadAttribute(elem) && (!isObjectLiteralExpression(elem.expression) || elem.expression.properties.some(isSpreadAssignment))) spread = true; + else if (spread && isJsxAttribute(elem) && isIdentifier(elem.name) && elem.name.escapedText === "key") return true; } return false; } @@ -80100,9 +81595,9 @@ ${lanes.join("\n")} return visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, children || emptyArray, isChild, location); } function visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, children, isChild, location) { - var _a2; + var _a; const nonWhitespaceChildren = getSemanticJsxChildren(children); - const isStaticChildren = length(nonWhitespaceChildren) > 1 || !!((_a2 = nonWhitespaceChildren[0]) == null ? void 0 : _a2.dotDotDotToken); + const isStaticChildren = length(nonWhitespaceChildren) > 1 || !!((_a = nonWhitespaceChildren[0]) == null ? void 0 : _a.dotDotDotToken); const args = [ tagName, objectProperties @@ -80150,7 +81645,8 @@ ${lanes.join("\n")} if (isChild) startOnNewLine(element); return element; } - function transformJsxSpreadAttributeToSpreadAssignment(node) { + function transformJsxSpreadAttributeToProps(node) { + if (isObjectLiteralExpression(node.expression) && !hasProto(node.expression)) return node.expression.properties; return factory2.createSpreadAssignment(Debug.checkDefined(visitNode(node.expression, visitor, isExpression))); } function transformJsxAttributesToObjectProps(attrs, children) { @@ -80158,20 +81654,42 @@ ${lanes.join("\n")} return target && target >= 5 /* ES2018 */ ? factory2.createObjectLiteralExpression(transformJsxAttributesToProps(attrs, children)) : transformJsxAttributesToExpression(attrs, children); } function transformJsxAttributesToProps(attrs, children) { - const props = flatten(spanMap(attrs, isJsxSpreadAttribute, (attrs2, isSpread)=>map(attrs2, (attr)=>isSpread ? transformJsxSpreadAttributeToSpreadAssignment(attr) : transformJsxAttributeToObjectLiteralElement(attr)))); + const props = flatten(spanMap(attrs, isJsxSpreadAttribute, (attrs2, isSpread)=>flatten(map(attrs2, (attr)=>isSpread ? transformJsxSpreadAttributeToProps(attr) : transformJsxAttributeToObjectLiteralElement(attr))))); if (children) props.push(children); return props; } function transformJsxAttributesToExpression(attrs, children) { - const expressions = flatten(spanMap(attrs, isJsxSpreadAttribute, (attrs2, isSpread)=>isSpread ? map(attrs2, transformJsxSpreadAttributeToExpression) : factory2.createObjectLiteralExpression(map(attrs2, transformJsxAttributeToObjectLiteralElement)))); - if (isJsxSpreadAttribute(attrs[0])) expressions.unshift(factory2.createObjectLiteralExpression()); - if (children) expressions.push(factory2.createObjectLiteralExpression([ - children - ])); + const expressions = []; + let properties = []; + for (const attr of attrs){ + if (isJsxSpreadAttribute(attr)) { + if (isObjectLiteralExpression(attr.expression) && !hasProto(attr.expression)) { + for (const prop of attr.expression.properties){ + if (isSpreadAssignment(prop)) { + finishObjectLiteralIfNeeded(); + expressions.push(Debug.checkDefined(visitNode(prop.expression, visitor, isExpression))); + continue; + } + properties.push(Debug.checkDefined(visitNode(prop, visitor))); + } + continue; + } + finishObjectLiteralIfNeeded(); + expressions.push(Debug.checkDefined(visitNode(attr.expression, visitor, isExpression))); + continue; + } + properties.push(transformJsxAttributeToObjectLiteralElement(attr)); + } + if (children) properties.push(children); + finishObjectLiteralIfNeeded(); + if (expressions.length && !isObjectLiteralExpression(expressions[0])) expressions.unshift(factory2.createObjectLiteralExpression()); return singleOrUndefined(expressions) || emitHelpers().createAssignHelper(expressions); - } - function transformJsxSpreadAttributeToExpression(node) { - return Debug.checkDefined(visitNode(node.expression, visitor, isExpression)); + function finishObjectLiteralIfNeeded() { + if (properties.length) { + expressions.push(factory2.createObjectLiteralExpression(properties)); + properties = []; + } + } } function transformJsxAttributeToObjectLiteralElement(node) { const name = getAttributeName(node); @@ -80180,12 +81698,12 @@ ${lanes.join("\n")} } function transformJsxAttributeInitializer(node) { if (node === void 0) return factory2.createTrue(); - if (node.kind === 10 /* StringLiteral */ ) { + if (node.kind === 11 /* StringLiteral */ ) { const singleQuote = node.singleQuote !== void 0 ? node.singleQuote : !isStringDoubleQuoted(node, currentSourceFile); const literal = factory2.createStringLiteral(tryDecodeEntities(node.text) || node.text, singleQuote); return setTextRange(literal, node); } - if (node.kind === 291 /* JsxExpression */ ) { + if (node.kind === 294 /* JsxExpression */ ) { if (node.expression === void 0) return factory2.createTrue(); return Debug.checkDefined(visitNode(node.expression, visitor, isExpression)); } @@ -80233,18 +81751,21 @@ ${lanes.join("\n")} return decoded === text ? void 0 : decoded; } function getTagName(node) { - if (node.kind === 281 /* JsxElement */ ) return getTagName(node.openingElement); + if (node.kind === 284 /* JsxElement */ ) return getTagName(node.openingElement); else { - const name = node.tagName; - if (isIdentifier(name) && isIntrinsicJsxName(name.escapedText)) return factory2.createStringLiteral(idText(name)); - else return createExpressionFromEntityName(factory2, name); + const tagName = node.tagName; + if (isIdentifier(tagName) && isIntrinsicJsxName(tagName.escapedText)) return factory2.createStringLiteral(idText(tagName)); + else if (isJsxNamespacedName(tagName)) return factory2.createStringLiteral(idText(tagName.namespace) + ":" + idText(tagName.name)); + else return createExpressionFromEntityName(factory2, tagName); } } function getAttributeName(node) { const name = node.name; - const text = idText(name); - if (/^[A-Za-z_]\w*$/.test(text)) return name; - else return factory2.createStringLiteral(text); + if (isIdentifier(name)) { + const text = idText(name); + return /^[A-Za-z_]\w*$/.test(text) ? name : factory2.createStringLiteral(text); + } + return factory2.createStringLiteral(idText(name.namespace) + ":" + idText(name.name)); } function visitJsxExpression(node) { const expression = visitNode(node.expression, visitor, isExpression); @@ -80515,7 +82036,7 @@ ${lanes.join("\n")} }); // src/compiler/transformers/es2016.ts function transformES2016(context) { - const { factory: factory2 , hoistVariableDeclaration: hoistVariableDeclaration } = context; + const { factory: factory2, hoistVariableDeclaration: hoistVariableDeclaration } = context; return chainBundle(context, transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) return node; @@ -80524,7 +82045,7 @@ ${lanes.join("\n")} function visitor(node) { if ((node.transformFlags & 512 /* ContainsES2016 */ ) === 0) return node; switch(node.kind){ - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : return visitBinaryExpression(node); default: return visitEachChild(node, visitor, context); @@ -80532,9 +82053,9 @@ ${lanes.join("\n")} } function visitBinaryExpression(node) { switch(node.operatorToken.kind){ - case 67 /* AsteriskAsteriskEqualsToken */ : + case 68 /* AsteriskAsteriskEqualsToken */ : return visitExponentiationAssignmentExpression(node); - case 42 /* AsteriskAsteriskToken */ : + case 43 /* AsteriskAsteriskToken */ : return visitExponentiationExpression(node); default: return visitEachChild(node, visitor, context); @@ -80586,7 +82107,7 @@ ${lanes.join("\n")} }; } function transformES2015(context) { - const { factory: factory2 , getEmitHelperFactory: emitHelpers , startLexicalEnvironment: startLexicalEnvironment , resumeLexicalEnvironment: resumeLexicalEnvironment , endLexicalEnvironment: endLexicalEnvironment , hoistVariableDeclaration: hoistVariableDeclaration } = context; + const { factory: factory2, getEmitHelperFactory: emitHelpers, startLexicalEnvironment: startLexicalEnvironment, resumeLexicalEnvironment: resumeLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, hoistVariableDeclaration: hoistVariableDeclaration } = context; const compilerOptions = context.getCompilerOptions(); const resolver = context.getEmitResolver(); const previousOnSubstituteNode = context.onSubstituteNode; @@ -80624,7 +82145,7 @@ ${lanes.join("\n")} hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -32768 /* SubtreeFactsMask */ | ancestorFacts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { - return (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ ) !== 0 && node.kind === 250 /* ReturnStatement */ && !node.expression; + return (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ ) !== 0 && node.kind === 253 /* ReturnStatement */ && !node.expression; } function isOrMayContainReturnCompletion(node) { return node.transformFlags & 4194304 /* ContainsHoistedDeclarationOrCompletion */ && (isReturnStatement(node) || isIfStatement(node) || isWithStatement(node) || isSwitchStatement(node) || isCaseBlock(node) || isCaseClause(node) || isDefaultClause(node) || isTryStatement(node) || isCatchClause(node) || isLabeledStatement(node) || isIterationStatement(node, /*lookInLabeledStatements*/ false) || isBlock(node)); @@ -80652,106 +82173,106 @@ ${lanes.join("\n")} return node; } function callExpressionVisitor(node) { - if (node.kind === 106 /* SuperKeyword */ ) return visitSuperKeyword(/*isExpressionOfCall*/ true); + if (node.kind === 108 /* SuperKeyword */ ) return visitSuperKeyword(/*isExpressionOfCall*/ true); return visitor(node); } function visitorWorker(node, expressionResultIsUnused2) { switch(node.kind){ - case 124 /* StaticKeyword */ : + case 126 /* StaticKeyword */ : return void 0; - case 260 /* ClassDeclaration */ : + case 263 /* ClassDeclaration */ : return visitClassDeclaration(node); - case 228 /* ClassExpression */ : + case 231 /* ClassExpression */ : return visitClassExpression(node); - case 166 /* Parameter */ : + case 169 /* Parameter */ : return visitParameter(node); - case 259 /* FunctionDeclaration */ : + case 262 /* FunctionDeclaration */ : return visitFunctionDeclaration(node); - case 216 /* ArrowFunction */ : + case 219 /* ArrowFunction */ : return visitArrowFunction(node); - case 215 /* FunctionExpression */ : + case 218 /* FunctionExpression */ : return visitFunctionExpression(node); - case 257 /* VariableDeclaration */ : + case 260 /* VariableDeclaration */ : return visitVariableDeclaration(node); - case 79 /* Identifier */ : + case 80 /* Identifier */ : return visitIdentifier(node); - case 258 /* VariableDeclarationList */ : + case 261 /* VariableDeclarationList */ : return visitVariableDeclarationList(node); - case 252 /* SwitchStatement */ : + case 255 /* SwitchStatement */ : return visitSwitchStatement(node); - case 266 /* CaseBlock */ : + case 269 /* CaseBlock */ : return visitCaseBlock(node); - case 238 /* Block */ : + case 241 /* Block */ : return visitBlock(node, /*isFunctionBody*/ false); - case 249 /* BreakStatement */ : - case 248 /* ContinueStatement */ : + case 252 /* BreakStatement */ : + case 251 /* ContinueStatement */ : return visitBreakOrContinueStatement(node); - case 253 /* LabeledStatement */ : + case 256 /* LabeledStatement */ : return visitLabeledStatement(node); - case 243 /* DoStatement */ : - case 244 /* WhileStatement */ : + case 246 /* DoStatement */ : + case 247 /* WhileStatement */ : return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ void 0); - case 245 /* ForStatement */ : + case 248 /* ForStatement */ : return visitForStatement(node, /*outermostLabeledStatement*/ void 0); - case 246 /* ForInStatement */ : + case 249 /* ForInStatement */ : return visitForInStatement(node, /*outermostLabeledStatement*/ void 0); - case 247 /* ForOfStatement */ : + case 250 /* ForOfStatement */ : return visitForOfStatement(node, /*outermostLabeledStatement*/ void 0); - case 241 /* ExpressionStatement */ : + case 244 /* ExpressionStatement */ : return visitExpressionStatement(node); - case 207 /* ObjectLiteralExpression */ : + case 210 /* ObjectLiteralExpression */ : return visitObjectLiteralExpression(node); - case 295 /* CatchClause */ : + case 299 /* CatchClause */ : return visitCatchClause(node); - case 300 /* ShorthandPropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : return visitShorthandPropertyAssignment(node); - case 164 /* ComputedPropertyName */ : + case 167 /* ComputedPropertyName */ : return visitComputedPropertyName(node); - case 206 /* ArrayLiteralExpression */ : + case 209 /* ArrayLiteralExpression */ : return visitArrayLiteralExpression(node); - case 210 /* CallExpression */ : + case 213 /* CallExpression */ : return visitCallExpression(node); - case 211 /* NewExpression */ : + case 214 /* NewExpression */ : return visitNewExpression(node); - case 214 /* ParenthesizedExpression */ : + case 217 /* ParenthesizedExpression */ : return visitParenthesizedExpression(node, expressionResultIsUnused2); - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : return visitBinaryExpression(node, expressionResultIsUnused2); - case 357 /* CommaListExpression */ : + case 361 /* CommaListExpression */ : return visitCommaListExpression(node, expressionResultIsUnused2); - case 14 /* NoSubstitutionTemplateLiteral */ : - case 15 /* TemplateHead */ : - case 16 /* TemplateMiddle */ : - case 17 /* TemplateTail */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + case 16 /* TemplateHead */ : + case 17 /* TemplateMiddle */ : + case 18 /* TemplateTail */ : return visitTemplateLiteral(node); - case 10 /* StringLiteral */ : + case 11 /* StringLiteral */ : return visitStringLiteral(node); - case 8 /* NumericLiteral */ : + case 9 /* NumericLiteral */ : return visitNumericLiteral(node); - case 212 /* TaggedTemplateExpression */ : + case 215 /* TaggedTemplateExpression */ : return visitTaggedTemplateExpression(node); - case 225 /* TemplateExpression */ : + case 228 /* TemplateExpression */ : return visitTemplateExpression(node); - case 226 /* YieldExpression */ : + case 229 /* YieldExpression */ : return visitYieldExpression(node); - case 227 /* SpreadElement */ : + case 230 /* SpreadElement */ : return visitSpreadElement(node); - case 106 /* SuperKeyword */ : + case 108 /* SuperKeyword */ : return visitSuperKeyword(/*isExpressionOfCall*/ false); - case 108 /* ThisKeyword */ : + case 110 /* ThisKeyword */ : return visitThisKeyword(node); - case 233 /* MetaProperty */ : + case 236 /* MetaProperty */ : return visitMetaProperty(node); - case 171 /* MethodDeclaration */ : + case 174 /* MethodDeclaration */ : return visitMethodDeclaration(node); - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : return visitAccessorDeclaration(node); - case 240 /* VariableStatement */ : + case 243 /* VariableStatement */ : return visitVariableStatement(node); - case 250 /* ReturnStatement */ : + case 253 /* ReturnStatement */ : return visitReturnStatement(node); - case 219 /* VoidExpression */ : + case 222 /* VoidExpression */ : return visitVoidExpression(node); default: return visitEachChild(node, visitor, context); @@ -80817,25 +82338,25 @@ ${lanes.join("\n")} if (convertedLoopState) { if (resolver.isArgumentsLocalBinding(node)) return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory2.createUniqueName("arguments")); } - if (node.flags & 128 /* IdentifierHasExtendedUnicodeEscape */ ) return setOriginalNode(setTextRange(factory2.createIdentifier(unescapeLeadingUnderscores(node.escapedText)), node), node); + if (node.flags & 256 /* IdentifierHasExtendedUnicodeEscape */ ) return setOriginalNode(setTextRange(factory2.createIdentifier(unescapeLeadingUnderscores(node.escapedText)), node), node); return node; } function visitBreakOrContinueStatement(node) { if (convertedLoopState) { - const jump = node.kind === 249 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */ ; + const jump = node.kind === 252 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */ ; const canUseBreakOrContinue = node.label && convertedLoopState.labels && convertedLoopState.labels.get(idText(node.label)) || !node.label && convertedLoopState.allowedNonLabeledJumps & jump; if (!canUseBreakOrContinue) { let labelMarker; const label = node.label; if (!label) { - if (node.kind === 249 /* BreakStatement */ ) { + if (node.kind === 252 /* BreakStatement */ ) { convertedLoopState.nonLocalJumps |= 2 /* Break */ ; labelMarker = "break"; } else { convertedLoopState.nonLocalJumps |= 4 /* Continue */ ; labelMarker = "continue"; } - } else if (node.kind === 249 /* BreakStatement */ ) { + } else if (node.kind === 252 /* BreakStatement */ ) { labelMarker = `break-${label.escapedText}`; setLabeledJump(convertedLoopState, /*isBreak*/ true, idText(label), labelMarker); } else { @@ -80849,9 +82370,9 @@ ${lanes.join("\n")} for(let i = 0; i < outParams.length; i++){ const copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */ ); if (i === 0) expr = copyExpr; - else expr = factory2.createBinaryExpression(expr, 27 /* CommaToken */ , copyExpr); + else expr = factory2.createBinaryExpression(expr, 28 /* CommaToken */ , copyExpr); } - returnExpression = factory2.createBinaryExpression(expr, 27 /* CommaToken */ , returnExpression); + returnExpression = factory2.createBinaryExpression(expr, 28 /* CommaToken */ , returnExpression); } return factory2.createReturnStatement(returnExpression); } @@ -80874,11 +82395,6 @@ ${lanes.join("\n")} setOriginalNode(exportStatement, statement); statements.push(exportStatement); } - const emitFlags = getEmitFlags(node); - if ((emitFlags & 8388608 /* HasEndOfDeclarationMarker */ ) === 0) { - statements.push(factory2.createEndOfDeclarationMarker(node)); - setEmitFlags(statement, emitFlags | 8388608 /* HasEndOfDeclarationMarker */ ); - } return singleOrMany(statements); } function visitClassExpression(node) { @@ -80911,7 +82427,7 @@ ${lanes.join("\n")} addExtendsHelperIfNeeded(statements, node, extendsClauseElement); addConstructor(statements, node, constructorLikeName, extendsClauseElement); addClassMembers(statements, node); - const closingBraceLocation = createTokenRange(skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */ ); + const closingBraceLocation = createTokenRange(skipTrivia(currentText, node.members.end), 20 /* CloseBraceToken */ ); const outer = factory2.createPartiallyEmittedExpression(constructorLikeName); setTextRangeEnd(outer, closingBraceLocation.end); setEmitFlags(outer, 3072 /* NoComments */ ); @@ -80955,70 +82471,101 @@ ${lanes.join("\n")} setEmitFlags(block, 3072 /* NoComments */ ); return block; } + function transformConstructorBodyWorker(prologueOut, statementsOut, statementsIn, statementOffset, superPath, superPathDepth, constructor, isDerivedClass, hasSynthesizedSuper, isFirstStatement) { + let mayReplaceThis = false; + const superStatementIndex = superPathDepth < superPath.length ? superPath[superPathDepth] : -1; + const leadingStatementsEnd = superStatementIndex >= 0 ? superStatementIndex : statementsIn.length; + if (isFirstStatement && superStatementIndex >= 0) { + let firstMaterialIndex = statementOffset; + while(isFirstStatement && firstMaterialIndex < superStatementIndex){ + const statement = constructor.body.statements[firstMaterialIndex]; + if (!isUninitializedVariableStatement(statement) && !isUsingDeclarationStateVariableStatement(statement)) break; + firstMaterialIndex++; + } + isFirstStatement = superStatementIndex === firstMaterialIndex; + } + addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, statementOffset, leadingStatementsEnd - statementOffset)); + const superStatement = superStatementIndex >= 0 ? statementsIn[superStatementIndex] : void 0; + if (superStatement && isTryStatement(superStatement)) { + const tryBlockStatements = []; + mayReplaceThis = transformConstructorBodyWorker(prologueOut, tryBlockStatements, superStatement.tryBlock.statements, /*statementOffset*/ 0, superPath, superPathDepth + 1, constructor, isDerivedClass, hasSynthesizedSuper, isFirstStatement); + const tryBlockStatementsArray = factory2.createNodeArray(tryBlockStatements); + setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); + statementsOut.push(factory2.updateTryStatement(superStatement, factory2.updateBlock(superStatement.tryBlock, tryBlockStatements), visitNode(superStatement.catchClause, visitor, isCatchClause), visitNode(superStatement.finallyBlock, visitor, isBlock))); + } else { + const superCall = superStatement && getSuperCallFromStatement(superStatement); + let superCallExpression; + if (hasSynthesizedSuper) { + superCallExpression = createDefaultSuperCallOrThis(); + hierarchyFacts |= 8192 /* ConstructorWithCapturedSuper */ ; + } else if (superCall) { + superCallExpression = visitSuperCallInBody(superCall); + hierarchyFacts |= 8192 /* ConstructorWithCapturedSuper */ ; + } + if (isDerivedClass || superCallExpression) { + if (superCallExpression && superStatementIndex === statementsIn.length - 1 && !(constructor.body.transformFlags & 16384 /* ContainsLexicalThis */ )) { + const superCall2 = cast(cast(superCallExpression, isBinaryExpression).left, isCallExpression); + const returnStatement = factory2.createReturnStatement(superCallExpression); + setCommentRange(returnStatement, getCommentRange(superCall2)); + setEmitFlags(superCall2, 3072 /* NoComments */ ); + statementsOut.push(returnStatement); + return false; + } else { + if (isFirstStatement) insertCaptureThisForNode(statementsOut, constructor, superCallExpression || createActualThis()); + else { + insertCaptureThisForNode(prologueOut, constructor, createActualThis()); + if (superCallExpression) addSuperThisCaptureThisForNode(statementsOut, superCallExpression); + } + mayReplaceThis = true; + } + } else insertCaptureThisForNodeIfNeeded(prologueOut, constructor); + } + if (superStatementIndex >= 0) addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, superStatementIndex + 1)); + return mayReplaceThis; + } + function isUninitializedVariableStatement(node) { + return isVariableStatement(node) && every(node.declarationList.declarations, (decl)=>isIdentifier(decl.name) && !decl.initializer); + } + function isUsingDeclarationStateVariableStatement(node) { + if (!isVariableStatement(node) || node.declarationList.declarations.length !== 1) return false; + const varDecl = node.declarationList.declarations[0]; + if (!isIdentifier(varDecl.name) || !varDecl.initializer) return false; + const initializer = varDecl.initializer; + if (!isObjectLiteralExpression(initializer) || initializer.properties.length !== 3) return false; + const [stackProp, errorProp, hasErrorProp] = initializer.properties; + if (!isPropertyAssignment(stackProp) || !isIdentifier(stackProp.name) || idText(stackProp.name) !== "stack" || !isArrayLiteralExpression(stackProp.initializer)) return false; + if (!isPropertyAssignment(errorProp) || !isIdentifier(errorProp.name) || idText(errorProp.name) !== "error" || !isVoidExpression(errorProp.initializer) || !isNumericLiteral(errorProp.initializer.expression)) return false; + if (!isPropertyAssignment(hasErrorProp) || !isIdentifier(hasErrorProp.name) || idText(hasErrorProp.name) !== "hasError" || hasErrorProp.initializer.kind !== 97 /* FalseKeyword */ ) return false; + return true; + } function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { - const isDerivedClass = !!extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 104 /* NullKeyword */ ; + const isDerivedClass = !!extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 106 /* NullKeyword */ ; if (!constructor) return createDefaultConstructorBody(node, isDerivedClass); const prologue = []; const statements = []; resumeLexicalEnvironment(); - const existingPrologue = takeWhile(constructor.body.statements, isPrologueDirective); - const { superCall: superCall , superStatementIndex: superStatementIndex } = findSuperCallAndStatementIndex(constructor.body.statements, existingPrologue); - const postSuperStatementsStart = superStatementIndex === -1 ? existingPrologue.length : superStatementIndex + 1; - let statementOffset = postSuperStatementsStart; - if (!hasSynthesizedSuper) statementOffset = factory2.copyStandardPrologue(constructor.body.statements, prologue, statementOffset, /*ensureUseStrict*/ false); - if (!hasSynthesizedSuper) statementOffset = factory2.copyCustomPrologue(constructor.body.statements, statements, statementOffset, visitor, /*filter*/ void 0); - let superCallExpression; - if (hasSynthesizedSuper) superCallExpression = createDefaultSuperCallOrThis(); - else if (superCall) superCallExpression = visitSuperCallInBody(superCall); - if (superCallExpression) hierarchyFacts |= 8192 /* ConstructorWithCapturedSuper */ ; + const standardPrologueEnd = factory2.copyStandardPrologue(constructor.body.statements, prologue, /*statementOffset*/ 0); + const superStatementIndices = findSuperStatementIndexPath(constructor.body.statements, standardPrologueEnd); + if (hasSynthesizedSuper || superStatementIndices.length > 0) hierarchyFacts |= 8192 /* ConstructorWithCapturedSuper */ ; + const mayReplaceThis = transformConstructorBodyWorker(prologue, statements, constructor.body.statements, standardPrologueEnd, superStatementIndices, /*superPathDepth*/ 0, constructor, isDerivedClass, hasSynthesizedSuper, /*isFirstStatement*/ true); addDefaultValueAssignmentsIfNeeded2(prologue, constructor); addRestParameterIfNeeded(prologue, constructor, hasSynthesizedSuper); - addRange(statements, visitNodes2(constructor.body.statements, visitor, isStatement, /*start*/ statementOffset)); + insertCaptureNewTargetIfNeeded(prologue, constructor); factory2.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); - insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false); - if (isDerivedClass || superCallExpression) { - if (superCallExpression && postSuperStatementsStart === constructor.body.statements.length && !(constructor.body.transformFlags & 16384 /* ContainsLexicalThis */ )) { - const superCall2 = cast(cast(superCallExpression, isBinaryExpression).left, isCallExpression); - const returnStatement = factory2.createReturnStatement(superCallExpression); - setCommentRange(returnStatement, getCommentRange(superCall2)); - setEmitFlags(superCall2, 3072 /* NoComments */ ); - statements.push(returnStatement); - } else { - if (superStatementIndex <= existingPrologue.length) insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis()); - else { - insertCaptureThisForNode(prologue, constructor, createActualThis()); - if (superCallExpression) insertSuperThisCaptureThisForNode(statements, superCallExpression); - } - if (!isSufficientlyCoveredByReturnStatements(constructor.body)) statements.push(factory2.createReturnStatement(factory2.createUniqueName("_this", 48 /* FileLevel */ ))); - } - } else insertCaptureThisForNodeIfNeeded(prologue, constructor); + if (mayReplaceThis && !isSufficientlyCoveredByReturnStatements(constructor.body)) statements.push(factory2.createReturnStatement(factory2.createUniqueName("_this", 48 /* FileLevel */ ))); const body = factory2.createBlock(setTextRange(factory2.createNodeArray([ - ...existingPrologue, ...prologue, - ...superStatementIndex <= existingPrologue.length ? emptyArray : visitNodes2(constructor.body.statements, visitor, isStatement, existingPrologue.length, superStatementIndex - existingPrologue.length), ...statements ]), /*location*/ constructor.body.statements), /*multiLine*/ true); setTextRange(body, constructor.body); return body; } - function findSuperCallAndStatementIndex(originalBodyStatements, existingPrologue) { - for(let i = existingPrologue.length; i < originalBodyStatements.length; i += 1){ - const superCall = getSuperCallFromStatement(originalBodyStatements[i]); - if (superCall) return { - superCall: superCall, - superStatementIndex: i - }; - } - return { - superStatementIndex: -1 - }; - } function isSufficientlyCoveredByReturnStatements(statement) { - if (statement.kind === 250 /* ReturnStatement */ ) return true; - else if (statement.kind === 242 /* IfStatement */ ) { + if (statement.kind === 253 /* ReturnStatement */ ) return true; + else if (statement.kind === 245 /* IfStatement */ ) { const ifStatement = statement; if (ifStatement.elseStatement) return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); - } else if (statement.kind === 238 /* Block */ ) { + } else if (statement.kind === 241 /* Block */ ) { const lastStatement = lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) return true; } @@ -81043,7 +82590,7 @@ ${lanes.join("\n")} if (!some(node.parameters, hasDefaultValueOrBindingPattern)) return false; let added = false; for (const parameter of node.parameters){ - const { name: name , initializer: initializer , dotDotDotToken: dotDotDotToken } = parameter; + const { name: name, initializer: initializer, dotDotDotToken: dotDotDotToken } = parameter; if (dotDotDotToken) continue; if (isBindingPattern(name)) added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added; else if (initializer) { @@ -81081,9 +82628,9 @@ ${lanes.join("\n")} const prologueStatements = []; const parameter = lastOrUndefined(node.parameters); if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) return false; - const declarationName = parameter.name.kind === 79 /* Identifier */ ? setParent(setTextRange(factory2.cloneNode(parameter.name), parameter.name), parameter.name.parent) : factory2.createTempVariable(/*recordTempVariable*/ void 0); + const declarationName = parameter.name.kind === 80 /* Identifier */ ? setParent(setTextRange(factory2.cloneNode(parameter.name), parameter.name), parameter.name.parent) : factory2.createTempVariable(/*recordTempVariable*/ void 0); setEmitFlags(declarationName, 96 /* NoSourceMap */ ); - const expressionName = parameter.name.kind === 79 /* Identifier */ ? factory2.cloneNode(parameter.name) : declarationName; + const expressionName = parameter.name.kind === 80 /* Identifier */ ? factory2.cloneNode(parameter.name) : declarationName; const restIndex = node.parameters.length - 1; const temp = factory2.createLoopVariable(); prologueStatements.push(setEmitFlags(setTextRange(factory2.createVariableStatement(/*modifiers*/ void 0, factory2.createVariableDeclarationList([ @@ -81097,21 +82644,21 @@ ${lanes.join("\n")} setEmitFlags(forStatement, 2097152 /* CustomPrologue */ ); startOnNewLine(forStatement); prologueStatements.push(forStatement); - if (parameter.name.kind !== 79 /* Identifier */ ) prologueStatements.push(setEmitFlags(setTextRange(factory2.createVariableStatement(/*modifiers*/ void 0, factory2.createVariableDeclarationList(flattenDestructuringBinding(parameter, visitor, context, 0 /* All */ , expressionName))), parameter), 2097152 /* CustomPrologue */ )); + if (parameter.name.kind !== 80 /* Identifier */ ) prologueStatements.push(setEmitFlags(setTextRange(factory2.createVariableStatement(/*modifiers*/ void 0, factory2.createVariableDeclarationList(flattenDestructuringBinding(parameter, visitor, context, 0 /* All */ , expressionName))), parameter), 2097152 /* CustomPrologue */ )); insertStatementsAfterCustomPrologue(statements, prologueStatements); return true; } function insertCaptureThisForNodeIfNeeded(statements, node) { - if (hierarchyFacts & 65536 /* CapturedLexicalThis */ && node.kind !== 216 /* ArrowFunction */ ) { + if (hierarchyFacts & 65536 /* CapturedLexicalThis */ && node.kind !== 219 /* ArrowFunction */ ) { insertCaptureThisForNode(statements, node, factory2.createThis()); return true; } return false; } - function insertSuperThisCaptureThisForNode(statements, superExpression) { + function addSuperThisCaptureThisForNode(statements, superExpression) { enableSubstitutionsForCapturedThis(); - const assignSuperExpression = factory2.createExpressionStatement(factory2.createBinaryExpression(factory2.createThis(), 63 /* EqualsToken */ , superExpression)); - insertStatementAfterCustomPrologue(statements, assignSuperExpression); + const assignSuperExpression = factory2.createExpressionStatement(factory2.createBinaryExpression(factory2.createThis(), 64 /* EqualsToken */ , superExpression)); + statements.push(assignSuperExpression); setCommentRange(assignSuperExpression, getOriginalNode(superExpression).parent); } function insertCaptureThisForNode(statements, node, initializer) { @@ -81123,23 +82670,23 @@ ${lanes.join("\n")} setSourceMapRange(captureThisStatement, node); insertStatementAfterCustomPrologue(statements, captureThisStatement); } - function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) { + function insertCaptureNewTargetIfNeeded(statements, node) { if (hierarchyFacts & 32768 /* NewTarget */ ) { let newTarget; switch(node.kind){ - case 216 /* ArrowFunction */ : + case 219 /* ArrowFunction */ : return statements; - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : newTarget = factory2.createVoidZero(); break; - case 173 /* Constructor */ : + case 176 /* Constructor */ : newTarget = factory2.createPropertyAccessExpression(setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */ ), "constructor"); break; - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - newTarget = factory2.createConditionalExpression(factory2.createLogicalAnd(setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */ ), factory2.createBinaryExpression(setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */ ), 102 /* InstanceOfKeyword */ , factory2.getLocalName(node))), /*questionToken*/ void 0, factory2.createPropertyAccessExpression(setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */ ), "constructor"), /*colonToken*/ void 0, factory2.createVoidZero()); + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + newTarget = factory2.createConditionalExpression(factory2.createLogicalAnd(setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */ ), factory2.createBinaryExpression(setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */ ), 104 /* InstanceOfKeyword */ , factory2.getLocalName(node))), /*questionToken*/ void 0, factory2.createPropertyAccessExpression(setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */ ), "constructor"), /*colonToken*/ void 0, factory2.createVoidZero()); break; default: return Debug.failBadSyntaxKind(node); @@ -81148,26 +82695,25 @@ ${lanes.join("\n")} factory2.createVariableDeclaration(factory2.createUniqueName("_newTarget", 48 /* FileLevel */ ), /*exclamationToken*/ void 0, /*type*/ void 0, newTarget) ])); setEmitFlags(captureNewTargetStatement, 2100224 /* CustomPrologue */ ); - if (copyOnWrite) statements = statements.slice(); insertStatementAfterCustomPrologue(statements, captureNewTargetStatement); } return statements; } function addClassMembers(statements, node) { for (const member of node.members)switch(member.kind){ - case 237 /* SemicolonClassElement */ : + case 240 /* SemicolonClassElement */ : statements.push(transformSemicolonClassElementToStatement(member)); break; - case 171 /* MethodDeclaration */ : + case 174 /* MethodDeclaration */ : statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); break; - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : const accessors = getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); break; - case 173 /* Constructor */ : - case 172 /* ClassStaticBlockDeclaration */ : + case 176 /* Constructor */ : + case 175 /* ClassStaticBlockDeclaration */ : break; default: Debug.failBadSyntaxKind(member, currentSourceFile && currentSourceFile.fileName); @@ -81210,7 +82756,7 @@ ${lanes.join("\n")} setSourceMapRange(statement, getSourceMapRange(accessors.firstAccessor)); return statement; } - function transformAccessorsToExpression(receiver, { firstAccessor: firstAccessor , getAccessor: getAccessor , setAccessor: setAccessor }, container, startsOnNewLine) { + function transformAccessorsToExpression(receiver, { firstAccessor: firstAccessor, getAccessor: getAccessor, setAccessor: setAccessor }, container, startsOnNewLine) { const target = setParent(setTextRange(factory2.cloneNode(receiver), receiver), receiver.parent); setEmitFlags(target, 3136 /* NoTrailingSourceMap */ ); setSourceMapRange(target, firstAccessor.name); @@ -81287,7 +82833,7 @@ ${lanes.join("\n")} const ancestorFacts = container && isClassLike(container) && !isStatic(node) ? enterSubtree(32670 /* FunctionExcludes */ , 73 /* NonStaticClassElement */ ) : enterSubtree(32670 /* FunctionExcludes */ , 65 /* FunctionIncludes */ ); const parameters = visitParameterList(node.parameters, visitor, context); const body = transformFunctionBody2(node); - if (hierarchyFacts & 32768 /* NewTarget */ && !name && (node.kind === 259 /* FunctionDeclaration */ || node.kind === 215 /* FunctionExpression */ )) name = factory2.getGeneratedNameForNode(node); + if (hierarchyFacts & 32768 /* NewTarget */ && !name && (node.kind === 262 /* FunctionDeclaration */ || node.kind === 218 /* FunctionExpression */ )) name = factory2.getGeneratedNameForNode(node); exitSubtree(ancestorFacts, 98304 /* FunctionSubtreeExcludes */ , 0 /* None */ ); convertedLoopState = savedConvertedLoopState; return setOriginalNode(setTextRange(factory2.createFunctionExpression(/*modifiers*/ void 0, node.asteriskToken, name, /*typeParameters*/ void 0, parameters, /*type*/ void 0, body), location), /*original*/ node); @@ -81315,7 +82861,7 @@ ${lanes.join("\n")} addRange(statements, visitNodes2(body.statements, visitor, isStatement, statementOffset)); if (!multiLine && body.multiLine) multiLine = true; } else { - Debug.assert(node.kind === 216 /* ArrowFunction */ ); + Debug.assert(node.kind === 219 /* ArrowFunction */ ); statementsLocation = moveRangeEnd(body, -1); const equalsGreaterThanToken = node.equalsGreaterThanToken; if (!nodeIsSynthesized(equalsGreaterThanToken) && !nodeIsSynthesized(body)) { @@ -81331,7 +82877,7 @@ ${lanes.join("\n")} closeBraceLocation = body; } factory2.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); - insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false); + insertCaptureNewTargetIfNeeded(prologue, node); insertCaptureThisForNodeIfNeeded(prologue, node); if (some(prologue)) multiLine = true; statements.unshift(...prologue); @@ -81339,7 +82885,7 @@ ${lanes.join("\n")} const block = factory2.createBlock(setTextRange(factory2.createNodeArray(statements), statementsLocation), multiLine); setTextRange(block, node.body); if (!multiLine && singleLine) setEmitFlags(block, 1 /* SingleLine */ ); - if (closeBraceLocation) setTokenSourceMapRange(block, 19 /* CloseBraceToken */ , closeBraceLocation); + if (closeBraceLocation) setTokenSourceMapRange(block, 20 /* CloseBraceToken */ , closeBraceLocation); setOriginalNode(block, node.body); return block; } @@ -81358,7 +82904,7 @@ ${lanes.join("\n")} } function visitBinaryExpression(node, expressionResultIsUnused2) { if (isDestructuringAssignment(node)) return flattenDestructuringAssignment(node, visitor, context, 0 /* All */ , !expressionResultIsUnused2); - if (node.operatorToken.kind === 27 /* CommaToken */ ) return factory2.updateBinaryExpression(node, Debug.checkDefined(visitNode(node.left, visitorWithUnusedExpressionResult, isExpression)), node.operatorToken, Debug.checkDefined(visitNode(node.right, expressionResultIsUnused2 ? visitorWithUnusedExpressionResult : visitor, isExpression))); + if (node.operatorToken.kind === 28 /* CommaToken */ ) return factory2.updateBinaryExpression(node, Debug.checkDefined(visitNode(node.left, visitorWithUnusedExpressionResult, isExpression)), node.operatorToken, Debug.checkDefined(visitNode(node.right, expressionResultIsUnused2 ? visitorWithUnusedExpressionResult : visitor, isExpression))); return visitEachChild(node, visitor, context); } function visitCommaListExpression(node, expressionResultIsUnused2) { @@ -81382,7 +82928,7 @@ ${lanes.join("\n")} function visitVariableStatement(node) { const ancestorFacts = enterSubtree(0 /* None */ , hasSyntacticModifier(node, 1 /* Export */ ) ? 32 /* ExportedVariableStatement */ : 0 /* None */ ); let updated; - if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */ ) === 0 && !isVariableStatementOfTypeScriptClassWrapper(node)) { + if (convertedLoopState && (node.declarationList.flags & 7 /* BlockScoped */ ) === 0 && !isVariableStatementOfTypeScriptClassWrapper(node)) { let assignments; for (const decl of node.declarationList.declarations){ hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl); @@ -81390,7 +82936,7 @@ ${lanes.join("\n")} let assignment; if (isBindingPattern(decl.name)) assignment = flattenDestructuringAssignment(decl, visitor, context, 0 /* All */ ); else { - assignment = factory2.createBinaryExpression(decl.name, 63 /* EqualsToken */ , Debug.checkDefined(visitNode(decl.initializer, visitor, isExpression))); + assignment = factory2.createBinaryExpression(decl.name, 64 /* EqualsToken */ , Debug.checkDefined(visitNode(decl.initializer, visitor, isExpression))); setTextRange(assignment, decl); } assignments = append(assignments, assignment); @@ -81403,8 +82949,8 @@ ${lanes.join("\n")} return updated; } function visitVariableDeclarationList(node) { - if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 524288 /* ContainsBindingPattern */ ) { - if (node.flags & 3 /* BlockScoped */ ) enableSubstitutionsForBlockScopedBindings(); + if (node.flags & 7 /* BlockScoped */ || node.transformFlags & 524288 /* ContainsBindingPattern */ ) { + if (node.flags & 7 /* BlockScoped */ ) enableSubstitutionsForBlockScopedBindings(); const declarations = visitNodes2(node.declarations, node.flags & 1 /* Let */ ? visitVariableDeclarationInLetDeclarationList : visitVariableDeclaration, isVariableDeclaration); const declarationList = factory2.createVariableDeclarationList(declarations); setOriginalNode(declarationList, node); @@ -81440,7 +82986,7 @@ ${lanes.join("\n")} function visitVariableDeclaration(node) { const ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */ , 0 /* None */ ); let updated; - if (isBindingPattern(node.name)) updated = flattenDestructuringBinding(node, visitor, context, 0 /* All */ , /*value*/ void 0, (ancestorFacts & 32 /* ExportedVariableStatement */ ) !== 0); + if (isBindingPattern(node.name)) updated = flattenDestructuringBinding(node, visitor, context, 0 /* All */ , /*rval*/ void 0, (ancestorFacts & 32 /* ExportedVariableStatement */ ) !== 0); else updated = visitEachChild(node, visitor, context); exitSubtree(ancestorFacts, 0 /* None */ , 0 /* None */ ); return updated; @@ -81458,14 +83004,14 @@ ${lanes.join("\n")} } function visitIterationStatement(node, outermostLabeledStatement) { switch(node.kind){ - case 243 /* DoStatement */ : - case 244 /* WhileStatement */ : + case 246 /* DoStatement */ : + case 247 /* WhileStatement */ : return visitDoOrWhileStatement(node, outermostLabeledStatement); - case 245 /* ForStatement */ : + case 248 /* ForStatement */ : return visitForStatement(node, outermostLabeledStatement); - case 246 /* ForInStatement */ : + case 249 /* ForInStatement */ : return visitForInStatement(node, outermostLabeledStatement); - case 247 /* ForOfStatement */ : + case 250 /* ForOfStatement */ : return visitForOfStatement(node, outermostLabeledStatement); } } @@ -81494,7 +83040,7 @@ ${lanes.join("\n")} const statements = []; const initializer = node.initializer; if (isVariableDeclarationList(initializer)) { - if (node.initializer.flags & 3 /* BlockScoped */ ) enableSubstitutionsForBlockScopedBindings(); + if (node.initializer.flags & 7 /* BlockScoped */ ) enableSubstitutionsForBlockScopedBindings(); const firstOriginalDeclaration = firstOrUndefined(initializer.declarations); if (firstOriginalDeclaration && isBindingPattern(firstOriginalDeclaration.name)) { const declarations = flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */ , boundValue); @@ -81580,7 +83126,7 @@ ${lanes.join("\n")} let numInitialProperties = -1, hasComputed = false; for(let i = 0; i < properties.length; i++){ const property = properties[i]; - if (property.transformFlags & 1048576 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */ || (hasComputed = Debug.checkDefined(property.name).kind === 164 /* ComputedPropertyName */ )) { + if (property.transformFlags & 1048576 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */ || (hasComputed = Debug.checkDefined(property.name).kind === 167 /* ComputedPropertyName */ )) { numInitialProperties = i; break; } @@ -81617,7 +83163,7 @@ ${lanes.join("\n")} if (!state.hoistedLocalVariables) state.hoistedLocalVariables = []; visit(node.name); function visit(node2) { - if (node2.kind === 79 /* Identifier */ ) state.hoistedLocalVariables.push(node2); + if (node2.kind === 80 /* Identifier */ ) state.hoistedLocalVariables.push(node2); else { for (const element of node2.elements)if (!isOmittedExpression(element)) visit(element.name); } @@ -81661,15 +83207,15 @@ ${lanes.join("\n")} } function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { switch(node.kind){ - case 245 /* ForStatement */ : + case 248 /* ForStatement */ : return convertForStatement(node, initializerFunction, convertedLoopBody); - case 246 /* ForInStatement */ : + case 249 /* ForInStatement */ : return convertForInStatement(node, convertedLoopBody); - case 247 /* ForOfStatement */ : + case 250 /* ForOfStatement */ : return convertForOfStatement(node, convertedLoopBody); - case 243 /* DoStatement */ : + case 246 /* DoStatement */ : return convertDoStatement(node, convertedLoopBody); - case 244 /* WhileStatement */ : + case 247 /* WhileStatement */ : return convertWhileStatement(node, convertedLoopBody); default: return Debug.failBadSyntaxKind(node, "IterationStatement expected"); @@ -81695,16 +83241,16 @@ ${lanes.join("\n")} function createConvertedLoopState(node) { let loopInitializer; switch(node.kind){ - case 245 /* ForStatement */ : - case 246 /* ForInStatement */ : - case 247 /* ForOfStatement */ : + case 248 /* ForStatement */ : + case 249 /* ForInStatement */ : + case 250 /* ForOfStatement */ : const initializer = node.initializer; - if (initializer && initializer.kind === 258 /* VariableDeclarationList */ ) loopInitializer = initializer; + if (initializer && initializer.kind === 261 /* VariableDeclarationList */ ) loopInitializer = initializer; break; } const loopParameters = []; const loopOutParameters = []; - if (loopInitializer && getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */ ) { + if (loopInitializer && getCombinedNodeFlags(loopInitializer) & 7 /* BlockScoped */ ) { const hasCapturedBindingsInForHead = shouldConvertInitializerOfForStatement(node) || shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node); for (const decl of loopInitializer.declarations)processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForHead); } @@ -81759,7 +83305,7 @@ ${lanes.join("\n")} statements.push(factory2.createVariableStatement(/*modifiers*/ void 0, node.initializer)); copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */ , 1 /* ToOutParameter */ , statements); const functionDeclaration = factory2.createVariableStatement(/*modifiers*/ void 0, setEmitFlags(factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration(functionName, /*exclamationToken*/ void 0, /*type*/ void 0, setEmitFlags(factory2.createFunctionExpression(/*modifiers*/ void 0, containsYield ? factory2.createToken(41 /* AsteriskToken */ ) : void 0, /*name*/ void 0, /*typeParameters*/ void 0, /*parameters*/ void 0, /*type*/ void 0, Debug.checkDefined(visitNode(factory2.createBlock(statements, /*multiLine*/ true), visitor, isBlock))), emitFlags)) + factory2.createVariableDeclaration(functionName, /*exclamationToken*/ void 0, /*type*/ void 0, setEmitFlags(factory2.createFunctionExpression(/*modifiers*/ void 0, containsYield ? factory2.createToken(42 /* AsteriskToken */ ) : void 0, /*name*/ void 0, /*typeParameters*/ void 0, /*parameters*/ void 0, /*type*/ void 0, Debug.checkDefined(visitNode(factory2.createBlock(statements, /*multiLine*/ true), visitor, isBlock))), emitFlags)) ]), 4194304 /* NoHoisting */ )); const part = factory2.createVariableDeclarationList(map(currentState.loopOutParameters, createOutVariable)); return { @@ -81779,7 +83325,7 @@ ${lanes.join("\n")} currentState.conditionVariable = factory2.createUniqueName("inc"); if (node.incrementor) statements.push(factory2.createIfStatement(currentState.conditionVariable, factory2.createExpressionStatement(Debug.checkDefined(visitNode(node.incrementor, visitor, isExpression))), factory2.createExpressionStatement(factory2.createAssignment(currentState.conditionVariable, factory2.createTrue())))); else statements.push(factory2.createIfStatement(factory2.createLogicalNot(currentState.conditionVariable), factory2.createExpressionStatement(factory2.createAssignment(currentState.conditionVariable, factory2.createTrue())))); - if (shouldConvertConditionOfForStatement(node)) statements.push(factory2.createIfStatement(factory2.createPrefixUnaryExpression(53 /* ExclamationToken */ , Debug.checkDefined(visitNode(node.condition, visitor, isExpression))), Debug.checkDefined(visitNode(factory2.createBreakStatement(), visitor, isStatement)))); + if (shouldConvertConditionOfForStatement(node)) statements.push(factory2.createIfStatement(factory2.createPrefixUnaryExpression(54 /* ExclamationToken */ , Debug.checkDefined(visitNode(node.condition, visitor, isExpression))), Debug.checkDefined(visitNode(factory2.createBreakStatement(), visitor, isStatement)))); } Debug.assert(statement); if (isBlock(statement)) addRange(statements, statement.statements); @@ -81793,7 +83339,7 @@ ${lanes.join("\n")} if (currentState.containsLexicalThis) emitFlags |= 16 /* CapturesThis */ ; if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */ ) !== 0) emitFlags |= 524288 /* AsyncFunctionBody */ ; const functionDeclaration = factory2.createVariableStatement(/*modifiers*/ void 0, setEmitFlags(factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration(functionName, /*exclamationToken*/ void 0, /*type*/ void 0, setEmitFlags(factory2.createFunctionExpression(/*modifiers*/ void 0, containsYield ? factory2.createToken(41 /* AsteriskToken */ ) : void 0, /*name*/ void 0, /*typeParameters*/ void 0, currentState.loopParameters, /*type*/ void 0, loopBody), emitFlags)) + factory2.createVariableDeclaration(functionName, /*exclamationToken*/ void 0, /*type*/ void 0, setEmitFlags(factory2.createFunctionExpression(/*modifiers*/ void 0, containsYield ? factory2.createToken(42 /* AsteriskToken */ ) : void 0, /*name*/ void 0, /*typeParameters*/ void 0, currentState.loopParameters, /*type*/ void 0, loopBody), emitFlags)) ]), 4194304 /* NoHoisting */ )); const part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); return { @@ -81806,21 +83352,21 @@ ${lanes.join("\n")} function copyOutParameter(outParam, copyDirection) { const source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; const target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; - return factory2.createBinaryExpression(target, 63 /* EqualsToken */ , source); + return factory2.createBinaryExpression(target, 64 /* EqualsToken */ , source); } function copyOutParameters(outParams, partFlags, copyDirection, statements) { for (const outParam of outParams)if (outParam.flags & partFlags) statements.push(factory2.createExpressionStatement(copyOutParameter(outParam, copyDirection))); } function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { const call = factory2.createCallExpression(initFunctionExpressionName, /*typeArguments*/ void 0, []); - const callResult = containsYield ? factory2.createYieldExpression(factory2.createToken(41 /* AsteriskToken */ ), setEmitFlags(call, 16777216 /* Iterator */ )) : call; + const callResult = containsYield ? factory2.createYieldExpression(factory2.createToken(42 /* AsteriskToken */ ), setEmitFlags(call, 8388608 /* Iterator */ )) : call; return factory2.createExpressionStatement(callResult); } function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { const statements = []; const isSimpleLoop = !(state.nonLocalJumps & -5 /* Continue */ ) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; const call = factory2.createCallExpression(loopFunctionExpressionName, /*typeArguments*/ void 0, map(state.loopParameters, (p)=>p.name)); - const callResult = containsYield ? factory2.createYieldExpression(factory2.createToken(41 /* AsteriskToken */ ), setEmitFlags(call, 16777216 /* Iterator */ )) : call; + const callResult = containsYield ? factory2.createYieldExpression(factory2.createToken(42 /* AsteriskToken */ ), setEmitFlags(call, 8388608 /* Iterator */ )) : call; if (isSimpleLoop) { statements.push(factory2.createExpressionStatement(callResult)); copyOutParameters(state.loopOutParameters, 1 /* Body */ , 0 /* ToOriginal */ , statements); @@ -81879,10 +83425,10 @@ ${lanes.join("\n")} } else { loopParameters.push(factory2.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, name)); const checkFlags = resolver.getNodeCheckFlags(decl); - if (checkFlags & 262144 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForHead) { + if (checkFlags & 65536 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForHead) { const outParamName = factory2.createUniqueName("out_" + idText(name)); let flags = 0 /* None */ ; - if (checkFlags & 262144 /* NeedsLoopOutParameter */ ) flags |= 1 /* Body */ ; + if (checkFlags & 65536 /* NeedsLoopOutParameter */ ) flags |= 1 /* Body */ ; if (isForStatement(container)) { if (container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) flags |= 2 /* Initializer */ ; if (container.condition && resolver.isBindingCapturedByNode(container.condition, decl) || container.incrementor && resolver.isBindingCapturedByNode(container.incrementor, decl)) flags |= 1 /* Body */ ; @@ -81901,18 +83447,18 @@ ${lanes.join("\n")} for(let i = start; i < numProperties; i++){ const property = properties[i]; switch(property.kind){ - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : const accessors = getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); break; - case 171 /* MethodDeclaration */ : + case 174 /* MethodDeclaration */ : expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; - case 299 /* PropertyAssignment */ : + case 303 /* PropertyAssignment */ : expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 300 /* ShorthandPropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: @@ -81977,7 +83523,7 @@ ${lanes.join("\n")} let updated; const parameters = visitParameterList(node.parameters, visitor, context); const body = transformFunctionBody2(node); - if (node.kind === 174 /* GetAccessor */ ) updated = factory2.updateGetAccessorDeclaration(node, node.modifiers, node.name, parameters, node.type, body); + if (node.kind === 177 /* GetAccessor */ ) updated = factory2.updateGetAccessorDeclaration(node, node.modifiers, node.name, parameters, node.type, body); else updated = factory2.updateSetAccessorDeclaration(node, node.modifiers, node.name, parameters, body); exitSubtree(ancestorFacts, 98304 /* FunctionSubtreeExcludes */ , 0 /* None */ ); convertedLoopState = savedConvertedLoopState; @@ -81999,7 +83545,7 @@ ${lanes.join("\n")} function visitCallExpression(node) { if (getInternalEmitFlags(node) & 1 /* TypeScriptClassWrapper */ ) return visitTypeScriptClassWrapper(node); const expression = skipOuterExpressions(node.expression); - if (expression.kind === 106 /* SuperKeyword */ || isSuperProperty(expression) || some(node.arguments, isSpreadElement)) return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); + if (expression.kind === 108 /* SuperKeyword */ || isSuperProperty(expression) || some(node.arguments, isSpreadElement)) return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); return factory2.updateCallExpression(node, Debug.checkDefined(visitNode(node.expression, callExpressionVisitor, isExpression)), /*typeArguments*/ void 0, visitNodes2(node.arguments, visitor, isExpression)); } function visitTypeScriptClassWrapper(node) { @@ -82015,7 +83561,7 @@ ${lanes.join("\n")} const variable = varStatement.declarationList.declarations[0]; const initializer = skipOuterExpressions(variable.initializer); let aliasAssignment = tryCast(initializer, isAssignmentExpression); - if (!aliasAssignment && isBinaryExpression(initializer) && initializer.operatorToken.kind === 27 /* CommaToken */ ) aliasAssignment = tryCast(initializer.left, isAssignmentExpression); + if (!aliasAssignment && isBinaryExpression(initializer) && initializer.operatorToken.kind === 28 /* CommaToken */ ) aliasAssignment = tryCast(initializer.left, isAssignmentExpression); const call = cast(aliasAssignment ? skipOuterExpressions(aliasAssignment.right) : initializer, isCallExpression); const func = cast(skipOuterExpressions(call.expression), isFunctionExpression); const funcStatements = func.body.statements; @@ -82045,13 +83591,13 @@ ${lanes.join("\n")} return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false); } function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { - if (node.transformFlags & 32768 /* ContainsRestOrSpread */ || node.expression.kind === 106 /* SuperKeyword */ || isSuperProperty(skipOuterExpressions(node.expression))) { - const { target: target , thisArg: thisArg } = factory2.createCallBinding(node.expression, hoistVariableDeclaration); - if (node.expression.kind === 106 /* SuperKeyword */ ) setEmitFlags(thisArg, 8 /* NoSubstitution */ ); + if (node.transformFlags & 32768 /* ContainsRestOrSpread */ || node.expression.kind === 108 /* SuperKeyword */ || isSuperProperty(skipOuterExpressions(node.expression))) { + const { target: target, thisArg: thisArg } = factory2.createCallBinding(node.expression, hoistVariableDeclaration); + if (node.expression.kind === 108 /* SuperKeyword */ ) setEmitFlags(thisArg, 8 /* NoSubstitution */ ); let resultingCall; - if (node.transformFlags & 32768 /* ContainsRestOrSpread */ ) resultingCall = factory2.createFunctionApplyCall(Debug.checkDefined(visitNode(target, callExpressionVisitor, isExpression)), node.expression.kind === 106 /* SuperKeyword */ ? thisArg : Debug.checkDefined(visitNode(thisArg, visitor, isExpression)), transformAndSpreadElements(node.arguments, /*isArgumentList*/ true, /*multiLine*/ false, /*hasTrailingComma*/ false)); - else resultingCall = setTextRange(factory2.createFunctionCallCall(Debug.checkDefined(visitNode(target, callExpressionVisitor, isExpression)), node.expression.kind === 106 /* SuperKeyword */ ? thisArg : Debug.checkDefined(visitNode(thisArg, visitor, isExpression)), visitNodes2(node.arguments, visitor, isExpression)), node); - if (node.expression.kind === 106 /* SuperKeyword */ ) { + if (node.transformFlags & 32768 /* ContainsRestOrSpread */ ) resultingCall = factory2.createFunctionApplyCall(Debug.checkDefined(visitNode(target, callExpressionVisitor, isExpression)), node.expression.kind === 108 /* SuperKeyword */ ? thisArg : Debug.checkDefined(visitNode(thisArg, visitor, isExpression)), transformAndSpreadElements(node.arguments, /*isArgumentList*/ true, /*multiLine*/ false, /*hasTrailingComma*/ false)); + else resultingCall = setTextRange(factory2.createFunctionCallCall(Debug.checkDefined(visitNode(target, callExpressionVisitor, isExpression)), node.expression.kind === 108 /* SuperKeyword */ ? thisArg : Debug.checkDefined(visitNode(thisArg, visitor, isExpression)), visitNodes2(node.arguments, visitor, isExpression)), node); + if (node.expression.kind === 108 /* SuperKeyword */ ) { const initializer = factory2.createLogicalOr(resultingCall, createActualThis()); resultingCall = assignToCapturedThis ? factory2.createAssignment(factory2.createUniqueName("_this", 48 /* FileLevel */ ), initializer) : initializer; } @@ -82061,7 +83607,7 @@ ${lanes.join("\n")} } function visitNewExpression(node) { if (some(node.arguments, isSpreadElement)) { - const { target: target , thisArg: thisArg } = factory2.createCallBinding(factory2.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration); + const { target: target, thisArg: thisArg } = factory2.createCallBinding(factory2.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration); return factory2.createNewExpression(factory2.createFunctionApplyCall(Debug.checkDefined(visitNode(target, visitor, isExpression)), thisArg, transformAndSpreadElements(factory2.createNodeArray([ factory2.createVoidZero(), ...node.arguments @@ -82142,7 +83688,7 @@ ${lanes.join("\n")} return hierarchyFacts & 8 /* NonStaticClassElement */ && !isExpressionOfCall ? factory2.createPropertyAccessExpression(factory2.createUniqueName("_super", 48 /* FileLevel */ ), "prototype") : factory2.createUniqueName("_super", 48 /* FileLevel */ ); } function visitMetaProperty(node) { - if (node.keywordToken === 103 /* NewKeyword */ && node.name.escapedText === "target") { + if (node.keywordToken === 105 /* NewKeyword */ && node.name.escapedText === "target") { hierarchyFacts |= 32768 /* NewTarget */ ; return factory2.createUniqueName("_newTarget", 48 /* FileLevel */ ); } @@ -82160,20 +83706,20 @@ ${lanes.join("\n")} function enableSubstitutionsForBlockScopedBindings() { if ((enabledSubstitutions & 2 /* BlockScopedBindings */ ) === 0) { enabledSubstitutions |= 2 /* BlockScopedBindings */ ; - context.enableSubstitution(79 /* Identifier */ ); + context.enableSubstitution(80 /* Identifier */ ); } } function enableSubstitutionsForCapturedThis() { if ((enabledSubstitutions & 1 /* CapturedThis */ ) === 0) { enabledSubstitutions |= 1 /* CapturedThis */ ; - context.enableSubstitution(108 /* ThisKeyword */ ); - context.enableEmitNotification(173 /* Constructor */ ); - context.enableEmitNotification(171 /* MethodDeclaration */ ); - context.enableEmitNotification(174 /* GetAccessor */ ); - context.enableEmitNotification(175 /* SetAccessor */ ); - context.enableEmitNotification(216 /* ArrowFunction */ ); - context.enableEmitNotification(215 /* FunctionExpression */ ); - context.enableEmitNotification(259 /* FunctionDeclaration */ ); + context.enableSubstitution(110 /* ThisKeyword */ ); + context.enableEmitNotification(176 /* Constructor */ ); + context.enableEmitNotification(174 /* MethodDeclaration */ ); + context.enableEmitNotification(177 /* GetAccessor */ ); + context.enableEmitNotification(178 /* SetAccessor */ ); + context.enableEmitNotification(219 /* ArrowFunction */ ); + context.enableEmitNotification(218 /* FunctionExpression */ ); + context.enableEmitNotification(262 /* FunctionDeclaration */ ); } } function onSubstituteNode(hint, node) { @@ -82191,19 +83737,19 @@ ${lanes.join("\n")} } function isNameOfDeclarationWithCollidingName(node) { switch(node.parent.kind){ - case 205 /* BindingElement */ : - case 260 /* ClassDeclaration */ : - case 263 /* EnumDeclaration */ : - case 257 /* VariableDeclaration */ : + case 208 /* BindingElement */ : + case 263 /* ClassDeclaration */ : + case 266 /* EnumDeclaration */ : + case 260 /* VariableDeclaration */ : return node.parent.name === node && resolver.isDeclarationWithCollidingName(node.parent); } return false; } function substituteExpression(node) { switch(node.kind){ - case 79 /* Identifier */ : + case 80 /* Identifier */ : return substituteExpressionIdentifier(node); - case 108 /* ThisKeyword */ : + case 110 /* ThisKeyword */ : return substituteThisKeyword(node); } return node; @@ -82237,13 +83783,13 @@ ${lanes.join("\n")} if (!constructor || !hasExtendsClause) return false; if (some(constructor.parameters)) return false; const statement = firstOrUndefined(constructor.body.statements); - if (!statement || !nodeIsSynthesized(statement) || statement.kind !== 241 /* ExpressionStatement */ ) return false; + if (!statement || !nodeIsSynthesized(statement) || statement.kind !== 244 /* ExpressionStatement */ ) return false; const statementExpression = statement.expression; - if (!nodeIsSynthesized(statementExpression) || statementExpression.kind !== 210 /* CallExpression */ ) return false; + if (!nodeIsSynthesized(statementExpression) || statementExpression.kind !== 213 /* CallExpression */ ) return false; const callTarget = statementExpression.expression; - if (!nodeIsSynthesized(callTarget) || callTarget.kind !== 106 /* SuperKeyword */ ) return false; + if (!nodeIsSynthesized(callTarget) || callTarget.kind !== 108 /* SuperKeyword */ ) return false; const callArgument = singleOrUndefined(statementExpression.arguments); - if (!callArgument || !nodeIsSynthesized(callArgument) || callArgument.kind !== 227 /* SpreadElement */ ) return false; + if (!callArgument || !nodeIsSynthesized(callArgument) || callArgument.kind !== 230 /* SpreadElement */ ) return false; const expression = callArgument.expression; return isIdentifier(expression) && expression.escapedText === "arguments"; } @@ -82256,31 +83802,31 @@ ${lanes.join("\n")} }); // src/compiler/transformers/es5.ts function transformES5(context) { - const { factory: factory2 } = context; + const { factory: factory2 } = context; const compilerOptions = context.getCompilerOptions(); let previousOnEmitNode; let noSubstitution; if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */ ) { previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; - context.enableEmitNotification(283 /* JsxOpeningElement */ ); - context.enableEmitNotification(284 /* JsxClosingElement */ ); - context.enableEmitNotification(282 /* JsxSelfClosingElement */ ); + context.enableEmitNotification(286 /* JsxOpeningElement */ ); + context.enableEmitNotification(287 /* JsxClosingElement */ ); + context.enableEmitNotification(285 /* JsxSelfClosingElement */ ); noSubstitution = []; } const previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(208 /* PropertyAccessExpression */ ); - context.enableSubstitution(299 /* PropertyAssignment */ ); + context.enableSubstitution(211 /* PropertyAccessExpression */ ); + context.enableSubstitution(303 /* PropertyAssignment */ ); return chainBundle(context, transformSourceFile); function transformSourceFile(node) { return node; } function onEmitNode(hint, node, emitCallback) { switch(node.kind){ - case 283 /* JsxOpeningElement */ : - case 284 /* JsxClosingElement */ : - case 282 /* JsxSelfClosingElement */ : + case 286 /* JsxOpeningElement */ : + case 287 /* JsxClosingElement */ : + case 285 /* JsxSelfClosingElement */ : const tagName = node.tagName; noSubstitution[getOriginalNodeId(tagName)] = true; break; @@ -82307,7 +83853,7 @@ ${lanes.join("\n")} } function trySubstituteReservedName(name) { const token = identifierToKeywordKind(name); - if (token !== void 0 && token >= 81 /* FirstReservedWord */ && token <= 116 /* LastReservedWord */ ) return setTextRange(factory2.createStringLiteralFromNode(name), name); + if (token !== void 0 && token >= 83 /* FirstReservedWord */ && token <= 118 /* LastReservedWord */ ) return setTextRange(factory2.createStringLiteralFromNode(name), name); return void 0; } } @@ -82335,7 +83881,7 @@ ${lanes.join("\n")} } } function transformGenerators(context) { - const { factory: factory2 , getEmitHelperFactory: emitHelpers , resumeLexicalEnvironment: resumeLexicalEnvironment , endLexicalEnvironment: endLexicalEnvironment , hoistFunctionDeclaration: hoistFunctionDeclaration , hoistVariableDeclaration: hoistVariableDeclaration } = context; + const { factory: factory2, getEmitHelperFactory: emitHelpers, resumeLexicalEnvironment: resumeLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, hoistFunctionDeclaration: hoistFunctionDeclaration, hoistVariableDeclaration: hoistVariableDeclaration } = context; const compilerOptions = context.getCompilerOptions(); const languageVersion = getEmitScriptTarget(compilerOptions); const resolver = context.getEmitResolver(); @@ -82383,13 +83929,13 @@ ${lanes.join("\n")} } function visitJavaScriptInStatementContainingYield(node) { switch(node.kind){ - case 243 /* DoStatement */ : + case 246 /* DoStatement */ : return visitDoStatement(node); - case 244 /* WhileStatement */ : + case 247 /* WhileStatement */ : return visitWhileStatement(node); - case 252 /* SwitchStatement */ : + case 255 /* SwitchStatement */ : return visitSwitchStatement(node); - case 253 /* LabeledStatement */ : + case 256 /* LabeledStatement */ : return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -82397,24 +83943,24 @@ ${lanes.join("\n")} } function visitJavaScriptInGeneratorFunctionBody(node) { switch(node.kind){ - case 259 /* FunctionDeclaration */ : + case 262 /* FunctionDeclaration */ : return visitFunctionDeclaration(node); - case 215 /* FunctionExpression */ : + case 218 /* FunctionExpression */ : return visitFunctionExpression(node); - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : return visitAccessorDeclaration(node); - case 240 /* VariableStatement */ : + case 243 /* VariableStatement */ : return visitVariableStatement(node); - case 245 /* ForStatement */ : + case 248 /* ForStatement */ : return visitForStatement(node); - case 246 /* ForInStatement */ : + case 249 /* ForInStatement */ : return visitForInStatement(node); - case 249 /* BreakStatement */ : + case 252 /* BreakStatement */ : return visitBreakStatement(node); - case 248 /* ContinueStatement */ : + case 251 /* ContinueStatement */ : return visitContinueStatement(node); - case 250 /* ReturnStatement */ : + case 253 /* ReturnStatement */ : return visitReturnStatement(node); default: if (node.transformFlags & 1048576 /* ContainsYield */ ) return visitJavaScriptContainingYield(node); @@ -82424,23 +83970,23 @@ ${lanes.join("\n")} } function visitJavaScriptContainingYield(node) { switch(node.kind){ - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : return visitBinaryExpression(node); - case 357 /* CommaListExpression */ : + case 361 /* CommaListExpression */ : return visitCommaListExpression(node); - case 224 /* ConditionalExpression */ : + case 227 /* ConditionalExpression */ : return visitConditionalExpression(node); - case 226 /* YieldExpression */ : + case 229 /* YieldExpression */ : return visitYieldExpression(node); - case 206 /* ArrayLiteralExpression */ : + case 209 /* ArrayLiteralExpression */ : return visitArrayLiteralExpression(node); - case 207 /* ObjectLiteralExpression */ : + case 210 /* ObjectLiteralExpression */ : return visitObjectLiteralExpression(node); - case 209 /* ElementAccessExpression */ : + case 212 /* ElementAccessExpression */ : return visitElementAccessExpression(node); - case 210 /* CallExpression */ : + case 213 /* CallExpression */ : return visitCallExpression(node); - case 211 /* NewExpression */ : + case 214 /* NewExpression */ : return visitNewExpression(node); default: return visitEachChild(node, visitor, context); @@ -82448,9 +83994,9 @@ ${lanes.join("\n")} } function visitGenerator(node) { switch(node.kind){ - case 259 /* FunctionDeclaration */ : + case 262 /* FunctionDeclaration */ : return visitFunctionDeclaration(node); - case 215 /* FunctionExpression */ : + case 218 /* FunctionExpression */ : return visitFunctionExpression(node); default: return Debug.failBadSyntaxKind(node); @@ -82568,14 +84114,14 @@ ${lanes.join("\n")} } } function visitRightAssociativeBinaryExpression(node) { - const { left: left , right: right } = node; + const { left: left, right: right } = node; if (containsYield(right)) { let target; switch(left.kind){ - case 208 /* PropertyAccessExpression */ : + case 211 /* PropertyAccessExpression */ : target = factory2.updatePropertyAccessExpression(left, cacheExpression(Debug.checkDefined(visitNode(left.expression, visitor, isLeftHandSideExpression))), left.name); break; - case 209 /* ElementAccessExpression */ : + case 212 /* ElementAccessExpression */ : target = factory2.updateElementAccessExpression(left, cacheExpression(Debug.checkDefined(visitNode(left.expression, visitor, isLeftHandSideExpression))), cacheExpression(Debug.checkDefined(visitNode(left.argumentExpression, visitor, isExpression)))); break; default: @@ -82591,7 +84137,7 @@ ${lanes.join("\n")} function visitLeftAssociativeBinaryExpression(node) { if (containsYield(node.right)) { if (isLogicalOperator(node.operatorToken.kind)) return visitLogicalBinaryExpression(node); - else if (node.operatorToken.kind === 27 /* CommaToken */ ) return visitCommaExpression(node); + else if (node.operatorToken.kind === 28 /* CommaToken */ ) return visitCommaExpression(node); return factory2.updateBinaryExpression(node, cacheExpression(Debug.checkDefined(visitNode(node.left, visitor, isExpression))), node.operatorToken, Debug.checkDefined(visitNode(node.right, visitor, isExpression))); } return visitEachChild(node, visitor, context); @@ -82602,7 +84148,7 @@ ${lanes.join("\n")} visit(node.right); return factory2.inlineExpressions(pendingExpressions); function visit(node2) { - if (isBinaryExpression(node2) && node2.operatorToken.kind === 27 /* CommaToken */ ) { + if (isBinaryExpression(node2) && node2.operatorToken.kind === 28 /* CommaToken */ ) { visit(node2.left); visit(node2.right); } else { @@ -82618,7 +84164,7 @@ ${lanes.join("\n")} } function visitCommaListExpression(node) { let pendingExpressions = []; - for (const elem of node.elements)if (isBinaryExpression(elem) && elem.operatorToken.kind === 27 /* CommaToken */ ) pendingExpressions.push(visitCommaExpression(elem)); + for (const elem of node.elements)if (isBinaryExpression(elem) && elem.operatorToken.kind === 28 /* CommaToken */ ) pendingExpressions.push(visitCommaExpression(elem)); else { if (containsYield(elem) && pendingExpressions.length > 0) { emitWorker(1 /* Statement */ , [ @@ -82634,7 +84180,7 @@ ${lanes.join("\n")} const resultLabel = defineLabel(); const resultLocal = declareLocal(); emitAssignment(resultLocal, Debug.checkDefined(visitNode(node.left, visitor, isExpression)), /*location*/ node.left); - if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ ) emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left); + if (node.operatorToken.kind === 56 /* AmpersandAmpersandToken */ ) emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left); else emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left); emitAssignment(resultLocal, Debug.checkDefined(visitNode(node.right, visitor, isExpression)), /*location*/ node.right); markLabel(resultLabel); @@ -82659,7 +84205,7 @@ ${lanes.join("\n")} const resumeLabel = defineLabel(); const expression = visitNode(node.expression, visitor, isExpression); if (node.asteriskToken) { - const iterator = (getEmitFlags(node.expression) & 16777216 /* Iterator */ ) === 0 ? setTextRange(emitHelpers().createValuesHelper(expression), node) : expression; + const iterator = (getEmitFlags(node.expression) & 8388608 /* Iterator */ ) === 0 ? setTextRange(emitHelpers().createValuesHelper(expression), node) : expression; emitYieldStar(iterator, /*location*/ node); } else emitYield(expression, /*location*/ node); markLabel(resumeLabel); @@ -82733,14 +84279,14 @@ ${lanes.join("\n")} } function visitCallExpression(node) { if (!isImportCall(node) && forEach(node.arguments, containsYield)) { - const { target: target , thisArg: thisArg } = factory2.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true); + const { target: target, thisArg: thisArg } = factory2.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true); return setOriginalNode(setTextRange(factory2.createFunctionApplyCall(cacheExpression(Debug.checkDefined(visitNode(target, visitor, isLeftHandSideExpression))), thisArg, visitElements(node.arguments)), node), node); } return visitEachChild(node, visitor, context); } function visitNewExpression(node) { if (forEach(node.arguments, containsYield)) { - const { target: target , thisArg: thisArg } = factory2.createCallBinding(factory2.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration); + const { target: target, thisArg: thisArg } = factory2.createCallBinding(factory2.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration); return setOriginalNode(setTextRange(factory2.createNewExpression(factory2.createFunctionApplyCall(cacheExpression(Debug.checkDefined(visitNode(target, visitor, isExpression))), thisArg, visitElements(node.arguments, /*leadingElement*/ factory2.createVoidZero())), /*typeArguments*/ void 0, []), node), node); } return visitEachChild(node, visitor, context); @@ -82761,35 +84307,35 @@ ${lanes.join("\n")} } function transformAndEmitStatementWorker(node) { switch(node.kind){ - case 238 /* Block */ : + case 241 /* Block */ : return transformAndEmitBlock(node); - case 241 /* ExpressionStatement */ : + case 244 /* ExpressionStatement */ : return transformAndEmitExpressionStatement(node); - case 242 /* IfStatement */ : + case 245 /* IfStatement */ : return transformAndEmitIfStatement(node); - case 243 /* DoStatement */ : + case 246 /* DoStatement */ : return transformAndEmitDoStatement(node); - case 244 /* WhileStatement */ : + case 247 /* WhileStatement */ : return transformAndEmitWhileStatement(node); - case 245 /* ForStatement */ : + case 248 /* ForStatement */ : return transformAndEmitForStatement(node); - case 246 /* ForInStatement */ : + case 249 /* ForInStatement */ : return transformAndEmitForInStatement(node); - case 248 /* ContinueStatement */ : + case 251 /* ContinueStatement */ : return transformAndEmitContinueStatement(node); - case 249 /* BreakStatement */ : + case 252 /* BreakStatement */ : return transformAndEmitBreakStatement(node); - case 250 /* ReturnStatement */ : + case 253 /* ReturnStatement */ : return transformAndEmitReturnStatement(node); - case 251 /* WithStatement */ : + case 254 /* WithStatement */ : return transformAndEmitWithStatement(node); - case 252 /* SwitchStatement */ : + case 255 /* SwitchStatement */ : return transformAndEmitSwitchStatement(node); - case 253 /* LabeledStatement */ : + case 256 /* LabeledStatement */ : return transformAndEmitLabeledStatement(node); - case 254 /* ThrowStatement */ : + case 257 /* ThrowStatement */ : return transformAndEmitThrowStatement(node); - case 255 /* TryStatement */ : + case 258 /* TryStatement */ : return transformAndEmitTryStatement(node); default: return emitStatement(visitNode(node, visitor, isStatement)); @@ -82934,7 +84480,7 @@ ${lanes.join("\n")} markLabel(conditionLabel); emitBreakWhenFalse(endLoopLabel, factory2.createLessThan(keysIndex, factory2.createPropertyAccessExpression(keysArray, "length"))); emitAssignment(key, factory2.createElementAccessExpression(keysArray, keysIndex)); - emitBreakWhenFalse(incrementLabel, factory2.createBinaryExpression(key, 101 /* InKeyword */ , obj)); + emitBreakWhenFalse(incrementLabel, factory2.createBinaryExpression(key, 103 /* InKeyword */ , obj)); let variable; if (isVariableDeclarationList(initializer)) { for (const variable2 of initializer.declarations)hoistVariableDeclaration(variable2.name); @@ -83009,7 +84555,7 @@ ${lanes.join("\n")} for(let i = 0; i < numClauses; i++){ const clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 293 /* DefaultClause */ && defaultClauseIndex === -1) defaultClauseIndex = i; + if (clause.kind === 297 /* DefaultClause */ && defaultClauseIndex === -1) defaultClauseIndex = i; } let clausesWritten = 0; let pendingClauses = []; @@ -83017,7 +84563,7 @@ ${lanes.join("\n")} let defaultClausesSkipped = 0; for(let i = clausesWritten; i < numClauses; i++){ const clause = caseBlock.clauses[i]; - if (clause.kind === 292 /* CaseClause */ ) { + if (clause.kind === 296 /* CaseClause */ ) { if (containsYield(clause.expression) && pendingClauses.length > 0) break; pendingClauses.push(factory2.createCaseClause(Debug.checkDefined(visitNode(clause.expression, visitor, isExpression)), [ createInlineBreak(clauseLabels[i], /*location*/ clause.expression) @@ -83063,8 +84609,7 @@ ${lanes.join("\n")} return node; } function transformAndEmitThrowStatement(node) { - var _a2; - emitThrow(Debug.checkDefined(visitNode((_a2 = node.expression) != null ? _a2 : factory2.createVoidZero(), visitor, isExpression)), /*location*/ node); + emitThrow(Debug.checkDefined(visitNode(node.expression ?? factory2.createVoidZero(), visitor, isExpression)), /*location*/ node); } function transformAndEmitTryStatement(node) { if (containsYield(node)) { @@ -83212,7 +84757,7 @@ ${lanes.join("\n")} if (!renamedCatchVariables) { renamedCatchVariables = /* @__PURE__ */ new Map(); renamedCatchVariableDeclarations = []; - context.enableSubstitution(79 /* Identifier */ ); + context.enableSubstitution(80 /* Identifier */ ); } renamedCatchVariables.set(text, true); renamedCatchVariableDeclarations[getOriginalNodeId(variable)] = name; @@ -83530,7 +85075,7 @@ ${lanes.join("\n")} ]; } if (currentExceptionBlock) { - const { startLabel: startLabel , catchLabel: catchLabel , finallyLabel: finallyLabel , endLabel: endLabel } = currentExceptionBlock; + const { startLabel: startLabel, catchLabel: catchLabel, finallyLabel: finallyLabel, endLabel: endLabel } = currentExceptionBlock; statements.unshift(factory2.createExpressionStatement(factory2.createCallExpression(factory2.createPropertyAccessExpression(factory2.createPropertyAccessExpression(state, "trys"), "push"), /*typeArguments*/ void 0, [ factory2.createArrayLiteralExpression([ createLabel(startLabel), @@ -83705,7 +85250,7 @@ ${lanes.join("\n")} return transformCommonJSModule; } } - const { factory: factory2 , getEmitHelperFactory: emitHelpers , startLexicalEnvironment: startLexicalEnvironment , endLexicalEnvironment: endLexicalEnvironment , hoistVariableDeclaration: hoistVariableDeclaration } = context; + const { factory: factory2, getEmitHelperFactory: emitHelpers, startLexicalEnvironment: startLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, hoistVariableDeclaration: hoistVariableDeclaration } = context; const compilerOptions = context.getCompilerOptions(); const resolver = context.getEmitResolver(); const host = context.getEmitHost(); @@ -83715,14 +85260,13 @@ ${lanes.join("\n")} const previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(210 /* CallExpression */ ); - context.enableSubstitution(212 /* TaggedTemplateExpression */ ); - context.enableSubstitution(79 /* Identifier */ ); - context.enableSubstitution(223 /* BinaryExpression */ ); - context.enableSubstitution(300 /* ShorthandPropertyAssignment */ ); - context.enableEmitNotification(308 /* SourceFile */ ); + context.enableSubstitution(213 /* CallExpression */ ); + context.enableSubstitution(215 /* TaggedTemplateExpression */ ); + context.enableSubstitution(80 /* Identifier */ ); + context.enableSubstitution(226 /* BinaryExpression */ ); + context.enableSubstitution(304 /* ShorthandPropertyAssignment */ ); + context.enableEmitNotification(312 /* SourceFile */ ); const moduleInfoMap = []; - const deferredExports = []; let currentSourceFile; let currentModuleInfo; const noSubstitution = []; @@ -83731,7 +85275,7 @@ ${lanes.join("\n")} function transformSourceFile(node) { if (node.isDeclarationFile || !(isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 8388608 /* ContainsDynamicImport */ || isJsonSourceFile(node) && hasJsonModuleEmitEnabled(compilerOptions) && outFile(compilerOptions))) return node; currentSourceFile = node; - currentModuleInfo = collectExternalModuleInfo(context, node, resolver, compilerOptions); + currentModuleInfo = collectExternalModuleInfo(context, node); moduleInfoMap[getOriginalNodeId(node)] = currentModuleInfo; const transformModule2 = getTransformModuleDelegate(moduleKind); const updated = transformModule2(node); @@ -83766,7 +85310,7 @@ ${lanes.join("\n")} const define = factory2.createIdentifier("define"); const moduleName = tryGetModuleNameFromFile(factory2, node, host, compilerOptions); const jsonSourceFile = isJsonSourceFile(node) && node; - const { aliasedModuleNames: aliasedModuleNames , unaliasedModuleNames: unaliasedModuleNames , importAliasNames: importAliasNames } = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true); + const { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames } = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true); const updated = factory2.updateSourceFile(node, setTextRange(factory2.createNodeArray([ factory2.createExpressionStatement(factory2.createCallExpression(define, /*typeArguments*/ void 0, [ // Add the module name (if provided). @@ -83796,7 +85340,7 @@ ${lanes.join("\n")} return updated; } function transformUMDModule(node) { - const { aliasedModuleNames: aliasedModuleNames , unaliasedModuleNames: unaliasedModuleNames , importAliasNames: importAliasNames } = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false); + const { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames } = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false); const moduleName = tryGetModuleNameFromFile(factory2, node, host, compilerOptions); const umdHeader = factory2.createFunctionExpression(/*modifiers*/ void 0, /*asteriskToken*/ void 0, /*name*/ void 0, /*typeParameters*/ void 0, [ factory2.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, "factory") @@ -83907,24 +85451,56 @@ ${lanes.join("\n")} } function topLevelVisitor(node) { switch(node.kind){ - case 269 /* ImportDeclaration */ : - return visitImportDeclaration(node); - case 268 /* ImportEqualsDeclaration */ : - return visitImportEqualsDeclaration(node); - case 275 /* ExportDeclaration */ : - return visitExportDeclaration(node); - case 274 /* ExportAssignment */ : - return visitExportAssignment(node); - case 240 /* VariableStatement */ : + case 272 /* ImportDeclaration */ : + return visitTopLevelImportDeclaration(node); + case 271 /* ImportEqualsDeclaration */ : + return visitTopLevelImportEqualsDeclaration(node); + case 278 /* ExportDeclaration */ : + return visitTopLevelExportDeclaration(node); + case 277 /* ExportAssignment */ : + return visitTopLevelExportAssignment(node); + default: + return topLevelNestedVisitor(node); + } + } + function topLevelNestedVisitor(node) { + switch(node.kind){ + case 243 /* VariableStatement */ : return visitVariableStatement(node); - case 259 /* FunctionDeclaration */ : + case 262 /* FunctionDeclaration */ : return visitFunctionDeclaration(node); - case 260 /* ClassDeclaration */ : + case 263 /* ClassDeclaration */ : return visitClassDeclaration(node); - case 358 /* MergeDeclarationMarker */ : - return visitMergeDeclarationMarker(node); - case 359 /* EndOfDeclarationMarker */ : - return visitEndOfDeclarationMarker(node); + case 248 /* ForStatement */ : + return visitForStatement(node, /*isTopLevel*/ true); + case 249 /* ForInStatement */ : + return visitForInStatement(node); + case 250 /* ForOfStatement */ : + return visitForOfStatement(node); + case 246 /* DoStatement */ : + return visitDoStatement(node); + case 247 /* WhileStatement */ : + return visitWhileStatement(node); + case 256 /* LabeledStatement */ : + return visitLabeledStatement(node); + case 254 /* WithStatement */ : + return visitWithStatement(node); + case 245 /* IfStatement */ : + return visitIfStatement(node); + case 255 /* SwitchStatement */ : + return visitSwitchStatement(node); + case 269 /* CaseBlock */ : + return visitCaseBlock(node); + case 296 /* CaseClause */ : + return visitCaseClause(node); + case 297 /* DefaultClause */ : + return visitDefaultClause(node); + case 258 /* TryStatement */ : + return visitTryStatement(node); + case 299 /* CatchClause */ : + return visitCatchClause(node); + case 241 /* Block */ : + return visitBlock(node); default: return visitor(node); } @@ -83932,22 +85508,22 @@ ${lanes.join("\n")} function visitorWorker(node, valueIsDiscarded) { if (!(node.transformFlags & 276828160 /* ContainsUpdateExpressionForIdentifier */ )) return node; switch(node.kind){ - case 245 /* ForStatement */ : - return visitForStatement(node); - case 241 /* ExpressionStatement */ : + case 248 /* ForStatement */ : + return visitForStatement(node, /*isTopLevel*/ false); + case 244 /* ExpressionStatement */ : return visitExpressionStatement(node); - case 214 /* ParenthesizedExpression */ : + case 217 /* ParenthesizedExpression */ : return visitParenthesizedExpression(node, valueIsDiscarded); - case 356 /* PartiallyEmittedExpression */ : + case 360 /* PartiallyEmittedExpression */ : return visitPartiallyEmittedExpression(node, valueIsDiscarded); - case 210 /* CallExpression */ : + case 213 /* CallExpression */ : if (isImportCall(node) && currentSourceFile.impliedNodeFormat === void 0) return visitImportCallExpression(node); break; - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : if (isDestructuringAssignment(node)) return visitDestructuringAssignment(node, valueIsDiscarded); break; - case 221 /* PrefixUnaryExpression */ : - case 222 /* PostfixUnaryExpression */ : + case 224 /* PrefixUnaryExpression */ : + case 225 /* PostfixUnaryExpression */ : return visitPreOrPostfixUnaryExpression(node, valueIsDiscarded); } return visitEachChild(node, visitor, context); @@ -83960,18 +85536,18 @@ ${lanes.join("\n")} } function destructuringNeedsFlattening(node) { if (isObjectLiteralExpression(node)) for (const elem of node.properties)switch(elem.kind){ - case 299 /* PropertyAssignment */ : + case 303 /* PropertyAssignment */ : if (destructuringNeedsFlattening(elem.initializer)) return true; break; - case 300 /* ShorthandPropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : if (destructuringNeedsFlattening(elem.name)) return true; break; - case 301 /* SpreadAssignment */ : + case 305 /* SpreadAssignment */ : if (destructuringNeedsFlattening(elem.expression)) return true; break; - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : return false; default: Debug.assertNever(elem, "Unhandled object member kind"); @@ -83988,8 +85564,96 @@ ${lanes.join("\n")} if (destructuringNeedsFlattening(node.left)) return flattenDestructuringAssignment(node, visitor, context, 0 /* All */ , !valueIsDiscarded, createAllExportExpressions); return visitEachChild(node, visitor, context); } - function visitForStatement(node) { - return factory2.updateForStatement(node, visitNode(node.initializer, discardedValueVisitor, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, discardedValueVisitor, isExpression), visitIterationBody(node.statement, visitor, context)); + function visitForStatement(node, isTopLevel) { + if (isTopLevel && node.initializer && isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 7 /* BlockScoped */ )) { + const exportStatements = appendExportsOfVariableDeclarationList(/*statements*/ void 0, node.initializer, /*isForInOrOfInitializer*/ false); + if (exportStatements) { + const statements = []; + const varDeclList = visitNode(node.initializer, discardedValueVisitor, isVariableDeclarationList); + const varStatement = factory2.createVariableStatement(/*modifiers*/ void 0, varDeclList); + statements.push(varStatement); + addRange(statements, exportStatements); + const condition = visitNode(node.condition, visitor, isExpression); + const incrementor = visitNode(node.incrementor, discardedValueVisitor, isExpression); + const body = visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context); + statements.push(factory2.updateForStatement(node, /*initializer*/ void 0, condition, incrementor, body)); + return statements; + } + } + return factory2.updateForStatement(node, visitNode(node.initializer, discardedValueVisitor, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, discardedValueVisitor, isExpression), visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context)); + } + function visitForInStatement(node) { + if (isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 7 /* BlockScoped */ )) { + const exportStatements = appendExportsOfVariableDeclarationList(/*statements*/ void 0, node.initializer, /*isForInOrOfInitializer*/ true); + if (some(exportStatements)) { + const initializer = visitNode(node.initializer, discardedValueVisitor, isForInitializer); + const expression = visitNode(node.expression, visitor, isExpression); + const body = visitIterationBody(node.statement, topLevelNestedVisitor, context); + const mergedBody = isBlock(body) ? factory2.updateBlock(body, [ + ...exportStatements, + ...body.statements + ]) : factory2.createBlock([ + ...exportStatements, + body + ], /*multiLine*/ true); + return factory2.updateForInStatement(node, initializer, expression, mergedBody); + } + } + return factory2.updateForInStatement(node, visitNode(node.initializer, discardedValueVisitor, isForInitializer), visitNode(node.expression, visitor, isExpression), visitIterationBody(node.statement, topLevelNestedVisitor, context)); + } + function visitForOfStatement(node) { + if (isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 7 /* BlockScoped */ )) { + const exportStatements = appendExportsOfVariableDeclarationList(/*statements*/ void 0, node.initializer, /*isForInOrOfInitializer*/ true); + const initializer = visitNode(node.initializer, discardedValueVisitor, isForInitializer); + const expression = visitNode(node.expression, visitor, isExpression); + let body = visitIterationBody(node.statement, topLevelNestedVisitor, context); + if (some(exportStatements)) body = isBlock(body) ? factory2.updateBlock(body, [ + ...exportStatements, + ...body.statements + ]) : factory2.createBlock([ + ...exportStatements, + body + ], /*multiLine*/ true); + return factory2.updateForOfStatement(node, node.awaitModifier, initializer, expression, body); + } + return factory2.updateForOfStatement(node, node.awaitModifier, visitNode(node.initializer, discardedValueVisitor, isForInitializer), visitNode(node.expression, visitor, isExpression), visitIterationBody(node.statement, topLevelNestedVisitor, context)); + } + function visitDoStatement(node) { + return factory2.updateDoStatement(node, visitIterationBody(node.statement, topLevelNestedVisitor, context), visitNode(node.expression, visitor, isExpression)); + } + function visitWhileStatement(node) { + return factory2.updateWhileStatement(node, visitNode(node.expression, visitor, isExpression), visitIterationBody(node.statement, topLevelNestedVisitor, context)); + } + function visitLabeledStatement(node) { + return factory2.updateLabeledStatement(node, node.label, Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock))); + } + function visitWithStatement(node) { + return factory2.updateWithStatement(node, visitNode(node.expression, visitor, isExpression), Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock))); + } + function visitIfStatement(node) { + return factory2.updateIfStatement(node, visitNode(node.expression, visitor, isExpression), Debug.checkDefined(visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)), visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)); + } + function visitSwitchStatement(node) { + return factory2.updateSwitchStatement(node, visitNode(node.expression, visitor, isExpression), Debug.checkDefined(visitNode(node.caseBlock, topLevelNestedVisitor, isCaseBlock))); + } + function visitCaseBlock(node) { + return factory2.updateCaseBlock(node, visitNodes2(node.clauses, topLevelNestedVisitor, isCaseOrDefaultClause)); + } + function visitCaseClause(node) { + return factory2.updateCaseClause(node, visitNode(node.expression, visitor, isExpression), visitNodes2(node.statements, topLevelNestedVisitor, isStatement)); + } + function visitDefaultClause(node) { + return visitEachChild(node, topLevelNestedVisitor, context); + } + function visitTryStatement(node) { + return visitEachChild(node, topLevelNestedVisitor, context); + } + function visitCatchClause(node) { + return factory2.updateCatchClause(node, node.variableDeclaration, Debug.checkDefined(visitNode(node.block, topLevelNestedVisitor, isBlock))); + } + function visitBlock(node) { + node = visitEachChild(node, topLevelNestedVisitor, context); + return node; } function visitExpressionStatement(node) { return factory2.updateExpressionStatement(node, visitNode(node.expression, discardedValueVisitor, isExpression)); @@ -84001,7 +85665,7 @@ ${lanes.join("\n")} return factory2.updatePartiallyEmittedExpression(node, visitNode(node.expression, valueIsDiscarded ? discardedValueVisitor : visitor, isExpression)); } function visitPreOrPostfixUnaryExpression(node, valueIsDiscarded) { - if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */ ) && isIdentifier(node.operand) && !isGeneratedIdentifier(node.operand) && !isLocalName(node.operand) && !isDeclarationNameOfEnumOrNamespace(node.operand)) { + if ((node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */ ) && isIdentifier(node.operand) && !isGeneratedIdentifier(node.operand) && !isLocalName(node.operand) && !isDeclarationNameOfEnumOrNamespace(node.operand)) { const exportedNames = getExports(node.operand); if (exportedNames) { let temp; @@ -84042,7 +85706,7 @@ ${lanes.join("\n")} case 2 /* AMD */ : return createImportCallExpressionAMD(argument, containsLexicalThis); case 3 /* UMD */ : - return createImportCallExpressionUMD(argument != null ? argument : factory2.createVoidZero(), containsLexicalThis); + return createImportCallExpressionUMD(argument ?? factory2.createVoidZero(), containsLexicalThis); case 1 /* CommonJS */ : default: return createImportCallExpressionCommonJS(argument); @@ -84055,7 +85719,7 @@ ${lanes.join("\n")} return factory2.createConditionalExpression(/*condition*/ factory2.createIdentifier("__syncRequire"), /*questionToken*/ void 0, /*whenTrue*/ createImportCallExpressionCommonJS(arg), /*colonToken*/ void 0, /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis)); } else { const temp = factory2.createTempVariable(hoistVariableDeclaration); - return factory2.createComma(factory2.createAssignment(temp, arg), factory2.createConditionalExpression(/*condition*/ factory2.createIdentifier("__syncRequire"), /*questionToken*/ void 0, /*whenTrue*/ createImportCallExpressionCommonJS(temp, /* isInlineable */ true), /*colonToken*/ void 0, /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis))); + return factory2.createComma(factory2.createAssignment(temp, arg), factory2.createConditionalExpression(/*condition*/ factory2.createIdentifier("__syncRequire"), /*questionToken*/ void 0, /*whenTrue*/ createImportCallExpressionCommonJS(temp, /*isInlineable*/ true), /*colonToken*/ void 0, /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis))); } } function createImportCallExpressionAMD(arg, containsLexicalThis) { @@ -84129,7 +85793,7 @@ ${lanes.join("\n")} if (getImportNeedsImportDefaultHelper(node)) return emitHelpers().createImportDefaultHelper(innerExpr); return innerExpr; } - function visitImportDeclaration(node) { + function visitTopLevelImportDeclaration(node) { let statements; const namespaceDeclaration = getNamespaceDeclarationNode(node); if (moduleKind !== 2 /* AMD */ ) { @@ -84146,10 +85810,7 @@ ${lanes.join("\n")} } else if (namespaceDeclaration && isDefaultImport(node)) statements = append(statements, factory2.createVariableStatement(/*modifiers*/ void 0, factory2.createVariableDeclarationList([ setOriginalNode(setTextRange(factory2.createVariableDeclaration(factory2.cloneNode(namespaceDeclaration.name), /*exclamationToken*/ void 0, /*type*/ void 0, factory2.getGeneratedNameForNode(node)), /*location*/ node), /*original*/ node) ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */ ))); - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); - } else statements = appendExportsOfImportDeclaration(statements, node); + statements = appendExportsOfImportDeclaration(statements, node); return singleOrMany(statements); } function createRequireCall2(importNode) { @@ -84158,7 +85819,7 @@ ${lanes.join("\n")} if (moduleName) args.push(moduleName); return factory2.createCallExpression(factory2.createIdentifier("require"), /*typeArguments*/ void 0, args); } - function visitImportEqualsDeclaration(node) { + function visitTopLevelImportEqualsDeclaration(node) { Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); let statements; if (moduleKind !== 2 /* AMD */ ) { @@ -84167,13 +85828,10 @@ ${lanes.join("\n")} factory2.createVariableDeclaration(factory2.cloneNode(node.name), /*exclamationToken*/ void 0, /*type*/ void 0, createRequireCall2(node)) ], /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */ )), node), node)); } else if (hasSyntacticModifier(node, 1 /* Export */ )) statements = append(statements, setOriginalNode(setTextRange(factory2.createExpressionStatement(createExportExpression(factory2.getExportName(node), factory2.getLocalName(node))), node), node)); - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); - } else statements = appendExportsOfImportEqualsDeclaration(statements, node); + statements = appendExportsOfImportEqualsDeclaration(statements, node); return singleOrMany(statements); } - function visitExportDeclaration(node) { + function visitTopLevelExportDeclaration(node) { if (!node.moduleSpecifier) return void 0; const generatedName = factory2.getGeneratedNameForNode(node); if (node.exportClause && isNamedExports(node.exportClause)) { @@ -84185,7 +85843,7 @@ ${lanes.join("\n")} else { const exportNeedsImportDefault = !!getESModuleInterop(compilerOptions) && !(getInternalEmitFlags(node) & 2 /* NeverApplyImportHelper */ ) && idText(specifier.propertyName || specifier.name) === "default"; const exportedValue = factory2.createPropertyAccessExpression(exportNeedsImportDefault ? emitHelpers().createImportDefaultHelper(generatedName) : generatedName, specifier.propertyName || specifier.name); - statements.push(setOriginalNode(setTextRange(factory2.createExpressionStatement(createExportExpression(factory2.getExportName(specifier), exportedValue, /* location */ void 0, /* liveBinding */ true)), specifier), specifier)); + statements.push(setOriginalNode(setTextRange(factory2.createExpressionStatement(createExportExpression(factory2.getExportName(specifier), exportedValue, /*location*/ void 0, /*liveBinding*/ true)), specifier), specifier)); } return singleOrMany(statements); } else if (node.exportClause) { @@ -84194,34 +85852,22 @@ ${lanes.join("\n")} return singleOrMany(statements); } else return setOriginalNode(setTextRange(factory2.createExpressionStatement(emitHelpers().createExportStarHelper(moduleKind !== 2 /* AMD */ ? createRequireCall2(node) : generatedName)), node), node); } - function visitExportAssignment(node) { + function visitTopLevelExportAssignment(node) { if (node.isExportEquals) return void 0; - let statements; - const original = node.original; - if (original && hasAssociatedEndOfDeclarationMarker(original)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportStatement(deferredExports[id], factory2.createIdentifier("default"), visitNode(node.expression, visitor, isExpression), /*location*/ node, /*allowComments*/ true); - } else statements = appendExportStatement(statements, factory2.createIdentifier("default"), visitNode(node.expression, visitor, isExpression), /*location*/ node, /*allowComments*/ true); - return singleOrMany(statements); + return createExportStatement(factory2.createIdentifier("default"), visitNode(node.expression, visitor, isExpression), /*location*/ node, /*allowComments*/ true); } function visitFunctionDeclaration(node) { let statements; if (hasSyntacticModifier(node, 1 /* Export */ )) statements = append(statements, setOriginalNode(setTextRange(factory2.createFunctionDeclaration(visitNodes2(node.modifiers, modifierVisitor, isModifier), node.asteriskToken, factory2.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ void 0, visitNodes2(node.parameters, visitor, isParameter), /*type*/ void 0, visitEachChild(node.body, visitor, context)), /*location*/ node), /*original*/ node)); else statements = append(statements, visitEachChild(node, visitor, context)); - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); - } else statements = appendExportsOfHoistedDeclaration(statements, node); + statements = appendExportsOfHoistedDeclaration(statements, node); return singleOrMany(statements); } function visitClassDeclaration(node) { let statements; if (hasSyntacticModifier(node, 1 /* Export */ )) statements = append(statements, setOriginalNode(setTextRange(factory2.createClassDeclaration(visitNodes2(node.modifiers, modifierVisitor, isModifierLike), factory2.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ void 0, visitNodes2(node.heritageClauses, visitor, isHeritageClause), visitNodes2(node.members, visitor, isClassElement)), node), node)); else statements = append(statements, visitEachChild(node, visitor, context)); - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); - } else statements = appendExportsOfHoistedDeclaration(statements, node); + statements = appendExportsOfHoistedDeclaration(statements, node); return singleOrMany(statements); } function visitVariableStatement(node) { @@ -84255,10 +85901,7 @@ ${lanes.join("\n")} statements = append(statements, statement); } } else statements = append(statements, visitEachChild(node, visitor, context)); - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node); - } else statements = appendExportsOfVariableStatement(statements, node); + statements = appendExportsOfVariableStatement(statements, node); return singleOrMany(statements); } function createAllExportExpressions(name, value1, location) { @@ -84277,74 +85920,63 @@ ${lanes.join("\n")} if (isBindingPattern(node.name)) return flattenDestructuringAssignment(visitNode(node, visitor, isInitializedVariable), visitor, context, 0 /* All */ , /*needsValue*/ false, createAllExportExpressions); else return factory2.createAssignment(setTextRange(factory2.createPropertyAccessExpression(factory2.createIdentifier("exports"), node.name), /*location*/ node.name), node.initializer ? visitNode(node.initializer, visitor, isExpression) : factory2.createVoidZero()); } - function visitMergeDeclarationMarker(node) { - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 240 /* VariableStatement */ ) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); - } - return node; - } - function hasAssociatedEndOfDeclarationMarker(node) { - return (getEmitFlags(node) & 8388608 /* HasEndOfDeclarationMarker */ ) !== 0; - } - function visitEndOfDeclarationMarker(node) { - const id = getOriginalNodeId(node); - const statements = deferredExports[id]; - if (statements) { - delete deferredExports[id]; - return append(statements, node); - } - return node; - } function appendExportsOfImportDeclaration(statements, decl) { if (currentModuleInfo.exportEquals) return statements; const importClause = decl.importClause; if (!importClause) return statements; - if (importClause.name) statements = appendExportsOfDeclaration(statements, importClause); + const seen = new IdentifierNameMap(); + if (importClause.name) statements = appendExportsOfDeclaration(statements, seen, importClause); const namedBindings = importClause.namedBindings; if (namedBindings) switch(namedBindings.kind){ - case 271 /* NamespaceImport */ : - statements = appendExportsOfDeclaration(statements, namedBindings); + case 274 /* NamespaceImport */ : + statements = appendExportsOfDeclaration(statements, seen, namedBindings); break; - case 272 /* NamedImports */ : - for (const importBinding of namedBindings.elements)statements = appendExportsOfDeclaration(statements, importBinding, /* liveBinding */ true); + case 275 /* NamedImports */ : + for (const importBinding of namedBindings.elements)statements = appendExportsOfDeclaration(statements, seen, importBinding, /*liveBinding*/ true); break; } return statements; } function appendExportsOfImportEqualsDeclaration(statements, decl) { if (currentModuleInfo.exportEquals) return statements; - return appendExportsOfDeclaration(statements, decl); + return appendExportsOfDeclaration(statements, new IdentifierNameMap(), decl); } function appendExportsOfVariableStatement(statements, node) { + return appendExportsOfVariableDeclarationList(statements, node.declarationList, /*isForInOrOfInitializer*/ false); + } + function appendExportsOfVariableDeclarationList(statements, node, isForInOrOfInitializer) { if (currentModuleInfo.exportEquals) return statements; - for (const decl of node.declarationList.declarations)statements = appendExportsOfBindingElement(statements, decl); + for (const decl of node.declarations)statements = appendExportsOfBindingElement(statements, decl, isForInOrOfInitializer); return statements; } - function appendExportsOfBindingElement(statements, decl) { + function appendExportsOfBindingElement(statements, decl, isForInOrOfInitializer) { if (currentModuleInfo.exportEquals) return statements; if (isBindingPattern(decl.name)) { - for (const element of decl.name.elements)if (!isOmittedExpression(element)) statements = appendExportsOfBindingElement(statements, element); - } else if (!isGeneratedIdentifier(decl.name)) statements = appendExportsOfDeclaration(statements, decl); + for (const element of decl.name.elements)if (!isOmittedExpression(element)) statements = appendExportsOfBindingElement(statements, element, isForInOrOfInitializer); + } else if (!isGeneratedIdentifier(decl.name) && (!isVariableDeclaration(decl) || decl.initializer || isForInOrOfInitializer)) statements = appendExportsOfDeclaration(statements, new IdentifierNameMap(), decl); return statements; } function appendExportsOfHoistedDeclaration(statements, decl) { if (currentModuleInfo.exportEquals) return statements; + const seen = new IdentifierNameMap(); if (hasSyntacticModifier(decl, 1 /* Export */ )) { const exportName = hasSyntacticModifier(decl, 1024 /* Default */ ) ? factory2.createIdentifier("default") : factory2.getDeclarationName(decl); - statements = appendExportStatement(statements, exportName, factory2.getLocalName(decl), /*location*/ decl); + statements = appendExportStatement(statements, seen, exportName, factory2.getLocalName(decl), /*location*/ decl); } - if (decl.name) statements = appendExportsOfDeclaration(statements, decl); + if (decl.name) statements = appendExportsOfDeclaration(statements, seen, decl); return statements; } - function appendExportsOfDeclaration(statements, decl, liveBinding) { + function appendExportsOfDeclaration(statements, seen, decl, liveBinding) { const name = factory2.getDeclarationName(decl); - const exportSpecifiers = currentModuleInfo.exportSpecifiers.get(idText(name)); - if (exportSpecifiers) for (const exportSpecifier of exportSpecifiers)statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name, /* allowComments */ void 0, liveBinding); + const exportSpecifiers = currentModuleInfo.exportSpecifiers.get(name); + if (exportSpecifiers) for (const exportSpecifier of exportSpecifiers)statements = appendExportStatement(statements, seen, exportSpecifier.name, name, /*location*/ exportSpecifier.name, /*allowComments*/ void 0, liveBinding); return statements; } - function appendExportStatement(statements, exportName, expression, location, allowComments, liveBinding) { - statements = append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding)); + function appendExportStatement(statements, seen, exportName, expression, location, allowComments, liveBinding) { + if (!seen.has(exportName)) { + seen.set(exportName, true); + statements = append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding)); + } return statements; } function createUnderscoreUnderscoreESModule() { @@ -84361,7 +85993,7 @@ ${lanes.join("\n")} return statement; } function createExportStatement(name, value1, location, allowComments, liveBinding) { - const statement = setTextRange(factory2.createExpressionStatement(createExportExpression(name, value1, /* location */ void 0, liveBinding)), location); + const statement = setTextRange(factory2.createExpressionStatement(createExportExpression(name, value1, /*location*/ void 0, liveBinding)), location); startOnNewLine(statement); if (!allowComments) setEmitFlags(statement, 3072 /* NoComments */ ); return statement; @@ -84380,14 +86012,14 @@ ${lanes.join("\n")} } function modifierVisitor(node) { switch(node.kind){ - case 93 /* ExportKeyword */ : - case 88 /* DefaultKeyword */ : + case 95 /* ExportKeyword */ : + case 90 /* DefaultKeyword */ : return void 0; } return node; } function onEmitNode(hint, node, emitCallback) { - if (node.kind === 308 /* SourceFile */ ) { + if (node.kind === 312 /* SourceFile */ ) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[getOriginalNodeId(currentSourceFile)]; previousOnEmitNode(hint, node, emitCallback); @@ -84416,13 +86048,13 @@ ${lanes.join("\n")} } function substituteExpression(node) { switch(node.kind){ - case 79 /* Identifier */ : + case 80 /* Identifier */ : return substituteExpressionIdentifier(node); - case 210 /* CallExpression */ : + case 213 /* CallExpression */ : return substituteCallExpression(node); - case 212 /* TaggedTemplateExpression */ : + case 215 /* TaggedTemplateExpression */ : return substituteTaggedTemplateExpression(node); - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : return substituteBinaryExpression(node); } return node; @@ -84444,27 +86076,27 @@ ${lanes.join("\n")} return node; } function substituteExpressionIdentifier(node) { - var _a2, _b; + var _a, _b; if (getEmitFlags(node) & 8192 /* HelperName */ ) { const externalHelpersModuleName = getExternalHelpersModuleName(currentSourceFile); if (externalHelpersModuleName) return factory2.createPropertyAccessExpression(externalHelpersModuleName, node); return node; } else if (!(isGeneratedIdentifier(node) && !(node.emitNode.autoGenerate.flags & 64 /* AllowNameSubstitution */ )) && !isLocalName(node)) { const exportContainer = resolver.getReferencedExportContainer(node, isExportName(node)); - if (exportContainer && exportContainer.kind === 308 /* SourceFile */ ) return setTextRange(factory2.createPropertyAccessExpression(factory2.createIdentifier("exports"), factory2.cloneNode(node)), /*location*/ node); + if (exportContainer && exportContainer.kind === 312 /* SourceFile */ ) return setTextRange(factory2.createPropertyAccessExpression(factory2.createIdentifier("exports"), factory2.cloneNode(node)), /*location*/ node); const importDeclaration = resolver.getReferencedImportDeclaration(node); if (importDeclaration) { if (isImportClause(importDeclaration)) return setTextRange(factory2.createPropertyAccessExpression(factory2.getGeneratedNameForNode(importDeclaration.parent), factory2.createIdentifier("default")), /*location*/ node); else if (isImportSpecifier(importDeclaration)) { const name = importDeclaration.propertyName || importDeclaration.name; - return setTextRange(factory2.createPropertyAccessExpression(factory2.getGeneratedNameForNode(((_b = (_a2 = importDeclaration.parent) == null ? void 0 : _a2.parent) == null ? void 0 : _b.parent) || importDeclaration), factory2.cloneNode(name)), /*location*/ node); + return setTextRange(factory2.createPropertyAccessExpression(factory2.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.parent) || importDeclaration), factory2.cloneNode(name)), /*location*/ node); } } } return node; } function substituteBinaryExpression(node) { - if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && !isGeneratedIdentifier(node.left) && !isLocalName(node.left) && !isDeclarationNameOfEnumOrNamespace(node.left)) { + if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && (!isGeneratedIdentifier(node.left) || isFileLevelReservedGeneratedIdentifier(node.left)) && !isLocalName(node.left)) { const exportedNames = getExports(node.left); if (exportedNames) { let expression = node; @@ -84479,8 +86111,24 @@ ${lanes.join("\n")} } function getExports(name) { if (!isGeneratedIdentifier(name)) { - const valueDeclaration = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name); - if (valueDeclaration) return currentModuleInfo && currentModuleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)]; + const importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) return currentModuleInfo == null ? void 0 : currentModuleInfo.exportedBindings[getOriginalNodeId(importDeclaration)]; + const bindingsSet = /* @__PURE__ */ new Set(); + const declarations = resolver.getReferencedValueDeclarations(name); + if (declarations) { + for (const declaration of declarations){ + const bindings = currentModuleInfo == null ? void 0 : currentModuleInfo.exportedBindings[getOriginalNodeId(declaration)]; + if (bindings) for (const binding of bindings)bindingsSet.add(binding); + } + if (bindingsSet.size) return arrayFrom(bindingsSet); + } + } else if (isFileLevelReservedGeneratedIdentifier(name)) { + const exportSpecifiers = currentModuleInfo == null ? void 0 : currentModuleInfo.exportSpecifiers.get(name); + if (exportSpecifiers) { + const exportedNames = []; + for (const exportSpecifier of exportSpecifiers)exportedNames.push(exportSpecifier.name); + return exportedNames; + } } } } @@ -84499,7 +86147,7 @@ ${lanes.join("\n")} }); // src/compiler/transformers/module/system.ts function transformSystemModule(context) { - const { factory: factory2 , startLexicalEnvironment: startLexicalEnvironment , endLexicalEnvironment: endLexicalEnvironment , hoistVariableDeclaration: hoistVariableDeclaration } = context; + const { factory: factory2, startLexicalEnvironment: startLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, hoistVariableDeclaration: hoistVariableDeclaration } = context; const compilerOptions = context.getCompilerOptions(); const resolver = context.getEmitResolver(); const host = context.getEmitHost(); @@ -84507,13 +86155,12 @@ ${lanes.join("\n")} const previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(79 /* Identifier */ ); - context.enableSubstitution(300 /* ShorthandPropertyAssignment */ ); - context.enableSubstitution(223 /* BinaryExpression */ ); - context.enableSubstitution(233 /* MetaProperty */ ); - context.enableEmitNotification(308 /* SourceFile */ ); + context.enableSubstitution(80 /* Identifier */ ); + context.enableSubstitution(304 /* ShorthandPropertyAssignment */ ); + context.enableSubstitution(226 /* BinaryExpression */ ); + context.enableSubstitution(236 /* MetaProperty */ ); + context.enableEmitNotification(312 /* SourceFile */ ); const moduleInfoMap = []; - const deferredExports = []; const exportFunctionsMap = []; const noSubstitutionMap = []; const contextObjectMap = []; @@ -84530,7 +86177,7 @@ ${lanes.join("\n")} const id = getOriginalNodeId(node); currentSourceFile = node; enclosingBlockScopedContainer = node; - moduleInfo = moduleInfoMap[id] = collectExternalModuleInfo(context, node, resolver, compilerOptions); + moduleInfo = moduleInfoMap[id] = collectExternalModuleInfo(context, node); exportFunction = factory2.createUniqueName("exports"); exportFunctionsMap[id] = exportFunction; contextObject = contextObjectMap[id] = factory2.createUniqueName("context"); @@ -84612,7 +86259,7 @@ ${lanes.join("\n")} if (!moduleInfo.hasExportStarsToExportValues) return; if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) { let hasExportDeclarationWithExportClause = false; - for (const externalImport of moduleInfo.externalImports)if (externalImport.kind === 275 /* ExportDeclaration */ && externalImport.exportClause) { + for (const externalImport of moduleInfo.externalImports)if (externalImport.kind === 278 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -84629,7 +86276,7 @@ ${lanes.join("\n")} } const exportedNamesStorageRef = factory2.createUniqueName("exportedNames"); statements.push(factory2.createVariableStatement(/*modifiers*/ void 0, factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration(exportedNamesStorageRef, /*exclamationToken*/ void 0, /*type*/ void 0, factory2.createObjectLiteralExpression(exportedNames, /*multiline*/ true)) + factory2.createVariableDeclaration(exportedNamesStorageRef, /*exclamationToken*/ void 0, /*type*/ void 0, factory2.createObjectLiteralExpression(exportedNames, /*multiLine*/ true)) ]))); const exportStarFunction = createExportStarFunction(exportedNamesStorageRef); statements.push(exportStarFunction); @@ -84658,7 +86305,7 @@ ${lanes.join("\n")} factory2.createExpressionStatement(factory2.createCallExpression(exportFunction, /*typeArguments*/ void 0, [ exports ])) - ], /*multiline*/ true)); + ], /*multiLine*/ true)); } function createSettersArray(exportStarFunction, dependencyGroups) { const setters = []; @@ -84669,9 +86316,9 @@ ${lanes.join("\n")} for (const entry of group2.externalImports){ const importVariableName = getLocalNameForExternalImport(factory2, entry, currentSourceFile); switch(entry.kind){ - case 269 /* ImportDeclaration */ : + case 272 /* ImportDeclaration */ : if (!entry.importClause) break; - case 268 /* ImportEqualsDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : Debug.assert(importVariableName !== void 0); statements.push(factory2.createExpressionStatement(factory2.createAssignment(importVariableName, parameterName))); if (hasSyntacticModifier(entry, 1 /* Export */ )) statements.push(factory2.createExpressionStatement(factory2.createCallExpression(exportFunction, /*typeArguments*/ void 0, [ @@ -84679,14 +86326,14 @@ ${lanes.join("\n")} parameterName ]))); break; - case 275 /* ExportDeclaration */ : + case 278 /* ExportDeclaration */ : Debug.assert(importVariableName !== void 0); if (entry.exportClause) { if (isNamedExports(entry.exportClause)) { const properties = []; for (const e of entry.exportClause.elements)properties.push(factory2.createPropertyAssignment(factory2.createStringLiteral(idText(e.name)), factory2.createElementAccessExpression(parameterName, factory2.createStringLiteral(idText(e.propertyName || e.name))))); statements.push(factory2.createExpressionStatement(factory2.createCallExpression(exportFunction, /*typeArguments*/ void 0, [ - factory2.createObjectLiteralExpression(properties, /*multiline*/ true) + factory2.createObjectLiteralExpression(properties, /*multiLine*/ true) ]))); } else statements.push(factory2.createExpressionStatement(factory2.createCallExpression(exportFunction, /*typeArguments*/ void 0, [ factory2.createStringLiteral(idText(entry.exportClause.name)), @@ -84706,13 +86353,13 @@ ${lanes.join("\n")} } function topLevelVisitor(node) { switch(node.kind){ - case 269 /* ImportDeclaration */ : + case 272 /* ImportDeclaration */ : return visitImportDeclaration(node); - case 268 /* ImportEqualsDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : return visitImportEqualsDeclaration(node); - case 275 /* ExportDeclaration */ : + case 278 /* ExportDeclaration */ : return visitExportDeclaration(node); - case 274 /* ExportAssignment */ : + case 277 /* ExportAssignment */ : return visitExportAssignment(node); default: return topLevelNestedVisitor(node); @@ -84721,11 +86368,7 @@ ${lanes.join("\n")} function visitImportDeclaration(node) { let statements; if (node.importClause) hoistVariableDeclaration(getLocalNameForExternalImport(factory2, node, currentSourceFile)); - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); - } else statements = appendExportsOfImportDeclaration(statements, node); - return singleOrMany(statements); + return singleOrMany(appendExportsOfImportDeclaration(statements, node)); } function visitExportDeclaration(node) { Debug.assertIsDefined(node); @@ -84735,28 +86378,17 @@ ${lanes.join("\n")} Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); let statements; hoistVariableDeclaration(getLocalNameForExternalImport(factory2, node, currentSourceFile)); - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); - } else statements = appendExportsOfImportEqualsDeclaration(statements, node); - return singleOrMany(statements); + return singleOrMany(appendExportsOfImportEqualsDeclaration(statements, node)); } function visitExportAssignment(node) { if (node.isExportEquals) return void 0; const expression = visitNode(node.expression, visitor, isExpression); - const original = node.original; - if (original && hasAssociatedEndOfDeclarationMarker(original)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportStatement(deferredExports[id], factory2.createIdentifier("default"), expression, /*allowComments*/ true); - } else return createExportStatement(factory2.createIdentifier("default"), expression, /*allowComments*/ true); + return createExportStatement(factory2.createIdentifier("default"), expression, /*allowComments*/ true); } function visitFunctionDeclaration(node) { if (hasSyntacticModifier(node, 1 /* Export */ )) hoistedStatements = append(hoistedStatements, factory2.updateFunctionDeclaration(node, visitNodes2(node.modifiers, modifierVisitor, isModifierLike), node.asteriskToken, factory2.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ void 0, visitNodes2(node.parameters, visitor, isParameter), /*type*/ void 0, visitNode(node.body, visitor, isBlock))); else hoistedStatements = append(hoistedStatements, visitEachChild(node, visitor, context)); - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); - } else hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); + hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); return void 0; } function visitClassDeclaration(node) { @@ -84764,25 +86396,26 @@ ${lanes.join("\n")} const name = factory2.getLocalName(node); hoistVariableDeclaration(name); statements = append(statements, setTextRange(factory2.createExpressionStatement(factory2.createAssignment(name, setTextRange(factory2.createClassExpression(visitNodes2(node.modifiers, modifierVisitor, isModifierLike), node.name, /*typeParameters*/ void 0, visitNodes2(node.heritageClauses, visitor, isHeritageClause), visitNodes2(node.members, visitor, isClassElement)), node))), node)); - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); - } else statements = appendExportsOfHoistedDeclaration(statements, node); + statements = appendExportsOfHoistedDeclaration(statements, node); return singleOrMany(statements); } function visitVariableStatement(node) { if (!shouldHoistVariableDeclarationList(node.declarationList)) return visitNode(node, visitor, isStatement); - let expressions; - const isExportedDeclaration = hasSyntacticModifier(node, 1 /* Export */ ); - const isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node); - for (const variable of node.declarationList.declarations)if (variable.initializer) expressions = append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration)); - else hoistBindingElement(variable); let statements; - if (expressions) statements = append(statements, setTextRange(factory2.createExpressionStatement(factory2.inlineExpressions(expressions)), node)); - if (isMarkedDeclaration) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration); - } else statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false); + if (isVarUsing(node.declarationList) || isVarAwaitUsing(node.declarationList)) { + const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifierLike); + const declarations = []; + for (const variable of node.declarationList.declarations)declarations.push(factory2.updateVariableDeclaration(variable, factory2.getGeneratedNameForNode(variable.name), /*exclamationToken*/ void 0, /*type*/ void 0, transformInitializedVariable(variable, /*isExportedDeclaration*/ false))); + const declarationList = factory2.updateVariableDeclarationList(node.declarationList, declarations); + statements = append(statements, factory2.updateVariableStatement(node, modifiers, declarationList)); + } else { + let expressions; + const isExportedDeclaration = hasSyntacticModifier(node, 1 /* Export */ ); + for (const variable of node.declarationList.declarations)if (variable.initializer) expressions = append(expressions, transformInitializedVariable(variable, isExportedDeclaration)); + else hoistBindingElement(variable); + if (expressions) statements = append(statements, setTextRange(factory2.createExpressionStatement(factory2.inlineExpressions(expressions)), node)); + } + statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false); return singleOrMany(statements); } function hoistBindingElement(node) { @@ -84791,7 +86424,7 @@ ${lanes.join("\n")} } else hoistVariableDeclaration(factory2.cloneNode(node.name)); } function shouldHoistVariableDeclarationList(node) { - return (getEmitFlags(node) & 4194304 /* NoHoisting */ ) === 0 && (enclosingBlockScopedContainer.kind === 308 /* SourceFile */ || (getOriginalNode(node).flags & 3 /* BlockScoped */ ) === 0); + return (getEmitFlags(node) & 4194304 /* NoHoisting */ ) === 0 && (enclosingBlockScopedContainer.kind === 312 /* SourceFile */ || (getOriginalNode(node).flags & 7 /* BlockScoped */ ) === 0); } function transformInitializedVariable(node, isExportedDeclaration) { const createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; @@ -84807,29 +86440,6 @@ ${lanes.join("\n")} hoistVariableDeclaration(factory2.cloneNode(name)); return isExportedDeclaration ? createExportExpression(name, preventSubstitution(setTextRange(factory2.createAssignment(name, value1), location))) : preventSubstitution(setTextRange(factory2.createAssignment(name, value1), location)); } - function visitMergeDeclarationMarker(node) { - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 240 /* VariableStatement */ ) { - const id = getOriginalNodeId(node); - const isExportedDeclaration = hasSyntacticModifier(node.original, 1 /* Export */ ); - deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); - } - return node; - } - function hasAssociatedEndOfDeclarationMarker(node) { - return (getEmitFlags(node) & 8388608 /* HasEndOfDeclarationMarker */ ) !== 0; - } - function visitEndOfDeclarationMarker(node) { - const id = getOriginalNodeId(node); - const statements = deferredExports[id]; - if (statements) { - delete deferredExports[id]; - return append(statements, node); - } else { - const original = getOriginalNode(node); - if (isModuleOrEnumDeclaration(original)) return append(appendExportsOfDeclaration(statements, original), node); - } - return node; - } function appendExportsOfImportDeclaration(statements, decl) { if (moduleInfo.exportEquals) return statements; const importClause = decl.importClause; @@ -84837,10 +86447,10 @@ ${lanes.join("\n")} if (importClause.name) statements = appendExportsOfDeclaration(statements, importClause); const namedBindings = importClause.namedBindings; if (namedBindings) switch(namedBindings.kind){ - case 271 /* NamespaceImport */ : + case 274 /* NamespaceImport */ : statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 272 /* NamedImports */ : + case 275 /* NamedImports */ : for (const importBinding of namedBindings.elements)statements = appendExportsOfDeclaration(statements, importBinding); break; } @@ -84883,7 +86493,7 @@ ${lanes.join("\n")} function appendExportsOfDeclaration(statements, decl, excludeName) { if (moduleInfo.exportEquals) return statements; const name = factory2.getDeclarationName(decl); - const exportSpecifiers = moduleInfo.exportSpecifiers.get(idText(name)); + const exportSpecifiers = moduleInfo.exportSpecifiers.get(name); if (exportSpecifiers) { for (const exportSpecifier of exportSpecifiers)if (exportSpecifier.name.escapedText !== excludeName) statements = appendExportStatement(statements, exportSpecifier.name, name); } @@ -84909,44 +86519,42 @@ ${lanes.join("\n")} } function topLevelNestedVisitor(node) { switch(node.kind){ - case 240 /* VariableStatement */ : + case 243 /* VariableStatement */ : return visitVariableStatement(node); - case 259 /* FunctionDeclaration */ : + case 262 /* FunctionDeclaration */ : return visitFunctionDeclaration(node); - case 260 /* ClassDeclaration */ : + case 263 /* ClassDeclaration */ : return visitClassDeclaration(node); - case 245 /* ForStatement */ : + case 248 /* ForStatement */ : return visitForStatement(node, /*isTopLevel*/ true); - case 246 /* ForInStatement */ : + case 249 /* ForInStatement */ : return visitForInStatement(node); - case 247 /* ForOfStatement */ : + case 250 /* ForOfStatement */ : return visitForOfStatement(node); - case 243 /* DoStatement */ : + case 246 /* DoStatement */ : return visitDoStatement(node); - case 244 /* WhileStatement */ : + case 247 /* WhileStatement */ : return visitWhileStatement(node); - case 253 /* LabeledStatement */ : + case 256 /* LabeledStatement */ : return visitLabeledStatement(node); - case 251 /* WithStatement */ : + case 254 /* WithStatement */ : return visitWithStatement(node); - case 252 /* SwitchStatement */ : + case 245 /* IfStatement */ : + return visitIfStatement(node); + case 255 /* SwitchStatement */ : return visitSwitchStatement(node); - case 266 /* CaseBlock */ : + case 269 /* CaseBlock */ : return visitCaseBlock(node); - case 292 /* CaseClause */ : + case 296 /* CaseClause */ : return visitCaseClause(node); - case 293 /* DefaultClause */ : + case 297 /* DefaultClause */ : return visitDefaultClause(node); - case 255 /* TryStatement */ : + case 258 /* TryStatement */ : return visitTryStatement(node); - case 295 /* CatchClause */ : + case 299 /* CatchClause */ : return visitCatchClause(node); - case 238 /* Block */ : + case 241 /* Block */ : return visitBlock(node); - case 358 /* MergeDeclarationMarker */ : - return visitMergeDeclarationMarker(node); - case 359 /* EndOfDeclarationMarker */ : - return visitEndOfDeclarationMarker(node); default: return visitor(node); } @@ -84997,6 +86605,9 @@ ${lanes.join("\n")} function visitWithStatement(node) { return factory2.updateWithStatement(node, visitNode(node.expression, visitor, isExpression), Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock))); } + function visitIfStatement(node) { + return factory2.updateIfStatement(node, visitNode(node.expression, visitor, isExpression), Debug.checkDefined(visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)), visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)); + } function visitSwitchStatement(node) { return factory2.updateSwitchStatement(node, visitNode(node.expression, visitor, isExpression), Debug.checkDefined(visitNode(node.caseBlock, topLevelNestedVisitor, isCaseBlock))); } @@ -85033,22 +86644,22 @@ ${lanes.join("\n")} function visitorWorker(node, valueIsDiscarded) { if (!(node.transformFlags & 276828160 /* ContainsUpdateExpressionForIdentifier */ )) return node; switch(node.kind){ - case 245 /* ForStatement */ : + case 248 /* ForStatement */ : return visitForStatement(node, /*isTopLevel*/ false); - case 241 /* ExpressionStatement */ : + case 244 /* ExpressionStatement */ : return visitExpressionStatement(node); - case 214 /* ParenthesizedExpression */ : + case 217 /* ParenthesizedExpression */ : return visitParenthesizedExpression(node, valueIsDiscarded); - case 356 /* PartiallyEmittedExpression */ : + case 360 /* PartiallyEmittedExpression */ : return visitPartiallyEmittedExpression(node, valueIsDiscarded); - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : if (isDestructuringAssignment(node)) return visitDestructuringAssignment(node, valueIsDiscarded); break; - case 210 /* CallExpression */ : + case 213 /* CallExpression */ : if (isImportCall(node)) return visitImportCallExpression(node); break; - case 221 /* PrefixUnaryExpression */ : - case 222 /* PostfixUnaryExpression */ : + case 224 /* PrefixUnaryExpression */ : + case 225 /* PostfixUnaryExpression */ : return visitPrefixOrPostfixUnaryExpression(node, valueIsDiscarded); } return visitEachChild(node, visitor, context); @@ -85089,11 +86700,11 @@ ${lanes.join("\n")} else if (isPropertyAssignment(node)) return hasExportedReferenceInDestructuringTarget(node.initializer); else if (isIdentifier(node)) { const container = resolver.getReferencedExportContainer(node); - return container !== void 0 && container.kind === 308 /* SourceFile */ ; + return container !== void 0 && container.kind === 312 /* SourceFile */ ; } else return false; } function visitPrefixOrPostfixUnaryExpression(node, valueIsDiscarded) { - if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */ ) && isIdentifier(node.operand) && !isGeneratedIdentifier(node.operand) && !isLocalName(node.operand) && !isDeclarationNameOfEnumOrNamespace(node.operand)) { + if ((node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */ ) && isIdentifier(node.operand) && !isGeneratedIdentifier(node.operand) && !isLocalName(node.operand) && !isDeclarationNameOfEnumOrNamespace(node.operand)) { const exportedNames = getExports(node.operand); if (exportedNames) { let temp; @@ -85121,14 +86732,14 @@ ${lanes.join("\n")} } function modifierVisitor(node) { switch(node.kind){ - case 93 /* ExportKeyword */ : - case 88 /* DefaultKeyword */ : + case 95 /* ExportKeyword */ : + case 90 /* DefaultKeyword */ : return void 0; } return node; } function onEmitNode(hint, node, emitCallback) { - if (node.kind === 308 /* SourceFile */ ) { + if (node.kind === 312 /* SourceFile */ ) { const id = getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -85153,36 +86764,36 @@ ${lanes.join("\n")} } function substituteUnspecified(node) { switch(node.kind){ - case 300 /* ShorthandPropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : return substituteShorthandPropertyAssignment(node); } return node; } function substituteShorthandPropertyAssignment(node) { - var _a2, _b; + var _a, _b; const name = node.name; if (!isGeneratedIdentifier(name) && !isLocalName(name)) { const importDeclaration = resolver.getReferencedImportDeclaration(name); if (importDeclaration) { if (isImportClause(importDeclaration)) return setTextRange(factory2.createPropertyAssignment(factory2.cloneNode(name), factory2.createPropertyAccessExpression(factory2.getGeneratedNameForNode(importDeclaration.parent), factory2.createIdentifier("default"))), /*location*/ node); - else if (isImportSpecifier(importDeclaration)) return setTextRange(factory2.createPropertyAssignment(factory2.cloneNode(name), factory2.createPropertyAccessExpression(factory2.getGeneratedNameForNode(((_b = (_a2 = importDeclaration.parent) == null ? void 0 : _a2.parent) == null ? void 0 : _b.parent) || importDeclaration), factory2.cloneNode(importDeclaration.propertyName || importDeclaration.name))), /*location*/ node); + else if (isImportSpecifier(importDeclaration)) return setTextRange(factory2.createPropertyAssignment(factory2.cloneNode(name), factory2.createPropertyAccessExpression(factory2.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.parent) || importDeclaration), factory2.cloneNode(importDeclaration.propertyName || importDeclaration.name))), /*location*/ node); } } return node; } function substituteExpression(node) { switch(node.kind){ - case 79 /* Identifier */ : + case 80 /* Identifier */ : return substituteExpressionIdentifier(node); - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : return substituteBinaryExpression(node); - case 233 /* MetaProperty */ : + case 236 /* MetaProperty */ : return substituteMetaProperty(node); } return node; } function substituteExpressionIdentifier(node) { - var _a2, _b; + var _a, _b; if (getEmitFlags(node) & 8192 /* HelperName */ ) { const externalHelpersModuleName = getExternalHelpersModuleName(currentSourceFile); if (externalHelpersModuleName) return factory2.createPropertyAccessExpression(externalHelpersModuleName, node); @@ -85192,13 +86803,13 @@ ${lanes.join("\n")} const importDeclaration = resolver.getReferencedImportDeclaration(node); if (importDeclaration) { if (isImportClause(importDeclaration)) return setTextRange(factory2.createPropertyAccessExpression(factory2.getGeneratedNameForNode(importDeclaration.parent), factory2.createIdentifier("default")), /*location*/ node); - else if (isImportSpecifier(importDeclaration)) return setTextRange(factory2.createPropertyAccessExpression(factory2.getGeneratedNameForNode(((_b = (_a2 = importDeclaration.parent) == null ? void 0 : _a2.parent) == null ? void 0 : _b.parent) || importDeclaration), factory2.cloneNode(importDeclaration.propertyName || importDeclaration.name)), /*location*/ node); + else if (isImportSpecifier(importDeclaration)) return setTextRange(factory2.createPropertyAccessExpression(factory2.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.parent) || importDeclaration), factory2.cloneNode(importDeclaration.propertyName || importDeclaration.name)), /*location*/ node); } } return node; } function substituteBinaryExpression(node) { - if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && !isGeneratedIdentifier(node.left) && !isLocalName(node.left) && !isDeclarationNameOfEnumOrNamespace(node.left)) { + if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && (!isGeneratedIdentifier(node.left) || isFileLevelReservedGeneratedIdentifier(node.left)) && !isLocalName(node.left)) { const exportedNames = getExports(node.left); if (exportedNames) { let expression = node; @@ -85214,16 +86825,34 @@ ${lanes.join("\n")} } function getExports(name) { let exportedNames; - if (!isGeneratedIdentifier(name)) { - const valueDeclaration = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name); - if (valueDeclaration) { - const exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); - if (exportContainer && exportContainer.kind === 308 /* SourceFile */ ) exportedNames = append(exportedNames, factory2.getDeclarationName(valueDeclaration)); - exportedNames = addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)]); + const valueDeclaration = getReferencedDeclaration(name); + if (valueDeclaration) { + const exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); + if (exportContainer && exportContainer.kind === 312 /* SourceFile */ ) exportedNames = append(exportedNames, factory2.getDeclarationName(valueDeclaration)); + exportedNames = addRange(exportedNames, moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)]); + } else if (isGeneratedIdentifier(name) && isFileLevelReservedGeneratedIdentifier(name)) { + const exportSpecifiers = moduleInfo == null ? void 0 : moduleInfo.exportSpecifiers.get(name); + if (exportSpecifiers) { + const exportedNames2 = []; + for (const exportSpecifier of exportSpecifiers)exportedNames2.push(exportSpecifier.name); + return exportedNames2; } } return exportedNames; } + function getReferencedDeclaration(name) { + if (!isGeneratedIdentifier(name)) { + const importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) return importDeclaration; + const valueDeclaration = resolver.getReferencedValueDeclaration(name); + if (valueDeclaration && (moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)])) return valueDeclaration; + const declarations = resolver.getReferencedValueDeclarations(name); + if (declarations) for (const declaration of declarations){ + if (declaration !== valueDeclaration && (moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(declaration)])) return declaration; + } + return valueDeclaration; + } + } function preventSubstitution(node) { if (noSubstitution === void 0) noSubstitution = []; noSubstitution[getNodeId(node)] = true; @@ -85241,7 +86870,7 @@ ${lanes.join("\n")} }); // src/compiler/transformers/module/esnextAnd2015.ts function transformECMAScriptModule(context) { - const { factory: factory2 , getEmitHelperFactory: emitHelpers } = context; + const { factory: factory2, getEmitHelperFactory: emitHelpers } = context; const host = context.getEmitHost(); const resolver = context.getEmitResolver(); const compilerOptions = context.getCompilerOptions(); @@ -85250,8 +86879,8 @@ ${lanes.join("\n")} const previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(308 /* SourceFile */ ); - context.enableSubstitution(79 /* Identifier */ ); + context.enableEmitNotification(312 /* SourceFile */ ); + context.enableSubstitution(80 /* Identifier */ ); let helperNameSubstitutions; let currentSourceFile; let importRequireStatements; @@ -85284,11 +86913,11 @@ ${lanes.join("\n")} } function visitor(node) { switch(node.kind){ - case 268 /* ImportEqualsDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : return getEmitModuleKind(compilerOptions) >= 100 /* Node16 */ ? visitImportEqualsDeclaration(node) : void 0; - case 274 /* ExportAssignment */ : + case 277 /* ExportAssignment */ : return visitExportAssignment(node); - case 275 /* ExportDeclaration */ : + case 278 /* ExportDeclaration */ : const exportDecl = node; return visitExportDeclaration(exportDecl); } @@ -85306,7 +86935,7 @@ ${lanes.join("\n")} const requireHelperName = factory2.createUniqueName("__require", 48 /* FileLevel */ ); const requireStatement = factory2.createVariableStatement(/*modifiers*/ void 0, factory2.createVariableDeclarationList([ factory2.createVariableDeclaration(requireHelperName, /*exclamationToken*/ void 0, /*type*/ void 0, factory2.createCallExpression(factory2.cloneNode(createRequireName), /*typeArguments*/ void 0, [ - factory2.createPropertyAccessExpression(factory2.createMetaProperty(100 /* ImportKeyword */ , factory2.createIdentifier("meta")), factory2.createIdentifier("url")) + factory2.createPropertyAccessExpression(factory2.createMetaProperty(102 /* ImportKeyword */ , factory2.createIdentifier("meta")), factory2.createIdentifier("url")) ])) ], /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */ )); importRequireStatements = [ @@ -85391,8 +87020,8 @@ ${lanes.join("\n")} const cjsOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(308 /* SourceFile */ ); - context.enableEmitNotification(308 /* SourceFile */ ); + context.enableSubstitution(312 /* SourceFile */ ); + context.enableEmitNotification(312 /* SourceFile */ ); let currentSourceFile; return transformSourceFileOrBundle; function onSubstituteNode(hint, node) { @@ -85423,7 +87052,7 @@ ${lanes.join("\n")} return result; } function transformSourceFileOrBundle(node) { - return node.kind === 308 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + return node.kind === 312 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); } function transformBundle(node) { return context.factory.createBundle(map(node.sourceFiles, transformSourceFile), node.prepends); @@ -85437,7 +87066,7 @@ ${lanes.join("\n")} }); // src/compiler/transformers/declarations/diagnostics.ts function canProduceDiagnostics(node) { - return isVariableDeclaration(node) || isPropertyDeclaration(node) || isPropertySignature(node) || isBindingElement(node) || isSetAccessor(node) || isGetAccessor(node) || isConstructSignatureDeclaration(node) || isCallSignatureDeclaration(node) || isMethodDeclaration(node) || isMethodSignature(node) || isFunctionDeclaration(node) || isParameter(node) || isTypeParameterDeclaration(node) || isExpressionWithTypeArguments(node) || isImportEqualsDeclaration(node) || isTypeAliasDeclaration(node) || isConstructorDeclaration(node) || isIndexSignatureDeclaration(node) || isPropertyAccessExpression(node) || isJSDocTypeAlias(node); + return isVariableDeclaration(node) || isPropertyDeclaration(node) || isPropertySignature(node) || isBindingElement(node) || isSetAccessor(node) || isGetAccessor(node) || isConstructSignatureDeclaration(node) || isCallSignatureDeclaration(node) || isMethodDeclaration(node) || isMethodSignature(node) || isFunctionDeclaration(node) || isParameter(node) || isTypeParameterDeclaration(node) || isExpressionWithTypeArguments(node) || isImportEqualsDeclaration(node) || isTypeAliasDeclaration(node) || isConstructorDeclaration(node) || isIndexSignatureDeclaration(node) || isPropertyAccessExpression(node) || isElementAccessExpression(node) || isBinaryExpression(node) || isJSDocTypeAlias(node); } function createGetSymbolAccessibilityDiagnosticForNodeName(node) { if (isSetAccessor(node) || isGetAccessor(node)) return getAccessorNameVisibilityError; @@ -85453,7 +87082,7 @@ ${lanes.join("\n")} } function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { if (isStatic(node)) return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; - else if (node.parent.kind === 260 /* ClassDeclaration */ ) return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + else if (node.parent.kind === 263 /* ClassDeclaration */ ) return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; else return symbolAccessibilityResult.errorModuleName ? Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; } function getMethodNameVisibilityError(symbolAccessibilityResult) { @@ -85466,12 +87095,12 @@ ${lanes.join("\n")} } function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { if (isStatic(node)) return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; - else if (node.parent.kind === 260 /* ClassDeclaration */ ) return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1; + else if (node.parent.kind === 263 /* ClassDeclaration */ ) return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1; else return symbolAccessibilityResult.errorModuleName ? Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1; } } function createGetSymbolAccessibilityDiagnosticForNode(node) { - if (isVariableDeclaration(node) || isPropertyDeclaration(node) || isPropertySignature(node) || isPropertyAccessExpression(node) || isBindingElement(node) || isConstructorDeclaration(node)) return getVariableDeclarationTypeVisibilityError; + if (isVariableDeclaration(node) || isPropertyDeclaration(node) || isPropertySignature(node) || isPropertyAccessExpression(node) || isElementAccessExpression(node) || isBinaryExpression(node) || isBindingElement(node) || isConstructorDeclaration(node)) return getVariableDeclarationTypeVisibilityError; else if (isSetAccessor(node) || isGetAccessor(node)) return getAccessorDeclarationTypeVisibilityError; else if (isConstructSignatureDeclaration(node) || isCallSignatureDeclaration(node) || isMethodDeclaration(node) || isMethodSignature(node) || isFunctionDeclaration(node) || isIndexSignatureDeclaration(node)) return getReturnTypeVisibilityError; else if (isParameter(node)) { @@ -85483,10 +87112,10 @@ ${lanes.join("\n")} else if (isTypeAliasDeclaration(node) || isJSDocTypeAlias(node)) return getTypeAliasDeclarationVisibilityError; else return Debug.assertNever(node, `Attempted to set a declaration diagnostic context for unhandled node kind: ${Debug.formatSyntaxKind(node.kind)}`); function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 257 /* VariableDeclaration */ || node.kind === 205 /* BindingElement */ ) return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; - else if (node.kind === 169 /* PropertyDeclaration */ || node.kind === 208 /* PropertyAccessExpression */ || node.kind === 168 /* PropertySignature */ || node.kind === 166 /* Parameter */ && hasSyntacticModifier(node.parent, 8 /* Private */ )) { + if (node.kind === 260 /* VariableDeclaration */ || node.kind === 208 /* BindingElement */ ) return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; + else if (node.kind === 172 /* PropertyDeclaration */ || node.kind === 211 /* PropertyAccessExpression */ || node.kind === 212 /* ElementAccessExpression */ || node.kind === 226 /* BinaryExpression */ || node.kind === 171 /* PropertySignature */ || node.kind === 169 /* Parameter */ && hasSyntacticModifier(node.parent, 8 /* Private */ )) { if (isStatic(node)) return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; - else if (node.parent.kind === 260 /* ClassDeclaration */ || node.kind === 166 /* Parameter */ ) return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + else if (node.parent.kind === 263 /* ClassDeclaration */ || node.kind === 169 /* Parameter */ ) return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; else return symbolAccessibilityResult.errorModuleName ? Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; } } @@ -85500,7 +87129,7 @@ ${lanes.join("\n")} } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { let diagnosticMessage; - if (node.kind === 175 /* SetAccessor */ ) { + if (node.kind === 178 /* SetAccessor */ ) { if (isStatic(node)) diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1; else diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1; } else if (isStatic(node)) diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1; @@ -85514,22 +87143,22 @@ ${lanes.join("\n")} function getReturnTypeVisibilityError(symbolAccessibilityResult) { let diagnosticMessage; switch(node.kind){ - case 177 /* ConstructSignature */ : + case 180 /* ConstructSignature */ : diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 176 /* CallSignature */ : + case 179 /* CallSignature */ : diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 178 /* IndexSignature */ : + case 181 /* IndexSignature */ : diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : if (isStatic(node)) diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; - else if (node.parent.kind === 260 /* ClassDeclaration */ ) diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; + else if (node.parent.kind === 263 /* ClassDeclaration */ ) diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; else diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; break; - case 259 /* FunctionDeclaration */ : + case 262 /* FunctionDeclaration */ : diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; break; default: @@ -85550,25 +87179,25 @@ ${lanes.join("\n")} } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch(node.parent.kind){ - case 173 /* Constructor */ : + case 176 /* Constructor */ : return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 177 /* ConstructSignature */ : - case 182 /* ConstructorType */ : + case 180 /* ConstructSignature */ : + case 185 /* ConstructorType */ : return symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 176 /* CallSignature */ : + case 179 /* CallSignature */ : return symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - case 178 /* IndexSignature */ : + case 181 /* IndexSignature */ : return symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : if (isStatic(node.parent)) return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; - else if (node.parent.parent.kind === 260 /* ClassDeclaration */ ) return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + else if (node.parent.parent.kind === 263 /* ClassDeclaration */ ) return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; else return symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; - case 259 /* FunctionDeclaration */ : - case 181 /* FunctionType */ : + case 262 /* FunctionDeclaration */ : + case 184 /* FunctionType */ : return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; - case 175 /* SetAccessor */ : - case 174 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 177 /* GetAccessor */ : return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1; default: return Debug.fail(`Unknown parent for parameter: ${Debug.formatSyntaxKind(node.parent.kind)}`); @@ -85577,36 +87206,36 @@ ${lanes.join("\n")} function getTypeParameterConstraintVisibilityError() { let diagnosticMessage; switch(node.parent.kind){ - case 260 /* ClassDeclaration */ : + case 263 /* ClassDeclaration */ : diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 261 /* InterfaceDeclaration */ : + case 264 /* InterfaceDeclaration */ : diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 197 /* MappedType */ : + case 200 /* MappedType */ : diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1; break; - case 182 /* ConstructorType */ : - case 177 /* ConstructSignature */ : + case 185 /* ConstructorType */ : + case 180 /* ConstructSignature */ : diagnosticMessage = Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 176 /* CallSignature */ : + case 179 /* CallSignature */ : diagnosticMessage = Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : if (isStatic(node.parent)) diagnosticMessage = Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; - else if (node.parent.parent.kind === 260 /* ClassDeclaration */ ) diagnosticMessage = Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + else if (node.parent.parent.kind === 263 /* ClassDeclaration */ ) diagnosticMessage = Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; else diagnosticMessage = Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; break; - case 181 /* FunctionType */ : - case 259 /* FunctionDeclaration */ : + case 184 /* FunctionType */ : + case 262 /* FunctionDeclaration */ : diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; - case 192 /* InferType */ : + case 195 /* InferType */ : diagnosticMessage = Diagnostics.Extends_clause_for_inferred_type_0_has_or_is_using_private_name_1; break; - case 262 /* TypeAliasDeclaration */ : + case 265 /* TypeAliasDeclaration */ : diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: @@ -85620,7 +87249,7 @@ ${lanes.join("\n")} } function getHeritageClauseVisibilityError() { let diagnosticMessage; - if (isClassDeclaration(node.parent.parent)) diagnosticMessage = isHeritageClause(node.parent) && node.parent.token === 117 /* ImplementsKeyword */ ? Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : node.parent.parent.name ? Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1 : Diagnostics.extends_clause_of_exported_class_has_or_is_using_private_name_0; + if (isClassDeclaration(node.parent.parent)) diagnosticMessage = isHeritageClause(node.parent) && node.parent.token === 119 /* ImplementsKeyword */ ? Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : node.parent.parent.name ? Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1 : Diagnostics.extends_clause_of_exported_class_has_or_is_using_private_name_0; else diagnosticMessage = Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; return { diagnosticMessage: diagnosticMessage, @@ -85665,14 +87294,14 @@ ${lanes.join("\n")} } function isInternalDeclaration(node, currentSourceFile) { const parseTreeNode = getParseTreeNode(node); - if (parseTreeNode && parseTreeNode.kind === 166 /* Parameter */ ) { + if (parseTreeNode && parseTreeNode.kind === 169 /* Parameter */ ) { const paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode); const previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : void 0; const text = currentSourceFile.text; const commentRanges = previousSibling ? concatenate(// to handle // ... parameters, /** @internal */ // public param: string - getTrailingCommentRanges(text, skipTrivia(text, previousSibling.end + 1, /* stopAfterLineBreak */ false, /* stopAtComments */ true)), getLeadingCommentRanges(text, node.pos)) : getTrailingCommentRanges(text, skipTrivia(text, node.pos, /* stopAfterLineBreak */ false, /* stopAtComments */ true)); + getTrailingCommentRanges(text, skipTrivia(text, previousSibling.end + 1, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true)), getLeadingCommentRanges(text, node.pos)) : getTrailingCommentRanges(text, skipTrivia(text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true)); return commentRanges && commentRanges.length && hasInternalAnnotation(last(commentRanges), currentSourceFile); } const leadingCommentRanges = parseTreeNode && getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile); @@ -85694,7 +87323,7 @@ ${lanes.join("\n")} let lateStatementReplacementMap; let suppressNewDiagnosticContexts; let exportedModulesFromDeclarationEmit; - const { factory: factory2 } = context; + const { factory: factory2 } = context; const host = context.getEmitHost(); const symbolTracker = { trackSymbol: trackSymbol, @@ -85719,7 +87348,7 @@ ${lanes.join("\n")} let emittedImports; const resolver = context.getEmitResolver(); const options = context.getCompilerOptions(); - const { noResolve: noResolve , stripInternal: stripInternal } = options; + const { noResolve: noResolve, stripInternal: stripInternal } = options; return transformRoot; function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { if (!typeReferenceDirectives) return; @@ -85753,7 +87382,7 @@ ${lanes.join("\n")} } function trackSymbol(symbol, enclosingDeclaration2, meaning) { if (symbol.flags & 262144 /* TypeParameter */ ) return false; - const issuedDiagnostic = handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration2, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); + const issuedDiagnostic = handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration2, meaning, /*shouldComputeAliasToMarkVisible*/ true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); return issuedDiagnostic; } @@ -85779,8 +87408,8 @@ ${lanes.join("\n")} if (errorNameNode || errorFallbackNode) context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); } function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) { - var _a2; - const primaryDeclaration = (_a2 = parentSymbol.declarations) == null ? void 0 : _a2.find((d)=>getSourceFileOfNode(d) === containingFile); + var _a; + const primaryDeclaration = (_a = parentSymbol.declarations) == null ? void 0 : _a.find((d)=>getSourceFileOfNode(d) === containingFile); const augmentingDeclarations = filter(symbol.declarations, (d)=>getSourceFileOfNode(d) !== containingFile); if (primaryDeclaration && augmentingDeclarations) for (const augmentations of augmentingDeclarations)context.addDiagnostic(addRelatedInfo(createDiagnosticForNode(augmentations, Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), createDiagnosticForNode(primaryDeclaration, Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file))); } @@ -85801,8 +87430,8 @@ ${lanes.join("\n")} return result; } function transformRoot(node) { - if (node.kind === 308 /* SourceFile */ && node.isDeclarationFile) return node; - if (node.kind === 309 /* Bundle */ ) { + if (node.kind === 312 /* SourceFile */ && node.isDeclarationFile) return node; + if (node.kind === 313 /* Bundle */ ) { isBundledEmit = true; refs = /* @__PURE__ */ new Map(); libs2 = /* @__PURE__ */ new Map(); @@ -85826,7 +87455,7 @@ ${lanes.join("\n")} const statements = isSourceFileJS(sourceFile) ? factory2.createNodeArray(transformDeclarationsForJS(sourceFile, /*bundled*/ true)) : visitNodes2(sourceFile.statements, visitDeclarationStatements, isStatement); const newFile = factory2.updateSourceFile(sourceFile, [ factory2.createModuleDeclaration([ - factory2.createModifier(136 /* DeclareKeyword */ ) + factory2.createModifier(138 /* DeclareKeyword */ ) ], factory2.createStringLiteral(getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), factory2.createModuleBlock(setTextRange(factory2.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements))) ], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; @@ -85835,7 +87464,7 @@ ${lanes.join("\n")} const updated2 = isSourceFileJS(sourceFile) ? factory2.createNodeArray(transformDeclarationsForJS(sourceFile)) : visitNodes2(sourceFile.statements, visitDeclarationStatements, isStatement); return factory2.updateSourceFile(sourceFile, transformAndReplaceLatePaintedStatements(updated2), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); }), mapDefined(node.prepends, (prepend)=>{ - if (prepend.kind === 311 /* InputFiles */ ) { + if (prepend.kind === 315 /* InputFiles */ ) { const sourceFile = createUnparsedSourceFile(prepend, "dts", stripInternal); hasNoDefaultLib = hasNoDefaultLib || !!sourceFile.hasNoDefaultLib; collectReferences(sourceFile, refs); @@ -85966,14 +87595,14 @@ ${lanes.join("\n")} return ret; } function filterBindingPatternInitializersAndRenamings(name) { - if (name.kind === 79 /* Identifier */ ) return name; + if (name.kind === 80 /* Identifier */ ) return name; else { - if (name.kind === 204 /* ArrayBindingPattern */ ) return factory2.updateArrayBindingPattern(name, visitNodes2(name.elements, visitBindingElement, isArrayBindingElement)); + if (name.kind === 207 /* ArrayBindingPattern */ ) return factory2.updateArrayBindingPattern(name, visitNodes2(name.elements, visitBindingElement, isArrayBindingElement)); else return factory2.updateObjectBindingPattern(name, visitNodes2(name.elements, visitBindingElement, isBindingElement)); } function visitBindingElement(elem) { - if (elem.kind === 229 /* OmittedExpression */ ) return elem; - if (elem.propertyName && isIdentifier(elem.propertyName) && isIdentifier(elem.name) && !elem.symbol.isReferenced && !isIdentifierANonContextualKeyword(elem.propertyName)) return factory2.updateBindingElement(elem, elem.dotDotDotToken, /* propertyName */ void 0, elem.propertyName, shouldPrintWithInitializer(elem) ? elem.initializer : void 0); + if (elem.kind === 232 /* OmittedExpression */ ) return elem; + if (elem.propertyName && isIdentifier(elem.propertyName) && isIdentifier(elem.name) && !elem.symbol.isReferenced && !isIdentifierANonContextualKeyword(elem.propertyName)) return factory2.updateBindingElement(elem, elem.dotDotDotToken, /*propertyName*/ void 0, elem.propertyName, shouldPrintWithInitializer(elem) ? elem.initializer : void 0); return factory2.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializersAndRenamings(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : void 0); } } @@ -85983,7 +87612,7 @@ ${lanes.join("\n")} oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(p); } - const newParam = factory2.updateParameterDeclaration(p, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializersAndRenamings(p.name), resolver.isOptionalParameter(p) ? p.questionToken || factory2.createToken(57 /* QuestionToken */ ) : void 0, ensureType(p, type || p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + const newParam = factory2.updateParameterDeclaration(p, maskModifiers(factory2, p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializersAndRenamings(p.name), resolver.isOptionalParameter(p) ? p.questionToken || factory2.createToken(58 /* QuestionToken */ ) : void 0, ensureType(p, type || p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param ensureNoInitializer(p)); if (!suppressNewDiagnosticContexts) getSymbolAccessibilityDiagnostic = oldDiag; return newParam; @@ -85998,18 +87627,18 @@ ${lanes.join("\n")} function ensureType(node, type, ignorePrivate) { if (!ignorePrivate && hasEffectiveModifier(node, 8 /* Private */ )) return; if (shouldPrintWithInitializer(node)) return; - const shouldUseResolverType = node.kind === 166 /* Parameter */ && (resolver.isRequiredInitializedParameter(node) || resolver.isOptionalUninitializedParameterProperty(node)); + const shouldUseResolverType = node.kind === 169 /* Parameter */ && (resolver.isRequiredInitializedParameter(node) || resolver.isOptionalUninitializedParameterProperty(node)); if (type && !shouldUseResolverType) return visitNode(type, visitDeclarationSubtree, isTypeNode); - if (!getParseTreeNode(node)) return type ? visitNode(type, visitDeclarationSubtree, isTypeNode) : factory2.createKeywordTypeNode(131 /* AnyKeyword */ ); - if (node.kind === 175 /* SetAccessor */ ) return factory2.createKeywordTypeNode(131 /* AnyKeyword */ ); + if (!getParseTreeNode(node)) return type ? visitNode(type, visitDeclarationSubtree, isTypeNode) : factory2.createKeywordTypeNode(133 /* AnyKeyword */ ); + if (node.kind === 178 /* SetAccessor */ ) return factory2.createKeywordTypeNode(133 /* AnyKeyword */ ); errorNameNode = node.name; let oldDiag; if (!suppressNewDiagnosticContexts) { oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(node); } - if (node.kind === 257 /* VariableDeclaration */ || node.kind === 205 /* BindingElement */ ) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); - if (node.kind === 166 /* Parameter */ || node.kind === 169 /* PropertyDeclaration */ || node.kind === 168 /* PropertySignature */ ) { + if (node.kind === 260 /* VariableDeclaration */ || node.kind === 208 /* BindingElement */ ) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + if (node.kind === 169 /* Parameter */ || node.kind === 172 /* PropertyDeclaration */ || node.kind === 171 /* PropertySignature */ ) { if (isPropertySignature(node) || !node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } @@ -86017,35 +87646,35 @@ ${lanes.join("\n")} function cleanup(returnValue) { errorNameNode = void 0; if (!suppressNewDiagnosticContexts) getSymbolAccessibilityDiagnostic = oldDiag; - return returnValue || factory2.createKeywordTypeNode(131 /* AnyKeyword */ ); + return returnValue || factory2.createKeywordTypeNode(133 /* AnyKeyword */ ); } } function isDeclarationAndNotVisible(node) { node = getParseTreeNode(node); switch(node.kind){ - case 259 /* FunctionDeclaration */ : - case 264 /* ModuleDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 260 /* ClassDeclaration */ : - case 262 /* TypeAliasDeclaration */ : - case 263 /* EnumDeclaration */ : + case 262 /* FunctionDeclaration */ : + case 267 /* ModuleDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 263 /* ClassDeclaration */ : + case 265 /* TypeAliasDeclaration */ : + case 266 /* EnumDeclaration */ : return !resolver.isDeclarationVisible(node); - case 257 /* VariableDeclaration */ : + case 260 /* VariableDeclaration */ : return !getBindingNameVisible(node); - case 268 /* ImportEqualsDeclaration */ : - case 269 /* ImportDeclaration */ : - case 275 /* ExportDeclaration */ : - case 274 /* ExportAssignment */ : + case 271 /* ImportEqualsDeclaration */ : + case 272 /* ImportDeclaration */ : + case 278 /* ExportDeclaration */ : + case 277 /* ExportAssignment */ : return false; - case 172 /* ClassStaticBlockDeclaration */ : + case 175 /* ClassStaticBlockDeclaration */ : return true; } return false; } function shouldEmitFunctionProperties(input) { - var _a2; + var _a; if (input.body) return true; - const overloadSignatures = (_a2 = input.symbol.declarations) == null ? void 0 : _a2.filter((decl)=>isFunctionDeclaration(decl) && !decl.body); + const overloadSignatures = (_a = input.symbol.declarations) == null ? void 0 : _a.filter((decl)=>isFunctionDeclaration(decl) && !decl.body); return !overloadSignatures || overloadSignatures.indexOf(input) === overloadSignatures.length - 1; } function getBindingNameVisible(elem) { @@ -86098,7 +87727,7 @@ ${lanes.join("\n")} } function rewriteModuleSpecifier(parent2, input) { if (!input) return void 0; - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent2.kind !== 264 /* ModuleDeclaration */ && parent2.kind !== 202 /* ImportType */ ; + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent2.kind !== 267 /* ModuleDeclaration */ && parent2.kind !== 205 /* ImportType */ ; if (isStringLiteralLike(input)) { if (isBundledEmit) { const newName = getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent2); @@ -86112,7 +87741,7 @@ ${lanes.join("\n")} } function transformImportEqualsDeclaration(decl) { if (!resolver.isDeclarationVisible(decl)) return; - if (decl.moduleReference.kind === 280 /* ExternalModuleReference */ ) { + if (decl.moduleReference.kind === 283 /* ExternalModuleReference */ ) { const specifier = getExternalModuleImportEqualsDeclarationExpression(decl); return factory2.updateImportEqualsDeclaration(decl, decl.modifiers, decl.isTypeOnly, decl.name, factory2.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); } else { @@ -86127,7 +87756,7 @@ ${lanes.join("\n")} if (!decl.importClause) return factory2.updateImportDeclaration(decl, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); const visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : void 0; if (!decl.importClause.namedBindings) return visibleDefaultBinding && factory2.updateImportDeclaration(decl, decl.modifiers, factory2.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, /*namedBindings*/ void 0), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); - if (decl.importClause.namedBindings.kind === 271 /* NamespaceImport */ ) { + if (decl.importClause.namedBindings.kind === 274 /* NamespaceImport */ ) { const namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ void 0; return visibleDefaultBinding || namedBindings ? factory2.updateImportDeclaration(decl, decl.modifiers, factory2.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)) : void 0; } @@ -86186,73 +87815,73 @@ ${lanes.join("\n")} const oldDiag = getSymbolAccessibilityDiagnostic; const canProduceDiagnostic = canProduceDiagnostics(input); const oldWithinObjectLiteralType = suppressNewDiagnosticContexts; - let shouldEnterSuppressNewDiagnosticsContextContext = (input.kind === 184 /* TypeLiteral */ || input.kind === 197 /* MappedType */ ) && input.parent.kind !== 262 /* TypeAliasDeclaration */ ; + let shouldEnterSuppressNewDiagnosticsContextContext = (input.kind === 187 /* TypeLiteral */ || input.kind === 200 /* MappedType */ ) && input.parent.kind !== 265 /* TypeAliasDeclaration */ ; if (isMethodDeclaration(input) || isMethodSignature(input)) { if (hasEffectiveModifier(input, 8 /* Private */ )) { if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) return; - return cleanup(factory2.createPropertyDeclaration(ensureModifiers(input), input.name, /*questionToken*/ void 0, /*type*/ void 0, /*initializer*/ void 0)); + return cleanup(factory2.createPropertyDeclaration(ensureModifiers(input), input.name, /*questionOrExclamationToken*/ void 0, /*type*/ void 0, /*initializer*/ void 0)); } } if (canProduceDiagnostic && !suppressNewDiagnosticContexts) getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(input); if (isTypeQueryNode(input)) checkEntityNameVisibility(input.exprName, enclosingDeclaration); if (shouldEnterSuppressNewDiagnosticsContextContext) suppressNewDiagnosticContexts = true; if (isProcessedComponent(input)) switch(input.kind){ - case 230 /* ExpressionWithTypeArguments */ : + case 233 /* ExpressionWithTypeArguments */ : { if (isEntityName(input.expression) || isEntityNameExpression(input.expression)) checkEntityNameVisibility(input.expression, enclosingDeclaration); const node = visitEachChild(input, visitDeclarationSubtree, context); return cleanup(factory2.updateExpressionWithTypeArguments(node, node.expression, node.typeArguments)); } - case 180 /* TypeReference */ : + case 183 /* TypeReference */ : { checkEntityNameVisibility(input.typeName, enclosingDeclaration); const node = visitEachChild(input, visitDeclarationSubtree, context); return cleanup(factory2.updateTypeReferenceNode(node, node.typeName, node.typeArguments)); } - case 177 /* ConstructSignature */ : + case 180 /* ConstructSignature */ : return cleanup(factory2.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); - case 173 /* Constructor */ : + case 176 /* Constructor */ : { const ctor = factory2.createConstructorDeclaration(/*modifiers*/ ensureModifiers(input), updateParamsList(input, input.parameters, 0 /* None */ ), /*body*/ void 0); return cleanup(ctor); } - case 171 /* MethodDeclaration */ : + case 174 /* MethodDeclaration */ : { if (isPrivateIdentifier(input.name)) return cleanup(/*returnValue*/ void 0); const sig = factory2.createMethodDeclaration(ensureModifiers(input), /*asteriskToken*/ void 0, input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ void 0); return cleanup(sig); } - case 174 /* GetAccessor */ : + case 177 /* GetAccessor */ : { if (isPrivateIdentifier(input.name)) return cleanup(/*returnValue*/ void 0); const accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input)); return cleanup(factory2.updateGetAccessorDeclaration(input, ensureModifiers(input), input.name, updateAccessorParamsList(input, hasEffectiveModifier(input, 8 /* Private */ )), ensureType(input, accessorType), /*body*/ void 0)); } - case 175 /* SetAccessor */ : + case 178 /* SetAccessor */ : if (isPrivateIdentifier(input.name)) return cleanup(/*returnValue*/ void 0); return cleanup(factory2.updateSetAccessorDeclaration(input, ensureModifiers(input), input.name, updateAccessorParamsList(input, hasEffectiveModifier(input, 8 /* Private */ )), /*body*/ void 0)); - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : if (isPrivateIdentifier(input.name)) return cleanup(/*returnValue*/ void 0); return cleanup(factory2.updatePropertyDeclaration(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); - case 168 /* PropertySignature */ : + case 171 /* PropertySignature */ : if (isPrivateIdentifier(input.name)) return cleanup(/*returnValue*/ void 0); return cleanup(factory2.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type))); - case 170 /* MethodSignature */ : + case 173 /* MethodSignature */ : if (isPrivateIdentifier(input.name)) return cleanup(/*returnValue*/ void 0); return cleanup(factory2.updateMethodSignature(input, ensureModifiers(input), input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); - case 176 /* CallSignature */ : + case 179 /* CallSignature */ : return cleanup(factory2.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); - case 178 /* IndexSignature */ : - return cleanup(factory2.updateIndexSignature(input, ensureModifiers(input), updateParamsList(input, input.parameters), visitNode(input.type, visitDeclarationSubtree, isTypeNode) || factory2.createKeywordTypeNode(131 /* AnyKeyword */ ))); - case 257 /* VariableDeclaration */ : + case 181 /* IndexSignature */ : + return cleanup(factory2.updateIndexSignature(input, ensureModifiers(input), updateParamsList(input, input.parameters), visitNode(input.type, visitDeclarationSubtree, isTypeNode) || factory2.createKeywordTypeNode(133 /* AnyKeyword */ ))); + case 260 /* VariableDeclaration */ : if (isBindingPattern(input.name)) return recreateBindingPattern(input.name); shouldEnterSuppressNewDiagnosticsContextContext = true; suppressNewDiagnosticContexts = true; return cleanup(factory2.updateVariableDeclaration(input, input.name, /*exclamationToken*/ void 0, ensureType(input, input.type), ensureNoInitializer(input))); - case 165 /* TypeParameter */ : + case 168 /* TypeParameter */ : if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) return cleanup(factory2.updateTypeParameterDeclaration(input, input.modifiers, input.name, /*constraint*/ void 0, /*defaultType*/ void 0)); return cleanup(visitEachChild(input, visitDeclarationSubtree, context)); - case 191 /* ConditionalType */ : + case 194 /* ConditionalType */ : { const checkType = visitNode(input.checkType, visitDeclarationSubtree, isTypeNode); const extendsType = visitNode(input.extendsType, visitDeclarationSubtree, isTypeNode); @@ -86267,11 +87896,11 @@ ${lanes.join("\n")} Debug.assert(falseType); return cleanup(factory2.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); } - case 181 /* FunctionType */ : + case 184 /* FunctionType */ : return cleanup(factory2.updateFunctionTypeNode(input, visitNodes2(input.typeParameters, visitDeclarationSubtree, isTypeParameterDeclaration), updateParamsList(input, input.parameters), Debug.checkDefined(visitNode(input.type, visitDeclarationSubtree, isTypeNode)))); - case 182 /* ConstructorType */ : + case 185 /* ConstructorType */ : return cleanup(factory2.updateConstructorTypeNode(input, ensureModifiers(input), visitNodes2(input.typeParameters, visitDeclarationSubtree, isTypeParameterDeclaration), updateParamsList(input, input.parameters), Debug.checkDefined(visitNode(input.type, visitDeclarationSubtree, isTypeNode)))); - case 202 /* ImportType */ : + case 205 /* ImportType */ : if (!isLiteralImportTypeNode(input)) return cleanup(input); return cleanup(factory2.updateImportTypeNode(input, factory2.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.assertions, input.qualifier, visitNodes2(input.typeArguments, visitDeclarationSubtree, isTypeNode), input.isTypeOf)); default: @@ -86289,20 +87918,20 @@ ${lanes.join("\n")} } } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 171 /* MethodDeclaration */ && hasEffectiveModifier(node.parent, 8 /* Private */ ); + return node.parent.kind === 174 /* MethodDeclaration */ && hasEffectiveModifier(node.parent, 8 /* Private */ ); } function visitDeclarationStatements(input) { if (!isPreservedDeclarationStatement(input)) return; if (shouldStripInternal(input)) return; switch(input.kind){ - case 275 /* ExportDeclaration */ : + case 278 /* ExportDeclaration */ : if (isSourceFile(input.parent)) resultHasExternalModuleIndicator = true; resultHasScopeMarker = true; return factory2.updateExportDeclaration(input, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), getResolutionModeOverrideForClause(input.assertClause) ? input.assertClause : void 0); - case 274 /* ExportAssignment */ : + case 277 /* ExportAssignment */ : if (isSourceFile(input.parent)) resultHasExternalModuleIndicator = true; resultHasScopeMarker = true; - if (input.expression.kind === 79 /* Identifier */ ) return input; + if (input.expression.kind === 80 /* Identifier */ ) return input; else { const newId = factory2.createUniqueName("_default", 16 /* Optimistic */ ); getSymbolAccessibilityDiagnostic = ()=>({ @@ -86313,7 +87942,7 @@ ${lanes.join("\n")} const varDecl = factory2.createVariableDeclaration(newId, /*exclamationToken*/ void 0, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ void 0); errorFallbackNode = void 0; const statement = factory2.createVariableStatement(needsDeclare ? [ - factory2.createModifier(136 /* DeclareKeyword */ ) + factory2.createModifier(138 /* DeclareKeyword */ ) ] : [], factory2.createVariableDeclarationList([ varDecl ], 2 /* Const */ )); @@ -86334,15 +87963,23 @@ ${lanes.join("\n")} const modifiers = factory2.createModifiersFromModifierFlags(getEffectiveModifierFlags(statement) & 258046 /* Export */ ); return factory2.updateModifiers(statement, modifiers); } + function updateModuleDeclarationAndKeyword(node, modifiers, name, body) { + const updated = factory2.updateModuleDeclaration(node, modifiers, name, body); + if (isAmbientModule(updated) || updated.flags & 32 /* Namespace */ ) return updated; + const fixed = factory2.createModuleDeclaration(updated.modifiers, updated.name, updated.body, updated.flags | 32 /* Namespace */ ); + setOriginalNode(fixed, updated); + setTextRange(fixed, updated); + return fixed; + } function transformTopLevelDeclaration(input) { if (lateMarkedStatements) { while(orderedRemoveItem(lateMarkedStatements, input)); } if (shouldStripInternal(input)) return; switch(input.kind){ - case 268 /* ImportEqualsDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : return transformImportEqualsDeclaration(input); - case 269 /* ImportDeclaration */ : + case 272 /* ImportDeclaration */ : return transformImportDeclaration(input); } if (isDeclaration(input) && isDeclarationAndNotVisible(input)) return; @@ -86357,31 +87994,32 @@ ${lanes.join("\n")} if (canProdiceDiagnostic) getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(input); const previousNeedsDeclare = needsDeclare; switch(input.kind){ - case 262 /* TypeAliasDeclaration */ : + case 265 /* TypeAliasDeclaration */ : { needsDeclare = false; const clean2 = cleanup(factory2.updateTypeAliasDeclaration(input, ensureModifiers(input), input.name, visitNodes2(input.typeParameters, visitDeclarationSubtree, isTypeParameterDeclaration), Debug.checkDefined(visitNode(input.type, visitDeclarationSubtree, isTypeNode)))); needsDeclare = previousNeedsDeclare; return clean2; } - case 261 /* InterfaceDeclaration */ : + case 264 /* InterfaceDeclaration */ : return cleanup(factory2.updateInterfaceDeclaration(input, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), visitNodes2(input.members, visitDeclarationSubtree, isTypeElement))); - case 259 /* FunctionDeclaration */ : + case 262 /* FunctionDeclaration */ : { const clean2 = cleanup(factory2.updateFunctionDeclaration(input, ensureModifiers(input), /*asteriskToken*/ void 0, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ void 0)); if (clean2 && resolver.isExpandoFunctionDeclaration(input) && shouldEmitFunctionProperties(input)) { const props = resolver.getPropertiesOfContainerFunction(input); - const fakespace = parseNodeFactory.createModuleDeclaration(/*modifiers*/ void 0, clean2.name || factory2.createIdentifier("_default"), factory2.createModuleBlock([]), 16 /* Namespace */ ); + const fakespace = parseNodeFactory.createModuleDeclaration(/*modifiers*/ void 0, clean2.name || factory2.createIdentifier("_default"), factory2.createModuleBlock([]), 32 /* Namespace */ ); setParent(fakespace, enclosingDeclaration); fakespace.locals = createSymbolTable(props); fakespace.symbol = props[0].parent; const exportMappings = []; let declarations = mapDefined(props, (p)=>{ - if (!p.valueDeclaration || !isPropertyAccessExpression(p.valueDeclaration)) return void 0; + if (!p.valueDeclaration || !(isPropertyAccessExpression(p.valueDeclaration) || isElementAccessExpression(p.valueDeclaration) || isBinaryExpression(p.valueDeclaration))) return void 0; + const nameStr = unescapeLeadingUnderscores(p.escapedName); + if (!isIdentifierText(nameStr, 99 /* ESNext */ )) return void 0; getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration); const type = resolver.createTypeOfDeclaration(p.valueDeclaration, fakespace, declarationEmitNodeBuilderFlags, symbolTracker); getSymbolAccessibilityDiagnostic = oldDiag; - const nameStr = unescapeLeadingUnderscores(p.escapedName); const isNonContextualKeywordName = isStringANonContextualKeyword(nameStr); const name = isNonContextualKeywordName ? factory2.getGeneratedNameForNode(p.valueDeclaration) : factory2.createIdentifier(nameStr); if (isNonContextualKeywordName) exportMappings.push([ @@ -86390,7 +88028,7 @@ ${lanes.join("\n")} ]); const varDecl = factory2.createVariableDeclaration(name, /*exclamationToken*/ void 0, type, /*initializer*/ void 0); return factory2.createVariableStatement(isNonContextualKeywordName ? void 0 : [ - factory2.createToken(93 /* ExportKeyword */ ) + factory2.createToken(95 /* ExportKeyword */ ) ], factory2.createVariableDeclarationList([ varDecl ])); @@ -86399,7 +88037,7 @@ ${lanes.join("\n")} else declarations.push(factory2.createExportDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, factory2.createNamedExports(map(exportMappings, ([gen, exp])=>{ return factory2.createExportSpecifier(/*isTypeOnly*/ false, gen, exp); })))); - const namespaceDecl = factory2.createModuleDeclaration(ensureModifiers(input), input.name, factory2.createModuleBlock(declarations), 16 /* Namespace */ ); + const namespaceDecl = factory2.createModuleDeclaration(ensureModifiers(input), input.name, factory2.createModuleBlock(declarations), 32 /* Namespace */ ); if (!hasEffectiveModifier(clean2, 1024 /* Default */ )) return [ clean2, namespaceDecl @@ -86417,18 +88055,18 @@ ${lanes.join("\n")} ]; } else return clean2; } - case 264 /* ModuleDeclaration */ : + case 267 /* ModuleDeclaration */ : { needsDeclare = false; const inner = input.body; - if (inner && inner.kind === 265 /* ModuleBlock */ ) { + if (inner && inner.kind === 268 /* ModuleBlock */ ) { const oldNeedsScopeFix = needsScopeFixMarker; const oldHasScopeFix = resultHasScopeMarker; resultHasScopeMarker = false; needsScopeFixMarker = false; const statements = visitNodes2(inner.statements, visitDeclarationStatements, isStatement); let lateStatements = transformAndReplaceLatePaintedStatements(statements); - if (input.flags & 16777216 /* Ambient */ ) needsScopeFixMarker = false; + if (input.flags & 33554432 /* Ambient */ ) needsScopeFixMarker = false; if (!isGlobalScopeAugmentation(input) && !hasScopeMarker2(lateStatements) && !resultHasScopeMarker) { if (needsScopeFixMarker) lateStatements = factory2.createNodeArray([ ...lateStatements, @@ -86441,7 +88079,7 @@ ${lanes.join("\n")} needsScopeFixMarker = oldNeedsScopeFix; resultHasScopeMarker = oldHasScopeFix; const mods = ensureModifiers(input); - return cleanup(factory2.updateModuleDeclaration(input, mods, isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); + return cleanup(updateModuleDeclarationAndKeyword(input, mods, isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); } else { needsDeclare = previousNeedsDeclare; const mods = ensureModifiers(input); @@ -86450,10 +88088,10 @@ ${lanes.join("\n")} const id = getOriginalNodeId(inner); const body = lateStatementReplacementMap.get(id); lateStatementReplacementMap.delete(id); - return cleanup(factory2.updateModuleDeclaration(input, mods, input.name, body)); + return cleanup(updateModuleDeclarationAndKeyword(input, mods, input.name, body)); } } - case 260 /* ClassDeclaration */ : + case 263 /* ClassDeclaration */ : { errorNameNode = input.name; errorFallbackNode = input; @@ -86466,7 +88104,7 @@ ${lanes.join("\n")} parameterProperties = compact(flatMap(ctor.parameters, (param)=>{ if (!hasSyntacticModifier(param, 16476 /* ParameterPropertyModifier */ ) || shouldStripInternal(param)) return; getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(param); - if (param.name.kind === 79 /* Identifier */ ) return preserveJsDoc(factory2.createPropertyDeclaration(ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); + if (param.name.kind === 80 /* Identifier */ ) return preserveJsDoc(factory2.createPropertyDeclaration(ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); else return walkBindingPattern(param.name); function walkBindingPattern(pattern) { let elems; @@ -86474,7 +88112,7 @@ ${lanes.join("\n")} if (isOmittedExpression(elem)) continue; if (isBindingPattern(elem.name)) elems = concatenate(elems, walkBindingPattern(elem.name)); elems = elems || []; - elems.push(factory2.createPropertyDeclaration(ensureModifiers(param), elem.name, /*questionToken*/ void 0, ensureType(elem, /*type*/ void 0), /*initializer*/ void 0)); + elems.push(factory2.createPropertyDeclaration(ensureModifiers(param), elem.name, /*questionOrExclamationToken*/ void 0, ensureType(elem, /*type*/ void 0), /*initializer*/ void 0)); } return elems; } @@ -86483,12 +88121,12 @@ ${lanes.join("\n")} } const hasPrivateIdentifier = some(input.members, (member)=>!!member.name && isPrivateIdentifier(member.name)); const privateIdentifier = hasPrivateIdentifier ? [ - factory2.createPropertyDeclaration(/*modifiers*/ void 0, factory2.createPrivateIdentifier("#private"), /*questionToken*/ void 0, /*type*/ void 0, /*initializer*/ void 0) + factory2.createPropertyDeclaration(/*modifiers*/ void 0, factory2.createPrivateIdentifier("#private"), /*questionOrExclamationToken*/ void 0, /*type*/ void 0, /*initializer*/ void 0) ] : void 0; const memberNodes = concatenate(concatenate(privateIdentifier, parameterProperties), visitNodes2(input.members, visitDeclarationSubtree, isClassElement)); const members = factory2.createNodeArray(memberNodes); const extendsClause = getEffectiveBaseTypeNode(input); - if (extendsClause && !isEntityNameExpression(extendsClause.expression) && extendsClause.expression.kind !== 104 /* NullKeyword */ ) { + if (extendsClause && !isEntityNameExpression(extendsClause.expression) && extendsClause.expression.kind !== 106 /* NullKeyword */ ) { const oldId = input.name ? unescapeLeadingUnderscores(input.name.escapedText) : "default"; const newId = factory2.createUniqueName(`${oldId}_base`, 16 /* Optimistic */ ); getSymbolAccessibilityDiagnostic = ()=>({ @@ -86498,19 +88136,19 @@ ${lanes.join("\n")} }); const varDecl = factory2.createVariableDeclaration(newId, /*exclamationToken*/ void 0, resolver.createTypeOfExpression(extendsClause.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ void 0); const statement = factory2.createVariableStatement(needsDeclare ? [ - factory2.createModifier(136 /* DeclareKeyword */ ) + factory2.createModifier(138 /* DeclareKeyword */ ) ] : [], factory2.createVariableDeclarationList([ varDecl ], 2 /* Const */ )); const heritageClauses = factory2.createNodeArray(map(input.heritageClauses, (clause)=>{ - if (clause.token === 94 /* ExtendsKeyword */ ) { + if (clause.token === 96 /* ExtendsKeyword */ ) { const oldDiag2 = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); const newClause = factory2.updateHeritageClause(clause, map(clause.types, (t)=>factory2.updateExpressionWithTypeArguments(t, newId, visitNodes2(t.typeArguments, visitDeclarationSubtree, isTypeNode)))); getSymbolAccessibilityDiagnostic = oldDiag2; return newClause; } - return factory2.updateHeritageClause(clause, visitNodes2(factory2.createNodeArray(filter(clause.types, (t)=>isEntityNameExpression(t.expression) || t.expression.kind === 104 /* NullKeyword */ )), visitDeclarationSubtree, isExpressionWithTypeArguments)); + return factory2.updateHeritageClause(clause, visitNodes2(factory2.createNodeArray(filter(clause.types, (t)=>isEntityNameExpression(t.expression) || t.expression.kind === 106 /* NullKeyword */ )), visitDeclarationSubtree, isExpressionWithTypeArguments)); })); return [ statement, @@ -86521,9 +88159,9 @@ ${lanes.join("\n")} return cleanup(factory2.updateClassDeclaration(input, modifiers, input.name, typeParameters, heritageClauses, members)); } } - case 240 /* VariableStatement */ : + case 243 /* VariableStatement */ : return cleanup(transformVariableStatement(input)); - case 263 /* EnumDeclaration */ : + case 266 /* EnumDeclaration */ : return cleanup(factory2.updateEnumDeclaration(input, factory2.createNodeArray(ensureModifiers(input)), input.name, factory2.createNodeArray(mapDefined(input.members, (m)=>{ if (shouldStripInternal(m)) return; const constValue = resolver.getConstantValue(m); @@ -86534,7 +88172,7 @@ ${lanes.join("\n")} function cleanup(node) { if (isEnclosingDeclaration(input)) enclosingDeclaration = previousEnclosingDeclaration; if (canProdiceDiagnostic) getSymbolAccessibilityDiagnostic = oldDiag; - if (input.kind === 264 /* ModuleDeclaration */ ) needsDeclare = previousNeedsDeclare; + if (input.kind === 267 /* ModuleDeclaration */ ) needsDeclare = previousNeedsDeclare; if (node === input) return node; errorFallbackNode = void 0; errorNameNode = void 0; @@ -86545,13 +88183,21 @@ ${lanes.join("\n")} if (!forEach(input.declarationList.declarations, getBindingNameVisible)) return; const nodes = visitNodes2(input.declarationList.declarations, visitDeclarationSubtree, isVariableDeclaration); if (!length(nodes)) return; - return factory2.updateVariableStatement(input, factory2.createNodeArray(ensureModifiers(input)), factory2.updateVariableDeclarationList(input.declarationList, nodes)); + const modifiers = factory2.createNodeArray(ensureModifiers(input)); + let declList; + if (isVarUsing(input.declarationList) || isVarAwaitUsing(input.declarationList)) { + declList = factory2.createVariableDeclarationList(nodes, 2 /* Const */ ); + setOriginalNode(declList, input.declarationList); + setTextRange(declList, input.declarationList); + setCommentRange(declList, input.declarationList); + } else declList = factory2.updateVariableDeclarationList(input.declarationList, nodes); + return factory2.updateVariableStatement(input, modifiers, declList); } function recreateBindingPattern(d) { return flatten(mapDefined(d.elements, (e)=>recreateBindingElement(e))); } function recreateBindingElement(e) { - if (e.kind === 229 /* OmittedExpression */ ) return; + if (e.kind === 232 /* OmittedExpression */ ) return; if (e.name) { if (!getBindingNameVisible(e)) return; if (isBindingPattern(e.name)) return recreateBindingPattern(e.name); @@ -86590,7 +88236,7 @@ ${lanes.join("\n")} function ensureModifierFlags(node) { let mask2 = 241147; let additions = needsDeclare && !isAlwaysType(node) ? 2 /* Ambient */ : 0 /* None */ ; - const parentIsFile = node.parent.kind === 308 /* SourceFile */ ; + const parentIsFile = node.parent.kind === 312 /* SourceFile */ ; if (!parentIsFile || isBundledEmit && parentIsFile && isExternalModule(node.parent)) { mask2 ^= 2 /* Ambient */ ; additions = 0 /* None */ ; @@ -86611,16 +88257,16 @@ ${lanes.join("\n")} } function transformHeritageClauses(nodes) { return factory2.createNodeArray(filter(map(nodes, (clause)=>factory2.updateHeritageClause(clause, visitNodes2(factory2.createNodeArray(filter(clause.types, (t)=>{ - return isEntityNameExpression(t.expression) || clause.token === 94 /* ExtendsKeyword */ && t.expression.kind === 104 /* NullKeyword */ ; + return isEntityNameExpression(t.expression) || clause.token === 96 /* ExtendsKeyword */ && t.expression.kind === 106 /* NullKeyword */ ; })), visitDeclarationSubtree, isExpressionWithTypeArguments))), (clause)=>clause.types && !!clause.types.length)); } } function isAlwaysType(node) { - if (node.kind === 261 /* InterfaceDeclaration */ ) return true; + if (node.kind === 264 /* InterfaceDeclaration */ ) return true; return false; } - function maskModifiers(node, modifierMask, modifierAdditions) { - return factory.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); + function maskModifiers(factory2, node, modifierMask, modifierAdditions) { + return factory2.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); } function maskModifierFlags(node, modifierMask = 258043 /* Public */ , modifierAdditions = 0 /* None */ ) { let flags = getEffectiveModifierFlags(node) & modifierMask | modifierAdditions; @@ -86629,56 +88275,56 @@ ${lanes.join("\n")} return flags; } function getTypeAnnotationFromAccessor(accessor) { - if (accessor) return accessor.kind === 174 /* GetAccessor */ ? accessor.type : accessor.parameters.length > 0 ? accessor.parameters[0].type : void 0; + if (accessor) return accessor.kind === 177 /* GetAccessor */ ? accessor.type : accessor.parameters.length > 0 ? accessor.parameters[0].type : void 0; } function canHaveLiteralInitializer(node) { switch(node.kind){ - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : return !hasEffectiveModifier(node, 8 /* Private */ ); - case 166 /* Parameter */ : - case 257 /* VariableDeclaration */ : + case 169 /* Parameter */ : + case 260 /* VariableDeclaration */ : return true; } return false; } function isPreservedDeclarationStatement(node) { switch(node.kind){ - case 259 /* FunctionDeclaration */ : - case 264 /* ModuleDeclaration */ : - case 268 /* ImportEqualsDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 260 /* ClassDeclaration */ : - case 262 /* TypeAliasDeclaration */ : - case 263 /* EnumDeclaration */ : - case 240 /* VariableStatement */ : - case 269 /* ImportDeclaration */ : - case 275 /* ExportDeclaration */ : - case 274 /* ExportAssignment */ : + case 262 /* FunctionDeclaration */ : + case 267 /* ModuleDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 263 /* ClassDeclaration */ : + case 265 /* TypeAliasDeclaration */ : + case 266 /* EnumDeclaration */ : + case 243 /* VariableStatement */ : + case 272 /* ImportDeclaration */ : + case 278 /* ExportDeclaration */ : + case 277 /* ExportAssignment */ : return true; } return false; } function isProcessedComponent(node) { switch(node.kind){ - case 177 /* ConstructSignature */ : - case 173 /* Constructor */ : - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : - case 170 /* MethodSignature */ : - case 176 /* CallSignature */ : - case 178 /* IndexSignature */ : - case 257 /* VariableDeclaration */ : - case 165 /* TypeParameter */ : - case 230 /* ExpressionWithTypeArguments */ : - case 180 /* TypeReference */ : - case 191 /* ConditionalType */ : - case 181 /* FunctionType */ : - case 182 /* ConstructorType */ : - case 202 /* ImportType */ : + case 180 /* ConstructSignature */ : + case 176 /* Constructor */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : + case 173 /* MethodSignature */ : + case 179 /* CallSignature */ : + case 181 /* IndexSignature */ : + case 260 /* VariableDeclaration */ : + case 168 /* TypeParameter */ : + case 233 /* ExpressionWithTypeArguments */ : + case 183 /* TypeReference */ : + case 194 /* ConditionalType */ : + case 184 /* FunctionType */ : + case 185 /* ConstructorType */ : + case 205 /* ImportType */ : return true; } return false; @@ -86724,10 +88370,10 @@ ${lanes.join("\n")} addRange(transformers, customTransformers && map(customTransformers.before, wrapScriptTransformerFactory)); transformers.push(transformTypeScript); if (compilerOptions.experimentalDecorators) transformers.push(transformLegacyDecorators); - else if (languageVersion < 99 /* ESNext */ || !useDefineForClassFields) transformers.push(transformESDecorators); - transformers.push(transformClassFields); if (getJSXTransformEnabled(compilerOptions)) transformers.push(transformJsx); if (languageVersion < 99 /* ESNext */ ) transformers.push(transformESNext); + if (!compilerOptions.experimentalDecorators && (languageVersion < 99 /* ESNext */ || !useDefineForClassFields)) transformers.push(transformESDecorators); + transformers.push(transformClassFields); if (languageVersion < 8 /* ES2021 */ ) transformers.push(transformES2021); if (languageVersion < 7 /* ES2020 */ ) transformers.push(transformES2020); if (languageVersion < 6 /* ES2019 */ ) transformers.push(transformES2019); @@ -86771,8 +88417,8 @@ ${lanes.join("\n")} callback(hint, node); } function transformNodes(resolver, host, factory2, options, nodes, transformers, allowDtsFiles) { - var _a2, _b; - const enabledSyntaxKindFeatures = new Array(361 /* Count */ ); + var _a, _b; + const enabledSyntaxKindFeatures = new Array(363 /* Count */ ); let lexicalEnvironmentVariableDeclarations; let lexicalEnvironmentFunctionDeclarations; let lexicalEnvironmentStatements; @@ -86847,7 +88493,7 @@ ${lanes.join("\n")} state = 1 /* Initialized */ ; const transformed = []; for (const node of nodes){ - (_a2 = tracing) == null || _a2.push(tracing.Phase.Emit, "transformNodes", node.kind === 308 /* SourceFile */ ? { + (_a = tracing) == null || _a.push(tracing.Phase.Emit, "transformNodes", node.kind === 312 /* SourceFile */ ? { path: node.path } : { kind: node.kind, @@ -87145,7 +88791,7 @@ ${lanes.join("\n")} } function getOutputPathsFor(sourceFile, host, forceDtsPaths) { const options = host.getCompilerOptions(); - if (sourceFile.kind === 309 /* Bundle */ ) return getOutputPathsForBundle(options, forceDtsPaths); + if (sourceFile.kind === 313 /* Bundle */ ) return getOutputPathsForBundle(options, forceDtsPaths); else { const ownOutputFilePath = getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile.fileName, options)); const isJsonFile = isJsonSourceFile(sourceFile); @@ -87204,7 +88850,7 @@ ${lanes.join("\n")} } } function getSingleOutputFileNames(configFile, addOutput) { - const { jsFilePath: jsFilePath , sourceMapFilePath: sourceMapFilePath , declarationFilePath: declarationFilePath , declarationMapPath: declarationMapPath , buildInfoPath: buildInfoPath } = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false); + const { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath } = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false); addOutput(jsFilePath); addOutput(sourceMapFilePath); addOutput(declarationFilePath); @@ -87235,11 +88881,11 @@ ${lanes.join("\n")} if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== directorySeparator) commonSourceDirectory += directorySeparator; return commonSourceDirectory; } - function getCommonSourceDirectoryOfConfig({ options: options , fileNames: fileNames }, ignoreCase) { + function getCommonSourceDirectoryOfConfig({ options: options, fileNames: fileNames }, ignoreCase) { return getCommonSourceDirectory(options, ()=>filter(fileNames, (file)=>!(options.noEmitForJsFiles && fileExtensionIsOneOf(file, supportedJSExtensionsFlat)) && !isDeclarationFileName(file)), getDirectoryPath(normalizeSlashes(Debug.checkDefined(options.configFilePath))), createGetCanonicalFileName(!ignoreCase)); } function getAllProjectOutputs(configFile, ignoreCase) { - const { addOutput: addOutput , getOutputs: getOutputs } = createAddOutput(); + const { addOutput: addOutput, getOutputs: getOutputs } = createAddOutput(); if (outFile(configFile.options)) getSingleOutputFileNames(configFile, addOutput); else { const getCommonSourceDirectory2 = memoize(()=>getCommonSourceDirectoryOfConfig(configFile, ignoreCase)); @@ -87251,14 +88897,14 @@ ${lanes.join("\n")} function getOutputFileNames(commandLine, inputFileName, ignoreCase) { inputFileName = normalizePath(inputFileName); Debug.assert(contains(commandLine.fileNames, inputFileName), `Expected fileName to be present in command line`); - const { addOutput: addOutput , getOutputs: getOutputs } = createAddOutput(); + const { addOutput: addOutput, getOutputs: getOutputs } = createAddOutput(); if (outFile(commandLine.options)) getSingleOutputFileNames(commandLine, addOutput); else getOwnOutputFileNames(commandLine, inputFileName, ignoreCase, addOutput); return getOutputs(); } function getFirstProjectOutput(configFile, ignoreCase) { if (outFile(configFile.options)) { - const { jsFilePath: jsFilePath , declarationFilePath: declarationFilePath } = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false); + const { jsFilePath: jsFilePath, declarationFilePath: declarationFilePath } = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false); return Debug.checkDefined(jsFilePath || declarationFilePath, `project ${configFile.options.configFilePath} expected to have at least one output`); } const getCommonSourceDirectory2 = memoize(()=>getCommonSourceDirectoryOfConfig(configFile, ignoreCase)); @@ -87273,14 +88919,14 @@ ${lanes.join("\n")} if (buildInfoPath) return buildInfoPath; return Debug.fail(`project ${configFile.options.configFilePath} expected to have at least one output`); } - function emitFiles(resolver, host, targetSourceFile, { scriptTransformers: scriptTransformers , declarationTransformers: declarationTransformers }, emitOnly, onlyBuildInfo, forceDtsEmit) { + function emitFiles(resolver, host, targetSourceFile, { scriptTransformers: scriptTransformers, declarationTransformers: declarationTransformers }, emitOnly, onlyBuildInfo, forceDtsEmit) { var compilerOptions = host.getCompilerOptions(); var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap || getAreDeclarationMapsEnabled(compilerOptions) ? [] : void 0; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : void 0; var emitterDiagnostics = createDiagnosticCollection(); var newLine = getNewLineCharacter(compilerOptions); var writer = createTextWriter(newLine); - var { enter: enter , exit: exit } = createTimer("printTime", "beforePrint", "afterPrint"); + var { enter: enter, exit: exit } = createTimer("printTime", "beforePrint", "afterPrint"); var bundleBuildInfo; var emitSkipped = false; enter(); @@ -87292,8 +88938,8 @@ ${lanes.join("\n")} emittedFiles: emittedFilesList, sourceMaps: sourceMapDataList }; - function emitSourceFileOrBundle({ jsFilePath: jsFilePath , sourceMapFilePath: sourceMapFilePath , declarationFilePath: declarationFilePath , declarationMapPath: declarationMapPath , buildInfoPath: buildInfoPath }, sourceFileOrBundle) { - var _a2, _b, _c, _d, _e, _f; + function emitSourceFileOrBundle({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath }, sourceFileOrBundle) { + var _a, _b, _c, _d, _e, _f; let buildInfoDirectory; if (buildInfoPath && sourceFileOrBundle && isBundle(sourceFileOrBundle)) { buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); @@ -87302,7 +88948,7 @@ ${lanes.join("\n")} sourceFiles: sourceFileOrBundle.sourceFiles.map((file)=>relativeToBuildInfo(getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory()))) }; } - (_a2 = tracing) == null || _a2.push(tracing.Phase.Emit, "emitJsFileOrBundle", { + (_a = tracing) == null || _a.push(tracing.Phase.Emit, "emitJsFileOrBundle", { jsFilePath: jsFilePath }); emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo); @@ -87432,7 +89078,7 @@ ${lanes.join("\n")} } function collectLinkedAliases(node) { if (isExportAssignment(node)) { - if (node.expression.kind === 79 /* Identifier */ ) resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true); + if (node.expression.kind === 80 /* Identifier */ ) resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true); return; } else if (isExportSpecifier(node)) { resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); @@ -87442,8 +89088,8 @@ ${lanes.join("\n")} } function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform2, printer, mapOptions) { const sourceFileOrBundle = transform2.transformed[0]; - const bundle = sourceFileOrBundle.kind === 309 /* Bundle */ ? sourceFileOrBundle : void 0; - const sourceFile = sourceFileOrBundle.kind === 308 /* SourceFile */ ? sourceFileOrBundle : void 0; + const bundle = sourceFileOrBundle.kind === 313 /* Bundle */ ? sourceFileOrBundle : void 0; + const sourceFile = sourceFileOrBundle.kind === 312 /* SourceFile */ ? sourceFileOrBundle : void 0; const sourceFiles = bundle ? bundle.sourceFiles : [ sourceFile ]; @@ -87478,7 +89124,7 @@ ${lanes.join("\n")} writer.clear(); } function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { - return (mapOptions.sourceMap || mapOptions.inlineSourceMap) && (sourceFileOrBundle.kind !== 308 /* SourceFile */ || !fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */ )); + return (mapOptions.sourceMap || mapOptions.inlineSourceMap) && (sourceFileOrBundle.kind !== 312 /* SourceFile */ || !fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */ )); } function getSourceRoot(mapOptions) { const sourceRoot = normalizeSlashes(mapOptions.sourceRoot || ""); @@ -87515,11 +89161,10 @@ ${lanes.join("\n")} } } function createBuildInfo(program, bundle) { - const version2 = version; return { bundle: bundle, program: program, - version: version2 + version: version }; } function getBuildInfoText(buildInfo) { @@ -87529,11 +89174,10 @@ ${lanes.join("\n")} return readJsonOrUndefined(buildInfoFile, buildInfoText); } function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) { - var _a2; + var _a; const jsBundle = Debug.checkDefined(bundle.js); - const prologueMap = ((_a2 = jsBundle.sources) == null ? void 0 : _a2.prologues) && arrayToMap(jsBundle.sources.prologues, (prologueInfo)=>prologueInfo.file); + const prologueMap = ((_a = jsBundle.sources) == null ? void 0 : _a.prologues) && arrayToMap(jsBundle.sources.prologues, (prologueInfo)=>prologueInfo.file); return bundle.sourceFiles.map((fileName, index)=>{ - var _a3, _b; const prologueInfo = prologueMap == null ? void 0 : prologueMap.get(index); const statements = prologueInfo == null ? void 0 : prologueInfo.directives.map((directive)=>{ const literal = setTextRange(factory.createStringLiteral(directive.expression.text), directive.expression); @@ -87542,10 +89186,10 @@ ${lanes.join("\n")} return statement; }); const eofToken = factory.createToken(1 /* EndOfFileToken */ ); - const sourceFile = factory.createSourceFile(statements != null ? statements : [], eofToken, 0 /* None */ ); + const sourceFile = factory.createSourceFile(statements ?? [], eofToken, 0 /* None */ ); sourceFile.fileName = getRelativePathFromDirectory(host.getCurrentDirectory(), getNormalizedAbsolutePath(fileName, buildInfoDirectory), !host.useCaseSensitiveFileNames()); - sourceFile.text = (_a3 = prologueInfo == null ? void 0 : prologueInfo.text) != null ? _a3 : ""; - setTextRangePosWidth(sourceFile, 0, (_b = prologueInfo == null ? void 0 : prologueInfo.text.length) != null ? _b : 0); + sourceFile.text = (prologueInfo == null ? void 0 : prologueInfo.text) ?? ""; + setTextRangePosWidth(sourceFile, 0, (prologueInfo == null ? void 0 : prologueInfo.text.length) ?? 0); setEachParent(sourceFile.statements, sourceFile); setTextRangePosWidth(eofToken, sourceFile.end, 0); setParent(eofToken, sourceFile); @@ -87553,17 +89197,17 @@ ${lanes.join("\n")} }); } function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) { - var _a2, _b; - (_a2 = tracing) == null || _a2.push(tracing.Phase.Emit, "emitUsingBuildInfo", {}, /*separateBeginAndEnd*/ true); - ts_performance_exports.mark("beforeEmit"); + var _a, _b; + (_a = tracing) == null || _a.push(tracing.Phase.Emit, "emitUsingBuildInfo", {}, /*separateBeginAndEnd*/ true); + mark("beforeEmit"); const result = emitUsingBuildInfoWorker(config, host, getCommandLine, customTransformers); - ts_performance_exports.mark("afterEmit"); - ts_performance_exports.measure("Emit", "beforeEmit", "afterEmit"); + mark("afterEmit"); + measure("Emit", "beforeEmit", "afterEmit"); (_b = tracing) == null || _b.pop(); return result; } function emitUsingBuildInfoWorker(config, host, getCommandLine, customTransformers) { - const { buildInfoPath: buildInfoPath , jsFilePath: jsFilePath , sourceMapFilePath: sourceMapFilePath , declarationFilePath: declarationFilePath , declarationMapPath: declarationMapPath } = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false); + const { buildInfoPath: buildInfoPath, jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath } = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false); const buildInfo = host.getBuildInfo(buildInfoPath, config.options.configFilePath); if (!buildInfo) return buildInfoPath; if (!buildInfo.bundle || !buildInfo.bundle.js || declarationFilePath && !buildInfo.bundle.dts) return buildInfoPath; @@ -87580,7 +89224,7 @@ ${lanes.join("\n")} if (declarationMapPath && !declarationMapText || config.options.inlineSourceMap) return declarationMapPath || "inline sourcemap decoding"; if (declarationMapPath && computeSignature(declarationMapText, host) !== buildInfo.bundle.dts.mapHash) return declarationMapPath; const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); - const ownPrependInput = createInputFilesWithFileTexts(jsFilePath, jsFileText, sourceMapFilePath, sourceMapText, declarationFilePath, declarationText, declarationMapPath, declarationMapText, buildInfoPath, buildInfo, /*onlyOwnText*/ true); + const ownPrependInput = createInputFilesWithFileTexts(jsFilePath, jsFileText, sourceMapFilePath, sourceMapText, declarationFilePath, declarationText, declarationMapPath, declarationMapText, buildInfoPath, buildInfo, /*oldFileOfCurrentEmit*/ true); const outputFiles = []; const prependNodes = createPrependNodes(config.projectReferences, getCommandLine, (f)=>host.readFile(f), host); const sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host); @@ -87638,7 +89282,7 @@ ${lanes.join("\n")} getBuildInfo: (bundle)=>{ const program = buildInfo.program; if (program && changedDtsText !== void 0 && config.options.composite) program.outSignature = computeSignature(changedDtsText, host, changedDtsData); - const { js: js , dts: dts , sourceFiles: sourceFiles } = buildInfo.bundle; + const { js: js, dts: dts, sourceFiles: sourceFiles } = buildInfo.bundle; bundle.js.sources = js.sources; if (dts) bundle.dts.sources = dts.sources; bundle.sourceFiles = sourceFiles; @@ -87653,7 +89297,7 @@ ${lanes.join("\n")} return outputFiles; } function createPrinter(printerOptions = {}, handlers = {}) { - var { hasGlobalName: hasGlobalName , onEmitNode: onEmitNode = noEmitNotification , isEmitNotificationEnabled: isEmitNotificationEnabled , substituteNode: substituteNode = noEmitSubstitution , onBeforeEmitNode: onBeforeEmitNode , onAfterEmitNode: onAfterEmitNode , onBeforeEmitNodeArray: onBeforeEmitNodeArray , onAfterEmitNodeArray: onAfterEmitNodeArray , onBeforeEmitToken: onBeforeEmitToken , onAfterEmitToken: onAfterEmitToken } = handlers; + var { hasGlobalName: hasGlobalName, onEmitNode: onEmitNode = noEmitNotification, isEmitNotificationEnabled: isEmitNotificationEnabled, substituteNode: substituteNode = noEmitSubstitution, onBeforeEmitNode: onBeforeEmitNode, onAfterEmitNode: onAfterEmitNode, onBeforeEmitNodeArray: onBeforeEmitNodeArray, onAfterEmitNodeArray: onAfterEmitNodeArray, onBeforeEmitToken: onBeforeEmitToken, onAfterEmitToken: onAfterEmitToken } = handlers; var extendedDiagnostics = !!printerOptions.extendedDiagnostics; var newLine = getNewLineCharacter(printerOptions); var moduleKind = getEmitModuleKind(printerOptions); @@ -87701,7 +89345,7 @@ ${lanes.join("\n")} var commentsDisabled = !!printerOptions.removeComments; var lastSubstitution; var currentParenthesizerRule; - var { enter: enterComment , exit: exitComment } = createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"); + var { enter: enterComment, exit: exitComment } = createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"); var parenthesizer = factory.parenthesizer; var typeArgumentParenthesizerRuleSelector = { select: (index)=>index === 0 ? parenthesizer.parenthesizeLeadingTypeArgument : void 0 @@ -87734,11 +89378,11 @@ ${lanes.join("\n")} break; } switch(node.kind){ - case 308 /* SourceFile */ : + case 312 /* SourceFile */ : return printFile(node); - case 309 /* Bundle */ : + case 313 /* Bundle */ : return printBundle(node); - case 310 /* UnparsedSource */ : + case 314 /* UnparsedSource */ : return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); @@ -87749,11 +89393,11 @@ ${lanes.join("\n")} return endPrint(); } function printBundle(bundle) { - writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ void 0); + writeBundle(bundle, beginPrint(), /*sourceMapGenerator*/ void 0); return endPrint(); } function printFile(sourceFile) { - writeFile2(sourceFile, beginPrint(), /*sourceMapEmitter*/ void 0); + writeFile2(sourceFile, beginPrint(), /*sourceMapGenerator*/ void 0); return endPrint(); } function printUnparsedSource(unparsed) { @@ -88012,306 +89656,306 @@ ${lanes.join("\n")} } if (hint === 4 /* Unspecified */ ) { switch(node.kind){ - case 15 /* TemplateHead */ : - case 16 /* TemplateMiddle */ : - case 17 /* TemplateTail */ : + case 16 /* TemplateHead */ : + case 17 /* TemplateMiddle */ : + case 18 /* TemplateTail */ : return emitLiteral(node, /*jsxAttributeEscape*/ false); - case 79 /* Identifier */ : + case 80 /* Identifier */ : return emitIdentifier(node); - case 80 /* PrivateIdentifier */ : + case 81 /* PrivateIdentifier */ : return emitPrivateIdentifier(node); - case 163 /* QualifiedName */ : + case 166 /* QualifiedName */ : return emitQualifiedName(node); - case 164 /* ComputedPropertyName */ : + case 167 /* ComputedPropertyName */ : return emitComputedPropertyName(node); - case 165 /* TypeParameter */ : + case 168 /* TypeParameter */ : return emitTypeParameter(node); - case 166 /* Parameter */ : + case 169 /* Parameter */ : return emitParameter(node); - case 167 /* Decorator */ : + case 170 /* Decorator */ : return emitDecorator(node); - case 168 /* PropertySignature */ : + case 171 /* PropertySignature */ : return emitPropertySignature(node); - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : return emitPropertyDeclaration(node); - case 170 /* MethodSignature */ : + case 173 /* MethodSignature */ : return emitMethodSignature(node); - case 171 /* MethodDeclaration */ : + case 174 /* MethodDeclaration */ : return emitMethodDeclaration(node); - case 172 /* ClassStaticBlockDeclaration */ : + case 175 /* ClassStaticBlockDeclaration */ : return emitClassStaticBlockDeclaration(node); - case 173 /* Constructor */ : + case 176 /* Constructor */ : return emitConstructor(node); - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : return emitAccessorDeclaration(node); - case 176 /* CallSignature */ : + case 179 /* CallSignature */ : return emitCallSignature(node); - case 177 /* ConstructSignature */ : + case 180 /* ConstructSignature */ : return emitConstructSignature(node); - case 178 /* IndexSignature */ : + case 181 /* IndexSignature */ : return emitIndexSignature(node); - case 179 /* TypePredicate */ : + case 182 /* TypePredicate */ : return emitTypePredicate(node); - case 180 /* TypeReference */ : + case 183 /* TypeReference */ : return emitTypeReference(node); - case 181 /* FunctionType */ : + case 184 /* FunctionType */ : return emitFunctionType(node); - case 182 /* ConstructorType */ : + case 185 /* ConstructorType */ : return emitConstructorType(node); - case 183 /* TypeQuery */ : + case 186 /* TypeQuery */ : return emitTypeQuery(node); - case 184 /* TypeLiteral */ : + case 187 /* TypeLiteral */ : return emitTypeLiteral(node); - case 185 /* ArrayType */ : + case 188 /* ArrayType */ : return emitArrayType(node); - case 186 /* TupleType */ : + case 189 /* TupleType */ : return emitTupleType(node); - case 187 /* OptionalType */ : + case 190 /* OptionalType */ : return emitOptionalType(node); - case 189 /* UnionType */ : + case 192 /* UnionType */ : return emitUnionType(node); - case 190 /* IntersectionType */ : + case 193 /* IntersectionType */ : return emitIntersectionType(node); - case 191 /* ConditionalType */ : + case 194 /* ConditionalType */ : return emitConditionalType(node); - case 192 /* InferType */ : + case 195 /* InferType */ : return emitInferType(node); - case 193 /* ParenthesizedType */ : + case 196 /* ParenthesizedType */ : return emitParenthesizedType(node); - case 230 /* ExpressionWithTypeArguments */ : + case 233 /* ExpressionWithTypeArguments */ : return emitExpressionWithTypeArguments(node); - case 194 /* ThisType */ : + case 197 /* ThisType */ : return emitThisType(); - case 195 /* TypeOperator */ : + case 198 /* TypeOperator */ : return emitTypeOperator(node); - case 196 /* IndexedAccessType */ : + case 199 /* IndexedAccessType */ : return emitIndexedAccessType(node); - case 197 /* MappedType */ : + case 200 /* MappedType */ : return emitMappedType(node); - case 198 /* LiteralType */ : + case 201 /* LiteralType */ : return emitLiteralType(node); - case 199 /* NamedTupleMember */ : + case 202 /* NamedTupleMember */ : return emitNamedTupleMember(node); - case 200 /* TemplateLiteralType */ : + case 203 /* TemplateLiteralType */ : return emitTemplateType(node); - case 201 /* TemplateLiteralTypeSpan */ : + case 204 /* TemplateLiteralTypeSpan */ : return emitTemplateTypeSpan(node); - case 202 /* ImportType */ : + case 205 /* ImportType */ : return emitImportTypeNode(node); - case 203 /* ObjectBindingPattern */ : + case 206 /* ObjectBindingPattern */ : return emitObjectBindingPattern(node); - case 204 /* ArrayBindingPattern */ : + case 207 /* ArrayBindingPattern */ : return emitArrayBindingPattern(node); - case 205 /* BindingElement */ : + case 208 /* BindingElement */ : return emitBindingElement(node); - case 236 /* TemplateSpan */ : + case 239 /* TemplateSpan */ : return emitTemplateSpan(node); - case 237 /* SemicolonClassElement */ : + case 240 /* SemicolonClassElement */ : return emitSemicolonClassElement(); - case 238 /* Block */ : + case 241 /* Block */ : return emitBlock(node); - case 240 /* VariableStatement */ : + case 243 /* VariableStatement */ : return emitVariableStatement(node); - case 239 /* EmptyStatement */ : + case 242 /* EmptyStatement */ : return emitEmptyStatement(/*isEmbeddedStatement*/ false); - case 241 /* ExpressionStatement */ : + case 244 /* ExpressionStatement */ : return emitExpressionStatement(node); - case 242 /* IfStatement */ : + case 245 /* IfStatement */ : return emitIfStatement(node); - case 243 /* DoStatement */ : + case 246 /* DoStatement */ : return emitDoStatement(node); - case 244 /* WhileStatement */ : + case 247 /* WhileStatement */ : return emitWhileStatement(node); - case 245 /* ForStatement */ : + case 248 /* ForStatement */ : return emitForStatement(node); - case 246 /* ForInStatement */ : + case 249 /* ForInStatement */ : return emitForInStatement(node); - case 247 /* ForOfStatement */ : + case 250 /* ForOfStatement */ : return emitForOfStatement(node); - case 248 /* ContinueStatement */ : + case 251 /* ContinueStatement */ : return emitContinueStatement(node); - case 249 /* BreakStatement */ : + case 252 /* BreakStatement */ : return emitBreakStatement(node); - case 250 /* ReturnStatement */ : + case 253 /* ReturnStatement */ : return emitReturnStatement(node); - case 251 /* WithStatement */ : + case 254 /* WithStatement */ : return emitWithStatement(node); - case 252 /* SwitchStatement */ : + case 255 /* SwitchStatement */ : return emitSwitchStatement(node); - case 253 /* LabeledStatement */ : + case 256 /* LabeledStatement */ : return emitLabeledStatement(node); - case 254 /* ThrowStatement */ : + case 257 /* ThrowStatement */ : return emitThrowStatement(node); - case 255 /* TryStatement */ : + case 258 /* TryStatement */ : return emitTryStatement(node); - case 256 /* DebuggerStatement */ : + case 259 /* DebuggerStatement */ : return emitDebuggerStatement(node); - case 257 /* VariableDeclaration */ : + case 260 /* VariableDeclaration */ : return emitVariableDeclaration(node); - case 258 /* VariableDeclarationList */ : + case 261 /* VariableDeclarationList */ : return emitVariableDeclarationList(node); - case 259 /* FunctionDeclaration */ : + case 262 /* FunctionDeclaration */ : return emitFunctionDeclaration(node); - case 260 /* ClassDeclaration */ : + case 263 /* ClassDeclaration */ : return emitClassDeclaration(node); - case 261 /* InterfaceDeclaration */ : + case 264 /* InterfaceDeclaration */ : return emitInterfaceDeclaration(node); - case 262 /* TypeAliasDeclaration */ : + case 265 /* TypeAliasDeclaration */ : return emitTypeAliasDeclaration(node); - case 263 /* EnumDeclaration */ : + case 266 /* EnumDeclaration */ : return emitEnumDeclaration(node); - case 264 /* ModuleDeclaration */ : + case 267 /* ModuleDeclaration */ : return emitModuleDeclaration(node); - case 265 /* ModuleBlock */ : + case 268 /* ModuleBlock */ : return emitModuleBlock(node); - case 266 /* CaseBlock */ : + case 269 /* CaseBlock */ : return emitCaseBlock(node); - case 267 /* NamespaceExportDeclaration */ : + case 270 /* NamespaceExportDeclaration */ : return emitNamespaceExportDeclaration(node); - case 268 /* ImportEqualsDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : return emitImportEqualsDeclaration(node); - case 269 /* ImportDeclaration */ : + case 272 /* ImportDeclaration */ : return emitImportDeclaration(node); - case 270 /* ImportClause */ : + case 273 /* ImportClause */ : return emitImportClause(node); - case 271 /* NamespaceImport */ : + case 274 /* NamespaceImport */ : return emitNamespaceImport(node); - case 277 /* NamespaceExport */ : + case 280 /* NamespaceExport */ : return emitNamespaceExport(node); - case 272 /* NamedImports */ : + case 275 /* NamedImports */ : return emitNamedImports(node); - case 273 /* ImportSpecifier */ : + case 276 /* ImportSpecifier */ : return emitImportSpecifier(node); - case 274 /* ExportAssignment */ : + case 277 /* ExportAssignment */ : return emitExportAssignment(node); - case 275 /* ExportDeclaration */ : + case 278 /* ExportDeclaration */ : return emitExportDeclaration(node); - case 276 /* NamedExports */ : + case 279 /* NamedExports */ : return emitNamedExports(node); - case 278 /* ExportSpecifier */ : + case 281 /* ExportSpecifier */ : return emitExportSpecifier(node); - case 296 /* AssertClause */ : + case 300 /* AssertClause */ : return emitAssertClause(node); - case 297 /* AssertEntry */ : + case 301 /* AssertEntry */ : return emitAssertEntry(node); - case 279 /* MissingDeclaration */ : + case 282 /* MissingDeclaration */ : return; - case 280 /* ExternalModuleReference */ : + case 283 /* ExternalModuleReference */ : return emitExternalModuleReference(node); - case 11 /* JsxText */ : + case 12 /* JsxText */ : return emitJsxText(node); - case 283 /* JsxOpeningElement */ : - case 286 /* JsxOpeningFragment */ : + case 286 /* JsxOpeningElement */ : + case 289 /* JsxOpeningFragment */ : return emitJsxOpeningElementOrFragment(node); - case 284 /* JsxClosingElement */ : - case 287 /* JsxClosingFragment */ : + case 287 /* JsxClosingElement */ : + case 290 /* JsxClosingFragment */ : return emitJsxClosingElementOrFragment(node); - case 288 /* JsxAttribute */ : + case 291 /* JsxAttribute */ : return emitJsxAttribute(node); - case 289 /* JsxAttributes */ : + case 292 /* JsxAttributes */ : return emitJsxAttributes(node); - case 290 /* JsxSpreadAttribute */ : + case 293 /* JsxSpreadAttribute */ : return emitJsxSpreadAttribute(node); - case 291 /* JsxExpression */ : + case 294 /* JsxExpression */ : return emitJsxExpression(node); - case 292 /* CaseClause */ : + case 295 /* JsxNamespacedName */ : + return emitJsxNamespacedName(node); + case 296 /* CaseClause */ : return emitCaseClause(node); - case 293 /* DefaultClause */ : + case 297 /* DefaultClause */ : return emitDefaultClause(node); - case 294 /* HeritageClause */ : + case 298 /* HeritageClause */ : return emitHeritageClause(node); - case 295 /* CatchClause */ : + case 299 /* CatchClause */ : return emitCatchClause(node); - case 299 /* PropertyAssignment */ : + case 303 /* PropertyAssignment */ : return emitPropertyAssignment(node); - case 300 /* ShorthandPropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : return emitShorthandPropertyAssignment(node); - case 301 /* SpreadAssignment */ : + case 305 /* SpreadAssignment */ : return emitSpreadAssignment(node); - case 302 /* EnumMember */ : + case 306 /* EnumMember */ : return emitEnumMember(node); - case 303 /* UnparsedPrologue */ : + case 307 /* UnparsedPrologue */ : return writeUnparsedNode(node); - case 310 /* UnparsedSource */ : - case 304 /* UnparsedPrepend */ : + case 314 /* UnparsedSource */ : + case 308 /* UnparsedPrepend */ : return emitUnparsedSourceOrPrepend(node); - case 305 /* UnparsedText */ : - case 306 /* UnparsedInternalText */ : + case 309 /* UnparsedText */ : + case 310 /* UnparsedInternalText */ : return emitUnparsedTextLike(node); - case 307 /* UnparsedSyntheticReference */ : + case 311 /* UnparsedSyntheticReference */ : return emitUnparsedSyntheticReference(node); - case 308 /* SourceFile */ : + case 312 /* SourceFile */ : return emitSourceFile(node); - case 309 /* Bundle */ : + case 313 /* Bundle */ : return Debug.fail("Bundles should be printed using printBundle"); - case 311 /* InputFiles */ : + case 315 /* InputFiles */ : return Debug.fail("InputFiles should not be printed"); - case 312 /* JSDocTypeExpression */ : + case 316 /* JSDocTypeExpression */ : return emitJSDocTypeExpression(node); - case 313 /* JSDocNameReference */ : + case 317 /* JSDocNameReference */ : return emitJSDocNameReference(node); - case 315 /* JSDocAllType */ : + case 319 /* JSDocAllType */ : return writePunctuation("*"); - case 316 /* JSDocUnknownType */ : + case 320 /* JSDocUnknownType */ : return writePunctuation("?"); - case 317 /* JSDocNullableType */ : + case 321 /* JSDocNullableType */ : return emitJSDocNullableType(node); - case 318 /* JSDocNonNullableType */ : + case 322 /* JSDocNonNullableType */ : return emitJSDocNonNullableType(node); - case 319 /* JSDocOptionalType */ : + case 323 /* JSDocOptionalType */ : return emitJSDocOptionalType(node); - case 320 /* JSDocFunctionType */ : + case 324 /* JSDocFunctionType */ : return emitJSDocFunctionType(node); - case 188 /* RestType */ : - case 321 /* JSDocVariadicType */ : + case 191 /* RestType */ : + case 325 /* JSDocVariadicType */ : return emitRestOrJSDocVariadicType(node); - case 322 /* JSDocNamepathType */ : + case 326 /* JSDocNamepathType */ : return; - case 323 /* JSDoc */ : + case 327 /* JSDoc */ : return emitJSDoc(node); - case 325 /* JSDocTypeLiteral */ : + case 329 /* JSDocTypeLiteral */ : return emitJSDocTypeLiteral(node); - case 326 /* JSDocSignature */ : + case 330 /* JSDocSignature */ : return emitJSDocSignature(node); - case 330 /* JSDocTag */ : - case 335 /* JSDocClassTag */ : - case 340 /* JSDocOverrideTag */ : + case 334 /* JSDocTag */ : + case 339 /* JSDocClassTag */ : + case 344 /* JSDocOverrideTag */ : return emitJSDocSimpleTag(node); - case 331 /* JSDocAugmentsTag */ : - case 332 /* JSDocImplementsTag */ : + case 335 /* JSDocAugmentsTag */ : + case 336 /* JSDocImplementsTag */ : return emitJSDocHeritageTag(node); - case 333 /* JSDocAuthorTag */ : - case 334 /* JSDocDeprecatedTag */ : + case 337 /* JSDocAuthorTag */ : + case 338 /* JSDocDeprecatedTag */ : return; - case 336 /* JSDocPublicTag */ : - case 337 /* JSDocPrivateTag */ : - case 338 /* JSDocProtectedTag */ : - case 339 /* JSDocReadonlyTag */ : + case 340 /* JSDocPublicTag */ : + case 341 /* JSDocPrivateTag */ : + case 342 /* JSDocProtectedTag */ : + case 343 /* JSDocReadonlyTag */ : return; - case 341 /* JSDocCallbackTag */ : + case 345 /* JSDocCallbackTag */ : return emitJSDocCallbackTag(node); - case 342 /* JSDocOverloadTag */ : + case 346 /* JSDocOverloadTag */ : return emitJSDocOverloadTag(node); - case 344 /* JSDocParameterTag */ : - case 351 /* JSDocPropertyTag */ : + case 348 /* JSDocParameterTag */ : + case 355 /* JSDocPropertyTag */ : return emitJSDocPropertyLikeTag(node); - case 343 /* JSDocEnumTag */ : - case 345 /* JSDocReturnTag */ : - case 346 /* JSDocThisTag */ : - case 347 /* JSDocTypeTag */ : - case 352 /* JSDocThrowsTag */ : - case 353 /* JSDocSatisfiesTag */ : + case 347 /* JSDocEnumTag */ : + case 349 /* JSDocReturnTag */ : + case 350 /* JSDocThisTag */ : + case 351 /* JSDocTypeTag */ : + case 356 /* JSDocThrowsTag */ : + case 357 /* JSDocSatisfiesTag */ : return emitJSDocSimpleTypedTag(node); - case 348 /* JSDocTemplateTag */ : + case 352 /* JSDocTemplateTag */ : return emitJSDocTemplateTag(node); - case 349 /* JSDocTypedefTag */ : + case 353 /* JSDocTypedefTag */ : return emitJSDocTypedefTag(node); - case 350 /* JSDocSeeTag */ : + case 354 /* JSDocSeeTag */ : return emitJSDocSeeTag(node); - case 355 /* NotEmittedStatement */ : - case 359 /* EndOfDeclarationMarker */ : - case 358 /* MergeDeclarationMarker */ : + case 359 /* NotEmittedStatement */ : return; } if (isExpression(node)) { @@ -88326,97 +89970,94 @@ ${lanes.join("\n")} } } if (hint === 1 /* Expression */ ) switch(node.kind){ - case 8 /* NumericLiteral */ : - case 9 /* BigIntLiteral */ : + case 9 /* NumericLiteral */ : + case 10 /* BigIntLiteral */ : return emitNumericOrBigIntLiteral(node); - case 10 /* StringLiteral */ : - case 13 /* RegularExpressionLiteral */ : - case 14 /* NoSubstitutionTemplateLiteral */ : + case 11 /* StringLiteral */ : + case 14 /* RegularExpressionLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : return emitLiteral(node, /*jsxAttributeEscape*/ false); - case 79 /* Identifier */ : + case 80 /* Identifier */ : return emitIdentifier(node); - case 80 /* PrivateIdentifier */ : + case 81 /* PrivateIdentifier */ : return emitPrivateIdentifier(node); - case 206 /* ArrayLiteralExpression */ : + case 209 /* ArrayLiteralExpression */ : return emitArrayLiteralExpression(node); - case 207 /* ObjectLiteralExpression */ : + case 210 /* ObjectLiteralExpression */ : return emitObjectLiteralExpression(node); - case 208 /* PropertyAccessExpression */ : + case 211 /* PropertyAccessExpression */ : return emitPropertyAccessExpression(node); - case 209 /* ElementAccessExpression */ : + case 212 /* ElementAccessExpression */ : return emitElementAccessExpression(node); - case 210 /* CallExpression */ : + case 213 /* CallExpression */ : return emitCallExpression(node); - case 211 /* NewExpression */ : + case 214 /* NewExpression */ : return emitNewExpression(node); - case 212 /* TaggedTemplateExpression */ : + case 215 /* TaggedTemplateExpression */ : return emitTaggedTemplateExpression(node); - case 213 /* TypeAssertionExpression */ : + case 216 /* TypeAssertionExpression */ : return emitTypeAssertionExpression(node); - case 214 /* ParenthesizedExpression */ : + case 217 /* ParenthesizedExpression */ : return emitParenthesizedExpression(node); - case 215 /* FunctionExpression */ : + case 218 /* FunctionExpression */ : return emitFunctionExpression(node); - case 216 /* ArrowFunction */ : + case 219 /* ArrowFunction */ : return emitArrowFunction(node); - case 217 /* DeleteExpression */ : + case 220 /* DeleteExpression */ : return emitDeleteExpression(node); - case 218 /* TypeOfExpression */ : + case 221 /* TypeOfExpression */ : return emitTypeOfExpression(node); - case 219 /* VoidExpression */ : + case 222 /* VoidExpression */ : return emitVoidExpression(node); - case 220 /* AwaitExpression */ : + case 223 /* AwaitExpression */ : return emitAwaitExpression(node); - case 221 /* PrefixUnaryExpression */ : + case 224 /* PrefixUnaryExpression */ : return emitPrefixUnaryExpression(node); - case 222 /* PostfixUnaryExpression */ : + case 225 /* PostfixUnaryExpression */ : return emitPostfixUnaryExpression(node); - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : return emitBinaryExpression(node); - case 224 /* ConditionalExpression */ : + case 227 /* ConditionalExpression */ : return emitConditionalExpression(node); - case 225 /* TemplateExpression */ : + case 228 /* TemplateExpression */ : return emitTemplateExpression(node); - case 226 /* YieldExpression */ : + case 229 /* YieldExpression */ : return emitYieldExpression(node); - case 227 /* SpreadElement */ : + case 230 /* SpreadElement */ : return emitSpreadElement(node); - case 228 /* ClassExpression */ : + case 231 /* ClassExpression */ : return emitClassExpression(node); - case 229 /* OmittedExpression */ : + case 232 /* OmittedExpression */ : return; - case 231 /* AsExpression */ : + case 234 /* AsExpression */ : return emitAsExpression(node); - case 232 /* NonNullExpression */ : + case 235 /* NonNullExpression */ : return emitNonNullExpression(node); - case 230 /* ExpressionWithTypeArguments */ : + case 233 /* ExpressionWithTypeArguments */ : return emitExpressionWithTypeArguments(node); - case 235 /* SatisfiesExpression */ : + case 238 /* SatisfiesExpression */ : return emitSatisfiesExpression(node); - case 233 /* MetaProperty */ : + case 236 /* MetaProperty */ : return emitMetaProperty(node); - case 234 /* SyntheticExpression */ : + case 237 /* SyntheticExpression */ : return Debug.fail("SyntheticExpression should never be printed."); - case 279 /* MissingDeclaration */ : + case 282 /* MissingDeclaration */ : return; - case 281 /* JsxElement */ : + case 284 /* JsxElement */ : return emitJsxElement(node); - case 282 /* JsxSelfClosingElement */ : + case 285 /* JsxSelfClosingElement */ : return emitJsxSelfClosingElement(node); - case 285 /* JsxFragment */ : + case 288 /* JsxFragment */ : return emitJsxFragment(node); - case 354 /* SyntaxList */ : + case 358 /* SyntaxList */ : return Debug.fail("SyntaxList should not be printed"); - case 355 /* NotEmittedStatement */ : + case 359 /* NotEmittedStatement */ : return; - case 356 /* PartiallyEmittedExpression */ : + case 360 /* PartiallyEmittedExpression */ : return emitPartiallyEmittedExpression(node); - case 357 /* CommaListExpression */ : + case 361 /* CommaListExpression */ : return emitCommaList(node); - case 358 /* MergeDeclarationMarker */ : - case 359 /* EndOfDeclarationMarker */ : - return; - case 360 /* SyntheticReferenceExpression */ : + case 362 /* SyntheticReferenceExpression */ : return Debug.fail("SyntheticReferenceExpression should not be printed"); } if (isKeyword(node.kind)) return writeTokenNode(node, writeKeyword); @@ -88454,7 +90095,7 @@ ${lanes.join("\n")} } function emitHelpers(node) { let helpersEmitted = false; - const bundle = node.kind === 309 /* Bundle */ ? node : void 0; + const bundle = node.kind === 313 /* Bundle */ ? node : void 0; if (bundle && moduleKind === 0 /* None */ ) return; const numPrepends = bundle ? bundle.prepends.length : 0; const numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1; @@ -88495,7 +90136,7 @@ ${lanes.join("\n")} } function emitLiteral(node, jsxAttributeEscape) { const text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape, jsxAttributeEscape); - if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind))) writeLiteral(text); + if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 11 /* StringLiteral */ || isTemplateLiteralKind(node.kind))) writeLiteral(text); else writeStringLiteral(text); } function emitUnparsedSourceOrPrepend(unparsed) { @@ -88510,7 +90151,7 @@ ${lanes.join("\n")} function emitUnparsedTextLike(unparsed) { const pos = getTextPosWithWriteLine(); writeUnparsedNode(unparsed); - if (bundleFileInfo) updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 305 /* UnparsedText */ ? "text" /* Text */ : "internal" /* Internal */ ); + if (bundleFileInfo) updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 309 /* UnparsedText */ ? "text" /* Text */ : "internal" /* Internal */ ); } function emitUnparsedSyntheticReference(unparsed) { const pos = getTextPosWithWriteLine(); @@ -88538,7 +90179,7 @@ ${lanes.join("\n")} nonEscapingWrite(`}`); } function emitTabStop(hint, node, snippet) { - Debug.assert(node.kind === 239 /* EmptyStatement */ , `A tab stop cannot be attached to a node of kind ${Debug.formatSyntaxKind(node.kind)}.`); + Debug.assert(node.kind === 242 /* EmptyStatement */ , `A tab stop cannot be attached to a node of kind ${Debug.formatSyntaxKind(node.kind)}.`); Debug.assert(hint !== 5 /* EmbeddedStatement */ , `A tab stop cannot be attached to an embedded statement.`); nonEscapingWrite(`$${snippet.order}`); } @@ -88556,7 +90197,7 @@ ${lanes.join("\n")} emit(node.right); } function emitEntityName(node) { - if (node.kind === 79 /* Identifier */ ) emitExpression(node); + if (node.kind === 80 /* Identifier */ ) emitExpression(node); else emit(node); } function emitComputedPropertyName(node) { @@ -88589,7 +90230,7 @@ ${lanes.join("\n")} emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); - if (node.parent && node.parent.kind === 320 /* JSDocFunctionType */ && !node.name) emit(node.type); + if (node.parent && node.parent.kind === 324 /* JSDocFunctionType */ && !node.name) emit(node.type); else emitTypeAnnotation(node.type); emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } @@ -88642,7 +90283,7 @@ ${lanes.join("\n")} } function emitAccessorDeclaration(node) { const pos = emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ true); - const token = node.kind === 174 /* GetAccessor */ ? 137 /* GetKeyword */ : 151 /* SetKeyword */ ; + const token = node.kind === 177 /* GetAccessor */ ? 139 /* GetKeyword */ : 153 /* SetKeyword */ ; emitTokenWithComment(token, pos, writeKeyword, node); writeSpace(); emit(node.name); @@ -88761,16 +90402,16 @@ ${lanes.join("\n")} emit(node.type); } function emitTupleType(node) { - emitTokenWithComment(22 /* OpenBracketToken */ , node.pos, writePunctuation, node); + emitTokenWithComment(23 /* OpenBracketToken */ , node.pos, writePunctuation, node); const flags = getEmitFlags(node) & 1 /* SingleLine */ ? 528 /* SingleLineTupleTypeElements */ : 657 /* MultiLineTupleTypeElements */ ; emitList(node, node.elements, flags | 524288 /* NoSpaceIfEmpty */ , parenthesizer.parenthesizeElementTypeOfTupleType); - emitTokenWithComment(23 /* CloseBracketToken */ , node.elements.end, writePunctuation, node); + emitTokenWithComment(24 /* CloseBracketToken */ , node.elements.end, writePunctuation, node); } function emitNamedTupleMember(node) { emit(node.dotDotDotToken); emit(node.name); emit(node.questionToken); - emitTokenWithComment(58 /* ColonToken */ , node.name.end, writePunctuation, node); + emitTokenWithComment(59 /* ColonToken */ , node.name.end, writePunctuation, node); writeSpace(); emit(node.type); } @@ -88815,7 +90456,7 @@ ${lanes.join("\n")} function emitTypeOperator(node) { writeTokenText(node.operator, writeKeyword); writeSpace(); - const parenthesizerRule = node.operator === 146 /* ReadonlyKeyword */ ? parenthesizer.parenthesizeOperandOfReadonlyTypeOperator : parenthesizer.parenthesizeOperandOfTypeOperator; + const parenthesizerRule = node.operator === 148 /* ReadonlyKeyword */ ? parenthesizer.parenthesizeOperandOfReadonlyTypeOperator : parenthesizer.parenthesizeOperandOfTypeOperator; emit(node.type, parenthesizerRule); } function emitIndexedAccessType(node) { @@ -88834,7 +90475,7 @@ ${lanes.join("\n")} } if (node.readonlyToken) { emit(node.readonlyToken); - if (node.readonlyToken.kind !== 146 /* ReadonlyKeyword */ ) writeKeyword("readonly"); + if (node.readonlyToken.kind !== 148 /* ReadonlyKeyword */ ) writeKeyword("readonly"); writeSpace(); } writePunctuation("["); @@ -88848,7 +90489,7 @@ ${lanes.join("\n")} writePunctuation("]"); if (node.questionToken) { emit(node.questionToken); - if (node.questionToken.kind !== 57 /* QuestionToken */ ) writePunctuation("?"); + if (node.questionToken.kind !== 58 /* QuestionToken */ ) writePunctuation("?"); } writePunctuation(":"); writeSpace(); @@ -88935,11 +90576,11 @@ ${lanes.join("\n")} } function emitPropertyAccessExpression(node) { emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); - const token = node.questionDotToken || setTextRangePosEnd(factory.createToken(24 /* DotToken */ ), node.expression.end, node.name.pos); + const token = node.questionDotToken || setTextRangePosEnd(factory.createToken(25 /* DotToken */ ), node.expression.end, node.name.pos); const linesBeforeDot = getLinesBetweenNodes(node, node.expression, token); const linesAfterDot = getLinesBetweenNodes(node, token, node.name); writeLinesAndIndent(linesBeforeDot, /*writeSpaceIfNotIndenting*/ false); - const shouldEmitDotDot = token.kind !== 28 /* QuestionDotToken */ && mayNeedDotDotForPropertyAccess(node.expression) && !writer.hasTrailingComment() && !writer.hasTrailingWhitespace(); + const shouldEmitDotDot = token.kind !== 29 /* QuestionDotToken */ && mayNeedDotDotForPropertyAccess(node.expression) && !writer.hasTrailingComment() && !writer.hasTrailingWhitespace(); if (shouldEmitDotDot) writePunctuation("."); if (node.questionDotToken) emit(token); else emitTokenWithComment(token.kind, node.expression.end, writePunctuation, node); @@ -88951,18 +90592,18 @@ ${lanes.join("\n")} expression = skipPartiallyEmittedExpressions(expression); if (isNumericLiteral(expression)) { const text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true, /*jsxAttributeEscape*/ false); - return !expression.numericLiteralFlags && !stringContains(text, tokenToString(24 /* DotToken */ )); + return !(expression.numericLiteralFlags & 448 /* WithSpecifier */ ) && !stringContains(text, tokenToString(25 /* DotToken */ )) && !stringContains(text, String.fromCharCode(69 /* E */ )) && !stringContains(text, String.fromCharCode(101 /* e */ )); } else if (isAccessExpression(expression)) { const constantValue = getConstantValue(expression); - return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue; + return typeof constantValue === "number" && isFinite(constantValue) && constantValue >= 0 && Math.floor(constantValue) === constantValue; } } function emitElementAccessExpression(node) { emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); - emitTokenWithComment(22 /* OpenBracketToken */ , node.expression.end, writePunctuation, node); + emitTokenWithComment(23 /* OpenBracketToken */ , node.expression.end, writePunctuation, node); emitExpression(node.argumentExpression); - emitTokenWithComment(23 /* CloseBracketToken */ , node.argumentExpression.end, writePunctuation, node); + emitTokenWithComment(24 /* CloseBracketToken */ , node.argumentExpression.end, writePunctuation, node); } function emitCallExpression(node) { const indirectCall = getInternalEmitFlags(node) & 16 /* IndirectCall */ ; @@ -88979,7 +90620,7 @@ ${lanes.join("\n")} emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */ , parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitNewExpression(node) { - emitTokenWithComment(103 /* NewKeyword */ , node.pos, writeKeyword, node); + emitTokenWithComment(105 /* NewKeyword */ , node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfNew); emitTypeArguments(node, node.typeArguments); @@ -89006,12 +90647,12 @@ ${lanes.join("\n")} emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitParenthesizedExpression(node) { - const openParenPos = emitTokenWithComment(20 /* OpenParenToken */ , node.pos, writePunctuation, node); + const openParenPos = emitTokenWithComment(21 /* OpenParenToken */ , node.pos, writePunctuation, node); const indented = writeLineSeparatorsAndIndentBefore(node.expression, node); - emitExpression(node.expression, /*parenthesizerRules*/ void 0); + emitExpression(node.expression, /*parenthesizerRule*/ void 0); writeLineSeparatorsAfter(node.expression, node); decreaseIndentIf(indented); - emitTokenWithComment(21 /* CloseParenToken */ , node.expression ? node.expression.end : openParenPos, writePunctuation, node); + emitTokenWithComment(22 /* CloseParenToken */ , node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { generateNameIfNeeded(node.name); @@ -89029,22 +90670,22 @@ ${lanes.join("\n")} emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { - emitTokenWithComment(89 /* DeleteKeyword */ , node.pos, writeKeyword, node); + emitTokenWithComment(91 /* DeleteKeyword */ , node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitTypeOfExpression(node) { - emitTokenWithComment(112 /* TypeOfKeyword */ , node.pos, writeKeyword, node); + emitTokenWithComment(114 /* TypeOfKeyword */ , node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitVoidExpression(node) { - emitTokenWithComment(114 /* VoidKeyword */ , node.pos, writeKeyword, node); + emitTokenWithComment(116 /* VoidKeyword */ , node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitAwaitExpression(node) { - emitTokenWithComment(133 /* AwaitKeyword */ , node.pos, writeKeyword, node); + emitTokenWithComment(135 /* AwaitKeyword */ , node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } @@ -89055,7 +90696,7 @@ ${lanes.join("\n")} } function shouldEmitWhitespaceBeforeOperand(node) { const operand = node.operand; - return operand.kind === 221 /* PrefixUnaryExpression */ && (node.operator === 39 /* PlusToken */ && (operand.operator === 39 /* PlusToken */ || operand.operator === 45 /* PlusPlusToken */ ) || node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */ )); + return operand.kind === 224 /* PrefixUnaryExpression */ && (node.operator === 40 /* PlusToken */ && (operand.operator === 40 /* PlusToken */ || operand.operator === 46 /* PlusPlusToken */ ) || node.operator === 41 /* MinusToken */ && (operand.operator === 41 /* MinusToken */ || operand.operator === 47 /* MinusMinusToken */ )); } function emitPostfixUnaryExpression(node) { emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPostfixUnary); @@ -89103,12 +90744,12 @@ ${lanes.join("\n")} return maybeEmitExpression(next, parent2, "left"); } function onOperator(operatorToken, _state, node) { - const isCommaOperator = operatorToken.kind !== 27 /* CommaToken */ ; + const isCommaOperator = operatorToken.kind !== 28 /* CommaToken */ ; const linesBeforeOperator = getLinesBetweenNodes(node, node.left, operatorToken); const linesAfterOperator = getLinesBetweenNodes(node, operatorToken, node.right); writeLinesAndIndent(linesBeforeOperator, isCommaOperator); emitLeadingCommentsOfPosition(operatorToken.pos); - writeTokenNode(operatorToken, operatorToken.kind === 101 /* InKeyword */ ? writeKeyword : writeOperator); + writeTokenNode(operatorToken, operatorToken.kind === 103 /* InKeyword */ ? writeKeyword : writeOperator); emitTrailingCommentsOfPosition(operatorToken.end, /*prefixSpace*/ true); writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true); } @@ -89171,12 +90812,12 @@ ${lanes.join("\n")} emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */ ); } function emitYieldExpression(node) { - emitTokenWithComment(125 /* YieldKeyword */ , node.pos, writeKeyword, node); + emitTokenWithComment(127 /* YieldKeyword */ , node.pos, writeKeyword, node); emit(node.asteriskToken); emitExpressionWithLeadingSpace(node.expression && parenthesizeExpressionForNoAsi(node.expression), parenthesizeExpressionForNoAsiAndDisallowedComma); } function emitSpreadElement(node) { - emitTokenWithComment(25 /* DotDotDotToken */ , node.pos, writePunctuation, node); + emitTokenWithComment(26 /* DotDotDotToken */ , node.pos, writePunctuation, node); emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitClassExpression(node) { @@ -89188,7 +90829,7 @@ ${lanes.join("\n")} emitTypeArguments(node, node.typeArguments); } function emitAsExpression(node) { - emitExpression(node.expression, /*parenthesizerRules*/ void 0); + emitExpression(node.expression, /*parenthesizerRule*/ void 0); if (node.type) { writeSpace(); writeKeyword("as"); @@ -89201,7 +90842,7 @@ ${lanes.join("\n")} writeOperator("!"); } function emitSatisfiesExpression(node) { - emitExpression(node.expression, /*parenthesizerRules*/ void 0); + emitExpression(node.expression, /*parenthesizerRule*/ void 0); if (node.type) { writeSpace(); writeKeyword("satisfies"); @@ -89222,10 +90863,10 @@ ${lanes.join("\n")} emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); } function emitBlockStatements(node, forceSingleLine) { - emitTokenWithComment(18 /* OpenBraceToken */ , node.pos, writePunctuation, /*contextNode*/ node); + emitTokenWithComment(19 /* OpenBraceToken */ , node.pos, writePunctuation, /*contextNode*/ node); const format = forceSingleLine || getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */ ; emitList(node, node.statements, format); - emitTokenWithComment(19 /* CloseBraceToken */ , node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */ )); + emitTokenWithComment(20 /* CloseBraceToken */ , node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */ )); } function emitVariableStatement(node) { emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ false); @@ -89241,30 +90882,30 @@ ${lanes.join("\n")} if (!currentSourceFile || !isJsonSourceFile(currentSourceFile) || nodeIsSynthesized(node.expression)) writeTrailingSemicolon(); } function emitIfStatement(node) { - const openParenPos = emitTokenWithComment(99 /* IfKeyword */ , node.pos, writeKeyword, node); + const openParenPos = emitTokenWithComment(101 /* IfKeyword */ , node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(20 /* OpenParenToken */ , openParenPos, writePunctuation, node); + emitTokenWithComment(21 /* OpenParenToken */ , openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(21 /* CloseParenToken */ , node.expression.end, writePunctuation, node); + emitTokenWithComment(22 /* CloseParenToken */ , node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node, node.thenStatement, node.elseStatement); - emitTokenWithComment(91 /* ElseKeyword */ , node.thenStatement.end, writeKeyword, node); - if (node.elseStatement.kind === 242 /* IfStatement */ ) { + emitTokenWithComment(93 /* ElseKeyword */ , node.thenStatement.end, writeKeyword, node); + if (node.elseStatement.kind === 245 /* IfStatement */ ) { writeSpace(); emit(node.elseStatement); } else emitEmbeddedStatement(node, node.elseStatement); } } function emitWhileClause(node, startPos) { - const openParenPos = emitTokenWithComment(115 /* WhileKeyword */ , startPos, writeKeyword, node); + const openParenPos = emitTokenWithComment(117 /* WhileKeyword */ , startPos, writeKeyword, node); writeSpace(); - emitTokenWithComment(20 /* OpenParenToken */ , openParenPos, writePunctuation, node); + emitTokenWithComment(21 /* OpenParenToken */ , openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(21 /* CloseParenToken */ , node.expression.end, writePunctuation, node); + emitTokenWithComment(22 /* CloseParenToken */ , node.expression.end, writePunctuation, node); } function emitDoStatement(node) { - emitTokenWithComment(90 /* DoKeyword */ , node.pos, writeKeyword, node); + emitTokenWithComment(92 /* DoKeyword */ , node.pos, writeKeyword, node); emitEmbeddedStatement(node, node.statement); if (isBlock(node.statement) && !preserveSourceNewlines) writeSpace(); else writeLineOrSpace(node, node.statement, node.expression); @@ -89276,55 +90917,55 @@ ${lanes.join("\n")} emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - const openParenPos = emitTokenWithComment(97 /* ForKeyword */ , node.pos, writeKeyword, node); + const openParenPos = emitTokenWithComment(99 /* ForKeyword */ , node.pos, writeKeyword, node); writeSpace(); - let pos = emitTokenWithComment(20 /* OpenParenToken */ , openParenPos, writePunctuation, /*contextNode*/ node); + let pos = emitTokenWithComment(21 /* OpenParenToken */ , openParenPos, writePunctuation, /*contextNode*/ node); emitForBinding(node.initializer); - pos = emitTokenWithComment(26 /* SemicolonToken */ , node.initializer ? node.initializer.end : pos, writePunctuation, node); + pos = emitTokenWithComment(27 /* SemicolonToken */ , node.initializer ? node.initializer.end : pos, writePunctuation, node); emitExpressionWithLeadingSpace(node.condition); - pos = emitTokenWithComment(26 /* SemicolonToken */ , node.condition ? node.condition.end : pos, writePunctuation, node); + pos = emitTokenWithComment(27 /* SemicolonToken */ , node.condition ? node.condition.end : pos, writePunctuation, node); emitExpressionWithLeadingSpace(node.incrementor); - emitTokenWithComment(21 /* CloseParenToken */ , node.incrementor ? node.incrementor.end : pos, writePunctuation, node); + emitTokenWithComment(22 /* CloseParenToken */ , node.incrementor ? node.incrementor.end : pos, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - const openParenPos = emitTokenWithComment(97 /* ForKeyword */ , node.pos, writeKeyword, node); + const openParenPos = emitTokenWithComment(99 /* ForKeyword */ , node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(20 /* OpenParenToken */ , openParenPos, writePunctuation, node); + emitTokenWithComment(21 /* OpenParenToken */ , openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(101 /* InKeyword */ , node.initializer.end, writeKeyword, node); + emitTokenWithComment(103 /* InKeyword */ , node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - emitTokenWithComment(21 /* CloseParenToken */ , node.expression.end, writePunctuation, node); + emitTokenWithComment(22 /* CloseParenToken */ , node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - const openParenPos = emitTokenWithComment(97 /* ForKeyword */ , node.pos, writeKeyword, node); + const openParenPos = emitTokenWithComment(99 /* ForKeyword */ , node.pos, writeKeyword, node); writeSpace(); emitWithTrailingSpace(node.awaitModifier); - emitTokenWithComment(20 /* OpenParenToken */ , openParenPos, writePunctuation, node); + emitTokenWithComment(21 /* OpenParenToken */ , openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(162 /* OfKeyword */ , node.initializer.end, writeKeyword, node); + emitTokenWithComment(165 /* OfKeyword */ , node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - emitTokenWithComment(21 /* CloseParenToken */ , node.expression.end, writePunctuation, node); + emitTokenWithComment(22 /* CloseParenToken */ , node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { if (node !== void 0) { - if (node.kind === 258 /* VariableDeclarationList */ ) emit(node); + if (node.kind === 261 /* VariableDeclarationList */ ) emit(node); else emitExpression(node); } } function emitContinueStatement(node) { - emitTokenWithComment(86 /* ContinueKeyword */ , node.pos, writeKeyword, node); + emitTokenWithComment(88 /* ContinueKeyword */ , node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); writeTrailingSemicolon(); } function emitBreakStatement(node) { - emitTokenWithComment(81 /* BreakKeyword */ , node.pos, writeKeyword, node); + emitTokenWithComment(83 /* BreakKeyword */ , node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); writeTrailingSemicolon(); } @@ -89341,7 +90982,7 @@ ${lanes.join("\n")} } pos = writeTokenText(token, writer2, pos); if (isSimilarNode && contextNode.end !== pos) { - const isJsxExprContext = contextNode.kind === 291 /* JsxExpression */ ; + const isJsxExprContext = contextNode.kind === 294 /* JsxExpression */ ; emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ !isJsxExprContext, /*forceNoNewline*/ isJsxExprContext); } return pos; @@ -89378,40 +91019,40 @@ ${lanes.join("\n")} return parenthesizeExpressionForNoAsi(parenthesizer.parenthesizeExpressionForDisallowedComma(node)); } function emitReturnStatement(node) { - emitTokenWithComment(105 /* ReturnKeyword */ , node.pos, writeKeyword, /*contextNode*/ node); + emitTokenWithComment(107 /* ReturnKeyword */ , node.pos, writeKeyword, /*contextNode*/ node); emitExpressionWithLeadingSpace(node.expression && parenthesizeExpressionForNoAsi(node.expression), parenthesizeExpressionForNoAsi); writeTrailingSemicolon(); } function emitWithStatement(node) { - const openParenPos = emitTokenWithComment(116 /* WithKeyword */ , node.pos, writeKeyword, node); + const openParenPos = emitTokenWithComment(118 /* WithKeyword */ , node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(20 /* OpenParenToken */ , openParenPos, writePunctuation, node); + emitTokenWithComment(21 /* OpenParenToken */ , openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(21 /* CloseParenToken */ , node.expression.end, writePunctuation, node); + emitTokenWithComment(22 /* CloseParenToken */ , node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - const openParenPos = emitTokenWithComment(107 /* SwitchKeyword */ , node.pos, writeKeyword, node); + const openParenPos = emitTokenWithComment(109 /* SwitchKeyword */ , node.pos, writeKeyword, node); writeSpace(); - emitTokenWithComment(20 /* OpenParenToken */ , openParenPos, writePunctuation, node); + emitTokenWithComment(21 /* OpenParenToken */ , openParenPos, writePunctuation, node); emitExpression(node.expression); - emitTokenWithComment(21 /* CloseParenToken */ , node.expression.end, writePunctuation, node); + emitTokenWithComment(22 /* CloseParenToken */ , node.expression.end, writePunctuation, node); writeSpace(); emit(node.caseBlock); } function emitLabeledStatement(node) { emit(node.label); - emitTokenWithComment(58 /* ColonToken */ , node.label.end, writePunctuation, node); + emitTokenWithComment(59 /* ColonToken */ , node.label.end, writePunctuation, node); writeSpace(); emit(node.statement); } function emitThrowStatement(node) { - emitTokenWithComment(109 /* ThrowKeyword */ , node.pos, writeKeyword, node); + emitTokenWithComment(111 /* ThrowKeyword */ , node.pos, writeKeyword, node); emitExpressionWithLeadingSpace(parenthesizeExpressionForNoAsi(node.expression), parenthesizeExpressionForNoAsi); writeTrailingSemicolon(); } function emitTryStatement(node) { - emitTokenWithComment(111 /* TryKeyword */ , node.pos, writeKeyword, node); + emitTokenWithComment(113 /* TryKeyword */ , node.pos, writeKeyword, node); writeSpace(); emit(node.tryBlock); if (node.catchClause) { @@ -89420,24 +91061,31 @@ ${lanes.join("\n")} } if (node.finallyBlock) { writeLineOrSpace(node, node.catchClause || node.tryBlock, node.finallyBlock); - emitTokenWithComment(96 /* FinallyKeyword */ , (node.catchClause || node.tryBlock).end, writeKeyword, node); + emitTokenWithComment(98 /* FinallyKeyword */ , (node.catchClause || node.tryBlock).end, writeKeyword, node); writeSpace(); emit(node.finallyBlock); } } function emitDebuggerStatement(node) { - writeToken(87 /* DebuggerKeyword */ , node.pos, writeKeyword); + writeToken(89 /* DebuggerKeyword */ , node.pos, writeKeyword); writeTrailingSemicolon(); } function emitVariableDeclaration(node) { - var _a2, _b, _c, _d, _e; + var _a, _b, _c; emit(node.name); emit(node.exclamationToken); emitTypeAnnotation(node.type); - emitInitializer(node.initializer, (_e = (_d = (_a2 = node.type) == null ? void 0 : _a2.end) != null ? _d : (_c = (_b = node.name.emitNode) == null ? void 0 : _b.typeNode) == null ? void 0 : _c.end) != null ? _e : node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); + emitInitializer(node.initializer, ((_a = node.type) == null ? void 0 : _a.end) ?? ((_c = (_b = node.name.emitNode) == null ? void 0 : _b.typeNode) == null ? void 0 : _c.end) ?? node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitVariableDeclarationList(node) { - writeKeyword(isLet(node) ? "let" : isVarConst(node) ? "const" : "var"); + if (isVarAwaitUsing(node)) { + writeKeyword("await"); + writeSpace(); + writeKeyword("using"); + } else { + const head = isLet(node) ? "let" : isVarConst(node) ? "const" : isVarUsing(node) ? "using" : "var"; + writeKeyword(head); + } writeSpace(); emitList(node, node.declarations, 528 /* VariableDeclarationList */ ); } @@ -89500,7 +91148,7 @@ ${lanes.join("\n")} const emitBlockFunctionBody2 = shouldEmitBlockFunctionBodyOnSingleLine(body) ? emitBlockFunctionBodyOnSingleLine : emitBlockFunctionBodyWorker; emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody2); decreaseIndent(); - writeToken(19 /* CloseBraceToken */ , body.statements.end, writePunctuation, body); + writeToken(20 /* CloseBraceToken */ , body.statements.end, writePunctuation, body); onAfterEmitNode == null || onAfterEmitNode(body); } function emitBlockFunctionBodyOnSingleLine(body) { @@ -89523,7 +91171,7 @@ ${lanes.join("\n")} pushPrivateNameGenerationScope(0 /* Auto */ , /*newReservedMemberNames*/ void 0); forEach(node.members, generateMemberNames); emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ true); - emitTokenWithComment(84 /* ClassKeyword */ , moveRangePastModifiers(node).pos, writeKeyword, node); + emitTokenWithComment(86 /* ClassKeyword */ , moveRangePastModifiers(node).pos, writeKeyword, node); if (node.name) { writeSpace(); emitIdentifierName(node.name); @@ -89577,8 +91225,8 @@ ${lanes.join("\n")} } function emitModuleDeclaration(node) { emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ false); - if (~node.flags & 1024 /* GlobalAugmentation */ ) { - writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module"); + if (~node.flags & 2048 /* GlobalAugmentation */ ) { + writeKeyword(node.flags & 32 /* Namespace */ ? "namespace" : "module"); writeSpace(); } emit(node.name); @@ -89599,37 +91247,37 @@ ${lanes.join("\n")} popNameGenerationScope(node); } function emitCaseBlock(node) { - emitTokenWithComment(18 /* OpenBraceToken */ , node.pos, writePunctuation, node); + emitTokenWithComment(19 /* OpenBraceToken */ , node.pos, writePunctuation, node); emitList(node, node.clauses, 129 /* CaseBlockClauses */ ); - emitTokenWithComment(19 /* CloseBraceToken */ , node.clauses.end, writePunctuation, node, /*indentLeading*/ true); + emitTokenWithComment(20 /* CloseBraceToken */ , node.clauses.end, writePunctuation, node, /*indentLeading*/ true); } function emitImportEqualsDeclaration(node) { emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ false); - emitTokenWithComment(100 /* ImportKeyword */ , node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + emitTokenWithComment(102 /* ImportKeyword */ , node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); if (node.isTypeOnly) { - emitTokenWithComment(154 /* TypeKeyword */ , node.pos, writeKeyword, node); + emitTokenWithComment(156 /* TypeKeyword */ , node.pos, writeKeyword, node); writeSpace(); } emit(node.name); writeSpace(); - emitTokenWithComment(63 /* EqualsToken */ , node.name.end, writePunctuation, node); + emitTokenWithComment(64 /* EqualsToken */ , node.name.end, writePunctuation, node); writeSpace(); emitModuleReference(node.moduleReference); writeTrailingSemicolon(); } function emitModuleReference(node) { - if (node.kind === 79 /* Identifier */ ) emitExpression(node); + if (node.kind === 80 /* Identifier */ ) emitExpression(node); else emit(node); } function emitImportDeclaration(node) { emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ false); - emitTokenWithComment(100 /* ImportKeyword */ , node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + emitTokenWithComment(102 /* ImportKeyword */ , node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); if (node.importClause) { emit(node.importClause); writeSpace(); - emitTokenWithComment(158 /* FromKeyword */ , node.importClause.end, writeKeyword, node); + emitTokenWithComment(161 /* FromKeyword */ , node.importClause.end, writeKeyword, node); writeSpace(); } emitExpression(node.moduleSpecifier); @@ -89638,20 +91286,20 @@ ${lanes.join("\n")} } function emitImportClause(node) { if (node.isTypeOnly) { - emitTokenWithComment(154 /* TypeKeyword */ , node.pos, writeKeyword, node); + emitTokenWithComment(156 /* TypeKeyword */ , node.pos, writeKeyword, node); writeSpace(); } emit(node.name); if (node.name && node.namedBindings) { - emitTokenWithComment(27 /* CommaToken */ , node.name.end, writePunctuation, node); + emitTokenWithComment(28 /* CommaToken */ , node.name.end, writePunctuation, node); writeSpace(); } emit(node.namedBindings); } function emitNamespaceImport(node) { - const asPos = emitTokenWithComment(41 /* AsteriskToken */ , node.pos, writePunctuation, node); + const asPos = emitTokenWithComment(42 /* AsteriskToken */ , node.pos, writePunctuation, node); writeSpace(); - emitTokenWithComment(128 /* AsKeyword */ , asPos, writeKeyword, node); + emitTokenWithComment(130 /* AsKeyword */ , asPos, writeKeyword, node); writeSpace(); emit(node.name); } @@ -89662,28 +91310,28 @@ ${lanes.join("\n")} emitImportOrExportSpecifier(node); } function emitExportAssignment(node) { - const nextPos = emitTokenWithComment(93 /* ExportKeyword */ , node.pos, writeKeyword, node); + const nextPos = emitTokenWithComment(95 /* ExportKeyword */ , node.pos, writeKeyword, node); writeSpace(); - if (node.isExportEquals) emitTokenWithComment(63 /* EqualsToken */ , nextPos, writeOperator, node); - else emitTokenWithComment(88 /* DefaultKeyword */ , nextPos, writeKeyword, node); + if (node.isExportEquals) emitTokenWithComment(64 /* EqualsToken */ , nextPos, writeOperator, node); + else emitTokenWithComment(90 /* DefaultKeyword */ , nextPos, writeKeyword, node); writeSpace(); - emitExpression(node.expression, node.isExportEquals ? parenthesizer.getParenthesizeRightSideOfBinaryForOperator(63 /* EqualsToken */ ) : parenthesizer.parenthesizeExpressionOfExportDefault); + emitExpression(node.expression, node.isExportEquals ? parenthesizer.getParenthesizeRightSideOfBinaryForOperator(64 /* EqualsToken */ ) : parenthesizer.parenthesizeExpressionOfExportDefault); writeTrailingSemicolon(); } function emitExportDeclaration(node) { emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ false); - let nextPos = emitTokenWithComment(93 /* ExportKeyword */ , node.pos, writeKeyword, node); + let nextPos = emitTokenWithComment(95 /* ExportKeyword */ , node.pos, writeKeyword, node); writeSpace(); if (node.isTypeOnly) { - nextPos = emitTokenWithComment(154 /* TypeKeyword */ , nextPos, writeKeyword, node); + nextPos = emitTokenWithComment(156 /* TypeKeyword */ , nextPos, writeKeyword, node); writeSpace(); } if (node.exportClause) emit(node.exportClause); - else nextPos = emitTokenWithComment(41 /* AsteriskToken */ , nextPos, writePunctuation, node); + else nextPos = emitTokenWithComment(42 /* AsteriskToken */ , nextPos, writePunctuation, node); if (node.moduleSpecifier) { writeSpace(); const fromPos = node.exportClause ? node.exportClause.end : nextPos; - emitTokenWithComment(158 /* FromKeyword */ , fromPos, writeKeyword, node); + emitTokenWithComment(161 /* FromKeyword */ , fromPos, writeKeyword, node); writeSpace(); emitExpression(node.moduleSpecifier); } @@ -89691,7 +91339,7 @@ ${lanes.join("\n")} writeTrailingSemicolon(); } function emitAssertClause(node) { - emitTokenWithComment(130 /* AssertKeyword */ , node.pos, writeKeyword, node); + emitTokenWithComment(132 /* AssertKeyword */ , node.pos, writeKeyword, node); writeSpace(); const elements = node.elements; emitList(node, elements, 526226 /* ImportClauseEntries */ ); @@ -89708,19 +91356,19 @@ ${lanes.join("\n")} emit(value1); } function emitNamespaceExportDeclaration(node) { - let nextPos = emitTokenWithComment(93 /* ExportKeyword */ , node.pos, writeKeyword, node); + let nextPos = emitTokenWithComment(95 /* ExportKeyword */ , node.pos, writeKeyword, node); writeSpace(); - nextPos = emitTokenWithComment(128 /* AsKeyword */ , nextPos, writeKeyword, node); + nextPos = emitTokenWithComment(130 /* AsKeyword */ , nextPos, writeKeyword, node); writeSpace(); - nextPos = emitTokenWithComment(143 /* NamespaceKeyword */ , nextPos, writeKeyword, node); + nextPos = emitTokenWithComment(145 /* NamespaceKeyword */ , nextPos, writeKeyword, node); writeSpace(); emit(node.name); writeTrailingSemicolon(); } function emitNamespaceExport(node) { - const asPos = emitTokenWithComment(41 /* AsteriskToken */ , node.pos, writePunctuation, node); + const asPos = emitTokenWithComment(42 /* AsteriskToken */ , node.pos, writePunctuation, node); writeSpace(); - emitTokenWithComment(128 /* AsKeyword */ , asPos, writeKeyword, node); + emitTokenWithComment(130 /* AsKeyword */ , asPos, writeKeyword, node); writeSpace(); emit(node.name); } @@ -89743,7 +91391,7 @@ ${lanes.join("\n")} if (node.propertyName) { emit(node.propertyName); writeSpace(); - emitTokenWithComment(128 /* AsKeyword */ , node.propertyName.end, writeKeyword, node); + emitTokenWithComment(130 /* AsKeyword */ , node.propertyName.end, writeKeyword, node); writeSpace(); } emit(node.name); @@ -89819,29 +91467,34 @@ ${lanes.join("\n")} return hasTrailingCommentsAtPosition(pos) || hasLeadingCommentsAtPosition(pos); } function emitJsxExpression(node) { - var _a2; + var _a; if (node.expression || !commentsDisabled && !nodeIsSynthesized(node) && hasCommentsAtPosition(node.pos)) { const isMultiline = currentSourceFile && !nodeIsSynthesized(node) && getLineAndCharacterOfPosition(currentSourceFile, node.pos).line !== getLineAndCharacterOfPosition(currentSourceFile, node.end).line; if (isMultiline) writer.increaseIndent(); - const end = emitTokenWithComment(18 /* OpenBraceToken */ , node.pos, writePunctuation, node); + const end = emitTokenWithComment(19 /* OpenBraceToken */ , node.pos, writePunctuation, node); emit(node.dotDotDotToken); emitExpression(node.expression); - emitTokenWithComment(19 /* CloseBraceToken */ , ((_a2 = node.expression) == null ? void 0 : _a2.end) || end, writePunctuation, node); + emitTokenWithComment(20 /* CloseBraceToken */ , ((_a = node.expression) == null ? void 0 : _a.end) || end, writePunctuation, node); if (isMultiline) writer.decreaseIndent(); } } + function emitJsxNamespacedName(node) { + emitIdentifierName(node.namespace); + writePunctuation(":"); + emitIdentifierName(node.name); + } function emitJsxTagName(node) { - if (node.kind === 79 /* Identifier */ ) emitExpression(node); + if (node.kind === 80 /* Identifier */ ) emitExpression(node); else emit(node); } function emitCaseClause(node) { - emitTokenWithComment(82 /* CaseKeyword */ , node.pos, writeKeyword, node); + emitTokenWithComment(84 /* CaseKeyword */ , node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { - const pos = emitTokenWithComment(88 /* DefaultKeyword */ , node.pos, writeKeyword, node); + const pos = emitTokenWithComment(90 /* DefaultKeyword */ , node.pos, writeKeyword, node); emitCaseOrDefaultClauseRest(node, node.statements, pos); } function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) { @@ -89849,10 +91502,10 @@ ${lanes.join("\n")} (!currentSourceFile || nodeIsSynthesized(parentNode) || nodeIsSynthesized(statements[0]) || rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); let format = 163969 /* CaseOrDefaultClauseStatements */ ; if (emitAsSingleStatement) { - writeToken(58 /* ColonToken */ , colonPos, writePunctuation, parentNode); + writeToken(59 /* ColonToken */ , colonPos, writePunctuation, parentNode); writeSpace(); format &= -130; - } else emitTokenWithComment(58 /* ColonToken */ , colonPos, writePunctuation, parentNode); + } else emitTokenWithComment(59 /* ColonToken */ , colonPos, writePunctuation, parentNode); emitList(parentNode, statements, format); } function emitHeritageClause(node) { @@ -89862,12 +91515,12 @@ ${lanes.join("\n")} emitList(node, node.types, 528 /* HeritageClauseTypes */ ); } function emitCatchClause(node) { - const openParenPos = emitTokenWithComment(83 /* CatchKeyword */ , node.pos, writeKeyword, node); + const openParenPos = emitTokenWithComment(85 /* CatchKeyword */ , node.pos, writeKeyword, node); writeSpace(); if (node.variableDeclaration) { - emitTokenWithComment(20 /* OpenParenToken */ , openParenPos, writePunctuation, node); + emitTokenWithComment(21 /* OpenParenToken */ , openParenPos, writePunctuation, node); emit(node.variableDeclaration); - emitTokenWithComment(21 /* CloseParenToken */ , node.variableDeclaration.end, writePunctuation, node); + emitTokenWithComment(22 /* CloseParenToken */ , node.variableDeclaration.end, writePunctuation, node); writeSpace(); } emit(node.block); @@ -89894,7 +91547,7 @@ ${lanes.join("\n")} } function emitSpreadAssignment(node) { if (node.expression) { - emitTokenWithComment(25 /* DotDotDotToken */ , node.pos, writePunctuation, node); + emitTokenWithComment(26 /* DotDotDotToken */ , node.pos, writePunctuation, node); emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } } @@ -89918,7 +91571,7 @@ ${lanes.join("\n")} } } if (node.tags) { - if (node.tags.length === 1 && node.tags[0].kind === 347 /* JSDocTypeTag */ && !node.comment) { + if (node.tags.length === 1 && node.tags[0].kind === 351 /* JSDocTypeTag */ && !node.comment) { writeSpace(); emit(node.tags[0]); } else emitList(node, node.tags, 33 /* JSDocComment */ ); @@ -89960,7 +91613,7 @@ ${lanes.join("\n")} function emitJSDocTypedefTag(tag) { emitJSDocTagName(tag.tagName); if (tag.typeExpression) { - if (tag.typeExpression.kind === 312 /* JSDocTypeExpression */ ) emitJSDocTypeExpression(tag.typeExpression); + if (tag.typeExpression.kind === 316 /* JSDocTypeExpression */ ) emitJSDocTypeExpression(tag.typeExpression); else { writeSpace(); writePunctuation("{"); @@ -89977,7 +91630,7 @@ ${lanes.join("\n")} emit(tag.fullName); } emitJSDocComment(tag.comment); - if (tag.typeExpression && tag.typeExpression.kind === 325 /* JSDocTypeLiteral */ ) emitJSDocTypeLiteral(tag.typeExpression); + if (tag.typeExpression && tag.typeExpression.kind === 329 /* JSDocTypeLiteral */ ) emitJSDocTypeLiteral(tag.typeExpression); } function emitJSDocCallbackTag(tag) { emitJSDocTagName(tag.tagName); @@ -90290,7 +91943,7 @@ ${lanes.join("\n")} function emitInitializer(node, equalCommentStartPos, container, parenthesizerRule) { if (node) { writeSpace(); - emitTokenWithComment(63 /* EqualsToken */ , equalCommentStartPos, writeOperator, container); + emitTokenWithComment(64 /* EqualsToken */ , equalCommentStartPos, writeOperator, container); writeSpace(); emitExpression(node, parenthesizerRule); } @@ -90320,7 +91973,7 @@ ${lanes.join("\n")} } } function emitEmbeddedStatement(parent2, node) { - if (isBlock(node) || getEmitFlags(parent2) & 1 /* SingleLine */ ) { + if (isBlock(node) || getEmitFlags(parent2) & 1 /* SingleLine */ || preserveSourceNewlines && !getLeadingLineTerminatorCount(parent2, node, 0 /* None */ )) { writeSpace(); emit(node); } else { @@ -90461,7 +92114,7 @@ ${lanes.join("\n")} const skipTrailingComments = commentsDisabled || !!(emitFlags & 2048 /* NoTrailingComments */ ); const emitTrailingComma = hasTrailingComma && format & 64 /* AllowTrailingComma */ && format & 16 /* CommaDelimited */ ; if (emitTrailingComma) { - if (previousSibling && !skipTrailingComments) emitTokenWithComment(27 /* CommaToken */ , previousSibling.end, writePunctuation, previousSibling); + if (previousSibling && !skipTrailingComments) emitTokenWithComment(28 /* CommaToken */ , previousSibling.end, writePunctuation, previousSibling); else writePunctuation(","); } if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && format & 60 /* DelimitersMask */ && !skipTrailingComments) emitLeadingCommentsOfPosition(emitTrailingComma && (childrenTextRange == null ? void 0 : childrenTextRange.end) ? childrenTextRange.end : previousSibling.end); @@ -90567,7 +92220,7 @@ ${lanes.join("\n")} if (format & 65536 /* PreferNewLine */ ) return 1; if (firstChild === void 0) return !parentNode || currentSourceFile && rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; if (firstChild.pos === nextListElementPos) return 0; - if (firstChild.kind === 11 /* JsxText */ ) return 0; + if (firstChild.kind === 12 /* JsxText */ ) return 0; if (currentSourceFile && parentNode && !positionIsSynthesized(parentNode.pos) && !nodeIsSynthesized(firstChild) && (!firstChild.parent || getOriginalNode(firstChild.parent) === getOriginalNode(parentNode))) { if (preserveSourceNewlines) return getEffectiveLines((includeComments)=>getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild.pos, parentNode.pos, currentSourceFile, includeComments)); return rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile) ? 0 : 1; @@ -90579,7 +92232,7 @@ ${lanes.join("\n")} function getSeparatingLineTerminatorCount(previousNode, nextNode, format) { if (format & 2 /* PreserveLines */ || preserveSourceNewlines) { if (previousNode === void 0 || nextNode === void 0) return 0; - if (nextNode.kind === 11 /* JsxText */ ) return 0; + if (nextNode.kind === 12 /* JsxText */ ) return 0; else if (currentSourceFile && !nodeIsSynthesized(previousNode) && !nodeIsSynthesized(nextNode)) { if (preserveSourceNewlines && siblingNodePositionsAreComparable(previousNode, nextNode)) return getEffectiveLines((includeComments)=>getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments)); else if (!preserveSourceNewlines && originalNodesHaveSameParent(previousNode, nextNode)) return rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1; @@ -90643,7 +92296,7 @@ ${lanes.join("\n")} return block.statements.length === 0 && (!currentSourceFile || rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile)); } function skipSynthesizedParentheses(node) { - while(node.kind === 214 /* ParenthesizedExpression */ && nodeIsSynthesized(node))node = node.expression; + while(node.kind === 217 /* ParenthesizedExpression */ && nodeIsSynthesized(node))node = node.expression; return node; } function getTextOfNode2(node, includeTrivia) { @@ -90653,6 +92306,8 @@ ${lanes.join("\n")} const canUseSourceFile = !!sourceFile && !!node.parent && !nodeIsSynthesized(node); if (isMemberName(node)) { if (!canUseSourceFile || getSourceFileOfNode(node) !== getOriginalNode(sourceFile)) return idText(node); + } else if (isJsxNamespacedName(node)) { + if (!canUseSourceFile || getSourceFileOfNode(node) !== getOriginalNode(sourceFile)) return getTextOfJsxNamespacedName(node); } else { Debug.assertNode(node, isLiteralExpression); if (!canUseSourceFile) return node.text; @@ -90660,11 +92315,11 @@ ${lanes.join("\n")} return getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia); } function getLiteralTextOfNode(node, neverAsciiEscape, jsxAttributeEscape) { - if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) { + if (node.kind === 11 /* StringLiteral */ && node.textSourceNode) { const textSourceNode = node.textSourceNode; - if (isIdentifier(textSourceNode) || isPrivateIdentifier(textSourceNode) || isNumericLiteral(textSourceNode)) { + if (isIdentifier(textSourceNode) || isPrivateIdentifier(textSourceNode) || isNumericLiteral(textSourceNode) || isJsxNamespacedName(textSourceNode)) { const text = isNumericLiteral(textSourceNode) ? textSourceNode.text : getTextOfNode2(textSourceNode); - return jsxAttributeEscape ? `"${escapeJsxAttributeString(text)}"` : neverAsciiEscape || getEmitFlags(node) & 33554432 /* NoAsciiEscaping */ ? `"${escapeString(text)}"` : `"${escapeNonAsciiString(text)}"`; + return jsxAttributeEscape ? `"${escapeJsxAttributeString(text)}"` : neverAsciiEscape || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? `"${escapeString(text)}"` : `"${escapeNonAsciiString(text)}"`; } else return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape); } const flags = (neverAsciiEscape ? 1 /* NeverAsciiEscape */ : 0) | (jsxAttributeEscape ? 2 /* JsxAttributeEscape */ : 0) | (printerOptions.terminateUnterminatedLiterals ? 4 /* TerminateUnterminatedLiterals */ : 0) | (printerOptions.target && printerOptions.target === 99 /* ESNext */ ? 8 /* AllowNumericSeparator */ : 0); @@ -90705,84 +92360,84 @@ ${lanes.join("\n")} function generateNames(node) { if (!node) return; switch(node.kind){ - case 238 /* Block */ : + case 241 /* Block */ : forEach(node.statements, generateNames); break; - case 253 /* LabeledStatement */ : - case 251 /* WithStatement */ : - case 243 /* DoStatement */ : - case 244 /* WhileStatement */ : + case 256 /* LabeledStatement */ : + case 254 /* WithStatement */ : + case 246 /* DoStatement */ : + case 247 /* WhileStatement */ : generateNames(node.statement); break; - case 242 /* IfStatement */ : + case 245 /* IfStatement */ : generateNames(node.thenStatement); generateNames(node.elseStatement); break; - case 245 /* ForStatement */ : - case 247 /* ForOfStatement */ : - case 246 /* ForInStatement */ : + case 248 /* ForStatement */ : + case 250 /* ForOfStatement */ : + case 249 /* ForInStatement */ : generateNames(node.initializer); generateNames(node.statement); break; - case 252 /* SwitchStatement */ : + case 255 /* SwitchStatement */ : generateNames(node.caseBlock); break; - case 266 /* CaseBlock */ : + case 269 /* CaseBlock */ : forEach(node.clauses, generateNames); break; - case 292 /* CaseClause */ : - case 293 /* DefaultClause */ : + case 296 /* CaseClause */ : + case 297 /* DefaultClause */ : forEach(node.statements, generateNames); break; - case 255 /* TryStatement */ : + case 258 /* TryStatement */ : generateNames(node.tryBlock); generateNames(node.catchClause); generateNames(node.finallyBlock); break; - case 295 /* CatchClause */ : + case 299 /* CatchClause */ : generateNames(node.variableDeclaration); generateNames(node.block); break; - case 240 /* VariableStatement */ : + case 243 /* VariableStatement */ : generateNames(node.declarationList); break; - case 258 /* VariableDeclarationList */ : + case 261 /* VariableDeclarationList */ : forEach(node.declarations, generateNames); break; - case 257 /* VariableDeclaration */ : - case 166 /* Parameter */ : - case 205 /* BindingElement */ : - case 260 /* ClassDeclaration */ : + case 260 /* VariableDeclaration */ : + case 169 /* Parameter */ : + case 208 /* BindingElement */ : + case 263 /* ClassDeclaration */ : generateNameIfNeeded(node.name); break; - case 259 /* FunctionDeclaration */ : + case 262 /* FunctionDeclaration */ : generateNameIfNeeded(node.name); if (getEmitFlags(node) & 1048576 /* ReuseTempVariableScope */ ) { forEach(node.parameters, generateNames); generateNames(node.body); } break; - case 203 /* ObjectBindingPattern */ : - case 204 /* ArrayBindingPattern */ : + case 206 /* ObjectBindingPattern */ : + case 207 /* ArrayBindingPattern */ : forEach(node.elements, generateNames); break; - case 269 /* ImportDeclaration */ : + case 272 /* ImportDeclaration */ : generateNames(node.importClause); break; - case 270 /* ImportClause */ : + case 273 /* ImportClause */ : generateNameIfNeeded(node.name); generateNames(node.namedBindings); break; - case 271 /* NamespaceImport */ : + case 274 /* NamespaceImport */ : generateNameIfNeeded(node.name); break; - case 277 /* NamespaceExport */ : + case 280 /* NamespaceExport */ : generateNameIfNeeded(node.name); break; - case 272 /* NamedImports */ : + case 275 /* NamedImports */ : forEach(node.elements, generateNames); break; - case 273 /* ImportSpecifier */ : + case 276 /* ImportSpecifier */ : generateNameIfNeeded(node.propertyName || node.name); break; } @@ -90790,12 +92445,12 @@ ${lanes.join("\n")} function generateMemberNames(node) { if (!node) return; switch(node.kind){ - case 299 /* PropertyAssignment */ : - case 300 /* ShorthandPropertyAssignment */ : - case 169 /* PropertyDeclaration */ : - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 303 /* PropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : + case 172 /* PropertyDeclaration */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : generateNameIfNeeded(node.name); break; } @@ -90817,15 +92472,15 @@ ${lanes.join("\n")} function generateNameCached(node, privateName, flags, prefix, suffix) { const nodeId = getNodeId(node); const cache = privateName ? nodeIdToGeneratedPrivateName : nodeIdToGeneratedName; - return cache[nodeId] || (cache[nodeId] = generateNameForNode(node, privateName, flags != null ? flags : 0 /* None */ , formatGeneratedNamePart(prefix, generateName), formatGeneratedNamePart(suffix))); + return cache[nodeId] || (cache[nodeId] = generateNameForNode(node, privateName, flags ?? 0 /* None */ , formatGeneratedNamePart(prefix, generateName), formatGeneratedNamePart(suffix))); } function isUniqueName(name, privateName) { - return isFileLevelUniqueName2(name, privateName) && !isReservedName(name, privateName) && !generatedNames.has(name); + return isFileLevelUniqueNameInCurrentFile(name, privateName) && !isReservedName(name, privateName) && !generatedNames.has(name); } function isReservedName(name, privateName) { return privateName ? !!(reservedPrivateNames == null ? void 0 : reservedPrivateNames.has(name)) : !!(reservedNames == null ? void 0 : reservedNames.has(name)); } - function isFileLevelUniqueName2(name, _isPrivate) { + function isFileLevelUniqueNameInCurrentFile(name, _isPrivate) { return currentSourceFile ? isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true; } function isUniqueLocalName(name, container) { @@ -90836,14 +92491,13 @@ ${lanes.join("\n")} return true; } function getTempFlags(formattedNameKey) { - var _a2; switch(formattedNameKey){ case "": return tempFlags; case "#": return privateNameTempFlags; default: - return (_a2 = formattedNameTempFlags == null ? void 0 : formattedNameTempFlags.get(formattedNameKey)) != null ? _a2 : 0 /* Auto */ ; + return (formattedNameTempFlags == null ? void 0 : formattedNameTempFlags.get(formattedNameKey)) ?? 0 /* Auto */ ; } } function setTempFlags(formattedNameKey, flags) { @@ -90855,7 +92509,7 @@ ${lanes.join("\n")} privateNameTempFlags = flags; break; default: - formattedNameTempFlags != null ? formattedNameTempFlags : formattedNameTempFlags = /* @__PURE__ */ new Map(); + formattedNameTempFlags ?? (formattedNameTempFlags = /* @__PURE__ */ new Map()); formattedNameTempFlags.set(formattedNameKey, flags); break; } @@ -90916,7 +92570,7 @@ ${lanes.join("\n")} } } function makeFileLevelOptimisticUniqueName(name) { - return makeUniqueName2(name, isFileLevelUniqueName2, /*optimistic*/ true, /*scoped*/ false, /*privateName*/ false, /*prefix*/ "", /*suffix*/ ""); + return makeUniqueName2(name, isFileLevelUniqueNameInCurrentFile, /*optimistic*/ true, /*scoped*/ false, /*privateName*/ false, /*prefix*/ "", /*suffix*/ ""); } function generateNameForModuleOrEnum(node) { const name = getTextOfNode2(node.name); @@ -90939,39 +92593,39 @@ ${lanes.join("\n")} } function generateNameForNode(node, privateName, flags, prefix, suffix) { switch(node.kind){ - case 79 /* Identifier */ : - case 80 /* PrivateIdentifier */ : + case 80 /* Identifier */ : + case 81 /* PrivateIdentifier */ : return makeUniqueName2(getTextOfNode2(node), isUniqueName, !!(flags & 16 /* Optimistic */ ), !!(flags & 8 /* ReservedInNestedScopes */ ), privateName, prefix, suffix); - case 264 /* ModuleDeclaration */ : - case 263 /* EnumDeclaration */ : + case 267 /* ModuleDeclaration */ : + case 266 /* EnumDeclaration */ : Debug.assert(!prefix && !suffix && !privateName); return generateNameForModuleOrEnum(node); - case 269 /* ImportDeclaration */ : - case 275 /* ExportDeclaration */ : + case 272 /* ImportDeclaration */ : + case 278 /* ExportDeclaration */ : Debug.assert(!prefix && !suffix && !privateName); return generateNameForImportOrExportDeclaration(node); - case 259 /* FunctionDeclaration */ : - case 260 /* ClassDeclaration */ : + case 262 /* FunctionDeclaration */ : + case 263 /* ClassDeclaration */ : { Debug.assert(!prefix && !suffix && !privateName); const name = node.name; if (name && !isGeneratedIdentifier(name)) return generateNameForNode(name, /*privateName*/ false, flags, prefix, suffix); return generateNameForExportDefault(); } - case 274 /* ExportAssignment */ : + case 277 /* ExportAssignment */ : Debug.assert(!prefix && !suffix && !privateName); return generateNameForExportDefault(); - case 228 /* ClassExpression */ : + case 231 /* ClassExpression */ : Debug.assert(!prefix && !suffix && !privateName); return generateNameForClassExpression(); - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : return generateNameForMethodOrAccessor(node, privateName, prefix, suffix); - case 164 /* ComputedPropertyName */ : - return makeTempVariableName(0 /* Auto */ , /*reserveInNestedScopes*/ true, privateName, prefix, suffix); + case 167 /* ComputedPropertyName */ : + return makeTempVariableName(0 /* Auto */ , /*reservedInNestedScopes*/ true, privateName, prefix, suffix); default: - return makeTempVariableName(0 /* Auto */ , /*reserveInNestedScopes*/ false, privateName, prefix, suffix); + return makeTempVariableName(0 /* Auto */ , /*reservedInNestedScopes*/ false, privateName, prefix, suffix); } } function makeName(name) { @@ -90985,7 +92639,7 @@ ${lanes.join("\n")} Debug.assertNode(name, isIdentifier); return makeTempVariableName(268435456 /* _i */ , !!(autoGenerate.flags & 8 /* ReservedInNestedScopes */ ), /*privateName*/ false, prefix, suffix); case 3 /* Unique */ : - return makeUniqueName2(idText(name), autoGenerate.flags & 32 /* FileLevel */ ? isFileLevelUniqueName2 : isUniqueName, !!(autoGenerate.flags & 16 /* Optimistic */ ), !!(autoGenerate.flags & 8 /* ReservedInNestedScopes */ ), isPrivateIdentifier(name), prefix, suffix); + return makeUniqueName2(idText(name), autoGenerate.flags & 32 /* FileLevel */ ? isFileLevelUniqueNameInCurrentFile : isUniqueName, !!(autoGenerate.flags & 16 /* Optimistic */ ), !!(autoGenerate.flags & 8 /* ReservedInNestedScopes */ ), isPrivateIdentifier(name), prefix, suffix); } return Debug.fail(`Unsupported GeneratedIdentifierKind: ${Debug.formatEnum(autoGenerate.flags & 7 /* KindMask */ , GeneratedIdentifierFlags, /*isFlags*/ true)}.`); } @@ -91015,14 +92669,14 @@ ${lanes.join("\n")} function emitLeadingCommentsOfNode(node, emitFlags, pos, end) { enterComment(); hasWrittenComment = false; - const skipLeadingComments = pos < 0 || (emitFlags & 1024 /* NoLeadingComments */ ) !== 0 || node.kind === 11 /* JsxText */ ; - const skipTrailingComments = end < 0 || (emitFlags & 2048 /* NoTrailingComments */ ) !== 0 || node.kind === 11 /* JsxText */ ; + const skipLeadingComments = pos < 0 || (emitFlags & 1024 /* NoLeadingComments */ ) !== 0 || node.kind === 12 /* JsxText */ ; + const skipTrailingComments = end < 0 || (emitFlags & 2048 /* NoTrailingComments */ ) !== 0 || node.kind === 12 /* JsxText */ ; if ((pos > 0 || end > 0) && pos !== end) { - if (!skipLeadingComments) emitLeadingComments(pos, /*isEmittedNode*/ node.kind !== 355 /* NotEmittedStatement */ ); + if (!skipLeadingComments) emitLeadingComments(pos, /*isEmittedNode*/ node.kind !== 359 /* NotEmittedStatement */ ); if (!skipLeadingComments || pos >= 0 && (emitFlags & 1024 /* NoLeadingComments */ ) !== 0) containerPos = pos; if (!skipTrailingComments || end >= 0 && (emitFlags & 2048 /* NoTrailingComments */ ) !== 0) { containerEnd = end; - if (node.kind === 258 /* VariableDeclarationList */ ) declarationListContainerEnd = end; + if (node.kind === 261 /* VariableDeclarationList */ ) declarationListContainerEnd = end; } } forEach(getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); @@ -91030,13 +92684,13 @@ ${lanes.join("\n")} } function emitTrailingCommentsOfNode(node, emitFlags, pos, end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { enterComment(); - const skipTrailingComments = end < 0 || (emitFlags & 2048 /* NoTrailingComments */ ) !== 0 || node.kind === 11 /* JsxText */ ; + const skipTrailingComments = end < 0 || (emitFlags & 2048 /* NoTrailingComments */ ) !== 0 || node.kind === 12 /* JsxText */ ; forEach(getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); if ((pos > 0 || end > 0) && pos !== end) { containerPos = savedContainerPos; containerEnd = savedContainerEnd; declarationListContainerEnd = savedDeclarationListContainerEnd; - if (!skipTrailingComments && node.kind !== 355 /* NotEmittedStatement */ ) emitTrailingComments(end); + if (!skipTrailingComments && node.kind !== 359 /* NotEmittedStatement */ ) emitTrailingComments(end); } exitComment(); } @@ -91061,7 +92715,7 @@ ${lanes.join("\n")} } function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { enterComment(); - const { pos: pos , end: end } = detachedRange; + const { pos: pos, end: end } = detachedRange; const emitFlags = getEmitFlags(node); const skipLeadingComments = pos < 0 || (emitFlags & 1024 /* NoLeadingComments */ ) !== 0; const skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 2048 /* NoTrailingComments */ ) !== 0; @@ -91214,7 +92868,7 @@ ${lanes.join("\n")} if (parsed && sourceMapGenerator) sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end)); } else { const source = sourceMapRange.source || sourceMapSource; - if (node.kind !== 355 /* NotEmittedStatement */ && (emitFlags & 32 /* NoLeadingSourceMap */ ) === 0 && sourceMapRange.pos >= 0) emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); + if (node.kind !== 359 /* NotEmittedStatement */ && (emitFlags & 32 /* NoLeadingSourceMap */ ) === 0 && sourceMapRange.pos >= 0) emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); if (emitFlags & 128 /* NoNestedSourceMaps */ ) sourceMapsDisabled = true; } } @@ -91223,7 +92877,7 @@ ${lanes.join("\n")} const sourceMapRange = getSourceMapRange(node); if (!isUnparsedNode(node)) { if (emitFlags & 128 /* NoNestedSourceMaps */ ) sourceMapsDisabled = false; - if (node.kind !== 355 /* NotEmittedStatement */ && (emitFlags & 64 /* NoTrailingSourceMap */ ) === 0 && sourceMapRange.end >= 0) emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); + if (node.kind !== 359 /* NotEmittedStatement */ && (emitFlags & 64 /* NoTrailingSourceMap */ ) === 0 && sourceMapRange.end >= 0) emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); } } function skipSourceTrivia(source, pos) { @@ -91231,7 +92885,7 @@ ${lanes.join("\n")} } function emitPos(pos) { if (sourceMapsDisabled || positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) return; - const { line: sourceLine , character: sourceCharacter } = getLineAndCharacterOfPosition(sourceMapSource, pos); + const { line: sourceLine, character: sourceCharacter } = getLineAndCharacterOfPosition(sourceMapSource, pos); sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, /*nameIndex*/ void 0); } function emitSourcePos(source, pos) { @@ -91350,6 +93004,7 @@ ${lanes.join("\n")} // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant getConstantValue: notImplemented, getReferencedValueDeclaration: notImplemented, + getReferencedValueDeclarations: notImplemented, getTypeReferenceSerializationKind: notImplemented, isOptionalParameter: notImplemented, moduleExportsSomeValue: notImplemented, @@ -91381,12 +93036,12 @@ ${lanes.join("\n")} } }); // src/compiler/watchUtilities.ts - function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) { + function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames2) { if (!host.getDirectories || !host.readDirectory) return void 0; const cachedReadDirectoryResult = /* @__PURE__ */ new Map(); - const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); return { - useCaseSensitiveFileNames: useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, fileExists: fileExists, readFile: (path, encoding)=>host.readFile(path, encoding), directoryExists: host.directoryExists && directoryExists, @@ -91418,7 +93073,7 @@ ${lanes.join("\n")} return getBaseFileName(normalizePath(fileName)); } function createCachedFileSystemEntries(rootDir, rootDirPath) { - var _a2; + var _a; if (!host.realpath || ensureTrailingDirectorySeparator(toPath3(host.realpath(rootDir))) === rootDirPath) { const resultFromHost = { files: map(host.readDirectory(rootDir, /*extensions*/ void 0, /*exclude*/ void 0, /*include*/ [ @@ -91429,7 +93084,7 @@ ${lanes.join("\n")} cachedReadDirectoryResult.set(ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); return resultFromHost; } - if ((_a2 = host.directoryExists) == null ? void 0 : _a2.call(host, rootDir)) { + if ((_a = host.directoryExists) == null ? void 0 : _a.call(host, rootDir)) { cachedReadDirectoryResult.set(rootDirPath, false); return false; } @@ -91486,7 +93141,7 @@ ${lanes.join("\n")} const rootDirPath = toPath3(rootDir); const rootResult = tryReadDirectory2(rootDir, rootDirPath); let rootSymLinkResult; - if (rootResult !== void 0) return matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath); + if (rootResult !== void 0) return matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames2, currentDirectory, depth, getFileSystemEntries, realpath); return host.readDirectory(rootDir, extensions, excludes, includes, depth); function getFileSystemEntries(dir) { const path = toPath3(dir); @@ -91554,8 +93209,8 @@ ${lanes.join("\n")} } } function updateSharedExtendedConfigFileWatcher(projectPath, options, extendedConfigFilesMap, createExtendedConfigFileWatch, toPath3) { - var _a2; - const extendedConfigs = arrayToMap(((_a2 = options == null ? void 0 : options.configFile) == null ? void 0 : _a2.extendedSourceFiles) || emptyArray, toPath3); + var _a; + const extendedConfigs = arrayToMap(((_a = options == null ? void 0 : options.configFile) == null ? void 0 : _a.extendedSourceFiles) || emptyArray, toPath3); extendedConfigFilesMap.forEach((watcher, extendedConfigFilePath)=>{ if (!extendedConfigs.has(extendedConfigFilePath)) { watcher.projects.delete(projectPath); @@ -91586,9 +93241,9 @@ ${lanes.join("\n")} } function cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath3) { if (!extendedConfigCache.delete(extendedConfigFilePath)) return; - extendedConfigCache.forEach(({ extendedResult: extendedResult }, key)=>{ - var _a2; - if ((_a2 = extendedResult.extendedSourceFiles) == null ? void 0 : _a2.some((extendedFile)=>toPath3(extendedFile) === extendedConfigFilePath)) cleanExtendedConfigCache(extendedConfigCache, key, toPath3); + extendedConfigCache.forEach(({ extendedResult: extendedResult }, key)=>{ + var _a; + if ((_a = extendedResult.extendedSourceFiles) == null ? void 0 : _a.some((extendedFile)=>toPath3(extendedFile) === extendedConfigFilePath)) cleanExtendedConfigCache(extendedConfigCache, key, toPath3); }); } function updatePackageJsonWatch(lookups, packageJsonWatches, createPackageJsonWatch) { @@ -91630,7 +93285,7 @@ ${lanes.join("\n")} existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags)); } } - function isIgnoredFileFromWildCardWatching({ watchedDirPath: watchedDirPath , fileOrDirectory: fileOrDirectory , fileOrDirectoryPath: fileOrDirectoryPath , configFileName: configFileName , options: options , program: program , extraFileExtensions: extraFileExtensions , currentDirectory: currentDirectory , useCaseSensitiveFileNames: useCaseSensitiveFileNames , writeLog: writeLog , toPath: toPath3 }) { + function isIgnoredFileFromWildCardWatching({ watchedDirPath: watchedDirPath, fileOrDirectory: fileOrDirectory, fileOrDirectoryPath: fileOrDirectoryPath, configFileName: configFileName, options: options, program: program, extraFileExtensions: extraFileExtensions, currentDirectory: currentDirectory, useCaseSensitiveFileNames: useCaseSensitiveFileNames2, writeLog: writeLog, toPath: toPath3 }) { const newPath = removeIgnoredPath(fileOrDirectoryPath); if (!newPath) { writeLog(`Project: ${configFileName} Detected ignored path: ${fileOrDirectory}`); @@ -91642,7 +93297,7 @@ ${lanes.join("\n")} writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); return true; } - if (isExcludedFile(fileOrDirectory, options.configFile.configFileSpecs, getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), useCaseSensitiveFileNames, currentDirectory)) { + if (isExcludedFile(fileOrDirectory, options.configFile.configFileSpecs, getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), useCaseSensitiveFileNames2, currentDirectory)) { writeLog(`Project: ${configFileName} Detected excluded file: ${fileOrDirectory}`); return true; } @@ -91691,11 +93346,11 @@ ${lanes.join("\n")} }; function createExcludeHandlingAddWatch(key) { return (file, cb, flags, options, detailInfo1, detailInfo2)=>{ - var _a2; - return !matchesExclude(file, key === "watchFile" ? options == null ? void 0 : options.excludeFiles : options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames(), ((_a2 = host.getCurrentDirectory) == null ? void 0 : _a2.call(host)) || "") ? factory2[key].call(/*thisArgs*/ void 0, file, cb, flags, options, detailInfo1, detailInfo2) : excludeWatcherFactory(file, flags, options, detailInfo1, detailInfo2); + var _a; + return !matchesExclude(file, key === "watchFile" ? options == null ? void 0 : options.excludeFiles : options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames2(), ((_a = host.getCurrentDirectory) == null ? void 0 : _a.call(host)) || "") ? factory2[key].call(/*thisArgs*/ void 0, file, cb, flags, options, detailInfo1, detailInfo2) : excludeWatcherFactory(file, flags, options, detailInfo1, detailInfo2); }; } - function useCaseSensitiveFileNames() { + function useCaseSensitiveFileNames2() { return typeof host.useCaseSensitiveFileNames === "boolean" ? host.useCaseSensitiveFileNames : host.useCaseSensitiveFileNames(); } function createExcludeWatcherWithLogging(file, flags, options, detailInfo1, detailInfo2) { @@ -91760,7 +93415,6 @@ ${lanes.join("\n")} "src/compiler/watchUtilities.ts" () { "use strict"; init_ts2(); - init_ts2(); ConfigFileProgramReloadLevel = /* @__PURE__ */ ((ConfigFileProgramReloadLevel2)=>{ ConfigFileProgramReloadLevel2[ConfigFileProgramReloadLevel2["None"] = 0] = "None"; ConfigFileProgramReloadLevel2[ConfigFileProgramReloadLevel2["Partial"] = 1] = "Partial"; @@ -91978,7 +93632,7 @@ ${lanes.join("\n")} function formatDiagnostic(diagnostic, host) { const errorMessage = `${diagnosticCategoryName(diagnostic)} TS${diagnostic.code}: ${flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine())}${host.getNewLine()}`; if (diagnostic.file) { - const { line: line , character: character } = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); + const { line: line, character: character } = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); const fileName = diagnostic.file.fileName; const relativeFileName = convertToRelativePath(fileName, host.getCurrentDirectory(), (fileName2)=>host.getCanonicalFileName(fileName2)); return `${relativeFileName}(${line + 1},${character + 1}): ` + errorMessage; @@ -92001,8 +93655,8 @@ ${lanes.join("\n")} return formatStyle + text + resetEscapeSequence; } function formatCodeSpan(file, start, length2, indent2, squiggleColor, host) { - const { line: firstLine , character: firstLineChar } = getLineAndCharacterOfPosition(file, start); - const { line: lastLine , character: lastLineChar } = getLineAndCharacterOfPosition(file, start + length2); + const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start); + const { line: lastLine, character: lastLineChar } = getLineAndCharacterOfPosition(file, start + length2); const lastLineInFile = getLineAndCharacterOfPosition(file, file.text.length).line; const hasMoreThanFiveLines = lastLine - firstLine >= 4; let gutterWidth = (lastLine + 1 + "").length; @@ -92034,7 +93688,7 @@ ${lanes.join("\n")} return context; } function formatLocation(file, start, host, color = formatColorAndReset) { - const { line: firstLine , character: firstLineChar } = getLineAndCharacterOfPosition(file, start); + const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start); const relativeFileName = host ? convertToRelativePath(file.fileName, host.getCurrentDirectory(), (fileName)=>host.getCanonicalFileName(fileName)) : file.fileName; let output = ""; output += color(relativeFileName, "\x1b[96m" /* Cyan */ ); @@ -92048,20 +93702,20 @@ ${lanes.join("\n")} let output = ""; for (const diagnostic of diagnostics){ if (diagnostic.file) { - const { file: file , start: start } = diagnostic; + const { file: file, start: start } = diagnostic; output += formatLocation(file, start, host); output += " - "; } output += formatColorAndReset(diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category)); output += formatColorAndReset(` TS${diagnostic.code}: `, "\x1b[90m" /* Grey */ ); output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); - if (diagnostic.file) { + if (diagnostic.file && diagnostic.code !== Diagnostics.File_appears_to_be_binary.code) { output += host.getNewLine(); output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); } if (diagnostic.relatedInformation) { output += host.getNewLine(); - for (const { file: file , start: start , length: length2 , messageText: messageText } of diagnostic.relatedInformation){ + for (const { file: file, start: start, length: length2, messageText: messageText } of diagnostic.relatedInformation){ if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); @@ -92096,13 +93750,13 @@ ${lanes.join("\n")} return getModeForUsageLocation(file, getModuleNameStringLiteralAt(file, index)); } function isExclusivelyTypeOnlyImportOrExport(decl) { - var _a2; + var _a; if (isExportDeclaration(decl)) return decl.isTypeOnly; - if ((_a2 = decl.importClause) == null ? void 0 : _a2.isTypeOnly) return true; + if ((_a = decl.importClause) == null ? void 0 : _a.isTypeOnly) return true; return false; } function getModeForUsageLocation(file, usage) { - var _a2, _b; + var _a, _b; if (file.impliedNodeFormat === void 0) return void 0; if (isImportDeclaration(usage.parent) || isExportDeclaration(usage.parent)) { const isTypeOnly = isExclusivelyTypeOnlyImportOrExport(usage.parent); @@ -92112,7 +93766,7 @@ ${lanes.join("\n")} } } if (usage.parent.parent && isImportTypeNode(usage.parent.parent)) { - const override = getResolutionModeOverrideForClause((_a2 = usage.parent.parent.assertions) == null ? void 0 : _a2.assertClause); + const override = getResolutionModeOverrideForClause((_a = usage.parent.parent.assertions) == null ? void 0 : _a.assertClause); if (override) return override; } if (file.impliedNodeFormat !== 99 /* ESNext */ ) return isImportCall(walkUpParenthesizedExpressions(usage.parent)) ? 99 /* ESNext */ : 1 /* CommonJS */ ; @@ -92191,6 +93845,28 @@ ${lanes.join("\n")} }); } } + function getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName) { + const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : currentDirectory; + return combinePaths(containingDirectory, `__lib_node_modules_lookup_${libFileName}__.ts`); + } + function getLibraryNameFromLibFileName(libFileName) { + const components = libFileName.split("."); + let path = components[1]; + let i = 2; + while(components[i] && components[i] !== "d"){ + path += (i === 2 ? "/" : "-") + components[i]; + i++; + } + return "@typescript/lib-" + path; + } + function getLibFileNameFromLibReference(libReference) { + const libName = toFileNameLowerCase(libReference.fileName); + const libFileName = libMap.get(libName); + return { + libName: libName, + libFileName: libFileName + }; + } function isReferencedFile(reason) { switch(reason == null ? void 0 : reason.kind){ case 3 /* Import */ : @@ -92206,14 +93882,14 @@ ${lanes.join("\n")} return location.pos !== void 0; } function getReferencedFileLocation(getSourceFileByPath, ref) { - var _a2, _b, _c, _d, _e, _f; + var _a, _b, _c, _d, _e, _f; const file = Debug.checkDefined(getSourceFileByPath(ref.file)); - const { kind: kind , index: index } = ref; + const { kind: kind, index: index } = ref; let pos, end, packageId, resolutionMode; switch(kind){ case 3 /* Import */ : const importLiteral = getModuleNameStringLiteralAt(file, index); - packageId = (_c = (_b = (_a2 = file.resolvedModules) == null ? void 0 : _a2.get(importLiteral.text, getModeForResolutionAtIndex(file, index))) == null ? void 0 : _b.resolvedModule) == null ? void 0 : _c.packageId; + packageId = (_c = (_b = (_a = file.resolvedModules) == null ? void 0 : _a.get(importLiteral.text, getModeForResolutionAtIndex(file, index))) == null ? void 0 : _b.resolvedModule) == null ? void 0 : _c.packageId; if (importLiteral.pos === -1) return { file: file, packageId: packageId, @@ -92223,14 +93899,14 @@ ${lanes.join("\n")} end = importLiteral.end; break; case 4 /* ReferenceFile */ : - ({ pos: pos , end: end } = file.referencedFiles[index]); + ({ pos: pos, end: end } = file.referencedFiles[index]); break; case 5 /* TypeReferenceDirective */ : - ({ pos: pos , end: end , resolutionMode: resolutionMode } = file.typeReferenceDirectives[index]); + ({ pos: pos, end: end, resolutionMode: resolutionMode } = file.typeReferenceDirectives[index]); packageId = (_f = (_e = (_d = file.resolvedTypeReferenceDirectiveNames) == null ? void 0 : _d.get(toFileNameLowerCase(file.typeReferenceDirectives[index].fileName), resolutionMode || file.impliedNodeFormat)) == null ? void 0 : _e.resolvedTypeReferenceDirective) == null ? void 0 : _f.packageId; break; case 7 /* LibReferenceDirective */ : - ({ pos: pos , end: end } = file.libReferenceDirectives[index]); + ({ pos: pos, end: end } = file.libReferenceDirectives[index]); break; default: return Debug.assertNever(kind); @@ -92242,7 +93918,7 @@ ${lanes.join("\n")} packageId: packageId }; } - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences) { if (!program || (hasChangedAutomaticTypeDirectiveNames == null ? void 0 : hasChangedAutomaticTypeDirectiveNames())) return false; if (!arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) return false; let seenResolvedRefs; @@ -92251,6 +93927,7 @@ ${lanes.join("\n")} if (program.getMissingFilePaths().some(fileExists)) return false; const currentOptions = program.getCompilerOptions(); if (!compareDataObjects(currentOptions, newOptions)) return false; + if (program.resolvedLibReferences && forEachEntry(program.resolvedLibReferences, (_value, libFileName)=>hasInvalidatedLibResolutions(libFileName))) return false; if (currentOptions.configFile && newOptions.configFile) return currentOptions.configFile.text === newOptions.configFile.text; return true; function sourceFileNotUptoDate(sourceFile) { @@ -92338,10 +94015,10 @@ ${lanes.join("\n")} }; } function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { - var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p; + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p; const createProgramOptions = isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; - const { rootNames: rootNames , options: options , configFileParsingDiagnostics: configFileParsingDiagnostics , projectReferences: projectReferences , typeScriptVersion: typeScriptVersion3 } = createProgramOptions; - let { oldProgram: oldProgram } = createProgramOptions; + const { rootNames: rootNames, options: options, configFileParsingDiagnostics: configFileParsingDiagnostics, projectReferences: projectReferences, typeScriptVersion: typeScriptVersion3 } = createProgramOptions; + let { oldProgram: oldProgram } = createProgramOptions; const reportInvalidIgnoreDeprecations = memoize(()=>createOptionValueDiagnostic("ignoreDeprecations", Diagnostics.Invalid_value_for_ignoreDeprecations)); let processingDefaultLibFiles; let processingOtherFiles; @@ -92358,11 +94035,14 @@ ${lanes.join("\n")} let fileProcessingDiagnostics; let automaticTypeDirectiveNames; let automaticTypeDirectiveResolutions; + let resolvedLibReferences; + let resolvedLibProcessing; + let packageMap; const maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; let currentNodeModulesDepth = 0; const modulesWithElidedImports = /* @__PURE__ */ new Map(); const sourceFilesFoundSearchingNodeModules = /* @__PURE__ */ new Map(); - (_a2 = tracing) == null || _a2.push(tracing.Phase.Program, "createProgram", { + (_a = tracing) == null || _a.push(tracing.Phase.Program, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); @@ -92408,6 +94088,13 @@ ${lanes.join("\n")} const typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ void 0, moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); actualResolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile, redirectedReference, options2, containingSourceFile)=>loadWithModeAwareCache(typeDirectiveNames, containingFile, redirectedReference, options2, containingSourceFile, host, typeReferenceDirectiveResolutionCache, createTypeReferenceResolutionLoader); } + const hasInvalidatedLibResolutions = host.hasInvalidatedLibResolutions || returnFalse; + let actualResolveLibrary; + if (host.resolveLibrary) actualResolveLibrary = host.resolveLibrary.bind(host); + else { + const libraryResolutionCache = createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); + actualResolveLibrary = (libraryName, resolveFrom, options2)=>resolveLibrary(libraryName, resolveFrom, options2, host, libraryResolutionCache); + } const packageIdToSourceFile = /* @__PURE__ */ new Map(); let sourceFileToPackageName = /* @__PURE__ */ new Map(); let redirectTargetsMap = createMultiMap(); @@ -92420,7 +94107,7 @@ ${lanes.join("\n")} let mapFromFileToProjectReferenceRedirects; let mapFromToProjectReferenceRedirectSource; const useSourceOfProjectReferenceRedirect = !!((_d = host.useSourceOfProjectReferenceRedirect) == null ? void 0 : _d.call(host)) && !options.disableSourceOfProjectReferenceRedirect; - const { onProgramCreateComplete: onProgramCreateComplete , fileExists: fileExists , directoryExists: directoryExists } = updateHostForUseSourceOfProjectReferenceRedirect({ + const { onProgramCreateComplete: onProgramCreateComplete, fileExists: fileExists, directoryExists: directoryExists } = updateHostForUseSourceOfProjectReferenceRedirect({ compilerHost: host, getSymlinkCache: getSymlinkCache, useSourceOfProjectReferenceRedirect: useSourceOfProjectReferenceRedirect, @@ -92475,13 +94162,13 @@ ${lanes.join("\n")} index: index })); (_j = tracing) == null || _j.pop(); - automaticTypeDirectiveNames != null ? automaticTypeDirectiveNames : automaticTypeDirectiveNames = rootNames.length ? getAutomaticTypeDirectiveNames(options, host) : emptyArray; + automaticTypeDirectiveNames ?? (automaticTypeDirectiveNames = rootNames.length ? getAutomaticTypeDirectiveNames(options, host) : emptyArray); automaticTypeDirectiveResolutions = createModeAwareCache(); if (automaticTypeDirectiveNames.length) { (_k = tracing) == null || _k.push(tracing.Phase.Program, "processTypeReferences", { count: automaticTypeDirectiveNames.length }); - const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); + const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : currentDirectory; const containingFilename = combinePaths(containingDirectory, inferredTypesContainingFile); const resolutions = resolveTypeReferenceDirectiveNamesReusingOldState(automaticTypeDirectiveNames, containingFilename); for(let i = 0; i < automaticTypeDirectiveNames.length; i++){ @@ -92529,6 +94216,7 @@ ${lanes.join("\n")} if (!(projectReferenceRedirects == null ? void 0 : projectReferenceRedirects.has(toPath3(oldRefPath)))) host.onReleaseParsedCommandLine(oldRefPath, oldResolvedRef, oldProgram.getCompilerOptions()); }); oldProgram = void 0; + resolvedLibProcessing = void 0; const program = { getRootFileNames: ()=>rootNames, getSourceFile: getSourceFile, @@ -92570,6 +94258,10 @@ ${lanes.join("\n")} sourceFileToPackageName: sourceFileToPackageName, redirectTargetsMap: redirectTargetsMap, usesUriStyleNodeCoreModules: usesUriStyleNodeCoreModules, + resolvedLibReferences: resolvedLibReferences, + getCurrentPackagesMap: ()=>packageMap, + typesPackageExists: typesPackageExists, + packageBundlesTypes: packageBundlesTypes, isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics2, getProjectReferences: getProjectReferences, @@ -92597,7 +94289,7 @@ ${lanes.join("\n")} case 1 /* FilePreprocessingFileExplainingDiagnostic */ : return programDiagnostics.add(createDiagnosticExplainingFile(diagnostic.file && getSourceFileByPath(diagnostic.file), diagnostic.fileProcessingReason, diagnostic.diagnostic, diagnostic.args || emptyArray)); case 0 /* FilePreprocessingReferencedDiagnostic */ : - const { file: file , pos: pos , end: end } = getReferencedFileLocation(getSourceFileByPath, diagnostic.reason); + const { file: file, pos: pos, end: end } = getReferencedFileLocation(getSourceFileByPath, diagnostic.reason); return programDiagnostics.add(createFileDiagnostic(file, Debug.checkDefined(pos), Debug.checkDefined(end) - pos, diagnostic.diagnostic, ...diagnostic.args || emptyArray)); case 2 /* ResolutionDiagnostics */ : return diagnostic.diagnostics.forEach((d)=>programDiagnostics.add(d)); @@ -92610,10 +94302,27 @@ ${lanes.join("\n")} measure("Program", "beforeProgram", "afterProgram"); (_p = tracing) == null || _p.pop(); return program; + function getPackagesMap() { + if (packageMap) return packageMap; + packageMap = /* @__PURE__ */ new Map(); + files.forEach((sf)=>{ + if (!sf.resolvedModules) return; + sf.resolvedModules.forEach(({ resolvedModule: resolvedModule })=>{ + if (resolvedModule == null ? void 0 : resolvedModule.packageId) packageMap.set(resolvedModule.packageId.name, resolvedModule.extension === ".d.ts" /* Dts */ || !!packageMap.get(resolvedModule.packageId.name)); + }); + }); + return packageMap; + } + function typesPackageExists(packageName) { + return getPackagesMap().has(getTypesPackageName(packageName)); + } + function packageBundlesTypes(packageName) { + return !!getPackagesMap().get(packageName); + } function addResolutionDiagnostics(resolution) { - var _a3; - if (!((_a3 = resolution.resolutionDiagnostics) == null ? void 0 : _a3.length)) return; - (fileProcessingDiagnostics != null ? fileProcessingDiagnostics : fileProcessingDiagnostics = []).push({ + var _a2; + if (!((_a2 = resolution.resolutionDiagnostics) == null ? void 0 : _a2.length)) return; + (fileProcessingDiagnostics ?? (fileProcessingDiagnostics = [])).push({ kind: 2 /* ResolutionDiagnostics */ , diagnostics: resolution.resolutionDiagnostics }); @@ -92628,11 +94337,11 @@ ${lanes.join("\n")} if (fromCache) addResolutionDiagnostics(fromCache); } function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) { - var _a3, _b2; + var _a2, _b2; if (!moduleNames.length) return emptyArray; const containingFileName = getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory); const redirectedReference = getRedirectReferenceForResolution(containingFile); - (_a3 = tracing) == null || _a3.push(tracing.Phase.Program, "resolveModuleNamesWorker", { + (_a2 = tracing) == null || _a2.push(tracing.Phase.Program, "resolveModuleNamesWorker", { containingFileName: containingFileName }); mark("beforeResolveModule"); @@ -92643,12 +94352,12 @@ ${lanes.join("\n")} return result; } function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, reusedNames) { - var _a3, _b2; + var _a2, _b2; if (!typeDirectiveNames.length) return []; const containingSourceFile = !isString(containingFile) ? containingFile : void 0; const containingFileName = !isString(containingFile) ? getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile; const redirectedReference = containingSourceFile && getRedirectReferenceForResolution(containingSourceFile); - (_a3 = tracing) == null || _a3.push(tracing.Phase.Program, "resolveTypeReferenceDirectiveNamesWorker", { + (_a2 = tracing) == null || _a2.push(tracing.Phase.Program, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); mark("beforeResolveTypeReference"); @@ -92701,16 +94410,16 @@ ${lanes.join("\n")} return commonSourceDirectory; } function getClassifiableNames() { - var _a3; + var _a2; if (!classifiableNames) { getTypeChecker(); classifiableNames = /* @__PURE__ */ new Set(); - for (const sourceFile of files)(_a3 = sourceFile.classifiableNames) == null || _a3.forEach((value1)=>classifiableNames.add(value1)); + for (const sourceFile of files)(_a2 = sourceFile.classifiableNames) == null || _a2.forEach((value1)=>classifiableNames.add(value1)); } return classifiableNames; } function resolveModuleNamesReusingOldState(moduleNames, file) { - var _a3; + var _a2; if (structureIsReused === 0 /* Not */ && !file.ambientModuleNames.length) return resolveModuleNamesWorker(moduleNames, file, /*reusedNames*/ void 0); const oldSourceFile = oldProgram && oldProgram.getSourceFile(file.fileName); if (oldSourceFile !== file && file.resolvedModules) { @@ -92729,11 +94438,11 @@ ${lanes.join("\n")} const moduleName = moduleNames[i]; if (file === oldSourceFile && !hasInvalidatedResolutions(oldSourceFile.path)) { const mode = getModeForUsageLocation(file, moduleName); - const oldResolution = (_a3 = oldSourceFile.resolvedModules) == null ? void 0 : _a3.get(moduleName.text, mode); + const oldResolution = (_a2 = oldSourceFile.resolvedModules) == null ? void 0 : _a2.get(moduleName.text, mode); if (oldResolution == null ? void 0 : oldResolution.resolvedModule) { if (isTraceEnabled(options, host)) trace(host, oldResolution.resolvedModule.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2, moduleName.text, getNormalizedAbsolutePath(file.originalFileName, currentDirectory), oldResolution.resolvedModule.resolvedFileName, oldResolution.resolvedModule.packageId && packageIdToString(oldResolution.resolvedModule.packageId)); - (result != null ? result : result = new Array(moduleNames.length))[i] = oldResolution; - (reusedNames != null ? reusedNames : reusedNames = []).push(moduleName); + (result ?? (result = new Array(moduleNames.length)))[i] = oldResolution; + (reusedNames ?? (reusedNames = [])).push(moduleName); continue; } } @@ -92743,7 +94452,7 @@ ${lanes.join("\n")} if (isTraceEnabled(options, host)) trace(host, Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName.text, getNormalizedAbsolutePath(file.originalFileName, currentDirectory)); } else resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); if (resolvesToAmbientModuleInNonModifiedFile) (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; - else (unknownModuleNames != null ? unknownModuleNames : unknownModuleNames = []).push(moduleName); + else (unknownModuleNames ?? (unknownModuleNames = [])).push(moduleName); } const resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, file, reusedNames) : emptyArray; if (!result) { @@ -92768,8 +94477,8 @@ ${lanes.join("\n")} } } function resolveTypeReferenceDirectiveNamesReusingOldState(typeDirectiveNames, containingFile) { - var _a3; - if (structureIsReused === 0 /* Not */ ) return resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, /*resuedNames*/ void 0); + var _a2; + if (structureIsReused === 0 /* Not */ ) return resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, /*reusedNames*/ void 0); const oldSourceFile = !isString(containingFile) ? oldProgram && oldProgram.getSourceFile(containingFile.fileName) : void 0; if (!isString(containingFile)) { if (oldSourceFile !== containingFile && containingFile.resolvedTypeReferenceDirectiveNames) { @@ -92791,15 +94500,15 @@ ${lanes.join("\n")} if (canReuseResolutions) { const typeDirectiveName = getTypeReferenceResolutionName(entry); const mode = getModeForFileReference(entry, containingSourceFile == null ? void 0 : containingSourceFile.impliedNodeFormat); - const oldResolution = (_a3 = !isString(containingFile) ? oldSourceFile == null ? void 0 : oldSourceFile.resolvedTypeReferenceDirectiveNames : oldProgram == null ? void 0 : oldProgram.getAutomaticTypeDirectiveResolutions()) == null ? void 0 : _a3.get(typeDirectiveName, mode); + const oldResolution = (_a2 = !isString(containingFile) ? oldSourceFile == null ? void 0 : oldSourceFile.resolvedTypeReferenceDirectiveNames : oldProgram == null ? void 0 : oldProgram.getAutomaticTypeDirectiveResolutions()) == null ? void 0 : _a2.get(typeDirectiveName, mode); if (oldResolution == null ? void 0 : oldResolution.resolvedTypeReferenceDirective) { if (isTraceEnabled(options, host)) trace(host, oldResolution.resolvedTypeReferenceDirective.packageId ? Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2, typeDirectiveName, !isString(containingFile) ? getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile, oldResolution.resolvedTypeReferenceDirective.resolvedFileName, oldResolution.resolvedTypeReferenceDirective.packageId && packageIdToString(oldResolution.resolvedTypeReferenceDirective.packageId)); - (result != null ? result : result = new Array(typeDirectiveNames.length))[i] = oldResolution; - (reusedNames != null ? reusedNames : reusedNames = []).push(entry); + (result ?? (result = new Array(typeDirectiveNames.length)))[i] = oldResolution; + (reusedNames ?? (reusedNames = [])).push(entry); continue; } } - (unknownTypeReferenceDirectiveNames != null ? unknownTypeReferenceDirectiveNames : unknownTypeReferenceDirectiveNames = []).push(entry); + (unknownTypeReferenceDirectiveNames ?? (unknownTypeReferenceDirectiveNames = [])).push(entry); } if (!unknownTypeReferenceDirectiveNames) return result || emptyArray; const resolutions = resolveTypeReferenceDirectiveNamesWorker(unknownTypeReferenceDirectiveNames, containingFile, reusedNames); @@ -92827,7 +94536,7 @@ ${lanes.join("\n")} }); } function tryReuseStructureFromOldProgram() { - var _a3; + var _a2; if (!oldProgram) return 0 /* Not */ ; const oldOptions = oldProgram.getCompilerOptions(); if (changesAffectModuleResolution(oldOptions, options)) return 0 /* Not */ ; @@ -92848,9 +94557,9 @@ ${lanes.join("\n")} const seenPackageNames = /* @__PURE__ */ new Map(); for (const oldSourceFile of oldSourceFiles){ const sourceFileOptions = getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options); - let newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, sourceFileOptions, /*onError*/ void 0, shouldCreateNewSourceFile || sourceFileOptions.impliedNodeFormat !== oldSourceFile.impliedNodeFormat) : host.getSourceFile(oldSourceFile.fileName, sourceFileOptions, /*onError*/ void 0, shouldCreateNewSourceFile || sourceFileOptions.impliedNodeFormat !== oldSourceFile.impliedNodeFormat); + let newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, sourceFileOptions, /*onError*/ void 0, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, sourceFileOptions, /*onError*/ void 0, shouldCreateNewSourceFile); if (!newSourceFile) return 0 /* Not */ ; - newSourceFile.packageJsonLocations = ((_a3 = sourceFileOptions.packageJsonLocations) == null ? void 0 : _a3.length) ? sourceFileOptions.packageJsonLocations : void 0; + newSourceFile.packageJsonLocations = ((_a2 = sourceFileOptions.packageJsonLocations) == null ? void 0 : _a2.length) ? sourceFileOptions.packageJsonLocations : void 0; newSourceFile.packageJsonScope = sourceFileOptions.packageJsonScope; Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`"); let fileChanged; @@ -92882,7 +94591,7 @@ ${lanes.join("\n")} collectExternalModuleReferences(newSourceFile); if (!arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) structureIsReused = 1 /* SafeModules */ ; else if (!arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) structureIsReused = 1 /* SafeModules */ ; - else if ((oldSourceFile.flags & 6291456 /* PermanentlySetIncrementalFlags */ ) !== (newSourceFile.flags & 6291456 /* PermanentlySetIncrementalFlags */ )) structureIsReused = 1 /* SafeModules */ ; + else if ((oldSourceFile.flags & 12582912 /* PermanentlySetIncrementalFlags */ ) !== (newSourceFile.flags & 12582912 /* PermanentlySetIncrementalFlags */ )) structureIsReused = 1 /* SafeModules */ ; else if (!arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) structureIsReused = 1 /* SafeModules */ ; } modifiedSourceFiles.push({ @@ -92903,7 +94612,7 @@ ${lanes.join("\n")} for (const oldFile of oldSourceFiles){ if (!contains(modifiedFiles, oldFile)) for (const moduleName of oldFile.ambientModuleNames)ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); } - for (const { oldFile: oldSourceFile , newFile: newSourceFile } of modifiedSourceFiles){ + for (const { oldFile: oldSourceFile, newFile: newSourceFile } of modifiedSourceFiles){ const moduleNames = getModuleNames(newSourceFile); const resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFile); const resolutionsChanged = hasChangesInResolutions(moduleNames, newSourceFile, resolutions, oldSourceFile.resolvedModules, moduleResolutionIsEqualTo, moduleResolutionNameAndModeGetter); @@ -92921,6 +94630,7 @@ ${lanes.join("\n")} } if (structureIsReused !== 2 /* Completely */ ) return structureIsReused; if (changesAffectingProgramStructure(oldOptions, options)) return 1 /* SafeModules */ ; + if (oldProgram.resolvedLibReferences && forEachEntry(oldProgram.resolvedLibReferences, (resolution, libFileName)=>pathForLibFileWorker(libFileName).actual !== resolution.actual)) return 1 /* SafeModules */ ; if (host.hasChangedAutomaticTypeDirectiveNames) { if (host.hasChangedAutomaticTypeDirectiveNames()) return 1 /* SafeModules */ ; } else { @@ -92951,6 +94661,8 @@ ${lanes.join("\n")} sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; usesUriStyleNodeCoreModules = oldProgram.usesUriStyleNodeCoreModules; + resolvedLibReferences = oldProgram.resolvedLibReferences; + packageMap = oldProgram.getCurrentPackagesMap(); return 2 /* Completely */ ; } function getEmitHost(writeFileCallback) { @@ -92980,8 +94692,8 @@ ${lanes.join("\n")} }, useCaseSensitiveFileNames: ()=>host.useCaseSensitiveFileNames(), getBuildInfo: (bundle)=>{ - var _a3; - return (_a3 = program.getBuildInfo) == null ? void 0 : _a3.call(program, bundle); + var _a2; + return (_a2 = program.getBuildInfo) == null ? void 0 : _a2.call(program, bundle); }, getSourceFileFromReference: (file, ref)=>program.getSourceFileFromReference(file, ref), redirectTargetsMap: redirectTargetsMap, @@ -92993,11 +94705,11 @@ ${lanes.join("\n")} host.writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data); } function emitBuildInfo(writeFileCallback) { - var _a3, _b2; + var _a2, _b2; Debug.assert(!outFile(options)); - (_a3 = tracing) == null || _a3.push(tracing.Phase.Emit, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true); + (_a2 = tracing) == null || _a2.push(tracing.Phase.Emit, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true); mark("beforeEmit"); - const emitResult = emitFiles(notImplementedResolver, getEmitHost(writeFileCallback), /*targetSourceFile*/ void 0, /*transformers*/ noTransformers, /*emitOnlyDtsFiles*/ false, /*onlyBuildInfo*/ true); + const emitResult = emitFiles(notImplementedResolver, getEmitHost(writeFileCallback), /*targetSourceFile*/ void 0, /*transformers*/ noTransformers, /*emitOnly*/ false, /*onlyBuildInfo*/ true); mark("afterEmit"); measure("Emit", "beforeEmit", "afterEmit"); (_b2 = tracing) == null || _b2.pop(); @@ -93011,8 +94723,8 @@ ${lanes.join("\n")} } function getPrependNodes() { return createPrependNodes(projectReferences, (_ref, index)=>{ - var _a3; - return (_a3 = resolvedProjectReferences[index]) == null ? void 0 : _a3.commandLine; + var _a2; + return (_a2 = resolvedProjectReferences[index]) == null ? void 0 : _a2.commandLine; }, (fileName)=>{ const path = toPath3(fileName); const sourceFile = getSourceFileByPath(path); @@ -93028,14 +94740,14 @@ ${lanes.join("\n")} if (!options.noLib) return false; const equalityComparer = host.useCaseSensitiveFileNames() ? equateStringsCaseSensitive : equateStringsCaseInsensitive; if (!options.lib) return equalityComparer(file.fileName, getDefaultLibraryFileName()); - else return some(options.lib, (libFileName)=>equalityComparer(file.fileName, pathForLibFile(libFileName))); + else return some(options.lib, (libFileName)=>equalityComparer(file.fileName, resolvedLibReferences.get(libFileName).actual)); } function getTypeChecker() { return typeChecker || (typeChecker = createTypeChecker(program)); } function emit(sourceFile, writeFileCallback, cancellationToken, emitOnly, transformers, forceDtsEmit) { - var _a3, _b2; - (_a3 = tracing) == null || _a3.push(tracing.Phase.Emit, "emit", { + var _a2, _b2; + (_a2 = tracing) == null || _a2.push(tracing.Phase.Emit, "emit", { path: sourceFile == null ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true); const result = runWithCancellationToken(()=>emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnly, transformers, forceDtsEmit)); @@ -93077,17 +94789,17 @@ ${lanes.join("\n")} return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken); } function getCachedSemanticDiagnostics(sourceFile) { - var _a3; - return sourceFile ? (_a3 = cachedBindAndCheckDiagnosticsForFile.perFile) == null ? void 0 : _a3.get(sourceFile.path) : cachedBindAndCheckDiagnosticsForFile.allDiagnostics; + var _a2; + return sourceFile ? (_a2 = cachedBindAndCheckDiagnosticsForFile.perFile) == null ? void 0 : _a2.get(sourceFile.path) : cachedBindAndCheckDiagnosticsForFile.allDiagnostics; } function getBindAndCheckDiagnostics(sourceFile, cancellationToken) { return getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken); } function getProgramDiagnostics(sourceFile) { - var _a3; + var _a2; if (skipTypeChecking(sourceFile, options, program)) return emptyArray; const programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); - if (!((_a3 = sourceFile.commentDirectives) == null ? void 0 : _a3.length)) return programDiagnosticsInFile; + if (!((_a2 = sourceFile.commentDirectives) == null ? void 0 : _a2.length)) return programDiagnosticsInFile; return getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, programDiagnosticsInFile).diagnostics; } function getDeclarationDiagnostics2(sourceFile, cancellationToken) { @@ -93136,10 +94848,10 @@ ${lanes.join("\n")} }); } function getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics, ...allDiagnostics) { - var _a3; + var _a2; const flatDiagnostics = flatten(allDiagnostics); - if (!includeBindAndCheckDiagnostics || !((_a3 = sourceFile.commentDirectives) == null ? void 0 : _a3.length)) return flatDiagnostics; - const { diagnostics: diagnostics , directives: directives } = getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics); + if (!includeBindAndCheckDiagnostics || !((_a2 = sourceFile.commentDirectives) == null ? void 0 : _a2.length)) return flatDiagnostics; + const { diagnostics: diagnostics, directives: directives } = getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics); for (const errorExpectation of directives.getUnusedExpectations())diagnostics.push(createDiagnosticForRange(sourceFile, errorExpectation.range, Diagnostics.Unused_ts_expect_error_directive)); return diagnostics; } @@ -93157,7 +94869,7 @@ ${lanes.join("\n")} }); } function markPrecedingCommentDirectiveLine(diagnostic, directives) { - const { file: file , start: start } = diagnostic; + const { file: file, start: start } = diagnostic; if (!file) return -1; const lineStarts = getLineStarts(file); let line = computeLineAndCharacterOfPosition(lineStarts, start).line - 1; @@ -93177,89 +94889,97 @@ ${lanes.join("\n")} return diagnostics; function walk(node, parent2) { switch(parent2.kind){ - case 166 /* Parameter */ : - case 169 /* PropertyDeclaration */ : - case 171 /* MethodDeclaration */ : + case 169 /* Parameter */ : + case 172 /* PropertyDeclaration */ : + case 174 /* MethodDeclaration */ : if (parent2.questionToken === node) { diagnostics.push(createDiagnosticForNode2(node, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?")); return "skip"; } - case 170 /* MethodSignature */ : - case 173 /* Constructor */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 215 /* FunctionExpression */ : - case 259 /* FunctionDeclaration */ : - case 216 /* ArrowFunction */ : - case 257 /* VariableDeclaration */ : + case 173 /* MethodSignature */ : + case 176 /* Constructor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 218 /* FunctionExpression */ : + case 262 /* FunctionDeclaration */ : + case 219 /* ArrowFunction */ : + case 260 /* VariableDeclaration */ : if (parent2.type === node) { diagnostics.push(createDiagnosticForNode2(node, Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files)); return "skip"; } } switch(node.kind){ - case 270 /* ImportClause */ : + case 273 /* ImportClause */ : if (node.isTypeOnly) { diagnostics.push(createDiagnosticForNode2(parent2, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type")); return "skip"; } break; - case 275 /* ExportDeclaration */ : + case 278 /* ExportDeclaration */ : if (node.isTypeOnly) { diagnostics.push(createDiagnosticForNode2(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type")); return "skip"; } break; - case 273 /* ImportSpecifier */ : - case 278 /* ExportSpecifier */ : + case 276 /* ImportSpecifier */ : + case 281 /* ExportSpecifier */ : if (node.isTypeOnly) { diagnostics.push(createDiagnosticForNode2(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, isImportSpecifier(node) ? "import...type" : "export...type")); return "skip"; } break; - case 268 /* ImportEqualsDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : diagnostics.push(createDiagnosticForNode2(node, Diagnostics.import_can_only_be_used_in_TypeScript_files)); return "skip"; - case 274 /* ExportAssignment */ : + case 277 /* ExportAssignment */ : if (node.isExportEquals) { diagnostics.push(createDiagnosticForNode2(node, Diagnostics.export_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 294 /* HeritageClause */ : + case 298 /* HeritageClause */ : const heritageClause = node; - if (heritageClause.token === 117 /* ImplementsKeyword */ ) { + if (heritageClause.token === 119 /* ImplementsKeyword */ ) { diagnostics.push(createDiagnosticForNode2(node, Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 261 /* InterfaceDeclaration */ : - const interfaceKeyword = tokenToString(118 /* InterfaceKeyword */ ); + case 264 /* InterfaceDeclaration */ : + const interfaceKeyword = tokenToString(120 /* InterfaceKeyword */ ); Debug.assertIsDefined(interfaceKeyword); diagnostics.push(createDiagnosticForNode2(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword)); return "skip"; - case 264 /* ModuleDeclaration */ : - const moduleKeyword = node.flags & 16 /* Namespace */ ? tokenToString(143 /* NamespaceKeyword */ ) : tokenToString(142 /* ModuleKeyword */ ); + case 267 /* ModuleDeclaration */ : + const moduleKeyword = node.flags & 32 /* Namespace */ ? tokenToString(145 /* NamespaceKeyword */ ) : tokenToString(144 /* ModuleKeyword */ ); Debug.assertIsDefined(moduleKeyword); diagnostics.push(createDiagnosticForNode2(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword)); return "skip"; - case 262 /* TypeAliasDeclaration */ : + case 265 /* TypeAliasDeclaration */ : diagnostics.push(createDiagnosticForNode2(node, Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files)); return "skip"; - case 263 /* EnumDeclaration */ : - const enumKeyword = Debug.checkDefined(tokenToString(92 /* EnumKeyword */ )); + case 176 /* Constructor */ : + case 174 /* MethodDeclaration */ : + case 262 /* FunctionDeclaration */ : + if (!node.body) { + diagnostics.push(createDiagnosticForNode2(node, Diagnostics.Signature_declarations_can_only_be_used_in_TypeScript_files)); + return "skip"; + } + return; + case 266 /* EnumDeclaration */ : + const enumKeyword = Debug.checkDefined(tokenToString(94 /* EnumKeyword */ )); diagnostics.push(createDiagnosticForNode2(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword)); return "skip"; - case 232 /* NonNullExpression */ : + case 235 /* NonNullExpression */ : diagnostics.push(createDiagnosticForNode2(node, Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files)); return "skip"; - case 231 /* AsExpression */ : + case 234 /* AsExpression */ : diagnostics.push(createDiagnosticForNode2(node.type, Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files)); return "skip"; - case 235 /* SatisfiesExpression */ : + case 238 /* SatisfiesExpression */ : diagnostics.push(createDiagnosticForNode2(node.type, Diagnostics.Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files)); return "skip"; - case 213 /* TypeAssertionExpression */ : + case 216 /* TypeAssertionExpression */ : Debug.fail(); } } @@ -93285,43 +95005,43 @@ ${lanes.join("\n")} } } switch(parent2.kind){ - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : - case 171 /* MethodDeclaration */ : - case 173 /* Constructor */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 215 /* FunctionExpression */ : - case 259 /* FunctionDeclaration */ : - case 216 /* ArrowFunction */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 174 /* MethodDeclaration */ : + case 176 /* Constructor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 218 /* FunctionExpression */ : + case 262 /* FunctionDeclaration */ : + case 219 /* ArrowFunction */ : if (nodes === parent2.typeParameters) { diagnostics.push(createDiagnosticForNodeArray2(nodes, Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files)); return "skip"; } - case 240 /* VariableStatement */ : + case 243 /* VariableStatement */ : if (nodes === parent2.modifiers) { - checkModifiers(parent2.modifiers, parent2.kind === 240 /* VariableStatement */ ); + checkModifiers(parent2.modifiers, parent2.kind === 243 /* VariableStatement */ ); return "skip"; } break; - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : if (nodes === parent2.modifiers) { - for (const modifier of nodes)if (isModifier(modifier) && modifier.kind !== 124 /* StaticKeyword */ && modifier.kind !== 127 /* AccessorKeyword */ ) diagnostics.push(createDiagnosticForNode2(modifier, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, tokenToString(modifier.kind))); + for (const modifier of nodes)if (isModifier(modifier) && modifier.kind !== 126 /* StaticKeyword */ && modifier.kind !== 129 /* AccessorKeyword */ ) diagnostics.push(createDiagnosticForNode2(modifier, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, tokenToString(modifier.kind))); return "skip"; } break; - case 166 /* Parameter */ : + case 169 /* Parameter */ : if (nodes === parent2.modifiers && some(nodes, isModifier)) { diagnostics.push(createDiagnosticForNodeArray2(nodes, Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 210 /* CallExpression */ : - case 211 /* NewExpression */ : - case 230 /* ExpressionWithTypeArguments */ : - case 282 /* JsxSelfClosingElement */ : - case 283 /* JsxOpeningElement */ : - case 212 /* TaggedTemplateExpression */ : + case 213 /* CallExpression */ : + case 214 /* NewExpression */ : + case 233 /* ExpressionWithTypeArguments */ : + case 285 /* JsxSelfClosingElement */ : + case 286 /* JsxOpeningElement */ : + case 215 /* TaggedTemplateExpression */ : if (nodes === parent2.typeArguments) { diagnostics.push(createDiagnosticForNodeArray2(nodes, Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files)); return "skip"; @@ -93331,31 +95051,31 @@ ${lanes.join("\n")} } function checkModifiers(modifiers, isConstValid) { for (const modifier of modifiers)switch(modifier.kind){ - case 85 /* ConstKeyword */ : + case 87 /* ConstKeyword */ : if (isConstValid) continue; - case 123 /* PublicKeyword */ : - case 121 /* PrivateKeyword */ : - case 122 /* ProtectedKeyword */ : - case 146 /* ReadonlyKeyword */ : - case 136 /* DeclareKeyword */ : - case 126 /* AbstractKeyword */ : - case 161 /* OverrideKeyword */ : - case 101 /* InKeyword */ : - case 145 /* OutKeyword */ : + case 125 /* PublicKeyword */ : + case 123 /* PrivateKeyword */ : + case 124 /* ProtectedKeyword */ : + case 148 /* ReadonlyKeyword */ : + case 138 /* DeclareKeyword */ : + case 128 /* AbstractKeyword */ : + case 164 /* OverrideKeyword */ : + case 103 /* InKeyword */ : + case 147 /* OutKeyword */ : diagnostics.push(createDiagnosticForNode2(modifier, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, tokenToString(modifier.kind))); break; - case 124 /* StaticKeyword */ : - case 93 /* ExportKeyword */ : - case 88 /* DefaultKeyword */ : - case 127 /* AccessorKeyword */ : + case 126 /* StaticKeyword */ : + case 95 /* ExportKeyword */ : + case 90 /* DefaultKeyword */ : + case 129 /* AccessorKeyword */ : } } - function createDiagnosticForNodeArray2(nodes, message, arg0, arg1, arg2) { + function createDiagnosticForNodeArray2(nodes, message, ...args) { const start = nodes.pos; - return createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2); + return createFileDiagnostic(sourceFile, start, nodes.end - start, message, ...args); } - function createDiagnosticForNode2(node, message, arg0, arg1, arg2) { - return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + function createDiagnosticForNode2(node, message, ...args) { + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, ...args); } }); } @@ -93369,8 +95089,8 @@ ${lanes.join("\n")} }); } function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics2) { - var _a3; - const cachedResult = sourceFile ? (_a3 = cache.perFile) == null ? void 0 : _a3.get(sourceFile.path) : cache.allDiagnostics; + var _a2; + const cachedResult = sourceFile ? (_a2 = cache.perFile) == null ? void 0 : _a2.get(sourceFile.path) : cache.allDiagnostics; if (cachedResult) return cachedResult; const result = getDiagnostics2(sourceFile, cancellationToken); if (sourceFile) (cache.perFile || (cache.perFile = /* @__PURE__ */ new Map())).set(sourceFile.path, result); @@ -93404,7 +95124,7 @@ ${lanes.join("\n")} return a.fileName === b.fileName; } function moduleNameIsEqualTo(a, b) { - return a.kind === 79 /* Identifier */ ? b.kind === 79 /* Identifier */ && a.escapedText === b.escapedText : b.kind === 10 /* StringLiteral */ && a.text === b.text; + return a.kind === 80 /* Identifier */ ? b.kind === 80 /* Identifier */ && a.escapedText === b.escapedText : b.kind === 11 /* StringLiteral */ && a.text === b.text; } function createSyntheticImport(text, file) { const externalHelpersModuleReference = factory.createStringLiteral(text); @@ -93412,8 +95132,8 @@ ${lanes.join("\n")} addInternalEmitFlags(importDecl, 2 /* NeverApplyImportHelper */ ); setParent(externalHelpersModuleReference, importDecl); setParent(importDecl, file); - externalHelpersModuleReference.flags &= -9 /* Synthesized */ ; - importDecl.flags &= -9 /* Synthesized */ ; + externalHelpersModuleReference.flags &= -17 /* Synthesized */ ; + importDecl.flags &= -17 /* Synthesized */ ; return externalHelpersModuleReference; } function collectExternalModuleReferences(file) { @@ -93432,7 +95152,7 @@ ${lanes.join("\n")} } for (const node of file.statements)collectModuleReferences(node, /*inAmbientModule*/ false); const shouldProcessRequires = isJavaScriptFile && shouldResolveJsRequire(options); - if (file.flags & 2097152 /* PossiblyContainsDynamicImport */ || shouldProcessRequires) collectDynamicImportOrRequireCalls(file); + if (file.flags & 4194304 /* PossiblyContainsDynamicImport */ || shouldProcessRequires) collectDynamicImportOrRequireCalls(file); file.imports = imports || emptyArray; file.moduleAugmentations = moduleAugmentations || emptyArray; file.ambientModuleNames = ambientModules || emptyArray; @@ -93462,7 +95182,7 @@ ${lanes.join("\n")} const r = /import|require/g; while(r.exec(file2.text) !== null){ const node = getNodeAtPosition(file2, r.lastIndex); - if (shouldProcessRequires && isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + if (shouldProcessRequires && isRequireCall(node, /*requireStringLiteralLikeArgument*/ true)) { setParentRecursive(node, /*incremental*/ false); imports = append(imports, node.arguments[0]); } else if (isImportCall(node) && node.arguments.length >= 1 && isStringLiteralLike(node.arguments[0])) { @@ -93487,9 +95207,10 @@ ${lanes.join("\n")} } } function getLibFileFromReference(ref) { - const libName = toFileNameLowerCase(ref.fileName); - const libFileName = libMap.get(libName); - if (libFileName) return getSourceFile(pathForLibFile(libFileName)); + var _a2; + const { libFileName: libFileName } = getLibFileNameFromLibReference(ref); + const actualFileName = libFileName && ((_a2 = resolvedLibReferences == null ? void 0 : resolvedLibReferences.get(libFileName)) == null ? void 0 : _a2.actual); + return actualFileName !== void 0 ? getSourceFile(actualFileName) : void 0; } function getSourceFileFromReference(referencingFile, ref) { return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), getSourceFile); @@ -93544,7 +95265,7 @@ ${lanes.join("\n")} ]); } function createRedirectedSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName, sourceFileOptions) { - var _a3; + var _a2; const redirect = parseNodeFactory.createRedirectedSourceFile({ redirectTarget: redirectTarget, unredirected: unredirected @@ -93553,14 +95274,14 @@ ${lanes.join("\n")} redirect.path = path; redirect.resolvedPath = resolvedPath; redirect.originalFileName = originalFileName; - redirect.packageJsonLocations = ((_a3 = sourceFileOptions.packageJsonLocations) == null ? void 0 : _a3.length) ? sourceFileOptions.packageJsonLocations : void 0; + redirect.packageJsonLocations = ((_a2 = sourceFileOptions.packageJsonLocations) == null ? void 0 : _a2.length) ? sourceFileOptions.packageJsonLocations : void 0; redirect.packageJsonScope = sourceFileOptions.packageJsonScope; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); return redirect; } function findSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { - var _a3, _b2; - (_a3 = tracing) == null || _a3.push(tracing.Phase.Program, "findSourceFile", { + var _a2, _b2; + (_a2 = tracing) == null || _a2.push(tracing.Phase.Program, "findSourceFile", { fileName: fileName, isDefaultLib: isDefaultLib || void 0, fileIncludeKind: FileIncludeKind[reason.kind] @@ -93584,7 +95305,7 @@ ${lanes.join("\n")} }; } function findSourceFileWorker(fileName, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { - var _a3, _b2; + var _a2; const path = toPath3(fileName); if (useSourceOfProjectReferenceRedirect) { let source = getSourceOfProjectReferenceRedirect(path); @@ -93641,7 +95362,7 @@ ${lanes.join("\n")} const file = host.getSourceFile(fileName, sourceFileOptions, (hostErrorMessage)=>addFilePreprocessingFileExplainingDiagnostic(/*file*/ void 0, reason, Diagnostics.Cannot_read_file_0_Colon_1, [ fileName, hostErrorMessage - ]), shouldCreateNewSourceFile || ((_a3 = oldProgram == null ? void 0 : oldProgram.getSourceFileByPath(toPath3(fileName))) == null ? void 0 : _a3.impliedNodeFormat) !== sourceFileOptions.impliedNodeFormat); + ]), shouldCreateNewSourceFile); if (packageId) { const packageIdKey = packageIdToString(packageId); const fileFromPackageId = packageIdToSourceFile.get(packageIdKey); @@ -93665,7 +95386,7 @@ ${lanes.join("\n")} file.path = path; file.resolvedPath = toPath3(fileName); file.originalFileName = originalFileName; - file.packageJsonLocations = ((_b2 = sourceFileOptions.packageJsonLocations) == null ? void 0 : _b2.length) ? sourceFileOptions.packageJsonLocations : void 0; + file.packageJsonLocations = ((_a2 = sourceFileOptions.packageJsonLocations) == null ? void 0 : _a2.length) ? sourceFileOptions.packageJsonLocations : void 0; file.packageJsonScope = sourceFileOptions.packageJsonScope; addFileIncludeReason(file, reason); if (host.useCaseSensitiveFileNames()) { @@ -93771,7 +95492,7 @@ ${lanes.join("\n")} const fileName = toFileNameLowerCase(ref.fileName); setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective, getModeForFileReference(ref, file.impliedNodeFormat)); const mode = ref.resolutionMode || file.impliedNodeFormat; - if (mode && getEmitModuleResolutionKind(options) !== 3 /* Node16 */ && getEmitModuleResolutionKind(options) !== 99 /* NodeNext */ ) (fileProcessingDiagnostics != null ? fileProcessingDiagnostics : fileProcessingDiagnostics = []).push({ + if (mode && getEmitModuleResolutionKind(options) !== 3 /* Node16 */ && getEmitModuleResolutionKind(options) !== 99 /* NodeNext */ ) (fileProcessingDiagnostics ?? (fileProcessingDiagnostics = [])).push({ kind: 2 /* ResolutionDiagnostics */ , diagnostics: [ createDiagnosticForRange(file, ref, Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext) @@ -93785,8 +95506,8 @@ ${lanes.join("\n")} } } function processTypeReferenceDirective(typeReferenceDirective, mode, resolution, reason) { - var _a3, _b2; - (_a3 = tracing) == null || _a3.push(tracing.Phase.Program, "processTypeReferenceDirective", { + var _a2, _b2; + (_a2 = tracing) == null || _a2.push(tracing.Phase.Program, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolution.resolvedTypeReferenceDirective, refKind: reason.kind, @@ -93796,12 +95517,12 @@ ${lanes.join("\n")} (_b2 = tracing) == null || _b2.pop(); } function processTypeReferenceDirectiveWorker(typeReferenceDirective, mode, resolution, reason) { - var _a3; + var _a2; addResolutionDiagnostics(resolution); - const previousResolution = (_a3 = resolvedTypeReferenceDirectives.get(typeReferenceDirective, mode)) == null ? void 0 : _a3.resolvedTypeReferenceDirective; + const previousResolution = (_a2 = resolvedTypeReferenceDirectives.get(typeReferenceDirective, mode)) == null ? void 0 : _a2.resolvedTypeReferenceDirective; if (previousResolution && previousResolution.primary) return; let saveResolution = true; - const { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective } = resolution; + const { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective } = resolution; if (resolvedTypeReferenceDirective) { if (resolvedTypeReferenceDirective.isExternalLibraryImport) currentNodeModulesDepth++; if (resolvedTypeReferenceDirective.primary) processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, reason); @@ -93824,24 +95545,48 @@ ${lanes.join("\n")} if (saveResolution) resolvedTypeReferenceDirectives.set(typeReferenceDirective, mode, resolution); } function pathForLibFile(libFileName) { - 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: 2 /* Node10 */ - }, host, moduleResolutionCache); - if (localOverrideModuleResult == null ? void 0 : localOverrideModuleResult.resolvedModule) return localOverrideModuleResult.resolvedModule.resolvedFileName; - return combinePaths(defaultLibraryPath, libFileName); + const existing = resolvedLibReferences == null ? void 0 : resolvedLibReferences.get(libFileName); + if (existing) return existing.actual; + const result = pathForLibFileWorker(libFileName); + (resolvedLibReferences ?? (resolvedLibReferences = /* @__PURE__ */ new Map())).set(libFileName, result); + return result.actual; + } + function pathForLibFileWorker(libFileName) { + var _a2, _b2, _c2, _d2, _e2; + const existing = resolvedLibProcessing == null ? void 0 : resolvedLibProcessing.get(libFileName); + if (existing) return existing; + if (structureIsReused !== 0 /* Not */ && oldProgram && !hasInvalidatedLibResolutions(libFileName)) { + const oldResolution = (_a2 = oldProgram.resolvedLibReferences) == null ? void 0 : _a2.get(libFileName); + if (oldResolution) { + if (oldResolution.resolution && isTraceEnabled(options, host)) { + const libraryName2 = getLibraryNameFromLibFileName(libFileName); + const resolveFrom2 = getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName); + trace(host, oldResolution.resolution.resolvedModule ? oldResolution.resolution.resolvedModule.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved, libraryName2, getNormalizedAbsolutePath(resolveFrom2, currentDirectory), (_b2 = oldResolution.resolution.resolvedModule) == null ? void 0 : _b2.resolvedFileName, ((_c2 = oldResolution.resolution.resolvedModule) == null ? void 0 : _c2.packageId) && packageIdToString(oldResolution.resolution.resolvedModule.packageId)); + } + (resolvedLibProcessing ?? (resolvedLibProcessing = /* @__PURE__ */ new Map())).set(libFileName, oldResolution); + return oldResolution; + } + } + const libraryName = getLibraryNameFromLibFileName(libFileName); + const resolveFrom = getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName); + (_d2 = tracing) == null || _d2.push(tracing.Phase.Program, "resolveLibrary", { + resolveFrom: resolveFrom + }); + mark("beforeResolveLibrary"); + const resolution = actualResolveLibrary(libraryName, resolveFrom, options, libFileName); + mark("afterResolveLibrary"); + measure("ResolveLibrary", "beforeResolveLibrary", "afterResolveLibrary"); + (_e2 = tracing) == null || _e2.pop(); + const result = { + resolution: resolution, + actual: resolution.resolvedModule ? resolution.resolvedModule.resolvedFileName : combinePaths(defaultLibraryPath, libFileName) + }; + (resolvedLibProcessing ?? (resolvedLibProcessing = /* @__PURE__ */ new Map())).set(libFileName, result); + return result; } function processLibReferenceDirectives(file) { forEach(file.libReferenceDirectives, (libReference, index)=>{ - const libName = toFileNameLowerCase(libReference.fileName); - const libFileName = libMap.get(libName); + const { libName: libName, libFileName: libFileName } = getLibFileNameFromLibReference(libReference); if (libFileName) processRootFile(pathForLibFile(libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true, { kind: 7 /* LibReferenceDirective */ , file: file.path, @@ -93851,6 +95596,12 @@ ${lanes.join("\n")} const unqualifiedLibName = removeSuffix(removePrefix(libName, "lib."), ".d.ts"); const suggestion = getSpellingSuggestion(unqualifiedLibName, libs, identity); const diagnostic = suggestion ? Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : Diagnostics.Cannot_find_lib_definition_for_0; + const args = suggestion ? [ + libName, + suggestion + ] : [ + libName + ]; (fileProcessingDiagnostics || (fileProcessingDiagnostics = [])).push({ kind: 0 /* FilePreprocessingReferencedDiagnostic */ , reason: { @@ -93859,10 +95610,7 @@ ${lanes.join("\n")} index: index }, diagnostic: diagnostic, - args: [ - libName, - suggestion - ] + args: args }); } }); @@ -93871,13 +95619,13 @@ ${lanes.join("\n")} return host.getCanonicalFileName(fileName); } function processImportedModules(file) { - var _a3; + var _a2; collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { const moduleNames = getModuleNames(file); const resolutions = resolveModuleNamesReusingOldState(moduleNames, file); Debug.assert(resolutions.length === moduleNames.length); - const optionsForFile = (useSourceOfProjectReferenceRedirect ? (_a3 = getRedirectReferenceForResolution(file)) == null ? void 0 : _a3.commandLine.options : void 0) || options; + const optionsForFile = (useSourceOfProjectReferenceRedirect ? (_a2 = getRedirectReferenceForResolution(file)) == null ? void 0 : _a2.commandLine.options : void 0) || options; for(let index = 0; index < moduleNames.length; index++){ const resolution = resolutions[index].resolvedModule; const moduleName = moduleNames[index].text; @@ -93891,7 +95639,7 @@ ${lanes.join("\n")} const resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) currentNodeModulesDepth++; const elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; - const shouldAddFile = resolvedFileName && !getResolutionDiagnostic(optionsForFile, resolution, file) && !optionsForFile.noResolve && index < file.imports.length && !elideImport && !(isJsFile && !getAllowJSCompilerOption(optionsForFile)) && (isInJSFile(file.imports[index]) || !(file.imports[index].flags & 8388608 /* JSDoc */ )); + const shouldAddFile = resolvedFileName && !getResolutionDiagnostic(optionsForFile, resolution, file) && !optionsForFile.noResolve && index < file.imports.length && !elideImport && !(isJsFile && !getAllowJSCompilerOption(optionsForFile)) && (isInJSFile(file.imports[index]) || !(file.imports[index].flags & 16777216 /* JSDoc */ )); if (elideImport) modulesWithElidedImports.set(file.path, true); else if (shouldAddFile) findSourceFile(resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, { kind: 3 /* Import */ , @@ -93928,7 +95676,7 @@ ${lanes.join("\n")} if (host.getParsedCommandLine) { commandLine = host.getParsedCommandLine(refPath); if (!commandLine) { - addFileToFilesByName(/*sourceFile*/ void 0, sourceFilePath, /*redirectedPath*/ void 0); + addFileToFilesByName(/*file*/ void 0, sourceFilePath, /*redirectedPath*/ void 0); projectReferenceRedirects.set(sourceFilePath, false); return void 0; } @@ -93936,7 +95684,7 @@ ${lanes.join("\n")} Debug.assert(!sourceFile.path || sourceFile.path === sourceFilePath); addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ void 0); } else { - const basePath = getNormalizedAbsolutePath(getDirectoryPath(refPath), host.getCurrentDirectory()); + const basePath = getNormalizedAbsolutePath(getDirectoryPath(refPath), currentDirectory); sourceFile = host.getSourceFile(refPath, 100 /* JSON */ ); addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ void 0); if (sourceFile === void 0) { @@ -94077,6 +95825,13 @@ ${lanes.join("\n")} if (options.resolvePackageJsonImports && !moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution)) createDiagnosticForOptionName(Diagnostics.Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler, "resolvePackageJsonImports"); if (options.customConditions && !moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution)) createDiagnosticForOptionName(Diagnostics.Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler, "customConditions"); if (moduleResolution === 100 /* Bundler */ && !emitModuleKindIsNonNodeESM(moduleKind)) createOptionValueDiagnostic("moduleResolution", Diagnostics.Option_0_can_only_be_used_when_module_is_set_to_es2015_or_later, "bundler"); + if (ModuleKind[moduleKind] && 100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */ && !(3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */ )) { + const moduleKindName = ModuleKind[moduleKind]; + createOptionValueDiagnostic("moduleResolution", Diagnostics.Option_moduleResolution_must_be_set_to_0_or_left_unspecified_when_option_module_is_set_to_1, moduleKindName, moduleKindName); + } else if (ModuleResolutionKind[moduleResolution] && 3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */ && !(100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */ )) { + const moduleResolutionName = ModuleResolutionKind[moduleResolution]; + createOptionValueDiagnostic("module", Diagnostics.Option_module_must_be_set_to_0_when_option_moduleResolution_is_set_to_1, moduleResolutionName, moduleResolutionName); + } if (!options.noEmit && !options.suppressOutputPathCheck) { const emitHost = getEmitHost(); const emitFilesSeen = /* @__PURE__ */ new Set(); @@ -94124,12 +95879,12 @@ ${lanes.join("\n")} }); } function verifyDeprecatedCompilerOptions() { - function createDiagnostic(name, value1, useInstead, message, arg0, arg1, arg2, arg3) { + function createDiagnostic(name, value1, useInstead, message, ...args) { if (useInstead) { const details = chainDiagnosticMessages(/*details*/ void 0, Diagnostics.Use_0_instead, useInstead); - const chain = chainDiagnosticMessages(details, message, arg0, arg1, arg2, arg3); + const chain = chainDiagnosticMessages(details, message, ...args); createDiagnosticForOption(/*onKey*/ !value1, name, /*option2*/ void 0, chain); - } else createDiagnosticForOption(/*onKey*/ !value1, name, /*option2*/ void 0, message, arg0, arg1, arg2, arg3); + } else createDiagnosticForOption(/*onKey*/ !value1, name, /*option2*/ void 0, message, ...args); } checkDeprecations("5.0", "5.5", createDiagnostic, (createDeprecatedDiagnostic)=>{ if (options.target === 0 /* ES3 */ ) createDeprecatedDiagnostic("target", "ES3"); @@ -94145,19 +95900,19 @@ ${lanes.join("\n")} }); } function verifyDeprecatedProjectReference(ref, parentFile, index) { - function createDiagnostic(_name, _value, _useInstead, message, arg0, arg1, arg2, arg3) { - createDiagnosticForReference(parentFile, index, message, arg0, arg1, arg2, arg3); + function createDiagnostic(_name, _value, _useInstead, message, ...args) { + createDiagnosticForReference(parentFile, index, message, ...args); } checkDeprecations("5.0", "5.5", createDiagnostic, (createDeprecatedDiagnostic)=>{ if (ref.prepend) createDeprecatedDiagnostic("prepend"); }); } function createDiagnosticExplainingFile(file, fileProcessingReason, diagnostic, args) { - var _a3; + var _a2; let fileIncludeReasons; let relatedInfo; let locationReason = isReferencedFile(fileProcessingReason) ? fileProcessingReason : void 0; - if (file) (_a3 = fileReasons.get(file.path)) == null || _a3.forEach(processReason); + if (file) (_a2 = fileReasons.get(file.path)) == null || _a2.forEach(processReason); if (fileProcessingReason) processReason(fileProcessingReason); if (locationReason && (fileIncludeReasons == null ? void 0 : fileIncludeReasons.length) === 1) fileIncludeReasons = void 0; const location = locationReason && getReferencedFileLocation(getSourceFileByPath, locationReason); @@ -94235,8 +95990,8 @@ ${lanes.join("\n")} index: index2 } : void 0); if (!referenceInfo) return void 0; - const { sourceFile: sourceFile , index: index } = referenceInfo; - const referencesSyntax = firstDefined(getTsConfigPropArray(sourceFile, "references"), (property)=>isArrayLiteralExpression(property.initializer) ? property.initializer : void 0); + const { sourceFile: sourceFile, index: index } = referenceInfo; + const referencesSyntax = forEachTsConfigPropArray(sourceFile, "references", (property)=>isArrayLiteralExpression(property.initializer) ? property.initializer : void 0); return referencesSyntax && referencesSyntax.elements.length > index ? createDiagnosticForNodeInSourceFile(sourceFile, referencesSyntax.elements[index], reason.kind === 2 /* OutputFromProjectReference */ ? Diagnostics.File_is_output_from_referenced_project_specified_here : Diagnostics.File_is_source_from_referenced_project_specified_here) : void 0; case 8 /* AutomaticTypeDirectiveFile */ : if (!options.types) return void 0; @@ -94288,36 +96043,34 @@ ${lanes.join("\n")} } }); } - function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { + function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, ...args) { let needCompilerDiagnostic = true; - const pathsSyntax = getOptionPathsSyntax(); - for (const pathProp of pathsSyntax){ - if (isObjectLiteralExpression(pathProp.initializer)) for (const keyProps of getPropertyAssignment(pathProp.initializer, key)){ + forEachOptionPathsSyntax((pathProp)=>{ + if (isObjectLiteralExpression(pathProp.initializer)) forEachPropertyAssignment(pathProp.initializer, key, (keyProps)=>{ const initializer = keyProps.initializer; if (isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) { - programDiagnostics.add(createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2)); + programDiagnostics.add(createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, ...args)); needCompilerDiagnostic = false; } - } - } - if (needCompilerDiagnostic) programDiagnostics.add(createCompilerDiagnostic(message, arg0, arg1, arg2)); + }); + }); + if (needCompilerDiagnostic) programDiagnostics.add(createCompilerDiagnostic(message, ...args)); } - function createDiagnosticForOptionPaths(onKey, key, message, arg0) { + function createDiagnosticForOptionPaths(onKey, key, message, ...args) { let needCompilerDiagnostic = true; - const pathsSyntax = getOptionPathsSyntax(); - for (const pathProp of pathsSyntax)if (isObjectLiteralExpression(pathProp.initializer) && createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ void 0, message, arg0)) needCompilerDiagnostic = false; - if (needCompilerDiagnostic) programDiagnostics.add(createCompilerDiagnostic(message, arg0)); + forEachOptionPathsSyntax((pathProp)=>{ + if (isObjectLiteralExpression(pathProp.initializer) && createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ void 0, message, ...args)) needCompilerDiagnostic = false; + }); + if (needCompilerDiagnostic) programDiagnostics.add(createCompilerDiagnostic(message, ...args)); } - function getOptionsSyntaxByName(name) { - const compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); - return compilerOptionsObjectLiteralSyntax && getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name); + function forEachOptionsSyntaxByName(name, callback) { + return forEachPropertyAssignment(getCompilerOptionsObjectLiteralSyntax(), name, callback); } - function getOptionPathsSyntax() { - return getOptionsSyntaxByName("paths") || emptyArray; + function forEachOptionPathsSyntax(callback) { + return forEachOptionsSyntaxByName("paths", callback); } function getOptionsSyntaxByValue(name, value1) { - const syntaxByName = getOptionsSyntaxByName(name); - return syntaxByName && firstDefined(syntaxByName, (property)=>isStringLiteral(property.initializer) && property.initializer.text === value1 ? property.initializer : void 0); + return forEachOptionsSyntaxByName(name, (property)=>isStringLiteral(property.initializer) && property.initializer.text === value1 ? property.initializer : void 0); } function getOptionsSyntaxByArrayElementValue(name, value1) { const compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); @@ -94326,40 +96079,34 @@ ${lanes.join("\n")} function createDiagnosticForOptionName(message, option1, option2, option3) { createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3); } - function createOptionValueDiagnostic(option1, message, arg0, arg1) { - createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ void 0, message, arg0, arg1); + function createOptionValueDiagnostic(option1, message, ...args) { + createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ void 0, message, ...args); } - function createDiagnosticForReference(sourceFile, index, message, arg0, arg1, arg2, arg3) { - const referencesSyntax = firstDefined(getTsConfigPropArray(sourceFile || options.configFile, "references"), (property)=>isArrayLiteralExpression(property.initializer) ? property.initializer : void 0); - if (referencesSyntax && referencesSyntax.elements.length > index) programDiagnostics.add(createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1, arg2, arg3)); - else programDiagnostics.add(createCompilerDiagnostic(message, arg0, arg1, arg2, arg3)); + function createDiagnosticForReference(sourceFile, index, message, ...args) { + const referencesSyntax = forEachTsConfigPropArray(sourceFile || options.configFile, "references", (property)=>isArrayLiteralExpression(property.initializer) ? property.initializer : void 0); + if (referencesSyntax && referencesSyntax.elements.length > index) programDiagnostics.add(createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, ...args)); + else programDiagnostics.add(createCompilerDiagnostic(message, ...args)); } - function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2, arg3) { + function createDiagnosticForOption(onKey, option1, option2, message, ...args) { const compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); - const needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2, arg3); + const needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, ...args); if (needCompilerDiagnostic) { if ("messageText" in message) programDiagnostics.add(createCompilerDiagnosticFromMessageChain(message)); - else programDiagnostics.add(createCompilerDiagnostic(message, arg0, arg1, arg2, arg3)); + else programDiagnostics.add(createCompilerDiagnostic(message, ...args)); } } function getCompilerOptionsObjectLiteralSyntax() { - if (_compilerOptionsObjectLiteralSyntax === void 0) { - _compilerOptionsObjectLiteralSyntax = false; - const jsonObjectLiteral = getTsConfigObjectLiteralExpression(options.configFile); - if (jsonObjectLiteral) { - for (const prop of getPropertyAssignment(jsonObjectLiteral, "compilerOptions"))if (isObjectLiteralExpression(prop.initializer)) { - _compilerOptionsObjectLiteralSyntax = prop.initializer; - break; - } - } - } + if (_compilerOptionsObjectLiteralSyntax === void 0) _compilerOptionsObjectLiteralSyntax = forEachPropertyAssignment(getTsConfigObjectLiteralExpression(options.configFile), "compilerOptions", (prop)=>isObjectLiteralExpression(prop.initializer) ? prop.initializer : void 0) || false; return _compilerOptionsObjectLiteralSyntax || void 0; } - function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2, arg3) { - const props = getPropertyAssignment(objectLiteral, key1, key2); - for (const prop of props)if ("messageText" in message) programDiagnostics.add(createDiagnosticForNodeFromMessageChain(options.configFile, onKey ? prop.name : prop.initializer, message)); - else programDiagnostics.add(createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2, arg3)); - return !!props.length; + function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, ...args) { + let needsCompilerDiagnostic = false; + forEachPropertyAssignment(objectLiteral, key1, (prop)=>{ + if ("messageText" in message) programDiagnostics.add(createDiagnosticForNodeFromMessageChain(options.configFile, onKey ? prop.name : prop.initializer, message)); + else programDiagnostics.add(createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, ...args)); + needsCompilerDiagnostic = true; + }, key2); + return needsCompilerDiagnostic; } function createRedundantOptionDiagnostic(errorOnOption, redundantWithOption) { const compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); @@ -94427,8 +96174,8 @@ ${lanes.join("\n")} }; if (originalGetDirectories) host.compilerHost.getDirectories = (path)=>!host.getResolvedProjectReferences() || originalDirectoryExists && originalDirectoryExists.call(host.compilerHost, path) ? originalGetDirectories.call(host.compilerHost, path) : []; if (originalRealpath) host.compilerHost.realpath = (s)=>{ - var _a2; - return ((_a2 = host.getSymlinkCache().getSymlinkedFiles()) == null ? void 0 : _a2.get(host.toPath(s))) || originalRealpath.call(host.compilerHost, s); + var _a; + return ((_a = host.getSymlinkCache().getSymlinkedFiles()) == null ? void 0 : _a.get(host.toPath(s))) || originalRealpath.call(host.compilerHost, s); }; return { onProgramCreateComplete: onProgramCreateComplete, @@ -94458,12 +96205,12 @@ ${lanes.join("\n")} startsWith(dirPath, `${declDirPath}/`)); } function handleDirectoryCouldBeSymlink(directory) { - var _a2; + var _a; if (!host.getResolvedProjectReferences() || containsIgnoredPath(directory)) return; if (!originalRealpath || !stringContains(directory, nodeModulesPathPart)) return; const symlinkCache = host.getSymlinkCache(); const directoryPath = ensureTrailingDirectorySeparator(host.toPath(directory)); - if ((_a2 = symlinkCache.getSymlinkedDirectories()) == null ? void 0 : _a2.has(directoryPath)) return; + if ((_a = symlinkCache.getSymlinkedDirectories()) == null ? void 0 : _a.has(directoryPath)) return; const real = normalizePath(originalRealpath.call(host.compilerHost, directory)); let realPath2; if (real === directory || (realPath2 = ensureTrailingDirectorySeparator(host.toPath(real))) === directoryPath) { @@ -94476,7 +96223,7 @@ ${lanes.join("\n")} }); } function fileOrDirectoryExistsUsingSource(fileOrDirectory, isFile) { - var _a2; + var _a; const fileOrDirectoryExistsUsingSource2 = isFile ? (file)=>fileExistsIfProjectReferenceDts(file) : (dir)=>directoryExistsIfProjectReferenceDeclDir(dir); const result = fileOrDirectoryExistsUsingSource2(fileOrDirectory); if (result !== void 0) return result; @@ -94485,7 +96232,7 @@ ${lanes.join("\n")} if (!symlinkedDirectories) return false; const fileOrDirectoryPath = host.toPath(fileOrDirectory); if (!stringContains(fileOrDirectoryPath, nodeModulesPathPart)) return false; - if (isFile && ((_a2 = symlinkCache.getSymlinkedFiles()) == null ? void 0 : _a2.has(fileOrDirectoryPath))) return true; + if (isFile && ((_a = symlinkCache.getSymlinkedFiles()) == null ? void 0 : _a.has(fileOrDirectoryPath))) return true; return firstDefinedIterator(symlinkedDirectories.entries(), ([directoryPath, symlinkedDirectory])=>{ if (!symlinkedDirectory || !startsWith(fileOrDirectoryPath, directoryPath)) return void 0; const result2 = fileOrDirectoryExistsUsingSource2(fileOrDirectoryPath.replace(directoryPath, symlinkedDirectory.realPath)); @@ -94539,6 +96286,9 @@ ${lanes.join("\n")} return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth); }, readFile: (f)=>directoryStructureHost.readFile(f), + directoryExists: maybeBind(directoryStructureHost, directoryStructureHost.directoryExists), + getDirectories: maybeBind(directoryStructureHost, directoryStructureHost.getDirectories), + realpath: maybeBind(directoryStructureHost, directoryStructureHost.realpath), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: ()=>host.getCurrentDirectory(), onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || returnUndefined, @@ -94554,7 +96304,7 @@ ${lanes.join("\n")} if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { const out = outFile(resolvedRefOpts.options); if (!out) continue; - const { jsFilePath: jsFilePath , sourceMapFilePath: sourceMapFilePath , declarationFilePath: declarationFilePath , declarationMapPath: declarationMapPath , buildInfoPath: buildInfoPath } = getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true); + const { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath } = getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true); const node = createInputFilesWithFilePaths(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath, host, resolvedRefOpts.options); (nodes || (nodes = [])).push(node); } @@ -94564,7 +96314,7 @@ ${lanes.join("\n")} function resolveProjectReferencePath(ref) { return resolveConfigFileProjectName(ref.path); } - function getResolutionDiagnostic(options, { extension: extension }, { isDeclarationFile: isDeclarationFile }) { + function getResolutionDiagnostic(options, { extension: extension }, { isDeclarationFile: isDeclarationFile }) { switch(extension){ case ".ts" /* Ts */ : case ".d.ts" /* Dts */ : @@ -94599,15 +96349,15 @@ ${lanes.join("\n")} return isDeclarationFile || options.allowArbitraryExtensions ? void 0 : Diagnostics.Module_0_was_resolved_to_1_but_allowArbitraryExtensions_is_not_set; } } - function getModuleNames({ imports: imports , moduleAugmentations: moduleAugmentations }) { + function getModuleNames({ imports: imports, moduleAugmentations: moduleAugmentations }) { const res = imports.map((i)=>i); - for (const aug of moduleAugmentations)if (aug.kind === 10 /* StringLiteral */ ) res.push(aug); + for (const aug of moduleAugmentations)if (aug.kind === 11 /* StringLiteral */ ) res.push(aug); return res; } - function getModuleNameStringLiteralAt({ imports: imports , moduleAugmentations: moduleAugmentations }, index) { + function getModuleNameStringLiteralAt({ imports: imports, moduleAugmentations: moduleAugmentations }, index) { if (index < imports.length) return imports[index]; let augIndex = imports.length; - for (const aug of moduleAugmentations)if (aug.kind === 10 /* StringLiteral */ ) { + for (const aug of moduleAugmentations)if (aug.kind === 11 /* StringLiteral */ ) { if (index === augIndex) return aug; augIndex++; } @@ -94618,7 +96368,6 @@ ${lanes.join("\n")} "src/compiler/program.ts" () { "use strict"; init_ts2(); - init_ts2(); init_ts_performance(); ForegroundColorEscapeSequences = /* @__PURE__ */ ((ForegroundColorEscapeSequences2)=>{ ForegroundColorEscapeSequences2["Grey"] = "\x1b[90m"; @@ -94662,7 +96411,6 @@ ${lanes.join("\n")} 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, @@ -94703,7 +96451,7 @@ ${lanes.join("\n")} 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.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, @@ -94733,14 +96481,17 @@ ${lanes.join("\n")} 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._0_declarations_can_only_be_declared_inside_a_block.code, + Diagnostics._0_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, Diagnostics.Class_constructor_may_not_be_a_generator.code, Diagnostics.Class_constructor_may_not_be_an_accessor.code, - Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code + Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, + Diagnostics.await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, + Diagnostics.Private_field_0_must_be_declared_in_an_enclosing_class.code, + // Type errors + Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value.code ]); emitSkippedWithNoDiagnostics = { diagnostics: emptyArray, @@ -94759,7 +96510,7 @@ ${lanes.join("\n")} // src/compiler/builderState.ts function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) { const outputFiles = []; - const { emitSkipped: emitSkipped , diagnostics: diagnostics } = program.emit(sourceFile, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit); + const { emitSkipped: emitSkipped, diagnostics: diagnostics } = program.emit(sourceFile, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit); return { outputFiles: outputFiles, emitSkipped: emitSkipped, @@ -94829,8 +96580,8 @@ ${lanes.join("\n")} } function getReferencedFilesFromImportedModuleSymbol(symbol) { return mapDefined(symbol.declarations, (declaration)=>{ - var _a2; - return (_a2 = getSourceFileOfNode(declaration)) == null ? void 0 : _a2.resolvedPath; + var _a; + return (_a = getSourceFileOfNode(declaration)) == null ? void 0 : _a.resolvedPath; }); } function getReferencedFilesFromImportLiteral(checker, importName) { @@ -94854,7 +96605,7 @@ ${lanes.join("\n")} const referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } - if (sourceFile.resolvedTypeReferenceDirectiveNames) sourceFile.resolvedTypeReferenceDirectiveNames.forEach(({ resolvedTypeReferenceDirective: resolvedTypeReferenceDirective })=>{ + if (sourceFile.resolvedTypeReferenceDirectiveNames) sourceFile.resolvedTypeReferenceDirectiveNames.forEach(({ resolvedTypeReferenceDirective: resolvedTypeReferenceDirective })=>{ if (!resolvedTypeReferenceDirective) return; const fileName = resolvedTypeReferenceDirective.resolvedFileName; const typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); @@ -94887,7 +96638,7 @@ ${lanes.join("\n")} } BuilderState2.canReuseOldState = canReuseOldState; function create(newProgram, oldState, disableUseFileVersionAsSignature) { - var _a2, _b, _c; + var _a, _b, _c; const fileInfos = /* @__PURE__ */ new Map(); const options = newProgram.getCompilerOptions(); const isOutFile = outFile(options); @@ -94897,7 +96648,7 @@ ${lanes.join("\n")} newProgram.getTypeChecker(); for (const sourceFile of newProgram.getSourceFiles()){ const version2 = Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set"); - const oldUncommittedSignature = useOldState ? (_a2 = oldState.oldSignatures) == null ? void 0 : _a2.get(sourceFile.resolvedPath) : void 0; + const oldUncommittedSignature = useOldState ? (_a = oldState.oldSignatures) == null ? void 0 : _a.get(sourceFile.resolvedPath) : void 0; const signature = oldUncommittedSignature === void 0 ? useOldState ? (_b = oldState.fileInfos.get(sourceFile.resolvedPath)) == null ? void 0 : _b.signature : void 0 : oldUncommittedSignature || void 0; if (referencedMap) { const newReferences = getReferencedFiles(newProgram, sourceFile, newProgram.getCanonicalFileName); @@ -94930,9 +96681,9 @@ ${lanes.join("\n")} } BuilderState2.releaseCache = releaseCache2; function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, host) { - var _a2, _b; + var _a, _b; const result = getFilesAffectedByWithOldState(state, programOfThisState, path, cancellationToken, host); - (_a2 = state.oldSignatures) == null || _a2.clear(); + (_a = state.oldSignatures) == null || _a.clear(); (_b = state.oldExportedModulesMap) == null || _b.clear(); return result; } @@ -94955,12 +96706,12 @@ ${lanes.join("\n")} programOfThisState.emit(sourceFile, (fileName, text, _writeByteOrderMark, _onError, sourceFiles, data)=>{ Debug.assert(isDeclarationFileName(fileName), `File extension for signature expected to be dts: Got:: ${fileName}`); onNewSignature(computeSignatureWithDiagnostics(programOfThisState, sourceFile, text, host, data), sourceFiles); - }, cancellationToken, /*emitOnlyDtsFiles*/ true, /*customTransformers*/ void 0, /*forceDtsEmit*/ true); + }, cancellationToken, /*emitOnly*/ true, /*customTransformers*/ void 0, /*forceDtsEmit*/ true); } BuilderState2.computeDtsSignature = computeDtsSignature; function updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, host, useFileVersionAsSignature = state.useFileVersionAsSignature) { - var _a2; - if ((_a2 = state.hasCalledUpdateShapeSignature) == null ? void 0 : _a2.has(sourceFile.resolvedPath)) return false; + var _a; + if ((_a = state.hasCalledUpdateShapeSignature) == null ? void 0 : _a.has(sourceFile.resolvedPath)) return false; const info = state.fileInfos.get(sourceFile.resolvedPath); const prevSignature = info.signature; let latestSignature; @@ -94993,7 +96744,7 @@ ${lanes.join("\n")} BuilderState2.updateExportedModules = updateExportedModules; function getExportedModules(exportedModulesFromDeclarationEmit) { let exportedModules; - exportedModulesFromDeclarationEmit == null || exportedModulesFromDeclarationEmit.forEach((symbol)=>getReferencedFilesFromImportedModuleSymbol(symbol).forEach((path)=>(exportedModules != null ? exportedModules : exportedModules = /* @__PURE__ */ new Set()).add(path))); + exportedModulesFromDeclarationEmit == null || exportedModulesFromDeclarationEmit.forEach((symbol)=>getReferencedFilesFromImportedModuleSymbol(symbol).forEach((path)=>(exportedModules ?? (exportedModules = /* @__PURE__ */ new Set())).add(path))); return exportedModules; } BuilderState2.getExportedModules = getExportedModules; @@ -95014,8 +96765,8 @@ ${lanes.join("\n")} } } return arrayFrom(mapDefinedIterator(seenMap.keys(), (path)=>{ - var _a2, _b; - return (_b = (_a2 = programOfThisState.getSourceFileByPath(path)) == null ? void 0 : _a2.fileName) != null ? _b : path; + var _a; + return ((_a = programOfThisState.getSourceFileByPath(path)) == null ? void 0 : _a.fileName) ?? path; })); } BuilderState2.getAllDependencies = getAllDependencies; @@ -95109,7 +96860,7 @@ ${lanes.join("\n")} return map1 === map2 || map1 !== void 0 && map2 !== void 0 && map1.size === map2.size && !forEachKey(map1, (key)=>!map2.has(key)); } function createBuilderProgramState(newProgram, oldState) { - var _a2, _b; + var _a, _b; const state = BuilderState.create(newProgram, oldState, /*disableUseFileVersionAsSignature*/ false); state.program = newProgram; const compilerOptions = newProgram.getCompilerOptions(); @@ -95124,7 +96875,7 @@ ${lanes.join("\n")} const canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); const canCopyEmitSignatures = compilerOptions.composite && (oldState == null ? void 0 : oldState.emitSignatures) && !outFilePath && !compilerOptionsAffectDeclarationPath(compilerOptions, oldState.compilerOptions); if (useOldState) { - (_a2 = oldState.changedFilesSet) == null || _a2.forEach((value1)=>state.changedFilesSet.add(value1)); + (_a = oldState.changedFilesSet) == null || _a.forEach((value1)=>state.changedFilesSet.add(value1)); if (!outFilePath && ((_b = oldState.affectedFilesPendingEmit) == null ? void 0 : _b.size)) { state.affectedFilesPendingEmit = new Map(oldState.affectedFilesPendingEmit); state.seenAffectedFiles = /* @__PURE__ */ new Set(); @@ -95136,7 +96887,6 @@ ${lanes.join("\n")} const copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck; const copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck; state.fileInfos.forEach((info, sourceFilePath)=>{ - var _a3; let oldInfo; let newReferences; if (!useOldState || // File wasn't present in old state @@ -95151,14 +96901,14 @@ ${lanes.join("\n")} if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) return; const diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); if (diagnostics) { - state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : diagnostics); + state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : repopulateDiagnostics(diagnostics, newProgram)); if (!state.semanticDiagnosticsFromOldState) state.semanticDiagnosticsFromOldState = /* @__PURE__ */ new Set(); state.semanticDiagnosticsFromOldState.add(sourceFilePath); } } if (canCopyEmitSignatures) { const oldEmitSignature = oldState.emitSignatures.get(sourceFilePath); - if (oldEmitSignature) ((_a3 = state.emitSignatures) != null ? _a3 : state.emitSignatures = /* @__PURE__ */ new Map()).set(sourceFilePath, getEmitSignatureFromOldSignature(compilerOptions, oldState.compilerOptions, oldEmitSignature)); + if (oldEmitSignature) (state.emitSignatures ?? (state.emitSignatures = /* @__PURE__ */ new Map())).set(sourceFilePath, getEmitSignatureFromOldSignature(compilerOptions, oldState.compilerOptions, oldEmitSignature)); } }); if (useOldState && forEachEntry(oldState.fileInfos, (info, sourceFilePath)=>{ @@ -95198,29 +96948,60 @@ ${lanes.join("\n")} oldEmitSignature ] : oldEmitSignature[0]; } + function repopulateDiagnostics(diagnostics, newProgram) { + if (!diagnostics.length) return diagnostics; + return sameMap(diagnostics, (diag2)=>{ + if (isString(diag2.messageText)) return diag2; + const repopulatedChain = convertOrRepopulateDiagnosticMessageChain(diag2.messageText, diag2.file, newProgram, (chain)=>{ + var _a; + return (_a = chain.repopulateInfo) == null ? void 0 : _a.call(chain); + }); + return repopulatedChain === diag2.messageText ? diag2 : { + ...diag2, + messageText: repopulatedChain + }; + }); + } + function convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram, repopulateInfo) { + const info = repopulateInfo(chain); + if (info) return { + ...createModuleNotFoundChain(sourceFile, newProgram, info.moduleReference, info.mode, info.packageName || info.moduleReference), + next: convertOrRepopulateDiagnosticMessageChainArray(chain.next, sourceFile, newProgram, repopulateInfo) + }; + const next = convertOrRepopulateDiagnosticMessageChainArray(chain.next, sourceFile, newProgram, repopulateInfo); + return next === chain.next ? chain : { + ...chain, + next: next + }; + } + function convertOrRepopulateDiagnosticMessageChainArray(array, sourceFile, newProgram, repopulateInfo) { + return sameMap(array, (chain)=>convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram, repopulateInfo)); + } function convertToDiagnostics(diagnostics, newProgram) { if (!diagnostics.length) return emptyArray; let buildInfoDirectory; return diagnostics.map((diagnostic)=>{ - const result = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath3); + const result = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPathInBuildInfoDirectory); result.reportsUnnecessary = diagnostic.reportsUnnecessary; result.reportsDeprecated = diagnostic.reportDeprecated; result.source = diagnostic.source; result.skippedOn = diagnostic.skippedOn; - const { relatedInformation: relatedInformation } = diagnostic; - result.relatedInformation = relatedInformation ? relatedInformation.length ? relatedInformation.map((r)=>convertToDiagnosticRelatedInformation(r, newProgram, toPath3)) : [] : void 0; + const { relatedInformation: relatedInformation } = diagnostic; + result.relatedInformation = relatedInformation ? relatedInformation.length ? relatedInformation.map((r)=>convertToDiagnosticRelatedInformation(r, newProgram, toPathInBuildInfoDirectory)) : [] : void 0; return result; }); - function toPath3(path) { - buildInfoDirectory != null ? buildInfoDirectory : buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions()), newProgram.getCurrentDirectory())); + function toPathInBuildInfoDirectory(path) { + buildInfoDirectory ?? (buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions()), newProgram.getCurrentDirectory()))); return toPath(path, buildInfoDirectory, newProgram.getCanonicalFileName); } } function convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath3) { - const { file: file } = diagnostic; + const { file: file } = diagnostic; + const sourceFile = file ? newProgram.getSourceFileByPath(toPath3(file)) : void 0; return { ...diagnostic, - file: file ? newProgram.getSourceFileByPath(toPath3(file)) : void 0 + file: sourceFile, + messageText: isString(diagnostic.messageText) ? diagnostic.messageText : convertOrRepopulateDiagnosticMessageChain(diagnostic.messageText, sourceFile, newProgram, (chain)=>chain.info) }; } function releaseCache(state) { @@ -95255,9 +97036,9 @@ ${lanes.join("\n")} Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.resolvedPath)); } function getNextAffectedFile(state, cancellationToken, host) { - var _a2, _b; + var _a, _b; while(true){ - const { affectedFiles: affectedFiles } = state; + const { affectedFiles: affectedFiles } = state; if (affectedFiles) { const seenAffectedFiles = state.seenAffectedFiles; let affectedFilesIndex = state.affectedFilesIndex; @@ -95273,7 +97054,7 @@ ${lanes.join("\n")} } state.changedFilesSet.delete(state.currentChangedFilePath); state.currentChangedFilePath = void 0; - (_a2 = state.oldSignatures) == null || _a2.clear(); + (_a = state.oldSignatures) == null || _a.clear(); (_b = state.oldExportedModulesMap) == null || _b.clear(); state.affectedFiles = void 0; } @@ -95292,8 +97073,8 @@ ${lanes.join("\n")} } } function clearAffectedFilesPendingEmit(state, emitOnlyDtsFiles) { - var _a2; - if (!((_a2 = state.affectedFilesPendingEmit) == null ? void 0 : _a2.size)) return; + var _a; + if (!((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.size)) return; if (!emitOnlyDtsFiles) return state.affectedFilesPendingEmit = void 0; state.affectedFilesPendingEmit.forEach((emitKind, path)=>{ const pending = emitKind & 7 /* AllJs */ ; @@ -95302,16 +97083,16 @@ ${lanes.join("\n")} }); } function getNextAffectedFilePendingEmit(state, emitOnlyDtsFiles) { - var _a2; - if (!((_a2 = state.affectedFilesPendingEmit) == null ? void 0 : _a2.size)) return void 0; + var _a; + if (!((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.size)) return void 0; return forEachEntry(state.affectedFilesPendingEmit, (emitKind, path)=>{ - var _a3; + var _a2; const affectedFile = state.program.getSourceFileByPath(path); if (!affectedFile || !sourceFileMayBeEmitted(affectedFile, state.program)) { state.affectedFilesPendingEmit.delete(path); return void 0; } - const seenKind = (_a3 = state.seenEmittedFiles) == null ? void 0 : _a3.get(affectedFile.resolvedPath); + const seenKind = (_a2 = state.seenEmittedFiles) == null ? void 0 : _a2.get(affectedFile.resolvedPath); let pendingKind = getPendingEmitKind(emitKind, seenKind); if (emitOnlyDtsFiles) pendingKind = pendingKind & 24 /* AllDts */ ; if (pendingKind) return { @@ -95361,14 +97142,14 @@ ${lanes.join("\n")} return newSignature !== oldSignature; } function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, host) { - var _a2; - if (!((_a2 = state.fileInfos.get(filePath)) == null ? void 0 : _a2.affectsGlobalScope)) return false; + var _a; + if (!((_a = state.fileInfos.get(filePath)) == null ? void 0 : _a.affectsGlobalScope)) return false; BuilderState.getAllFilesExcludingDefaultLibraryFile(state, state.program, /*firstSourceFile*/ void 0).forEach((file)=>handleDtsMayChangeOf(state, file.resolvedPath, cancellationToken, host)); removeDiagnosticsOfLibraryFiles(state); return true; } function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, host) { - var _a2; + var _a; if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) return; if (!isChangedSignature(state, affectedFile.resolvedPath)) return; if (getIsolatedModules(state.compilerOptions)) { @@ -95389,18 +97170,18 @@ ${lanes.join("\n")} } } const seenFileAndExportsOfFile = /* @__PURE__ */ new Set(); - (_a2 = state.exportedModulesMap.getKeys(affectedFile.resolvedPath)) == null || _a2.forEach((exportedFromPath)=>{ + (_a = state.exportedModulesMap.getKeys(affectedFile.resolvedPath)) == null || _a.forEach((exportedFromPath)=>{ if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, host)) return true; const references = state.referencedMap.getKeys(exportedFromPath); return references && forEachKey(references, (filePath)=>handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, host)); }); } function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, host) { - var _a2, _b; + var _a, _b; if (!tryAddToSet(seenFileAndExportsOfFile, filePath)) return void 0; if (handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, host)) return true; handleDtsMayChangeOf(state, filePath, cancellationToken, host); - (_a2 = state.exportedModulesMap.getKeys(filePath)) == null || _a2.forEach((exportedFromPath)=>handleDtsMayChangeOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, cancellationToken, host)); + (_a = state.exportedModulesMap.getKeys(filePath)) == null || _a.forEach((exportedFromPath)=>handleDtsMayChangeOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, cancellationToken, host)); (_b = state.referencedMap.getKeys(filePath)) == null || _b.forEach((referencingFilePath)=>!seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file handleDtsMayChangeOf(// Dont add to seen since this is not yet done with the export removal state, referencingFilePath, cancellationToken, host)); @@ -95423,7 +97204,7 @@ ${lanes.join("\n")} return !!outFile(info.options || {}); } function getBuildInfo2(state, bundle) { - var _a2, _b, _c; + var _a, _b, _c; const currentDirectory = Debug.checkDefined(state.program).getCurrentDirectory(); const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory)); const latestChangedDtsFile = state.latestChangedDtsFile ? relativeToBuildInfoEnsuringAbsolutePath(state.latestChangedDtsFile) : void 0; @@ -95452,11 +97233,11 @@ ${lanes.join("\n")} state.programEmitPending === getBuilderFileEmit(state.compilerOptions) ? false : // Pending emit is same as deteremined by compilerOptions state.programEmitPending }; - const { js: js , dts: dts , commonSourceDirectory: commonSourceDirectory , sourceFiles: sourceFiles } = bundle; + const { js: js, dts: dts, commonSourceDirectory: commonSourceDirectory, sourceFiles: sourceFiles } = bundle; state.bundle = bundle = { commonSourceDirectory: commonSourceDirectory, sourceFiles: sourceFiles, - js: js || (!state.compilerOptions.emitDeclarationOnly ? (_a2 = state.bundle) == null ? void 0 : _a2.js : void 0), + js: js || (!state.compilerOptions.emitDeclarationOnly ? (_a = state.bundle) == null ? void 0 : _a.js : void 0), dts: dts || (getEmitDeclarations(state.compilerOptions) ? (_b = state.bundle) == null ? void 0 : _b.dts : void 0) }; return createBuildInfo(program2, bundle); @@ -95465,11 +97246,11 @@ ${lanes.join("\n")} let fileNamesToFileIdListId; let emitSignatures; const fileInfos = arrayFrom(state.fileInfos.entries(), ([key, value1])=>{ - var _a3, _b2; + var _a2, _b2; const fileId = toFileId(key); tryAddRoot(key, fileId); Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); - const oldSignature = (_a3 = state.oldSignatures) == null ? void 0 : _a3.get(key); + const oldSignature = (_a2 = state.oldSignatures) == null ? void 0 : _a2.get(key); const actualSignature = oldSignature !== void 0 ? oldSignature || void 0 : value1.signature; if (state.compilerOptions.composite) { const file = state.program.getSourceFileByPath(key); @@ -95513,8 +97294,8 @@ ${lanes.join("\n")} ]); let exportedModulesMap; if (state.exportedModulesMap) exportedModulesMap = mapDefined(arrayFrom(state.exportedModulesMap.keys()).sort(compareStringsCaseSensitive), (key)=>{ - var _a3; - const oldValue = (_a3 = state.oldExportedModulesMap) == null ? void 0 : _a3.get(key); + var _a2; + const oldValue = (_a2 = state.oldExportedModulesMap) == null ? void 0 : _a2.get(key); if (oldValue === void 0) return [ toFileId(key), toFileIdListId(state.exportedModulesMap.getValues(key)) @@ -95610,7 +97391,7 @@ ${lanes.join("\n")} } function convertToProgramBuildInfoCompilerOptions(options) { let result; - const { optionsNameMap: optionsNameMap } = getOptionsNameMap(); + const { optionsNameMap: optionsNameMap } = getOptionsNameMap(); for (const name of getOwnKeys(options).sort(compareStringsCaseSensitive)){ const optionInfo = optionsNameMap.get(name.toLowerCase()); if (optionInfo == null ? void 0 : optionInfo.affectsBuildInfo) (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfoEnsuringAbsolutePath); @@ -95636,18 +97417,41 @@ ${lanes.join("\n")} result.reportDeprecated = diagnostic.reportsDeprecated; result.source = diagnostic.source; result.skippedOn = diagnostic.skippedOn; - const { relatedInformation: relatedInformation } = diagnostic; + const { relatedInformation: relatedInformation } = diagnostic; result.relatedInformation = relatedInformation ? relatedInformation.length ? relatedInformation.map((r)=>convertToReusableDiagnosticRelatedInformation(r, relativeToBuildInfo)) : [] : void 0; return result; }); } function convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo) { - const { file: file } = diagnostic; + const { file: file } = diagnostic; return { ...diagnostic, - file: file ? relativeToBuildInfo(file.resolvedPath) : void 0 + file: file ? relativeToBuildInfo(file.resolvedPath) : void 0, + messageText: isString(diagnostic.messageText) ? diagnostic.messageText : convertToReusableDiagnosticMessageChain(diagnostic.messageText) }; } + function convertToReusableDiagnosticMessageChain(chain) { + if (chain.repopulateInfo) return { + info: chain.repopulateInfo(), + next: convertToReusableDiagnosticMessageChainArray(chain.next) + }; + const next = convertToReusableDiagnosticMessageChainArray(chain.next); + return next === chain.next ? chain : { + ...chain, + next: next + }; + } + function convertToReusableDiagnosticMessageChainArray(array) { + if (!array) return array; + return forEach(array, (chain, index)=>{ + const reusable = convertToReusableDiagnosticMessageChain(chain); + if (chain === reusable) return void 0; + const result = index > 0 ? array.slice(0, index - 1) : []; + result.push(reusable); + for(let i = index + 1; i < array.length; i++)result.push(convertToReusableDiagnosticMessageChain(array[i])); + return result; + }) || array; + } function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { let host; let newProgram; @@ -95686,11 +97490,11 @@ ${lanes.join("\n")} return (data == null ? void 0 : data.sourceMapUrlPos) !== void 0 ? text.substring(0, data.sourceMapUrlPos) : text; } function computeSignatureWithDiagnostics(program, sourceFile, text, host, data) { - var _a2, _b; + var _a; text = getTextHandlingSourceMapForSignature(text, data); let sourceFileDirectory; - if ((_a2 = data == null ? void 0 : data.diagnostics) == null ? void 0 : _a2.length) text += data.diagnostics.map((diagnostic)=>`${locationInfo(diagnostic)}${DiagnosticCategory[diagnostic.category]}${diagnostic.code}: ${flattenDiagnosticMessageText2(diagnostic.messageText)}`).join("\n"); - return ((_b = host.createHash) != null ? _b : generateDjb2Hash)(text); + if ((_a = data == null ? void 0 : data.diagnostics) == null ? void 0 : _a.length) text += data.diagnostics.map((diagnostic)=>`${locationInfo(diagnostic)}${DiagnosticCategory[diagnostic.category]}${diagnostic.code}: ${flattenDiagnosticMessageText2(diagnostic.messageText)}`).join("\n"); + return (host.createHash ?? generateDjb2Hash)(text); function flattenDiagnosticMessageText2(diagnostic) { return isString(diagnostic) ? diagnostic : diagnostic === void 0 ? "" : !diagnostic.next ? diagnostic.messageText : diagnostic.messageText + diagnostic.next.map(flattenDiagnosticMessageText2).join("\n"); } @@ -95701,10 +97505,9 @@ ${lanes.join("\n")} } } function computeSignature(text, host, data) { - var _a2; - return ((_a2 = host.createHash) != null ? _a2 : generateDjb2Hash)(getTextHandlingSourceMapForSignature(text, data)); + return (host.createHash ?? generateDjb2Hash)(getTextHandlingSourceMapForSignature(text, data)); } - function createBuilderProgram(kind, { newProgram: newProgram , host: host , oldProgram: oldProgram , configFileParsingDiagnostics: configFileParsingDiagnostics }) { + function createBuilderProgram(kind, { newProgram: newProgram, host: host, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics }) { let oldState = oldProgram && oldProgram.getState(); if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) { newProgram = void 0; @@ -95742,7 +97545,7 @@ ${lanes.join("\n")} return emitSkippedWithNoDiagnostics; } function emitNextAffectedFile(writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers) { - var _a2, _b, _c, _d, _e; + var _a, _b, _c; let affected = getNextAffectedFile(state, cancellationToken, host); const programEmitKind = getBuilderFileEmit(state.compilerOptions); let emitKind = emitOnlyDtsFiles ? programEmitKind & 24 /* AllDts */ : programEmitKind; @@ -95759,7 +97562,7 @@ ${lanes.join("\n")} affected: affected2 }; } - ({ affectedFile: affected , emitKind: emitKind } = pendingAffectedFile); + ({ affectedFile: affected, emitKind: emitKind } = pendingAffectedFile); } else { if (!state.programEmitPending) return void 0; emitKind = state.programEmitPending; @@ -95778,12 +97581,12 @@ ${lanes.join("\n")} state.seenAffectedFiles.add(affectedSourceFile.resolvedPath); if (state.affectedFilesIndex !== void 0) state.affectedFilesIndex++; state.buildInfoEmitPending = true; - const existing = ((_a2 = state.seenEmittedFiles) == null ? void 0 : _a2.get(affectedSourceFile.resolvedPath)) || 0 /* None */ ; - ((_b = state.seenEmittedFiles) != null ? _b : state.seenEmittedFiles = /* @__PURE__ */ new Map()).set(affectedSourceFile.resolvedPath, emitKind | existing); - const existingPending = ((_c = state.affectedFilesPendingEmit) == null ? void 0 : _c.get(affectedSourceFile.resolvedPath)) || programEmitKind; + const existing = ((_a = state.seenEmittedFiles) == null ? void 0 : _a.get(affectedSourceFile.resolvedPath)) || 0 /* None */ ; + (state.seenEmittedFiles ?? (state.seenEmittedFiles = /* @__PURE__ */ new Map())).set(affectedSourceFile.resolvedPath, emitKind | existing); + const existingPending = ((_b = state.affectedFilesPendingEmit) == null ? void 0 : _b.get(affectedSourceFile.resolvedPath)) || programEmitKind; const pendingKind = getPendingEmitKind(existingPending, emitKind | existing); - if (pendingKind) ((_d = state.affectedFilesPendingEmit) != null ? _d : state.affectedFilesPendingEmit = /* @__PURE__ */ new Map()).set(affectedSourceFile.resolvedPath, pendingKind); - else (_e = state.affectedFilesPendingEmit) == null || _e.delete(affectedSourceFile.resolvedPath); + if (pendingKind) (state.affectedFilesPendingEmit ?? (state.affectedFilesPendingEmit = /* @__PURE__ */ new Map())).set(affectedSourceFile.resolvedPath, pendingKind); + else (_c = state.affectedFilesPendingEmit) == null || _c.delete(affectedSourceFile.resolvedPath); } else state.changedFilesSet.clear(); return { result: result, @@ -95793,7 +97596,7 @@ ${lanes.join("\n")} function getWriteFileCallback(writeFile2, customTransformers) { if (!getEmitDeclarations(state.compilerOptions)) return writeFile2 || maybeBind(host, host.writeFile); return (fileName, text, writeByteOrderMark, onError, sourceFiles, data)=>{ - var _a2, _b, _c, _d, _e, _f, _g; + var _a, _b, _c, _d; if (isDeclarationFileName(fileName)) { if (!outFile(state.compilerOptions)) { Debug.assert((sourceFiles == null ? void 0 : sourceFiles.length) === 1); @@ -95803,26 +97606,26 @@ ${lanes.join("\n")} const info = state.fileInfos.get(file.resolvedPath); if (info.signature === file.version) { const signature = computeSignatureWithDiagnostics(state.program, file, text, host, data); - if (!((_a2 = data == null ? void 0 : data.diagnostics) == null ? void 0 : _a2.length)) emitSignature = signature; + if (!((_a = data == null ? void 0 : data.diagnostics) == null ? void 0 : _a.length)) emitSignature = signature; if (signature !== file.version) { - if (host.storeFilesChangingSignatureDuringEmit) ((_b = state.filesChangingSignature) != null ? _b : state.filesChangingSignature = /* @__PURE__ */ new Set()).add(file.resolvedPath); + if (host.storeFilesChangingSignatureDuringEmit) (state.filesChangingSignature ?? (state.filesChangingSignature = /* @__PURE__ */ new Set())).add(file.resolvedPath); if (state.exportedModulesMap) BuilderState.updateExportedModules(state, file, file.exportedModulesFromDeclarationEmit); if (state.affectedFiles) { - const existing = (_c = state.oldSignatures) == null ? void 0 : _c.get(file.resolvedPath); - if (existing === void 0) ((_d = state.oldSignatures) != null ? _d : state.oldSignatures = /* @__PURE__ */ new Map()).set(file.resolvedPath, info.signature || false); + const existing = (_b = state.oldSignatures) == null ? void 0 : _b.get(file.resolvedPath); + if (existing === void 0) (state.oldSignatures ?? (state.oldSignatures = /* @__PURE__ */ new Map())).set(file.resolvedPath, info.signature || false); info.signature = signature; } else { info.signature = signature; - (_e = state.oldExportedModulesMap) == null || _e.clear(); + (_c = state.oldExportedModulesMap) == null || _c.clear(); } } } } if (state.compilerOptions.composite) { const filePath = sourceFiles[0].resolvedPath; - emitSignature = handleNewSignature((_f = state.emitSignatures) == null ? void 0 : _f.get(filePath), emitSignature); + emitSignature = handleNewSignature((_d = state.emitSignatures) == null ? void 0 : _d.get(filePath), emitSignature); if (!emitSignature) return; - ((_g = state.emitSignatures) != null ? _g : state.emitSignatures = /* @__PURE__ */ new Map()).set(filePath, emitSignature); + (state.emitSignatures ?? (state.emitSignatures = /* @__PURE__ */ new Map())).set(filePath, emitSignature); } } else if (state.compilerOptions.composite) { const newSignature = handleNewSignature(state.outSignature, /*newSignature*/ void 0); @@ -95835,7 +97638,7 @@ ${lanes.join("\n")} else state.program.writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data); function handleNewSignature(oldSignatureFormat, newSignature) { const oldSignature = !oldSignatureFormat || isString(oldSignatureFormat) ? oldSignatureFormat : oldSignatureFormat[0]; - newSignature != null ? newSignature : newSignature = computeSignature(text, host, data); + newSignature ?? (newSignature = computeSignature(text, host, data)); if (newSignature === oldSignature) { if (oldSignatureFormat === oldSignature) return void 0; else if (data) data.differsOnlyInMap = true; @@ -95890,7 +97693,7 @@ ${lanes.join("\n")} state.buildInfoEmitPending = true; if (!result) continue; } else { - result = state.program.getSemanticDiagnostics(/*targetSourceFile*/ void 0, cancellationToken); + result = state.program.getSemanticDiagnostics(/*sourceFile*/ void 0, cancellationToken); state.changedFilesSet.clear(); state.programEmitPending = getBuilderFileEmit(state.compilerOptions); } @@ -95915,9 +97718,9 @@ ${lanes.join("\n")} } } function addToAffectedFilesPendingEmit(state, affectedFilePendingEmit, kind) { - var _a2, _b; - const existingKind = ((_a2 = state.affectedFilesPendingEmit) == null ? void 0 : _a2.get(affectedFilePendingEmit)) || 0 /* None */ ; - ((_b = state.affectedFilesPendingEmit) != null ? _b : state.affectedFilesPendingEmit = /* @__PURE__ */ new Map()).set(affectedFilePendingEmit, existingKind | kind); + var _a; + const existingKind = ((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.get(affectedFilePendingEmit)) || 0 /* None */ ; + (state.affectedFilesPendingEmit ?? (state.affectedFilesPendingEmit = /* @__PURE__ */ new Map())).set(affectedFilePendingEmit, existingKind | kind); } function toBuilderStateFileInfoForMultiEmit(fileInfo) { return isString(fileInfo) ? { @@ -95939,12 +97742,12 @@ ${lanes.join("\n")} return !value1 ? getBuilderFileEmit(options || {}) : value1; } function createBuilderProgramUsingProgramBuildInfo(buildInfo, buildInfoPath, host) { - var _a2, _b, _c, _d; + var _a, _b, _c, _d; const program = buildInfo.program; const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); let state; - const filePaths = (_a2 = program.fileNames) == null ? void 0 : _a2.map(toPath3); + const filePaths = (_a = program.fileNames) == null ? void 0 : _a.map(toPathInBuildInfoDirectory); let filePathsSetList; const latestChangedDtsFile = program.latestChangedDtsFile ? toAbsolutePath(program.latestChangedDtsFile) : void 0; if (isProgramBundleEmitBuildInfo(program)) { @@ -96025,7 +97828,7 @@ ${lanes.join("\n")} close: noop, hasChangedEmitSignature: returnFalse }; - function toPath3(path) { + function toPathInBuildInfoDirectory(path) { return toPath(path, buildInfoDirectory, getCanonicalFileName); } function toAbsolutePath(path) { @@ -96105,7 +97908,6 @@ ${lanes.join("\n")} "src/compiler/builder.ts" () { "use strict"; init_ts2(); - init_ts2(); BuilderFileEmit = /* @__PURE__ */ ((BuilderFileEmit2)=>{ BuilderFileEmit2[BuilderFileEmit2["None"] = 0] = "None"; BuilderFileEmit2[BuilderFileEmit2["Js"] = 1] = "Js"; @@ -96133,7 +97935,7 @@ ${lanes.join("\n")} return createBuilderProgram(1 /* EmitAndSemanticDiagnosticsBuilderProgram */ , getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { - const { newProgram: newProgram , configFileParsingDiagnostics: newConfigFileParsingDiagnostics } = getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences); + const { newProgram: newProgram, configFileParsingDiagnostics: newConfigFileParsingDiagnostics } = getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences); return createRedirectedBuilderProgram(()=>({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() @@ -96150,26 +97952,91 @@ ${lanes.join("\n")} if (endsWith(path, "/node_modules/.staging")) return removeSuffix(path, "/.staging"); return some(ignoredPaths, (searchPath)=>stringContains(path, searchPath)) ? void 0 : path; } - function canWatchDirectoryOrFile(dirPath) { - const rootLength = getRootLength(dirPath); - if (dirPath.length === rootLength) return false; - let nextDirectorySeparator = dirPath.indexOf(directorySeparator, rootLength); - if (nextDirectorySeparator === -1) return false; - let pathPartForUserCheck = dirPath.substring(rootLength, nextDirectorySeparator + 1); - const isNonDirectorySeparatorRoot = rootLength > 1 || dirPath.charCodeAt(0) !== 47 /* slash */ ; - if (isNonDirectorySeparatorRoot && dirPath.search(/[a-zA-Z]:/) !== 0 && // Non dos style paths - pathPartForUserCheck.search(/[a-zA-Z]\$\//) === 0) { - nextDirectorySeparator = dirPath.indexOf(directorySeparator, nextDirectorySeparator + 1); - if (nextDirectorySeparator === -1) return false; - pathPartForUserCheck = dirPath.substring(rootLength + pathPartForUserCheck.length, nextDirectorySeparator + 1); - } - if (isNonDirectorySeparatorRoot && pathPartForUserCheck.search(/users\//i) !== 0) return true; - for(let searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--){ - searchIndex = dirPath.indexOf(directorySeparator, searchIndex) + 1; - if (searchIndex === 0) return false; + function perceivedOsRootLengthForWatching(pathComponents2, length2) { + if (length2 <= 1) return 1; + let userCheckIndex = 1; + let isDosStyle = pathComponents2[0].search(/[a-zA-Z]:/) === 0; + if (pathComponents2[0] !== directorySeparator && !isDosStyle && // Non dos style paths + pathComponents2[1].search(/[a-zA-Z]\$$/) === 0) { + if (length2 === 2) return 2; + userCheckIndex = 2; + isDosStyle = true; + } + if (isDosStyle && !pathComponents2[userCheckIndex].match(/^users$/i)) return userCheckIndex; + return userCheckIndex + 2; + } + function canWatchDirectoryOrFile(pathComponents2, length2) { + if (length2 === void 0) length2 = pathComponents2.length; + if (length2 <= 2) return false; + const perceivedOsRootLength = perceivedOsRootLengthForWatching(pathComponents2, length2); + return length2 > perceivedOsRootLength + 1; + } + function canWatchAtTypes(atTypes) { + return canWatchAffectedPackageJsonOrNodeModulesOfAtTypes(getDirectoryPath(atTypes)); + } + function isInDirectoryPath(dirComponents, fileOrDirComponents) { + if (fileOrDirComponents.length < fileOrDirComponents.length) return false; + for(let i = 0; i < dirComponents.length; i++){ + if (fileOrDirComponents[i] !== dirComponents[i]) return false; } return true; } + function canWatchAffectedPackageJsonOrNodeModulesOfAtTypes(fileOrDirPath) { + return canWatchDirectoryOrFile(getPathComponents(fileOrDirPath)); + } + function canWatchAffectingLocation(filePath) { + return canWatchAffectedPackageJsonOrNodeModulesOfAtTypes(filePath); + } + function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath, rootDir, rootPath, rootPathComponents, getCurrentDirectory) { + const failedLookupPathComponents = getPathComponents(failedLookupLocationPath); + failedLookupLocation = isRootedDiskPath(failedLookupLocation) ? normalizePath(failedLookupLocation) : getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + const failedLookupComponents = getPathComponents(failedLookupLocation); + const perceivedOsRootLength = perceivedOsRootLengthForWatching(failedLookupPathComponents, failedLookupPathComponents.length); + if (failedLookupPathComponents.length <= perceivedOsRootLength + 1) return void 0; + const nodeModulesIndex = failedLookupPathComponents.indexOf("node_modules"); + if (nodeModulesIndex !== -1 && nodeModulesIndex + 1 <= perceivedOsRootLength + 1) return void 0; + if (isInDirectoryPath(rootPathComponents, failedLookupPathComponents)) { + if (failedLookupPathComponents.length > rootPathComponents.length + 1) return getDirectoryOfFailedLookupWatch(failedLookupComponents, failedLookupPathComponents, Math.max(rootPathComponents.length + 1, perceivedOsRootLength + 1)); + else return { + dir: rootDir, + dirPath: rootPath, + nonRecursive: true + }; + } + return getDirectoryToWatchFromFailedLookupLocationDirectory(failedLookupComponents, failedLookupPathComponents, failedLookupPathComponents.length - 1, perceivedOsRootLength, nodeModulesIndex, rootPathComponents); + } + function getDirectoryToWatchFromFailedLookupLocationDirectory(dirComponents, dirPathComponents, dirPathComponentsLength, perceivedOsRootLength, nodeModulesIndex, rootPathComponents) { + if (nodeModulesIndex !== -1) return getDirectoryOfFailedLookupWatch(dirComponents, dirPathComponents, nodeModulesIndex + 1); + let nonRecursive = true; + let length2 = dirPathComponentsLength; + for(let i = 0; i < dirPathComponentsLength; i++)if (dirPathComponents[i] !== rootPathComponents[i]) { + nonRecursive = false; + length2 = Math.max(i + 1, perceivedOsRootLength + 1); + break; + } + return getDirectoryOfFailedLookupWatch(dirComponents, dirPathComponents, length2, nonRecursive); + } + function getDirectoryOfFailedLookupWatch(dirComponents, dirPathComponents, length2, nonRecursive) { + return { + dir: getPathFromPathComponents(dirComponents, length2), + dirPath: getPathFromPathComponents(dirPathComponents, length2), + nonRecursive: nonRecursive + }; + } + function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath, rootPath, rootPathComponents, getCurrentDirectory, filterCustomPath) { + const typeRootPathComponents = getPathComponents(typeRootPath); + if (isInDirectoryPath(rootPathComponents, typeRootPathComponents)) return rootPath; + typeRoot = isRootedDiskPath(typeRoot) ? normalizePath(typeRoot) : getNormalizedAbsolutePath(typeRoot, getCurrentDirectory()); + const toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(getPathComponents(typeRoot), typeRootPathComponents, typeRootPathComponents.length, perceivedOsRootLengthForWatching(typeRootPathComponents, typeRootPathComponents.length), typeRootPathComponents.indexOf("node_modules"), rootPathComponents); + return toWatch && filterCustomPath(toWatch.dirPath) ? toWatch.dirPath : void 0; + } + function getRootDirectoryOfResolutionCache(rootDirForResolution, getCurrentDirectory) { + const normalized = getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory()); + return !isDiskPathRoot(normalized) ? removeTrailingDirectorySeparator(normalized) : normalized; + } + function getRootPathSplitLength(rootPath) { + return rootPath.split(directorySeparator).length - (hasTrailingDirectorySeparator(rootPath) ? 1 : 0); + } function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { let filesWithChangedSetOfUnresolvedImports; let filesWithInvalidatedResolutions; @@ -96185,25 +98052,20 @@ ${lanes.join("\n")} let failedLookupChecks; let startsWithPathChecks; let isInDirectoryChecks; + let allModuleAndTypeResolutionsAreInvalidated = false; const getCurrentDirectory = memoize(()=>resolutionHost.getCurrentDirectory()); const cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); const resolvedModuleNames = /* @__PURE__ */ new Map(); const moduleResolutionCache = createModuleResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, resolutionHost.getCompilationSettings()); const resolvedTypeReferenceDirectives = /* @__PURE__ */ new Map(); const typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, resolutionHost.getCompilationSettings(), moduleResolutionCache.getPackageJsonInfoCache()); - const failedLookupDefaultExtensions = [ - ".ts" /* Ts */ , - ".tsx" /* Tsx */ , - ".js" /* Js */ , - ".jsx" /* Jsx */ , - ".json" /* Json */ - ]; - const customFailedLookupPaths = /* @__PURE__ */ new Map(); + const resolvedLibraries = /* @__PURE__ */ new Map(); + const libraryResolutionCache = createModuleResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, getOptionsForLibraryResolution(resolutionHost.getCompilationSettings()), moduleResolutionCache.getPackageJsonInfoCache()); const directoryWatchesOfFailedLookups = /* @__PURE__ */ new Map(); const fileWatchesOfAffectingLocations = /* @__PURE__ */ new Map(); - const rootDir = rootDirForResolution && removeTrailingDirectorySeparator(getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); - const rootPath = rootDir && resolutionHost.toPath(rootDir); - const rootSplitLength = rootPath !== void 0 ? rootPath.split(directorySeparator).length : 0; + const rootDir = getRootDirectoryOfResolutionCache(rootDirForResolution, getCurrentDirectory); + const rootPath = resolutionHost.toPath(rootDir); + const rootPathComponents = getPathComponents(rootPath); const typeRootsWatches = /* @__PURE__ */ new Map(); return { getModuleResolutionCache: ()=>moduleResolutionCache, @@ -96215,6 +98077,7 @@ ${lanes.join("\n")} finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, resolveModuleNameLiterals: resolveModuleNameLiterals, resolveTypeReferenceDirectiveReferences: resolveTypeReferenceDirectiveReferences, + resolveLibrary: resolveLibrary2, resolveSingleModuleNameWithoutWatching: resolveSingleModuleNameWithoutWatching, removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects, removeResolutionsOfFile: removeResolutionsOfFile, @@ -96226,7 +98089,8 @@ ${lanes.join("\n")} isFileWithInvalidatedNonRelativeUnresolvedImports: isFileWithInvalidatedNonRelativeUnresolvedImports, updateTypeRootsWatch: updateTypeRootsWatch, closeTypeRootsWatch: closeTypeRootsWatch, - clear: clear2 + clear: clear2, + onChangesAffectModuleResolution: onChangesAffectModuleResolution }; function getResolvedModule2(resolution) { return resolution.resolvedModule; @@ -96234,14 +98098,9 @@ ${lanes.join("\n")} function getResolvedTypeReferenceDirective2(resolution) { return resolution.resolvedTypeReferenceDirective; } - function isInDirectoryPath(dir, file) { - if (dir === void 0 || file.length <= dir.length) return false; - return startsWith(file, dir) && file[dir.length] === directorySeparator; - } function clear2() { clearMap(directoryWatchesOfFailedLookups, closeFileWatcherOf); clearMap(fileWatchesOfAffectingLocations, closeFileWatcherOf); - customFailedLookupPaths.clear(); nonRelativeExternalModuleResolutions.clear(); closeTypeRootsWatch(); resolvedModuleNames.clear(); @@ -96254,13 +98113,23 @@ ${lanes.join("\n")} isInDirectoryChecks = void 0; affectingPathChecks = void 0; affectingPathChecksForFile = void 0; + allModuleAndTypeResolutionsAreInvalidated = false; moduleResolutionCache.clear(); typeReferenceDirectiveResolutionCache.clear(); moduleResolutionCache.update(resolutionHost.getCompilationSettings()); typeReferenceDirectiveResolutionCache.update(resolutionHost.getCompilationSettings()); + libraryResolutionCache.clear(); impliedFormatPackageJsons.clear(); + resolvedLibraries.clear(); hasChangedAutomaticTypeDirectiveNames = false; } + function onChangesAffectModuleResolution() { + allModuleAndTypeResolutionsAreInvalidated = true; + moduleResolutionCache.clearAllExceptPackageJsonInfoCache(); + typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache(); + moduleResolutionCache.update(resolutionHost.getCompilationSettings()); + typeReferenceDirectiveResolutionCache.update(resolutionHost.getCompilationSettings()); + } function startRecordingFilesWithChangedResolutions() { filesWithChangedSetOfUnresolvedImports = []; } @@ -96274,27 +98143,45 @@ ${lanes.join("\n")} const value1 = filesWithInvalidatedNonRelativeUnresolvedImports.get(path); return !!value1 && !!value1.length; } - function createHasInvalidatedResolutions(customHasInvalidatedResolutions) { + function createHasInvalidatedResolutions(customHasInvalidatedResolutions, customHasInvalidatedLibResolutions) { invalidateResolutionsOfFailedLookupLocations(); const collected = filesWithInvalidatedResolutions; filesWithInvalidatedResolutions = void 0; - return (path)=>customHasInvalidatedResolutions(path) || !!(collected == null ? void 0 : collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path); + return { + hasInvalidatedResolutions: (path)=>customHasInvalidatedResolutions(path) || allModuleAndTypeResolutionsAreInvalidated || !!(collected == null ? void 0 : collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path), + hasInvalidatedLibResolutions: (libFileName)=>{ + var _a; + return customHasInvalidatedLibResolutions(libFileName) || !!((_a = resolvedLibraries == null ? void 0 : resolvedLibraries.get(libFileName)) == null ? void 0 : _a.isInvalidated); + } + }; } function startCachingPerDirectoryResolution() { moduleResolutionCache.clearAllExceptPackageJsonInfoCache(); typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache(); + libraryResolutionCache.clearAllExceptPackageJsonInfoCache(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } + function cleanupLibResolutionWatching(newProgram) { + resolvedLibraries.forEach((resolution, libFileName)=>{ + var _a; + if (!((_a = newProgram == null ? void 0 : newProgram.resolvedLibReferences) == null ? void 0 : _a.has(libFileName))) { + stopWatchFailedLookupLocationOfResolution(resolution, resolutionHost.toPath(getInferredLibraryNameResolveFrom(newProgram.getCompilerOptions(), getCurrentDirectory(), libFileName)), getResolvedModule2); + resolvedLibraries.delete(libFileName); + } + }); + } function finishCachingPerDirectoryResolution(newProgram, oldProgram) { filesWithInvalidatedNonRelativeUnresolvedImports = void 0; + allModuleAndTypeResolutionsAreInvalidated = false; nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); if (newProgram !== oldProgram) { + cleanupLibResolutionWatching(newProgram); newProgram == null || newProgram.getSourceFiles().forEach((newFile)=>{ - var _a2, _b, _c; - const expected = isExternalOrCommonJsModule(newFile) ? (_b = (_a2 = newFile.packageJsonLocations) == null ? void 0 : _a2.length) != null ? _b : 0 : 0; - const existing = (_c = impliedFormatPackageJsons.get(newFile.path)) != null ? _c : emptyArray; + var _a; + const expected = isExternalOrCommonJsModule(newFile) ? ((_a = newFile.packageJsonLocations) == null ? void 0 : _a.length) ?? 0 : 0; + const existing = impliedFormatPackageJsons.get(newFile.path) ?? emptyArray; for(let i = existing.length; i < expected; i++)createFileWatcherOfAffectingLocation(newFile.packageJsonLocations[i], /*forResolution*/ false); if (existing.length > expected) for(let i = expected; i < existing.length; i++)fileWatchesOfAffectingLocations.get(existing[i]).files--; if (expected) impliedFormatPackageJsons.set(newFile.path, newFile.packageJsonLocations); @@ -96322,13 +98209,13 @@ ${lanes.join("\n")} hasChangedAutomaticTypeDirectiveNames = false; } function resolveModuleName2(moduleName, containingFile, compilerOptions, redirectedReference, mode) { - var _a2; - const host = ((_a2 = resolutionHost.getCompilerHost) == null ? void 0 : _a2.call(resolutionHost)) || resolutionHost; + var _a; + const host = ((_a = resolutionHost.getCompilerHost) == null ? void 0 : _a.call(resolutionHost)) || resolutionHost; const primaryResult = resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference, mode); if (!resolutionHost.getGlobalCache) return primaryResult; const globalCache = resolutionHost.getGlobalCache(); if (globalCache !== void 0 && !isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && extensionIsTS(primaryResult.resolvedModule.extension))) { - const { resolvedModule: resolvedModule , failedLookupLocations: failedLookupLocations , affectingLocations: affectingLocations , resolutionDiagnostics: resolutionDiagnostics } = loadModuleFromGlobalCache(Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache); + const { resolvedModule: resolvedModule, failedLookupLocations: failedLookupLocations, affectingLocations: affectingLocations, resolutionDiagnostics: resolutionDiagnostics } = loadModuleFromGlobalCache(Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache); if (resolvedModule) { primaryResult.resolvedModule = resolvedModule; primaryResult.failedLookupLocations = updateResolutionField(primaryResult.failedLookupLocations, failedLookupLocations); @@ -96345,8 +98232,8 @@ ${lanes.join("\n")} resolve: (moduleName, resoluionMode)=>resolveModuleName2(moduleName, containingFile, options, redirectedReference, resoluionMode) }; } - function resolveNamesWithLocalCache({ entries: entries , containingFile: containingFile , containingSourceFile: containingSourceFile , redirectedReference: redirectedReference , options: options , perFileCache: perFileCache , reusedNames: reusedNames , loader: loader , getResolutionWithResolvedFileName: getResolutionWithResolvedFileName , shouldRetryResolution: shouldRetryResolution , logChanges: logChanges }) { - var _a2; + function resolveNamesWithLocalCache({ entries: entries, containingFile: containingFile, containingSourceFile: containingSourceFile, redirectedReference: redirectedReference, options: options, perFileCache: perFileCache, reusedNames: reusedNames, loader: loader, getResolutionWithResolvedFileName: getResolutionWithResolvedFileName, deferWatchingNonRelativeResolution: deferWatchingNonRelativeResolution, shouldRetryResolution: shouldRetryResolution, logChanges: logChanges }) { + var _a; const path = resolutionHost.toPath(containingFile); const resolutionsInFile = perFileCache.get(path) || perFileCache.set(path, createModeAwareCache()).get(path); const resolvedModules = []; @@ -96359,20 +98246,20 @@ ${lanes.join("\n")} const name = loader.nameAndMode.getName(entry); const mode = loader.nameAndMode.getMode(entry, containingSourceFile); let resolution = resolutionsInFile.get(name, mode); - if (!seenNamesInFile.has(name, mode) && unmatchedRedirects || !resolution || resolution.isInvalidated || // If the name is unresolved import that was invalidated, recalculate - hasInvalidatedNonRelativeUnresolvedImport && !isExternalModuleNameRelative(name) && shouldRetryResolution(resolution)) { + if (!seenNamesInFile.has(name, mode) && (allModuleAndTypeResolutionsAreInvalidated || unmatchedRedirects || !resolution || resolution.isInvalidated || // If the name is unresolved import that was invalidated, recalculate + hasInvalidatedNonRelativeUnresolvedImport && !isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) { const existingResolution = resolution; resolution = loader.resolve(name, mode); if (resolutionHost.onDiscoveredSymlink && resolutionIsSymlink(resolution)) resolutionHost.onDiscoveredSymlink(); resolutionsInFile.set(name, mode, resolution); - watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName); + watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName, deferWatchingNonRelativeResolution); if (existingResolution) stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolutionWithResolvedFileName); if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { filesWithChangedSetOfUnresolvedImports.push(path); logChanges = false; } } else { - const host = ((_a2 = resolutionHost.getCompilerHost) == null ? void 0 : _a2.call(resolutionHost)) || resolutionHost; + const host = ((_a = resolutionHost.getCompilerHost) == null ? void 0 : _a.call(resolutionHost)) || resolutionHost; if (isTraceEnabled(options, host) && !seenNamesInFile.has(name, mode)) { const resolved = getResolutionWithResolvedFileName(resolution); trace(host, perFileCache === resolvedModuleNames ? (resolved == null ? void 0 : resolved.resolvedFileName) ? resolved.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved : (resolved == null ? void 0 : resolved.resolvedFileName) ? resolved.packageId ? Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_not_resolved, name, containingFile, resolved == null ? void 0 : resolved.resolvedFileName, (resolved == null ? void 0 : resolved.packageId) && packageIdToString(resolved.packageId)); @@ -96401,7 +98288,7 @@ ${lanes.join("\n")} } } function resolveTypeReferenceDirectiveReferences(typeDirectiveReferences, containingFile, redirectedReference, options, containingSourceFile, reusedNames) { - var _a2; + var _a; return resolveNamesWithLocalCache({ entries: typeDirectiveReferences, containingFile: containingFile, @@ -96410,9 +98297,10 @@ ${lanes.join("\n")} options: options, reusedNames: reusedNames, perFileCache: resolvedTypeReferenceDirectives, - loader: createTypeReferenceResolutionLoader(containingFile, redirectedReference, options, ((_a2 = resolutionHost.getCompilerHost) == null ? void 0 : _a2.call(resolutionHost)) || resolutionHost, typeReferenceDirectiveResolutionCache), + loader: createTypeReferenceResolutionLoader(containingFile, redirectedReference, options, ((_a = resolutionHost.getCompilerHost) == null ? void 0 : _a.call(resolutionHost)) || resolutionHost, typeReferenceDirectiveResolutionCache), getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective2, - shouldRetryResolution: (resolution)=>resolution.resolvedTypeReferenceDirective === void 0 + shouldRetryResolution: (resolution)=>resolution.resolvedTypeReferenceDirective === void 0, + deferWatchingNonRelativeResolution: false }); } function resolveModuleNameLiterals(moduleLiterals, containingFile, redirectedReference, options, containingSourceFile, reusedNames) { @@ -96427,9 +98315,27 @@ ${lanes.join("\n")} loader: createModuleResolutionLoader2(containingFile, redirectedReference, options), getResolutionWithResolvedFileName: getResolvedModule2, shouldRetryResolution: (resolution)=>!resolution.resolvedModule || !resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension), - logChanges: logChangesWhenResolvingModule + logChanges: logChangesWhenResolvingModule, + deferWatchingNonRelativeResolution: true }); } + function resolveLibrary2(libraryName, resolveFrom, options, libFileName) { + var _a; + const host = ((_a = resolutionHost.getCompilerHost) == null ? void 0 : _a.call(resolutionHost)) || resolutionHost; + let resolution = resolvedLibraries == null ? void 0 : resolvedLibraries.get(libFileName); + if (!resolution || resolution.isInvalidated) { + const existingResolution = resolution; + resolution = resolveLibrary(libraryName, resolveFrom, options, host, libraryResolutionCache); + const path = resolutionHost.toPath(resolveFrom); + watchFailedLookupLocationsOfExternalModuleResolutions(libraryName, resolution, path, getResolvedModule2, /*deferWatchingNonRelativeResolution*/ false); + resolvedLibraries.set(libFileName, resolution); + if (existingResolution) stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolvedModule2); + } else if (isTraceEnabled(options, host)) { + const resolved = getResolvedModule2(resolution); + trace(host, (resolved == null ? void 0 : resolved.resolvedFileName) ? resolved.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved, libraryName, resolveFrom, resolved == null ? void 0 : resolved.resolvedFileName, (resolved == null ? void 0 : resolved.packageId) && packageIdToString(resolved.packageId)); + } + return resolution; + } function resolveSingleModuleNameWithoutWatching(moduleName, containingFile) { const path = resolutionHost.toPath(containingFile); const resolutionsInFile = resolvedModuleNames.get(path); @@ -96440,62 +98346,15 @@ ${lanes.join("\n")} function isNodeModulesAtTypesDirectory(dirPath) { return endsWith(dirPath, "/node_modules/@types"); } - function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { - if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - failedLookupLocation = isRootedDiskPath(failedLookupLocation) ? normalizePath(failedLookupLocation) : getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); - const failedLookupPathSplit = failedLookupLocationPath.split(directorySeparator); - const failedLookupSplit = failedLookupLocation.split(directorySeparator); - Debug.assert(failedLookupSplit.length === failedLookupPathSplit.length, `FailedLookup: ${failedLookupLocation} failedLookupLocationPath: ${failedLookupLocationPath}`); - if (failedLookupPathSplit.length > rootSplitLength + 1) return { - dir: failedLookupSplit.slice(0, rootSplitLength + 1).join(directorySeparator), - dirPath: failedLookupPathSplit.slice(0, rootSplitLength + 1).join(directorySeparator) - }; - else return { - dir: rootDir, - dirPath: rootPath, - nonRecursive: false - }; - } - return getDirectoryToWatchFromFailedLookupLocationDirectory(getDirectoryPath(getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), getDirectoryPath(failedLookupLocationPath)); - } - function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { - while(pathContainsNodeModules(dirPath)){ - dir = getDirectoryPath(dir); - dirPath = getDirectoryPath(dirPath); - } - if (isNodeModulesDirectory(dirPath)) return canWatchDirectoryOrFile(getDirectoryPath(dirPath)) ? { - dir: dir, - dirPath: dirPath - } : void 0; - let nonRecursive = true; - let subDirectoryPath, subDirectory; - if (rootPath !== void 0) while(!isInDirectoryPath(dirPath, rootPath)){ - const parentPath = getDirectoryPath(dirPath); - if (parentPath === dirPath) break; - nonRecursive = false; - subDirectoryPath = dirPath; - subDirectory = dir; - dirPath = parentPath; - dir = getDirectoryPath(dir); - } - return canWatchDirectoryOrFile(dirPath) ? { - dir: subDirectory || dir, - dirPath: subDirectoryPath || dirPath, - nonRecursive: nonRecursive - } : void 0; - } - function isPathWithDefaultFailedLookupExtension(path) { - return fileExtensionIsOneOf(path, failedLookupDefaultExtensions); - } - function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName) { - var _a2, _b; + function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName, deferWatchingNonRelativeResolution) { + var _a; if (resolution.refCount) { resolution.refCount++; Debug.assertIsDefined(resolution.files); } else { resolution.refCount = 1; - Debug.assert(!((_a2 = resolution.files) == null ? void 0 : _a2.size)); - if (isExternalModuleNameRelative(name)) watchFailedLookupLocationOfResolution(resolution); + Debug.assert(!((_a = resolution.files) == null ? void 0 : _a.size)); + if (!deferWatchingNonRelativeResolution || isExternalModuleNameRelative(name)) watchFailedLookupLocationOfResolution(resolution); else nonRelativeExternalModuleResolutions.add(name, resolution); const resolved = getResolutionWithResolvedFileName(resolution); if (resolved && resolved.resolvedFileName) { @@ -96505,37 +98364,34 @@ ${lanes.join("\n")} resolutions.add(resolution); } } - ((_b = resolution.files) != null ? _b : resolution.files = /* @__PURE__ */ new Set()).add(filePath); + (resolution.files ?? (resolution.files = /* @__PURE__ */ new Set())).add(filePath); + } + function watchFailedLookupLocation(failedLookupLocation, setAtRoot) { + const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + const toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath, rootDir, rootPath, rootPathComponents, getCurrentDirectory); + if (toWatch) { + const { dir: dir, dirPath: dirPath, nonRecursive: nonRecursive } = toWatch; + if (dirPath === rootPath) { + Debug.assert(nonRecursive); + setAtRoot = true; + } else setDirectoryWatcher(dir, dirPath, nonRecursive); + } + return setAtRoot; } function watchFailedLookupLocationOfResolution(resolution) { Debug.assert(!!resolution.refCount); - const { failedLookupLocations: failedLookupLocations , affectingLocations: affectingLocations } = resolution; - if (!(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !(affectingLocations == null ? void 0 : affectingLocations.length)) return; - if (failedLookupLocations == null ? void 0 : failedLookupLocations.length) resolutionsWithFailedLookups.add(resolution); + const { failedLookupLocations: failedLookupLocations, affectingLocations: affectingLocations, node10Result: node10Result } = resolution; + if (!(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !(affectingLocations == null ? void 0 : affectingLocations.length) && !node10Result) return; + if ((failedLookupLocations == null ? void 0 : failedLookupLocations.length) || node10Result) resolutionsWithFailedLookups.add(resolution); let setAtRoot = false; - if (failedLookupLocations) { - for (const failedLookupLocation of failedLookupLocations){ - const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - const toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); - if (toWatch) { - const { dir: dir , dirPath: dirPath , nonRecursive: nonRecursive } = toWatch; - if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { - const refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0; - customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); - } - if (dirPath === rootPath) { - Debug.assert(!nonRecursive); - setAtRoot = true; - } else setDirectoryWatcher(dir, dirPath, nonRecursive); - } - } - if (setAtRoot) setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); - } - watchAffectingLocationsOfResolution(resolution, !(failedLookupLocations == null ? void 0 : failedLookupLocations.length)); + if (failedLookupLocations) for (const failedLookupLocation of failedLookupLocations)setAtRoot = watchFailedLookupLocation(failedLookupLocation, setAtRoot); + if (node10Result) setAtRoot = watchFailedLookupLocation(node10Result, setAtRoot); + if (setAtRoot) setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); + watchAffectingLocationsOfResolution(resolution, !(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !node10Result); } function watchAffectingLocationsOfResolution(resolution, addToResolutionsWithOnlyAffectingLocations) { Debug.assert(!!resolution.refCount); - const { affectingLocations: affectingLocations } = resolution; + const { affectingLocations: affectingLocations } = resolution; if (!(affectingLocations == null ? void 0 : affectingLocations.length)) return; if (addToResolutionsWithOnlyAffectingLocations) resolutionsWithOnlyAffectingLocations.add(resolution); for (const affectingLocation of affectingLocations)createFileWatcherOfAffectingLocation(affectingLocation, /*forResolution*/ true); @@ -96563,12 +98419,12 @@ ${lanes.join("\n")} } const paths = /* @__PURE__ */ new Set(); paths.add(locationToWatch); - let actualWatcher = canWatchDirectoryOrFile(resolutionHost.toPath(locationToWatch)) ? resolutionHost.watchAffectingFileLocation(locationToWatch, (fileName, eventKind)=>{ + let actualWatcher = canWatchAffectingLocation(resolutionHost.toPath(locationToWatch)) ? resolutionHost.watchAffectingFileLocation(locationToWatch, (fileName, eventKind)=>{ cachedDirectoryStructureHost == null || cachedDirectoryStructureHost.addOrDeleteFile(fileName, resolutionHost.toPath(locationToWatch), eventKind); const packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); paths.forEach((path)=>{ - if (watcher.resolutions) (affectingPathChecks != null ? affectingPathChecks : affectingPathChecks = /* @__PURE__ */ new Set()).add(path); - if (watcher.files) (affectingPathChecksForFile != null ? affectingPathChecksForFile : affectingPathChecksForFile = /* @__PURE__ */ new Set()).add(path); + if (watcher.resolutions) (affectingPathChecks ?? (affectingPathChecks = /* @__PURE__ */ new Set())).add(path); + if (watcher.files) (affectingPathChecksForFile ?? (affectingPathChecksForFile = /* @__PURE__ */ new Set())).add(path); packageJsonMap == null || packageJsonMap.delete(resolutionHost.toPath(path)); }); resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); @@ -96593,7 +98449,7 @@ ${lanes.join("\n")} function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { const program = resolutionHost.getCurrentProgram(); if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) resolutions.forEach(watchFailedLookupLocationOfResolution); - else resolutions.forEach((resolution)=>watchAffectingLocationsOfResolution(resolution, /*addToResolutionWithOnlyAffectingLocations*/ true)); + else resolutions.forEach((resolution)=>watchAffectingLocationsOfResolution(resolution, /*addToResolutionsWithOnlyAffectingLocations*/ true)); } function setDirectoryWatcher(dir, dirPath, nonRecursive) { const dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); @@ -96606,6 +98462,16 @@ ${lanes.join("\n")} nonRecursive: nonRecursive }); } + function stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot) { + const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + const toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath, rootDir, rootPath, rootPathComponents, getCurrentDirectory); + if (toWatch) { + const { dirPath: dirPath } = toWatch; + if (dirPath === rootPath) removeAtRoot = true; + else removeDirectoryWatcher(dirPath); + } + return removeAtRoot; + } function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) { Debug.checkDefined(resolution.files).delete(filePath); resolution.refCount--; @@ -96616,26 +98482,11 @@ ${lanes.join("\n")} const resolutions = resolvedFileToResolution.get(key); if ((resolutions == null ? void 0 : resolutions.delete(resolution)) && !resolutions.size) resolvedFileToResolution.delete(key); } - const { failedLookupLocations: failedLookupLocations , affectingLocations: affectingLocations } = resolution; + const { failedLookupLocations: failedLookupLocations, affectingLocations: affectingLocations, node10Result: node10Result } = resolution; if (resolutionsWithFailedLookups.delete(resolution)) { let removeAtRoot = false; - for (const failedLookupLocation of failedLookupLocations){ - const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - const toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); - if (toWatch) { - const { dirPath: dirPath } = toWatch; - const refCount = customFailedLookupPaths.get(failedLookupLocationPath); - if (refCount) { - if (refCount === 1) customFailedLookupPaths.delete(failedLookupLocationPath); - else { - Debug.assert(refCount > 1); - customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); - } - } - if (dirPath === rootPath) removeAtRoot = true; - else removeDirectoryWatcher(dirPath); - } - } + if (failedLookupLocations) for (const failedLookupLocation of failedLookupLocations)removeAtRoot = stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot); + if (node10Result) removeAtRoot = stopWatchFailedLookupLocation(node10Result, removeAtRoot); if (removeAtRoot) removeDirectoryWatcher(rootPath); } else if (affectingLocations == null ? void 0 : affectingLocations.length) resolutionsWithOnlyAffectingLocations.delete(resolution); if (affectingLocations) for (const affectingLocation of affectingLocations){ @@ -96680,7 +98531,7 @@ ${lanes.join("\n")} if (resolution.isInvalidated || !canInvalidate(resolution)) return; resolution.isInvalidated = invalidated = true; for (const containingFilePath of Debug.checkDefined(resolution.files)){ - (filesWithInvalidatedResolutions != null ? filesWithInvalidatedResolutions : filesWithInvalidatedResolutions = /* @__PURE__ */ new Set()).add(containingFilePath); + (filesWithInvalidatedResolutions ?? (filesWithInvalidatedResolutions = /* @__PURE__ */ new Set())).add(containingFilePath); hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames || endsWith(containingFilePath, inferredTypesContainingFile); } }); @@ -96707,22 +98558,36 @@ ${lanes.join("\n")} (failedLookupChecks || (failedLookupChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath); (startsWithPathChecks || (startsWithPathChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath); } else { - if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) return false; if (isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) return false; + if (fileExtensionIs(fileOrDirectoryPath, ".map")) return false; (failedLookupChecks || (failedLookupChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath); - const packagePath = parseNodeModuleFromPath(fileOrDirectoryPath); + const packagePath = parseNodeModuleFromPath(fileOrDirectoryPath, /*isFolder*/ true); if (packagePath) (startsWithPathChecks || (startsWithPathChecks = /* @__PURE__ */ new Set())).add(packagePath); } } resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } + function invalidatePackageJsonMap() { + const packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); + if (packageJsonMap && (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks)) packageJsonMap.forEach((_value, path)=>isInvalidatedFailedLookup(path) ? packageJsonMap.delete(path) : void 0); + } function invalidateResolutionsOfFailedLookupLocations() { - var _a2; + var _a; + if (allModuleAndTypeResolutionsAreInvalidated) { + affectingPathChecksForFile = void 0; + invalidatePackageJsonMap(); + if (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks || affectingPathChecks) invalidateResolutions(resolvedLibraries, canInvalidateFailedLookupResolution); + failedLookupChecks = void 0; + startsWithPathChecks = void 0; + isInDirectoryChecks = void 0; + affectingPathChecks = void 0; + return true; + } let invalidated = false; if (affectingPathChecksForFile) { - (_a2 = resolutionHost.getCurrentProgram()) == null || _a2.getSourceFiles().forEach((f)=>{ + (_a = resolutionHost.getCurrentProgram()) == null || _a.getSourceFiles().forEach((f)=>{ if (some(f.packageJsonLocations, (location)=>affectingPathChecksForFile.has(location))) { - (filesWithInvalidatedResolutions != null ? filesWithInvalidatedResolutions : filesWithInvalidatedResolutions = /* @__PURE__ */ new Set()).add(f.path); + (filesWithInvalidatedResolutions ?? (filesWithInvalidatedResolutions = /* @__PURE__ */ new Set())).add(f.path); invalidated = true; } }); @@ -96730,8 +98595,7 @@ ${lanes.join("\n")} } if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks && !affectingPathChecks) return invalidated; invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution) || invalidated; - const packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); - if (packageJsonMap && (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks)) packageJsonMap.forEach((_value, path)=>isInvalidatedFailedLookup(path) ? packageJsonMap.delete(path) : void 0); + invalidatePackageJsonMap(); failedLookupChecks = void 0; startsWithPathChecks = void 0; isInDirectoryChecks = void 0; @@ -96740,35 +98604,30 @@ ${lanes.join("\n")} return invalidated; } function canInvalidateFailedLookupResolution(resolution) { - var _a2; + var _a; if (canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution)) return true; if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) return false; - return (_a2 = resolution.failedLookupLocations) == null ? void 0 : _a2.some((location)=>isInvalidatedFailedLookup(resolutionHost.toPath(location))); + return ((_a = resolution.failedLookupLocations) == null ? void 0 : _a.some((location)=>isInvalidatedFailedLookup(resolutionHost.toPath(location)))) || !!resolution.node10Result && isInvalidatedFailedLookup(resolutionHost.toPath(resolution.node10Result)); } function isInvalidatedFailedLookup(locationPath) { - return (failedLookupChecks == null ? void 0 : failedLookupChecks.has(locationPath)) || firstDefinedIterator((startsWithPathChecks == null ? void 0 : startsWithPathChecks.keys()) || [], (fileOrDirectoryPath)=>startsWith(locationPath, fileOrDirectoryPath) ? true : void 0) || firstDefinedIterator((isInDirectoryChecks == null ? void 0 : isInDirectoryChecks.keys()) || [], (fileOrDirectoryPath)=>isInDirectoryPath(fileOrDirectoryPath, locationPath) ? true : void 0); + return (failedLookupChecks == null ? void 0 : failedLookupChecks.has(locationPath)) || firstDefinedIterator((startsWithPathChecks == null ? void 0 : startsWithPathChecks.keys()) || [], (fileOrDirectoryPath)=>startsWith(locationPath, fileOrDirectoryPath) ? true : void 0) || firstDefinedIterator((isInDirectoryChecks == null ? void 0 : isInDirectoryChecks.keys()) || [], (dirPath)=>locationPath.length > dirPath.length && startsWith(locationPath, dirPath) && (isDiskPathRoot(dirPath) || locationPath[dirPath.length] === directorySeparator) ? true : void 0); } function canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution) { - var _a2; - return !!affectingPathChecks && ((_a2 = resolution.affectingLocations) == null ? void 0 : _a2.some((location)=>affectingPathChecks.has(location))); + var _a; + return !!affectingPathChecks && ((_a = resolution.affectingLocations) == null ? void 0 : _a.some((location)=>affectingPathChecks.has(location))); } function closeTypeRootsWatch() { clearMap(typeRootsWatches, closeFileWatcher); } - function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) { - if (isInDirectoryPath(rootPath, typeRootPath)) return rootPath; - const toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath); - return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : void 0; - } function createTypeRootsWatch(typeRootPath, typeRoot) { - return resolutionHost.watchTypeRootsDirectory(typeRoot, (fileOrDirectory)=>{ + return canWatchTypeRootPath(typeRootPath) ? resolutionHost.watchTypeRootsDirectory(typeRoot, (fileOrDirectory)=>{ const fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); if (cachedDirectoryStructureHost) cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); hasChangedAutomaticTypeDirectiveNames = true; resolutionHost.onChangedAutomaticTypeDirectiveNames(); - const dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath); + const dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath, rootPath, rootPathComponents, getCurrentDirectory, (dirPath2)=>directoryWatchesOfFailedLookups.has(dirPath2)); if (dirPath) scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath); - }, 1 /* Recursive */ ); + }, 1 /* Recursive */ ) : noopFileWatcher; } function updateTypeRootsWatch() { const options = resolutionHost.getCompilationSettings(); @@ -96777,7 +98636,6 @@ ${lanes.join("\n")} return; } const typeRoots = getEffectiveTypeRoots(options, { - directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory }); if (typeRoots) mutateMap(typeRootsWatches, arrayToMap(typeRoots, (tr)=>resolutionHost.toPath(tr)), { @@ -96786,21 +98644,19 @@ ${lanes.join("\n")} }); else closeTypeRootsWatch(); } - function directoryExistsForTypeRootWatch(nodeTypesDirectory) { - const dir = getDirectoryPath(getDirectoryPath(nodeTypesDirectory)); - const dirPath = resolutionHost.toPath(dir); - return dirPath === rootPath || canWatchDirectoryOrFile(dirPath); + function canWatchTypeRootPath(typeRoot) { + if (resolutionHost.getCompilationSettings().typeRoots) return true; + return canWatchAtTypes(resolutionHost.toPath(typeRoot)); } } function resolutionIsSymlink(resolution) { - var _a2, _b; - return !!(((_a2 = resolution.resolvedModule) == null ? void 0 : _a2.originalPath) || ((_b = resolution.resolvedTypeReferenceDirective) == null ? void 0 : _b.originalPath)); + var _a, _b; + return !!(((_a = resolution.resolvedModule) == null ? void 0 : _a.originalPath) || ((_b = resolution.resolvedTypeReferenceDirective) == null ? void 0 : _b.originalPath)); } var init_resolutionCache = __esm({ "src/compiler/resolutionCache.ts" () { "use strict"; init_ts2(); - init_ts2(); } }); // src/compiler/watch.ts @@ -96836,7 +98692,7 @@ ${lanes.join("\n")} // - https://github.com/nodejs/node/issues/45753 system.now().toLocaleTimeString("en-US", { timeZone: "UTC" - }).replace(" ", " "); + }).replace("\u202F", " "); } function createWatchStatusReporter(system, pretty) { return pretty ? (diagnostic, newLine, options)=>{ @@ -96871,7 +98727,7 @@ ${lanes.join("\n")} if (fileName === void 0) return void 0; const diagnosticForFileName = find(diagnostics, (diagnostic)=>diagnostic.file !== void 0 && diagnostic.file.fileName === fileName); if (diagnosticForFileName !== void 0) { - const { line: line } = getLineAndCharacterOfPosition(diagnosticForFileName.file, diagnosticForFileName.start); + const { line: line } = getLineAndCharacterOfPosition(diagnosticForFileName.file, diagnosticForFileName.start); return { fileName: fileName, line: line + 1 @@ -96882,17 +98738,36 @@ ${lanes.join("\n")} function getWatchErrorSummaryDiagnosticMessage(errorCount) { return errorCount === 1 ? Diagnostics.Found_1_error_Watching_for_file_changes : Diagnostics.Found_0_errors_Watching_for_file_changes; } - function prettyPathForFileError(error, cwd) { - const line = formatColorAndReset(":" + error.line, "\x1b[90m" /* Grey */ ); - if (pathIsAbsolute(error.fileName) && pathIsAbsolute(cwd)) return getRelativePathFromDirectory(cwd, error.fileName, /* ignoreCase */ false) + line; - return error.fileName + line; + function prettyPathForFileError(error2, cwd) { + const line = formatColorAndReset(":" + error2.line, "\x1b[90m" /* Grey */ ); + if (pathIsAbsolute(error2.fileName) && pathIsAbsolute(cwd)) return getRelativePathFromDirectory(cwd, error2.fileName, /*ignoreCase*/ false) + line; + return error2.fileName + line; } function getErrorSummaryText(errorCount, filesInError, newLine, host) { if (errorCount === 0) return ""; const nonNilFiles = filesInError.filter((fileInError)=>fileInError !== void 0); const distinctFileNamesWithLines = nonNilFiles.map((fileInError)=>`${fileInError.fileName}:${fileInError.line}`).filter((value1, index, self)=>self.indexOf(value1) === index); const firstFileReference = nonNilFiles[0] && prettyPathForFileError(nonNilFiles[0], host.getCurrentDirectory()); - const d = errorCount === 1 ? createCompilerDiagnostic(filesInError[0] !== void 0 ? 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); + let messageAndArgs; + if (errorCount === 1) messageAndArgs = filesInError[0] !== void 0 ? [ + Diagnostics.Found_1_error_in_0, + firstFileReference + ] : [ + Diagnostics.Found_1_error + ]; + else messageAndArgs = distinctFileNamesWithLines.length === 0 ? [ + Diagnostics.Found_0_errors, + errorCount + ] : distinctFileNamesWithLines.length === 1 ? [ + Diagnostics.Found_0_errors_in_the_same_file_starting_at_Colon_1, + errorCount, + firstFileReference + ] : [ + Diagnostics.Found_0_errors_in_1_files, + errorCount, + distinctFileNamesWithLines.length + ]; + const d = createCompilerDiagnostic(...messageAndArgs); const suffix = distinctFileNamesWithLines.length > 1 ? createTabularErrorsDisplay(nonNilFiles, host) : ""; return `${newLine}${flattenDiagnosticMessageText(d.messageText, newLine)}${newLine}${newLine}${suffix}`; } @@ -96932,55 +98807,55 @@ ${lanes.join("\n")} }); } function explainFiles(program, write) { - var _a2, _b; + var _a, _b; const reasons = program.getFileIncludeReasons(); const relativeFileName = (fileName)=>convertToRelativePath(fileName, program.getCurrentDirectory(), program.getCanonicalFileName); for (const file of program.getSourceFiles()){ write(`${toFileName(file, relativeFileName)}`); - (_a2 = reasons.get(file.path)) == null || _a2.forEach((reason)=>write(` ${fileIncludeReasonToDiagnostics(program, reason, relativeFileName).messageText}`)); + (_a = reasons.get(file.path)) == null || _a.forEach((reason)=>write(` ${fileIncludeReasonToDiagnostics(program, reason, relativeFileName).messageText}`)); (_b = explainIfFileIsRedirectAndImpliedFormat(file, relativeFileName)) == null || _b.forEach((d)=>write(` ${d.messageText}`)); } } function explainIfFileIsRedirectAndImpliedFormat(file, fileNameConvertor) { - var _a2; + var _a; let result; - if (file.path !== file.resolvedPath) (result != null ? result : result = []).push(chainDiagnosticMessages(/*details*/ void 0, Diagnostics.File_is_output_of_project_reference_source_0, toFileName(file.originalFileName, fileNameConvertor))); - if (file.redirectInfo) (result != null ? result : result = []).push(chainDiagnosticMessages(/*details*/ void 0, Diagnostics.File_redirects_to_file_0, toFileName(file.redirectInfo.redirectTarget, fileNameConvertor))); + if (file.path !== file.resolvedPath) (result ?? (result = [])).push(chainDiagnosticMessages(/*details*/ void 0, Diagnostics.File_is_output_of_project_reference_source_0, toFileName(file.originalFileName, fileNameConvertor))); + if (file.redirectInfo) (result ?? (result = [])).push(chainDiagnosticMessages(/*details*/ void 0, Diagnostics.File_redirects_to_file_0, toFileName(file.redirectInfo.redirectTarget, fileNameConvertor))); if (isExternalOrCommonJsModule(file)) switch(file.impliedNodeFormat){ case 99 /* ESNext */ : - if (file.packageJsonScope) (result != null ? result : result = []).push(chainDiagnosticMessages(/*details*/ void 0, Diagnostics.File_is_ECMAScript_module_because_0_has_field_type_with_value_module, toFileName(last(file.packageJsonLocations), fileNameConvertor))); + if (file.packageJsonScope) (result ?? (result = [])).push(chainDiagnosticMessages(/*details*/ void 0, Diagnostics.File_is_ECMAScript_module_because_0_has_field_type_with_value_module, toFileName(last(file.packageJsonLocations), fileNameConvertor))); break; case 1 /* CommonJS */ : - if (file.packageJsonScope) (result != null ? result : result = []).push(chainDiagnosticMessages(/*details*/ void 0, file.packageJsonScope.contents.packageJsonContent.type ? Diagnostics.File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module : Diagnostics.File_is_CommonJS_module_because_0_does_not_have_field_type, toFileName(last(file.packageJsonLocations), fileNameConvertor))); - else if ((_a2 = file.packageJsonLocations) == null ? void 0 : _a2.length) (result != null ? result : result = []).push(chainDiagnosticMessages(/*details*/ void 0, Diagnostics.File_is_CommonJS_module_because_package_json_was_not_found)); + if (file.packageJsonScope) (result ?? (result = [])).push(chainDiagnosticMessages(/*details*/ void 0, file.packageJsonScope.contents.packageJsonContent.type ? Diagnostics.File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module : Diagnostics.File_is_CommonJS_module_because_0_does_not_have_field_type, toFileName(last(file.packageJsonLocations), fileNameConvertor))); + else if ((_a = file.packageJsonLocations) == null ? void 0 : _a.length) (result ?? (result = [])).push(chainDiagnosticMessages(/*details*/ void 0, Diagnostics.File_is_CommonJS_module_because_package_json_was_not_found)); break; } return result; } function getMatchedFileSpec(program, fileName) { - var _a2; + var _a; const configFile = program.getCompilerOptions().configFile; - if (!((_a2 = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _a2.validatedFilesSpec)) return void 0; + if (!((_a = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _a.validatedFilesSpec)) return void 0; const filePath = program.getCanonicalFileName(fileName); const basePath = getDirectoryPath(getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory())); return find(configFile.configFileSpecs.validatedFilesSpec, (fileSpec)=>program.getCanonicalFileName(getNormalizedAbsolutePath(fileSpec, basePath)) === filePath); } function getMatchedIncludeSpec(program, fileName) { - var _a2, _b; + var _a, _b; const configFile = program.getCompilerOptions().configFile; - if (!((_a2 = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _a2.validatedIncludeSpecs)) return void 0; + if (!((_a = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _a.validatedIncludeSpecs)) return void 0; if (configFile.configFileSpecs.isDefaultIncludeSpec) return true; const isJsonFile = fileExtensionIs(fileName, ".json" /* Json */ ); const basePath = getDirectoryPath(getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory())); - const useCaseSensitiveFileNames = program.useCaseSensitiveFileNames(); + const useCaseSensitiveFileNames2 = program.useCaseSensitiveFileNames(); return find((_b = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _b.validatedIncludeSpecs, (includeSpec)=>{ if (isJsonFile && !endsWith(includeSpec, ".json" /* Json */ )) return false; const pattern = getPatternFromSpec(includeSpec, basePath, "files"); - return !!pattern && getRegexFromPattern(`(${pattern})$`, useCaseSensitiveFileNames).test(fileName); + return !!pattern && getRegexFromPattern(`(${pattern})$`, useCaseSensitiveFileNames2).test(fileName); }); } function fileIncludeReasonToDiagnostics(program, reason, fileNameConvertor) { - var _a2, _b; + var _a, _b; const options = program.getCompilerOptions(); if (isReferencedFile(reason)) { const referenceLocation = getReferencedFileLocation((path)=>program.getSourceFileByPath(path), reason); @@ -97011,7 +98886,7 @@ ${lanes.join("\n")} } switch(reason.kind){ case 0 /* RootFile */ : - if (!((_a2 = options.configFile) == null ? void 0 : _a2.configFileSpecs)) return chainDiagnosticMessages(/*details*/ void 0, Diagnostics.Root_file_specified_for_compilation); + if (!((_a = options.configFile) == null ? void 0 : _a.configFileSpecs)) return chainDiagnosticMessages(/*details*/ void 0, Diagnostics.Root_file_specified_for_compilation); const fileName = getNormalizedAbsolutePath(program.getRootFileNames()[reason.index], program.getCurrentDirectory()); const matchedByFiles = getMatchedFileSpec(program, fileName); if (matchedByFiles) return chainDiagnosticMessages(/*details*/ void 0, Diagnostics.Part_of_files_list_in_tsconfig_json); @@ -97024,11 +98899,36 @@ ${lanes.join("\n")} const referencedResolvedRef = Debug.checkDefined((_b = program.getResolvedProjectReferences()) == null ? void 0 : _b[reason.index]); return chainDiagnosticMessages(/*details*/ void 0, outFile(options) ? isOutput ? Diagnostics.Output_from_referenced_project_0_included_because_1_specified : Diagnostics.Source_from_referenced_project_0_included_because_1_specified : isOutput ? Diagnostics.Output_from_referenced_project_0_included_because_module_is_specified_as_none : Diagnostics.Source_from_referenced_project_0_included_because_module_is_specified_as_none, toFileName(referencedResolvedRef.sourceFile.fileName, fileNameConvertor), options.outFile ? "--outFile" : "--out"); case 8 /* AutomaticTypeDirectiveFile */ : - return chainDiagnosticMessages(/*details*/ void 0, options.types ? reason.packageId ? Diagnostics.Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1 : Diagnostics.Entry_point_of_type_library_0_specified_in_compilerOptions : reason.packageId ? Diagnostics.Entry_point_for_implicit_type_library_0_with_packageId_1 : Diagnostics.Entry_point_for_implicit_type_library_0, reason.typeReference, reason.packageId && packageIdToString(reason.packageId)); + { + const messageAndArgs = options.types ? reason.packageId ? [ + Diagnostics.Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1, + reason.typeReference, + packageIdToString(reason.packageId) + ] : [ + Diagnostics.Entry_point_of_type_library_0_specified_in_compilerOptions, + reason.typeReference + ] : reason.packageId ? [ + Diagnostics.Entry_point_for_implicit_type_library_0_with_packageId_1, + reason.typeReference, + packageIdToString(reason.packageId) + ] : [ + Diagnostics.Entry_point_for_implicit_type_library_0, + reason.typeReference + ]; + return chainDiagnosticMessages(/*details*/ void 0, ...messageAndArgs); + } case 6 /* LibFile */ : - if (reason.index !== void 0) return chainDiagnosticMessages(/*details*/ void 0, Diagnostics.Library_0_specified_in_compilerOptions, options.lib[reason.index]); - const target = forEachEntry(targetOptionDeclaration.type, (value1, key)=>value1 === getEmitScriptTarget(options) ? key : void 0); - return chainDiagnosticMessages(/*details*/ void 0, target ? Diagnostics.Default_library_for_target_0 : Diagnostics.Default_library, target); + { + if (reason.index !== void 0) return chainDiagnosticMessages(/*details*/ void 0, Diagnostics.Library_0_specified_in_compilerOptions, options.lib[reason.index]); + const target = forEachEntry(targetOptionDeclaration.type, (value1, key)=>value1 === getEmitScriptTarget(options) ? key : void 0); + const messageAndArgs = target ? [ + Diagnostics.Default_library_for_target_0, + target + ] : [ + Diagnostics.Default_library + ]; + return chainDiagnosticMessages(/*details*/ void 0, ...messageAndArgs); + } default: Debug.assertNever(reason); } @@ -97053,7 +98953,7 @@ ${lanes.join("\n")} emitSkipped: true, diagnostics: emptyArray } : program.emit(/*targetSourceFile*/ void 0, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers); - const { emittedFiles: emittedFiles , diagnostics: emitDiagnostics } = emitResult; + const { emittedFiles: emittedFiles, diagnostics: emitDiagnostics } = emitResult; addRange(allDiagnostics, emitDiagnostics); const diagnostics = sortAndDeduplicateDiagnostics(allDiagnostics); diagnostics.forEach(reportDiagnostic); @@ -97072,7 +98972,7 @@ ${lanes.join("\n")} }; } function emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic, write, reportSummary, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers) { - const { emitResult: emitResult , diagnostics: diagnostics } = emitFilesAndReportErrors(program, reportDiagnostic, write, reportSummary, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers); + const { emitResult: emitResult, diagnostics: diagnostics } = emitFilesAndReportErrors(program, reportDiagnostic, write, reportSummary, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers); if (emitResult.emitSkipped && diagnostics.length > 0) return 1 /* DiagnosticsPresent_OutputsSkipped */ ; else if (diagnostics.length > 0) return 2 /* DiagnosticsPresent_OutputsGenerated */ ; return 0 /* Success */ ; @@ -97095,15 +98995,15 @@ ${lanes.join("\n")} return result; } function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost = host) { - const useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + const useCaseSensitiveFileNames2 = host.useCaseSensitiveFileNames(); const compilerHost = { getSourceFile: createGetSourceFile((fileName, encoding)=>!encoding ? compilerHost.readFile(fileName) : host.readFile(fileName, encoding), getCompilerOptions, /*setParentNodes*/ void 0), getDefaultLibLocation: maybeBind(host, host.getDefaultLibLocation), getDefaultLibFileName: (options)=>host.getDefaultLibFileName(options), writeFile: createWriteFileMeasuringIO((path, data, writeByteOrderMark)=>host.writeFile(path, data, writeByteOrderMark), (path)=>host.createDirectory(path), (path)=>host.directoryExists(path)), getCurrentDirectory: memoize(()=>host.getCurrentDirectory()), - useCaseSensitiveFileNames: ()=>useCaseSensitiveFileNames, - getCanonicalFileName: createGetCanonicalFileName(useCaseSensitiveFileNames), + useCaseSensitiveFileNames: ()=>useCaseSensitiveFileNames2, + getCanonicalFileName: createGetCanonicalFileName(useCaseSensitiveFileNames2), getNewLine: ()=>getNewLineCharacter(getCompilerOptions()), fileExists: (f)=>host.fileExists(f), readFile: (f)=>host.readFile(f), @@ -97193,7 +99093,7 @@ ${lanes.join("\n")} reportDiagnostic(diagnostic); system.exit(1 /* DiagnosticsPresent_OutputsSkipped */ ); } - function createWatchCompilerHostOfConfigFile({ configFileName: configFileName , optionsToExtend: optionsToExtend , watchOptionsToExtend: watchOptionsToExtend , extraFileExtensions: extraFileExtensions , system: system , createProgram: createProgram2 , reportDiagnostic: reportDiagnostic , reportWatchStatus: reportWatchStatus2 }) { + function createWatchCompilerHostOfConfigFile({ configFileName: configFileName, optionsToExtend: optionsToExtend, watchOptionsToExtend: watchOptionsToExtend, extraFileExtensions: extraFileExtensions, system: system, createProgram: createProgram2, reportDiagnostic: reportDiagnostic, reportWatchStatus: reportWatchStatus2 }) { const diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); const host = createWatchCompilerHost(system, createProgram2, diagnosticReporter, reportWatchStatus2); host.onUnRecoverableConfigFileDiagnostic = (diagnostic)=>reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); @@ -97203,7 +99103,7 @@ ${lanes.join("\n")} host.extraFileExtensions = extraFileExtensions; return host; } - function createWatchCompilerHostOfFilesAndCompilerOptions({ rootFiles: rootFiles , options: options , watchOptions: watchOptions , projectReferences: projectReferences , system: system , createProgram: createProgram2 , reportDiagnostic: reportDiagnostic , reportWatchStatus: reportWatchStatus2 }) { + function createWatchCompilerHostOfFilesAndCompilerOptions({ rootFiles: rootFiles, options: options, watchOptions: watchOptions, projectReferences: projectReferences, system: system, createProgram: createProgram2, reportDiagnostic: reportDiagnostic, reportWatchStatus: reportWatchStatus2 }) { const host = createWatchCompilerHost(system, createProgram2, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus2); host.rootFiles = rootFiles; host.options = options; @@ -97256,7 +99156,9 @@ ${lanes.join("\n")} MissingSourceMapFile: "Missing source map file", NoopConfigFileForInferredRoot: "Noop Config file for the inferred project root", MissingGeneratedFile: "Missing generated file", - NodeModulesForModuleSpecifierCache: "node_modules for module specifier cache invalidation" + NodeModulesForModuleSpecifierCache: "node_modules for module specifier cache invalidation", + TypingInstallerLocationFile: "File location for typing installer", + TypingInstallerLocationDirectory: "Directory location for typing installer" }; } }); @@ -97282,7 +99184,7 @@ ${lanes.join("\n")} changeCompilerHostLikeToUseCache(host, (fileName)=>toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName)); return host; } - function createIncrementalProgram({ rootNames: rootNames , options: options , configFileParsingDiagnostics: configFileParsingDiagnostics , projectReferences: projectReferences , host: host , createProgram: createProgram2 }) { + function createIncrementalProgram({ rootNames: rootNames, options: options, configFileParsingDiagnostics: configFileParsingDiagnostics, projectReferences: projectReferences, host: host, createProgram: createProgram2 }) { host = host || createIncrementalCompilerHost(options); createProgram2 = createProgram2 || createEmitAndSemanticDiagnosticsBuilderProgram; const oldProgram = readBuilderProgram(options, host); @@ -97324,15 +99226,15 @@ ${lanes.join("\n")} const sourceFilesCache = /* @__PURE__ */ new Map(); let missingFilePathsRequestedForRelease; let hasChangedCompilerOptions = false; - const useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + const useCaseSensitiveFileNames2 = host.useCaseSensitiveFileNames(); const currentDirectory = host.getCurrentDirectory(); - const { configFileName: configFileName , optionsToExtend: optionsToExtendForConfigFile = {} , watchOptionsToExtend: watchOptionsToExtend , extraFileExtensions: extraFileExtensions , createProgram: createProgram2 } = host; - let { rootFiles: rootFileNames , options: compilerOptions , watchOptions: watchOptions , projectReferences: projectReferences } = host; + const { configFileName: configFileName, optionsToExtend: optionsToExtendForConfigFile = {}, watchOptionsToExtend: watchOptionsToExtend, extraFileExtensions: extraFileExtensions, createProgram: createProgram2 } = host; + let { rootFiles: rootFileNames, options: compilerOptions, watchOptions: watchOptions, projectReferences: projectReferences } = host; let wildcardDirectories; let configFileParsingDiagnostics; let canConfigFileJsonReportNoInputFiles = false; let hasChangedConfigFileParsingErrors = false; - const cachedDirectoryStructureHost = configFileName === void 0 ? void 0 : createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + const cachedDirectoryStructureHost = configFileName === void 0 ? void 0 : createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames2); const directoryStructureHost = cachedDirectoryStructureHost || host; const parseConfigFileHost = parseConfigHostFromCompilerHostLike(host, directoryStructureHost); let newLine = updateNewLine(); @@ -97349,9 +99251,9 @@ ${lanes.join("\n")} } Debug.assert(compilerOptions); Debug.assert(rootFileNames); - const { watchFile: watchFile2 , watchDirectory: watchDirectory , writeLog: writeLog } = createWatchFactory(host, compilerOptions); - const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); - writeLog(`Current directory: ${currentDirectory} CaseSensitiveFileNames: ${useCaseSensitiveFileNames}`); + const { watchFile: watchFile2, watchDirectory: watchDirectory, writeLog: writeLog } = createWatchFactory(host, compilerOptions); + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); + writeLog(`Current directory: ${currentDirectory} CaseSensitiveFileNames: ${useCaseSensitiveFileNames2}`); let configFileWatcher; if (configFileName) configFileWatcher = watchFile2(configFileName, scheduleProgramReload, 2e3 /* High */ , watchOptions, WatchType.ConfigFile); const compilerHost = createCompilerHostFromProgramHost(host, ()=>compilerOptions, directoryStructureHost); @@ -97384,9 +99286,11 @@ ${lanes.join("\n")} compilerHost.resolveTypeReferenceDirectiveReferences = maybeBind(host, host.resolveTypeReferenceDirectiveReferences); compilerHost.resolveTypeReferenceDirectives = maybeBind(host, host.resolveTypeReferenceDirectives); if (!compilerHost.resolveTypeReferenceDirectiveReferences && !compilerHost.resolveTypeReferenceDirectives) compilerHost.resolveTypeReferenceDirectiveReferences = resolutionCache.resolveTypeReferenceDirectiveReferences.bind(resolutionCache); + compilerHost.resolveLibrary = !host.resolveLibrary ? resolutionCache.resolveLibrary.bind(resolutionCache) : host.resolveLibrary.bind(host); compilerHost.getModuleResolutionCache = host.resolveModuleNameLiterals || host.resolveModuleNames ? maybeBind(host, host.getModuleResolutionCache) : ()=>resolutionCache.getModuleResolutionCache(); const userProvidedResolution = !!host.resolveModuleNameLiterals || !!host.resolveTypeReferenceDirectiveReferences || !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; const customHasInvalidatedResolutions = userProvidedResolution ? maybeBind(host, host.hasInvalidatedResolutions) || returnTrue : returnFalse; + const customHasInvalidLibResolutions = host.resolveLibrary ? maybeBind(host, host.hasInvalidatedLibResolutions) || returnTrue : returnFalse; builderProgram = readBuilderProgram(compilerOptions, compilerHost); synchronizeProgram(); watchConfigFileWildCardDirectories(); @@ -97430,8 +99334,8 @@ ${lanes.join("\n")} } if (parsedConfigs) { clearMap(parsedConfigs, (config)=>{ - var _a2; - (_a2 = config.watcher) == null || _a2.close(); + var _a; + (_a = config.watcher) == null || _a.close(); config.watcher = void 0; if (config.watchedDirectories) clearMap(config.watchedDirectories, closeFileWatcherOf); config.watchedDirectories = void 0; @@ -97453,11 +99357,11 @@ ${lanes.join("\n")} const program = getCurrentBuilderProgram(); if (hasChangedCompilerOptions) { newLine = updateNewLine(); - if (program && changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) resolutionCache.clear(); + if (program && changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) resolutionCache.onChangesAffectModuleResolution(); } - const hasInvalidatedResolutions = resolutionCache.createHasInvalidatedResolutions(customHasInvalidatedResolutions); - const { originalReadFile: originalReadFile , originalFileExists: originalFileExists , originalDirectoryExists: originalDirectoryExists , originalCreateDirectory: originalCreateDirectory , originalWriteFile: originalWriteFile , readFileWithCache: readFileWithCache } = changeCompilerHostLikeToUseCache(compilerHost, toPath3); - if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, (path)=>getSourceVersion(path, readFileWithCache), (fileName)=>compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { + const { hasInvalidatedResolutions: hasInvalidatedResolutions, hasInvalidatedLibResolutions: hasInvalidatedLibResolutions } = resolutionCache.createHasInvalidatedResolutions(customHasInvalidatedResolutions, customHasInvalidLibResolutions); + const { originalReadFile: originalReadFile, originalFileExists: originalFileExists, originalDirectoryExists: originalDirectoryExists, originalCreateDirectory: originalCreateDirectory, originalWriteFile: originalWriteFile, readFileWithCache: readFileWithCache } = changeCompilerHostLikeToUseCache(compilerHost, toPath3); + if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, (path)=>getSourceVersion(path, readFileWithCache), (fileName)=>compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { if (reportFileChangeDetectedOnCreateProgram) reportWatchDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation); builderProgram = createProgram2(/*rootNames*/ void 0, /*options*/ void 0, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); @@ -97465,7 +99369,7 @@ ${lanes.join("\n")} } } else { if (reportFileChangeDetectedOnCreateProgram) reportWatchDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation); - createNewProgram(hasInvalidatedResolutions); + createNewProgram(hasInvalidatedResolutions, hasInvalidatedLibResolutions); } reportFileChangeDetectedOnCreateProgram = false; if (host.afterProgramCreate && program !== builderProgram) host.afterProgramCreate(builderProgram); @@ -97476,7 +99380,7 @@ ${lanes.join("\n")} compilerHost.writeFile = originalWriteFile; return builderProgram; } - function createNewProgram(hasInvalidatedResolutions) { + function createNewProgram(hasInvalidatedResolutions, hasInvalidatedLibResolutions) { writeLog("CreatingProgramWith::"); writeLog(` roots: ${JSON.stringify(rootFileNames)}`); writeLog(` options: ${JSON.stringify(compilerOptions)}`); @@ -97486,6 +99390,7 @@ ${lanes.join("\n")} hasChangedConfigFileParsingErrors = false; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolutions = hasInvalidatedResolutions; + compilerHost.hasInvalidatedLibResolutions = hasInvalidatedLibResolutions; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; const oldProgram = getCurrentProgram(); builderProgram = createProgram2(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); @@ -97522,7 +99427,8 @@ ${lanes.join("\n")} function getVersionedSourceFileByPath(fileName, path, languageVersionOrOptions, onError, shouldCreateNewSourceFile) { const hostSourceFile = sourceFilesCache.get(path); if (isFileMissingOnHost(hostSourceFile)) return void 0; - if (hostSourceFile === void 0 || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) { + const impliedNodeFormat = typeof languageVersionOrOptions === "object" ? languageVersionOrOptions.impliedNodeFormat : void 0; + if (hostSourceFile === void 0 || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile) || hostSourceFile.sourceFile.impliedNodeFormat !== impliedNodeFormat) { const sourceFile = getNewSourceFile(fileName, languageVersionOrOptions, onError); if (hostSourceFile) { if (sourceFile) { @@ -97588,7 +99494,7 @@ ${lanes.join("\n")} if (!host.setTimeout || !host.clearTimeout) return resolutionCache.invalidateResolutionsOfFailedLookupLocations(); const pending = clearInvalidateResolutionsOfFailedLookupLocations(); writeLog(`Scheduling invalidateFailedLookup${pending ? ", Cancelled earlier one" : ""}`); - timerToInvalidateFailedLookupResolutions = host.setTimeout(invalidateResolutionsOfFailedLookup, 250); + timerToInvalidateFailedLookupResolutions = host.setTimeout(invalidateResolutionsOfFailedLookup, 250, "timerToInvalidateFailedLookupResolutions"); } function invalidateResolutionsOfFailedLookup() { timerToInvalidateFailedLookupResolutions = void 0; @@ -97598,7 +99504,7 @@ ${lanes.join("\n")} if (!host.setTimeout || !host.clearTimeout) return; if (timerToUpdateProgram) host.clearTimeout(timerToUpdateProgram); writeLog("Scheduling update"); - timerToUpdateProgram = host.setTimeout(updateProgramWithWatchStatus, 250); + timerToUpdateProgram = host.setTimeout(updateProgramWithWatchStatus, 250, "timerToUpdateProgram"); } function scheduleProgramReload() { Debug.assert(!!configFileName); @@ -97611,21 +99517,22 @@ ${lanes.join("\n")} updateProgram(); } function updateProgram() { + var _a, _b, _c, _d; switch(reloadLevel){ case 1 /* Partial */ : - perfLogger.logStartUpdateProgram("PartialConfigReload"); + (_a = perfLogger) == null || _a.logStartUpdateProgram("PartialConfigReload"); reloadFileNamesFromConfigFile(); break; case 2 /* Full */ : - perfLogger.logStartUpdateProgram("FullConfigReload"); + (_b = perfLogger) == null || _b.logStartUpdateProgram("FullConfigReload"); reloadConfigFile(); break; default: - perfLogger.logStartUpdateProgram("SynchronizeProgram"); + (_c = perfLogger) == null || _c.logStartUpdateProgram("SynchronizeProgram"); synchronizeProgram(); break; } - perfLogger.logStopUpdateProgram("Done"); + (_d = perfLogger) == null || _d.logStopUpdateProgram("Done"); return getCurrentBuilderProgram(); } function reloadFileNamesFromConfigFile() { @@ -97698,13 +99605,13 @@ ${lanes.join("\n")} return parsedCommandLine; } function onReleaseParsedCommandLine(fileName) { - var _a2; + var _a; const path = toPath3(fileName); const config = parsedConfigs == null ? void 0 : parsedConfigs.get(path); if (!config) return; parsedConfigs.delete(path); if (config.watchedDirectories) clearMap(config.watchedDirectories, closeFileWatcherOf); - (_a2 = config.watcher) == null || _a2.close(); + (_a = config.watcher) == null || _a.close(); clearSharedExtendedConfigFileWatcher(path, sharedExtendedConfigFileWatchers); } function watchFilePath(path, file, callback, pollingInterval, options, watchType) { @@ -97751,7 +99658,7 @@ ${lanes.join("\n")} options: compilerOptions, program: getCurrentBuilderProgram() || rootFileNames, currentDirectory: currentDirectory, - useCaseSensitiveFileNames: useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, writeLog: writeLog, toPath: toPath3 })) return; @@ -97763,10 +99670,10 @@ ${lanes.join("\n")} } function updateExtendedConfigFilesWatches(forProjectPath, options, watchOptions2, watchType) { updateSharedExtendedConfigFileWatcher(forProjectPath, options, sharedExtendedConfigFileWatchers || (sharedExtendedConfigFileWatchers = /* @__PURE__ */ new Map()), (extendedConfigFileName, extendedConfigFilePath)=>watchFile2(extendedConfigFileName, (_fileName, eventKind)=>{ - var _a2; + var _a; updateCachedSystemWithFile(extendedConfigFileName, extendedConfigFilePath, eventKind); if (extendedConfigCache) cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath3); - const projects = (_a2 = sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)) == null ? void 0 : _a2.projects; + const projects = (_a = sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)) == null ? void 0 : _a.projects; if (!(projects == null ? void 0 : projects.size)) return; projects.forEach((projectPath)=>{ if (configFileName && toPath3(configFileName) === projectPath) reloadLevel = 2 /* Full */ ; @@ -97780,16 +99687,16 @@ ${lanes.join("\n")} }, 2e3 /* High */ , watchOptions2, watchType), toPath3); } function watchReferencedProject(configFileName2, configPath, commandLine) { - var _a2, _b, _c, _d, _e; + var _a, _b, _c, _d, _e; commandLine.watcher || (commandLine.watcher = watchFile2(configFileName2, (_fileName, eventKind)=>{ updateCachedSystemWithFile(configFileName2, configPath, eventKind); const config = parsedConfigs == null ? void 0 : parsedConfigs.get(configPath); if (config) config.reloadLevel = 2 /* Full */ ; resolutionCache.removeResolutionsFromProjectReferenceRedirects(configPath); scheduleProgramUpdate(); - }, 2e3 /* High */ , ((_a2 = commandLine.parsedCommandLine) == null ? void 0 : _a2.watchOptions) || watchOptions, WatchType.ConfigFileOfReferencedProject)); + }, 2e3 /* High */ , ((_a = commandLine.parsedCommandLine) == null ? void 0 : _a.watchOptions) || watchOptions, WatchType.ConfigFileOfReferencedProject)); if ((_b = commandLine.parsedCommandLine) == null ? void 0 : _b.wildcardDirectories) updateWatchingWildcardDirectories(commandLine.watchedDirectories || (commandLine.watchedDirectories = /* @__PURE__ */ new Map()), new Map(Object.entries((_c = commandLine.parsedCommandLine) == null ? void 0 : _c.wildcardDirectories)), (directory, flags)=>{ - var _a3; + var _a2; return watchDirectory(directory, (fileOrDirectory)=>{ const fileOrDirectoryPath = toPath3(fileOrDirectory); if (cachedDirectoryStructureHost) cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); @@ -97804,7 +99711,7 @@ ${lanes.join("\n")} options: config.parsedCommandLine.options, program: config.parsedCommandLine.fileNames, currentDirectory: currentDirectory, - useCaseSensitiveFileNames: useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, writeLog: writeLog, toPath: toPath3 })) return; @@ -97812,7 +99719,7 @@ ${lanes.join("\n")} config.reloadLevel = 1 /* Partial */ ; scheduleProgramUpdate(); } - }, flags, ((_a3 = commandLine.parsedCommandLine) == null ? void 0 : _a3.watchOptions) || watchOptions, WatchType.WildcardDirectoryOfReferencedProject); + }, flags, ((_a2 = commandLine.parsedCommandLine) == null ? void 0 : _a2.watchOptions) || watchOptions, WatchType.WildcardDirectoryOfReferencedProject); }); else if (commandLine.watchedDirectories) { clearMap(commandLine.watchedDirectories, closeFileWatcherOf); @@ -97825,7 +99732,6 @@ ${lanes.join("\n")} "src/compiler/watchPublic.ts" () { "use strict"; init_ts2(); - init_ts2(); } }); // src/compiler/tsbuild.ts @@ -97933,6 +99839,7 @@ ${lanes.join("\n")} compilerHost.getParsedCommandLine = (fileName)=>parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); compilerHost.resolveModuleNameLiterals = maybeBind(host, host.resolveModuleNameLiterals); compilerHost.resolveTypeReferenceDirectiveReferences = maybeBind(host, host.resolveTypeReferenceDirectiveReferences); + compilerHost.resolveLibrary = maybeBind(host, host.resolveLibrary); compilerHost.resolveModuleNames = maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = maybeBind(host, host.resolveTypeReferenceDirectives); compilerHost.getModuleResolutionCache = maybeBind(host, host.getModuleResolutionCache); @@ -97946,8 +99853,13 @@ ${lanes.join("\n")} typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache(compilerHost.getCurrentDirectory(), compilerHost.getCanonicalFileName, /*options*/ void 0, moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); compilerHost.resolveTypeReferenceDirectiveReferences = (typeDirectiveNames, containingFile, redirectedReference, options2, containingSourceFile)=>loadWithModeAwareCache(typeDirectiveNames, containingFile, redirectedReference, options2, containingSourceFile, host, typeReferenceDirectiveResolutionCache, createTypeReferenceResolutionLoader); } + let libraryResolutionCache; + if (!compilerHost.resolveLibrary) { + libraryResolutionCache = createModuleResolutionCache(compilerHost.getCurrentDirectory(), compilerHost.getCanonicalFileName, /*options*/ void 0, moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); + compilerHost.resolveLibrary = (libraryName, resolveFrom, options2)=>resolveLibrary(libraryName, resolveFrom, options2, host, libraryResolutionCache); + } compilerHost.getBuildInfo = (fileName, configFilePath)=>getBuildInfo3(state, fileName, toResolvedConfigFilePath(state, configFilePath), /*modifiedTime*/ void 0); - const { watchFile: watchFile2 , watchDirectory: watchDirectory , writeLog: writeLog } = createWatchFactory(hostWithWatch, options); + const { watchFile: watchFile2, watchDirectory: watchDirectory, writeLog: writeLog } = createWatchFactory(hostWithWatch, options); const state = { host: host, hostWithWatch: hostWithWatch, @@ -97971,6 +99883,7 @@ ${lanes.join("\n")} compilerHost: compilerHost, moduleResolutionCache: moduleResolutionCache, typeReferenceDirectiveResolutionCache: typeReferenceDirectiveResolutionCache, + libraryResolutionCache: libraryResolutionCache, // Mutable state buildOrder: void 0, readFileWithCache: (f)=>host.readFile(f), @@ -98000,7 +99913,7 @@ ${lanes.join("\n")} return toPath(fileName, state.compilerHost.getCurrentDirectory(), state.compilerHost.getCanonicalFileName); } function toResolvedConfigFilePath(state, fileName) { - const { resolvedConfigFilePaths: resolvedConfigFilePaths } = state; + const { resolvedConfigFilePaths: resolvedConfigFilePaths } = state; const path = resolvedConfigFilePaths.get(fileName); if (path !== void 0) return path; const resolvedPath = toPath2(state, fileName); @@ -98015,12 +99928,12 @@ ${lanes.join("\n")} return value1 && isParsedCommandLine(value1) ? value1 : void 0; } function parseConfigFile(state, configFileName, configFilePath) { - const { configFileCache: configFileCache } = state; + const { configFileCache: configFileCache } = state; const value1 = configFileCache.get(configFilePath); if (value1) return isParsedCommandLine(value1) ? value1 : void 0; mark("SolutionBuilder::beforeConfigFileParsing"); let diagnostic; - const { parseConfigFileHost: parseConfigFileHost , baseCompilerOptions: baseCompilerOptions , baseWatchOptions: baseWatchOptions , extendedConfigCache: extendedConfigCache , host: host } = state; + const { parseConfigFileHost: parseConfigFileHost, baseCompilerOptions: baseCompilerOptions, baseWatchOptions: baseWatchOptions, extendedConfigCache: extendedConfigCache, host: host } = state; let parsed; if (host.getParsedCommandLine) { parsed = host.getParsedCommandLine(configFileName); @@ -98130,10 +100043,10 @@ ${lanes.join("\n")} } function enableCache(state) { if (state.cache) disableCache(state); - const { compilerHost: compilerHost , host: host } = state; + const { compilerHost: compilerHost, host: host } = state; const originalReadFileWithCache = state.readFileWithCache; const originalGetSourceFile = compilerHost.getSourceFile; - const { originalReadFile: originalReadFile , originalFileExists: originalFileExists , originalDirectoryExists: originalDirectoryExists , originalCreateDirectory: originalCreateDirectory , originalWriteFile: originalWriteFile , getSourceFileWithCache: getSourceFileWithCache , readFileWithCache: readFileWithCache } = changeCompilerHostLikeToUseCache(host, (fileName)=>toPath2(state, fileName), (...args)=>originalGetSourceFile.call(compilerHost, ...args)); + const { originalReadFile: originalReadFile, originalFileExists: originalFileExists, originalDirectoryExists: originalDirectoryExists, originalCreateDirectory: originalCreateDirectory, originalWriteFile: originalWriteFile, getSourceFileWithCache: getSourceFileWithCache, readFileWithCache: readFileWithCache } = changeCompilerHostLikeToUseCache(host, (fileName)=>toPath2(state, fileName), (...args)=>originalGetSourceFile.call(compilerHost, ...args)); state.readFileWithCache = readFileWithCache; compilerHost.getSourceFile = getSourceFileWithCache; state.cache = { @@ -98148,7 +100061,7 @@ ${lanes.join("\n")} } function disableCache(state) { if (!state.cache) return; - const { cache: cache , host: host , compilerHost: compilerHost , extendedConfigCache: extendedConfigCache , moduleResolutionCache: moduleResolutionCache , typeReferenceDirectiveResolutionCache: typeReferenceDirectiveResolutionCache } = state; + const { cache: cache, host: host, compilerHost: compilerHost, extendedConfigCache: extendedConfigCache, moduleResolutionCache: moduleResolutionCache, typeReferenceDirectiveResolutionCache: typeReferenceDirectiveResolutionCache, libraryResolutionCache: libraryResolutionCache } = state; host.readFile = cache.originalReadFile; host.fileExists = cache.originalFileExists; host.directoryExists = cache.originalDirectoryExists; @@ -98159,13 +100072,14 @@ ${lanes.join("\n")} extendedConfigCache.clear(); moduleResolutionCache == null || moduleResolutionCache.clear(); typeReferenceDirectiveResolutionCache == null || typeReferenceDirectiveResolutionCache.clear(); + libraryResolutionCache == null || libraryResolutionCache.clear(); state.cache = void 0; } function clearProjectStatus(state, resolved) { state.projectStatus.delete(resolved); state.diagnostics.delete(resolved); } - function addProjToQueue({ projectPendingBuild: projectPendingBuild }, proj, reloadLevel) { + function addProjToQueue({ projectPendingBuild: projectPendingBuild }, proj, reloadLevel) { const value1 = projectPendingBuild.get(proj); if (value1 === void 0) projectPendingBuild.set(proj, reloadLevel); else if (value1 < reloadLevel) projectPendingBuild.set(proj, reloadLevel); @@ -98228,8 +100142,8 @@ ${lanes.join("\n")} getSemanticDiagnosticsOfNextAffectedFile: (cancellationToken, ignoreSourceFile)=>withProgramOrUndefined((program2)=>program2.getSemanticDiagnosticsOfNextAffectedFile && program2.getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile)), emit: (targetSourceFile, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers)=>{ if (targetSourceFile || emitOnlyDtsFiles) return withProgramOrUndefined((program2)=>{ - var _a2, _b; - return program2.emit(targetSourceFile, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers || ((_b = (_a2 = state.host).getCustomTransformers) == null ? void 0 : _b.call(_a2, project))); + var _a, _b; + return program2.emit(targetSourceFile, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers || ((_b = (_a = state.host).getCustomTransformers) == null ? void 0 : _b.call(_a, project))); }); executeSteps(2 /* SemanticDiagnostics */ , cancellationToken); if (step === 5 /* EmitBuildInfo */ ) return emitBuildInfo(writeFile2, cancellationToken); @@ -98264,7 +100178,7 @@ ${lanes.join("\n")} return withProgramOrUndefined(action) || emptyArray; } function createProgram2() { - var _a2, _b; + var _a, _b; Debug.assert(program === void 0); if (state.options.dry) { reportStatus(state, Diagnostics.A_non_dry_build_would_build_project_0, project); @@ -98279,9 +100193,9 @@ ${lanes.join("\n")} step = 7 /* QueueReferencingProjects */ ; return; } - const { host: host , compilerHost: compilerHost } = state; + const { host: host, compilerHost: compilerHost } = state; state.projectCompilerOptions = config.options; - (_a2 = state.moduleResolutionCache) == null || _a2.update(config.options); + (_a = state.moduleResolutionCache) == null || _a.update(config.options); (_b = state.typeReferenceDirectiveResolutionCache) == null || _b.update(config.options); program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), getConfigFileParsingDiagnostics(config), config.projectReferences); if (state.watch) { @@ -98294,7 +100208,7 @@ ${lanes.join("\n")} step++; } function handleDiagnostics(diagnostics, errorFlags, errorType) { - if (diagnostics.length) ({ buildResult: buildResult , step: step } = buildErrors(state, projectPath, program, config, diagnostics, errorFlags, errorType)); + if (diagnostics.length) ({ buildResult: buildResult, step: step } = buildErrors(state, projectPath, program, config, diagnostics, errorFlags, errorType)); else step++; } function getSyntaxDiagnostics(cancellationToken) { @@ -98310,28 +100224,28 @@ ${lanes.join("\n")} handleDiagnostics(Debug.checkDefined(program).getSemanticDiagnostics(/*sourceFile*/ void 0, cancellationToken), 16 /* TypeErrors */ , "Semantic"); } function emit(writeFileCallback, cancellationToken, customTransformers) { - var _a2, _b, _c; + var _a, _b, _c; Debug.assertIsDefined(program); Debug.assert(step === 3 /* Emit */ ); const saved = program.saveEmitState(); let declDiagnostics; const reportDeclarationDiagnostics = (d)=>(declDiagnostics || (declDiagnostics = [])).push(d); const outputFiles = []; - const { emitResult: emitResult } = emitFilesAndReportErrors(program, reportDeclarationDiagnostics, /*write*/ void 0, /*reportSummary*/ void 0, (name, text, writeByteOrderMark, _onError, _sourceFiles, data)=>outputFiles.push({ + const { emitResult: emitResult } = emitFilesAndReportErrors(program, reportDeclarationDiagnostics, /*write*/ void 0, /*reportSummary*/ void 0, (name, text, writeByteOrderMark, _onError, _sourceFiles, data)=>outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark, data: data - }), cancellationToken, /*emitOnlyDts*/ false, customTransformers || ((_b = (_a2 = state.host).getCustomTransformers) == null ? void 0 : _b.call(_a2, project))); + }), cancellationToken, /*emitOnlyDtsFiles*/ false, customTransformers || ((_b = (_a = state.host).getCustomTransformers) == null ? void 0 : _b.call(_a, project))); if (declDiagnostics) { program.restoreEmitState(saved); - ({ buildResult: buildResult , step: step } = buildErrors(state, projectPath, program, config, declDiagnostics, 32 /* DeclarationEmitErrors */ , "Declaration file")); + ({ buildResult: buildResult, step: step } = buildErrors(state, projectPath, program, config, declDiagnostics, 32 /* DeclarationEmitErrors */ , "Declaration file")); return { emitSkipped: true, diagnostics: emitResult.diagnostics }; } - const { host: host , compilerHost: compilerHost } = state; + const { host: host, compilerHost: compilerHost } = state; const resultFlags = ((_c = program.hasChangedEmitSignature) == null ? void 0 : _c.call(program)) ? 0 /* None */ : 2 /* DeclarationOutputUnchanged */ ; const emitterDiagnostics = createDiagnosticCollection(); const emittedOutputs = /* @__PURE__ */ new Map(); @@ -98339,7 +100253,7 @@ ${lanes.join("\n")} const isIncremental = isIncrementalCompilation(options); let outputTimeStampMap; let now; - outputFiles.forEach(({ name: name , text: text , writeByteOrderMark: writeByteOrderMark , data: data })=>{ + outputFiles.forEach(({ name: name, text: text, writeByteOrderMark: writeByteOrderMark, data: data })=>{ const path = toPath2(state, name); emittedOutputs.set(toPath2(state, name), name); if (data == null ? void 0 : data.buildInfo) setBuildInfo(state, data.buildInfo, projectPath, options, resultFlags); @@ -98377,7 +100291,7 @@ ${lanes.join("\n")} function finishEmit(emitterDiagnostics, emittedOutputs, oldestOutputFileName, resultFlags) { const emitDiagnostics = emitterDiagnostics.getDiagnostics(); if (emitDiagnostics.length) { - ({ buildResult: buildResult , step: step } = buildErrors(state, projectPath, program, config, emitDiagnostics, 64 /* EmitErrors */ , "Emit")); + ({ buildResult: buildResult, step: step } = buildErrors(state, projectPath, program, config, emitDiagnostics, 64 /* EmitErrors */ , "Emit")); return emitDiagnostics; } if (state.write) emittedOutputs.forEach((name)=>listEmittedFile(state, config, name)); @@ -98393,7 +100307,7 @@ ${lanes.join("\n")} return emitDiagnostics; } function emitBundle(writeFileCallback, customTransformers) { - var _a2, _b, _c, _d; + var _a, _b, _c, _d; Debug.assert(kind === 1 /* UpdateBundle */ ); if (state.options.dry) { reportStatus(state, Diagnostics.A_non_dry_build_would_update_output_of_project_0, project); @@ -98402,9 +100316,9 @@ ${lanes.join("\n")} return void 0; } if (state.options.verbose) reportStatus(state, Diagnostics.Updating_output_of_project_0, project); - const { compilerHost: compilerHost } = state; + const { compilerHost: compilerHost } = state; state.projectCompilerOptions = config.options; - (_b = (_a2 = state.host).beforeEmitBundle) == null || _b.call(_a2, config); + (_b = (_a = state.host).beforeEmitBundle) == null || _b.call(_a, config); const outputFiles = emitUsingBuildInfo(config, compilerHost, (ref)=>{ const refName = resolveProjectName(state, ref.path); return parseConfigFile(state, refName, toResolvedConfigFilePath(state, refName)); @@ -98419,11 +100333,11 @@ ${lanes.join("\n")} const emittedOutputs = /* @__PURE__ */ new Map(); let resultFlags = 2 /* DeclarationOutputUnchanged */ ; const existingBuildInfo = state.buildInfoCache.get(projectPath).buildInfo || void 0; - outputFiles.forEach(({ name: name , text: text , writeByteOrderMark: writeByteOrderMark , data: data })=>{ - var _a3, _b2; + outputFiles.forEach(({ name: name, text: text, writeByteOrderMark: writeByteOrderMark, data: data })=>{ + var _a2, _b2; emittedOutputs.set(toPath2(state, name), name); if (data == null ? void 0 : data.buildInfo) { - if (((_a3 = data.buildInfo.program) == null ? void 0 : _a3.outSignature) !== ((_b2 = existingBuildInfo == null ? void 0 : existingBuildInfo.program) == null ? void 0 : _b2.outSignature)) resultFlags &= -3 /* DeclarationOutputUnchanged */ ; + if (((_a2 = data.buildInfo.program) == null ? void 0 : _a2.outSignature) !== ((_b2 = existingBuildInfo == null ? void 0 : existingBuildInfo.program) == null ? void 0 : _b2.outSignature)) resultFlags &= -3 /* DeclarationOutputUnchanged */ ; setBuildInfo(state, data.buildInfo, projectPath, config.options, resultFlags); } writeFile(writeFileCallback ? { @@ -98474,14 +100388,14 @@ ${lanes.join("\n")} } } } - function needsBuild({ options: options }, status, config) { + function needsBuild({ options: options }, status, config) { if (status.type !== 3 /* OutOfDateWithPrepend */ || options.force) return true; return config.fileNames.length === 0 || !!getConfigFileParsingDiagnostics(config).length || !isIncrementalCompilation(config.options); } function getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue) { if (!state.projectPendingBuild.size) return void 0; if (isCircularBuildOrder(buildOrder)) return void 0; - const { options: options , projectPendingBuild: projectPendingBuild } = state; + const { options: options, projectPendingBuild: projectPendingBuild } = state; for(let projectIndex = 0; projectIndex < buildOrder.length; projectIndex++){ const project = buildOrder[projectIndex]; const projectPath = toResolvedConfigFilePath(state, project); @@ -98563,10 +100477,10 @@ ${lanes.join("\n")} if (!info) return info; return createInvalidatedProjectWithInfo(state, info, buildOrder); } - function listEmittedFile({ write: write }, proj, file) { + function listEmittedFile({ write: write }, proj, file) { if (write && proj.options.listEmittedFiles) write(`TSFILE: ${file}`); } - function getOldProgram({ options: options , builderPrograms: builderPrograms , compilerHost: compilerHost }, proj, parsed) { + function getOldProgram({ options: options, builderPrograms: builderPrograms, compilerHost: compilerHost }, proj, parsed) { if (options.force) return void 0; const value1 = builderPrograms.get(proj); if (value1) return value1; @@ -98692,7 +100606,7 @@ ${lanes.join("\n")} }; } function getUpToDateStatusWorker(state, project, resolvedPath) { - var _a2, _b; + var _a, _b; if (!project.fileNames.length && !canJsonReportNoInputFiles(project.raw)) return { type: 16 /* ContainerOnly */ }; @@ -98728,7 +100642,7 @@ ${lanes.join("\n")} if (force) return { type: 17 /* ForceBuild */ }; - const { host: host } = state; + const { host: host } = state; const buildInfoPath = getTsBuildInfoEmitOutputFilePath(project.options); let oldestOutputFileName; let oldestOutputFileTime = maximumDate; @@ -98759,7 +100673,7 @@ ${lanes.join("\n")} version: buildInfo.version }; if (buildInfo.program) { - if (((_a2 = buildInfo.program.changeFileSet) == null ? void 0 : _a2.length) || (!project.options.noEmit ? (_b = buildInfo.program.affectedFilesPendingEmit) == null ? void 0 : _b.length : some(buildInfo.program.semanticDiagnosticsPerFile, isArray))) return { + if (((_a = buildInfo.program.changeFileSet) == null ? void 0 : _a.length) || (!project.options.noEmit ? (_b = buildInfo.program.affectedFilesPendingEmit) == null ? void 0 : _b.length : some(buildInfo.program.semanticDiagnosticsPerFile, isArray))) return { type: 8 /* OutOfDateBuildInfo */ , buildInfoFile: buildInfoPath }; @@ -98843,7 +100757,7 @@ ${lanes.join("\n")} let pseudoUpToDate = false; let usesPrepend = false; let upstreamChangedProject; - if (referenceStatuses) for (const { ref: ref , refStatus: refStatus , resolvedConfig: resolvedConfig , resolvedRefPath: resolvedRefPath } of referenceStatuses){ + if (referenceStatuses) for (const { ref: ref, refStatus: refStatus, resolvedConfig: resolvedConfig, resolvedRefPath: resolvedRefPath } of referenceStatuses){ usesPrepend = usesPrepend || !!ref.prepend; if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) continue; if (buildInfoCacheEntry && hasSameBuildInfo(state, buildInfoCacheEntry, resolvedRefPath)) return { @@ -98913,7 +100827,7 @@ ${lanes.join("\n")} state.outputTimeStamps.delete(projectPath); return; } - const { host: host } = state; + const { host: host } = state; const outputs = getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames()); const outputTimeStampMap = getOutputTimeStampMap(state, projectPath); const modifiedOutputs = outputTimeStampMap ? /* @__PURE__ */ new Set() : void 0; @@ -99034,7 +100948,7 @@ ${lanes.join("\n")} reportErrors(state, buildOrder.circularDiagnostics); return 4 /* ProjectReferenceCycle_OutputsSkipped */ ; } - const { options: options , host: host } = state; + const { options: options, host: host } = state; const filesToDelete = options.dry ? [] : void 0; for (const proj of buildOrder){ const resolvedPath = toResolvedConfigFilePath(state, proj); @@ -99078,12 +100992,12 @@ ${lanes.join("\n")} scheduleBuildInvalidatedProject(state, 250, /*changeDetected*/ true); } function scheduleBuildInvalidatedProject(state, time, changeDetected) { - const { hostWithWatch: hostWithWatch } = state; + const { hostWithWatch: hostWithWatch } = state; if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) return; if (state.timerToBuildInvalidatedProject) hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject); - state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, time, state, changeDetected); + state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, time, "timerToBuildInvalidatedProject", state, changeDetected); } - function buildNextInvalidatedProject(state, changeDetected) { + function buildNextInvalidatedProject(_timeoutType, state, changeDetected) { mark("SolutionBuilder::beforeBuild"); const buildOrder = buildNextInvalidatedProjectWorker(state, changeDetected); mark("SolutionBuilder::afterBuild"); @@ -99125,14 +101039,14 @@ ${lanes.join("\n")} } function watchExtendedConfigFiles(state, resolvedPath, parsed) { updateSharedExtendedConfigFileWatcher(resolvedPath, parsed == null ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, (extendedConfigFileName, extendedConfigFilePath)=>watchFile(state, extendedConfigFileName, ()=>{ - var _a2; - return (_a2 = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) == null ? void 0 : _a2.projects.forEach((projectConfigFilePath)=>invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, 2 /* Full */ )); + var _a; + return (_a = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) == null ? void 0 : _a.projects.forEach((projectConfigFilePath)=>invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, 2 /* Full */ )); }, 2e3 /* High */ , parsed == null ? void 0 : parsed.watchOptions, WatchType.ExtendedConfigFile), (fileName)=>toPath2(state, fileName)); } function watchWildCardDirectories(state, resolved, resolvedPath, parsed) { if (!state.watch) return; updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), new Map(Object.entries(parsed.wildcardDirectories)), (dir, flags)=>state.watchDirectory(dir, (fileOrDirectory)=>{ - var _a2; + var _a; if (isIgnoredFileFromWildCardWatching({ watchedDirPath: toPath2(state, dir), fileOrDirectory: fileOrDirectory, @@ -99140,7 +101054,7 @@ ${lanes.join("\n")} configFileName: resolved, currentDirectory: state.compilerHost.getCurrentDirectory(), options: parsed.options, - program: state.builderPrograms.get(resolvedPath) || ((_a2 = getCachedParsedConfigFile(state, resolvedPath)) == null ? void 0 : _a2.fileNames), + program: state.builderPrograms.get(resolvedPath) || ((_a = getCachedParsedConfigFile(state, resolvedPath)) == null ? void 0 : _a.fileNames), useCaseSensitiveFileNames: state.parseConfigFileHost.useCaseSensitiveFileNames, writeLog: (s)=>state.writeLog(s), toPath: (fileName)=>toPath2(state, fileName) @@ -99215,10 +101129,10 @@ ${lanes.join("\n")} state.host.reportSolutionBuilderStatus(createCompilerDiagnostic(message, ...args)); } function reportWatchStatus(state, message, ...args) { - var _a2, _b; - (_b = (_a2 = state.hostWithWatch).onWatchStatusChange) == null || _b.call(_a2, createCompilerDiagnostic(message, ...args), state.host.getNewLine(), state.baseCompilerOptions); + var _a, _b; + (_b = (_a = state.hostWithWatch).onWatchStatusChange) == null || _b.call(_a, createCompilerDiagnostic(message, ...args), state.host.getNewLine(), state.baseCompilerOptions); } - function reportErrors({ host: host }, errors) { + function reportErrors({ host: host }, errors) { errors.forEach((err)=>host.reportDiagnostic(err)); } function reportAndStoreErrors(state, proj, errors) { @@ -99235,7 +101149,7 @@ ${lanes.join("\n")} if (!state.needsSummary) return; state.needsSummary = false; const canReportSummary = state.watch || !!state.host.reportErrorSummary; - const { diagnostics: diagnostics } = state; + const { diagnostics: diagnostics } = state; let totalErrors = 0; let filesInError = []; if (isCircularBuildOrder(buildOrder)) { @@ -99313,7 +101227,6 @@ ${lanes.join("\n")} "src/compiler/tsbuildPublic.ts" () { "use strict"; init_ts2(); - init_ts2(); init_ts_performance(); minimumDate = /* @__PURE__ */ new Date(-8640000000000000); maximumDate = /* @__PURE__ */ new Date(864e13); @@ -99362,6 +101275,8 @@ ${lanes.join("\n")} init_sourcemap(); init_utilities3(); init_destructuring(); + init_classThis(); + init_namedEvaluation(); init_taggedTemplate(); init_ts(); init_classFields(); @@ -99415,9 +101330,9 @@ ${lanes.join("\n")} return new Map(Object.entries(result.config)); } function loadTypesMap(host, typesMapPath) { - var _a2; + var _a; const result = readConfigFile(typesMapPath, (path)=>host.readFile(path)); - if ((_a2 = result.config) == null ? void 0 : _a2.simpleMap) return new Map(Object.entries(result.config.simpleMap)); + if ((_a = result.config) == null ? void 0 : _a.simpleMap) return new Map(Object.entries(result.config.simpleMap)); return void 0; } function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry, compilerOptions) { @@ -99583,7 +101498,7 @@ ${lanes.join("\n")} case 0 /* Ok */ : return Debug.fail(); default: - throw Debug.assertNever(result); + Debug.assertNever(result); } } var unprefixedNodeCoreModuleList, prefixedNodeCoreModuleList, nodeCoreModuleList, nodeCoreModules, NameValidationResult, maxPackageNameLength; @@ -99691,7 +101606,7 @@ ${lanes.join("\n")} const d = /* @__PURE__ */ new Date(); return `${padLeft(d.getHours().toString(), 2, "0")}:${padLeft(d.getMinutes().toString(), 2, "0")}:${padLeft(d.getSeconds().toString(), 2, "0")}.${padLeft(d.getMilliseconds().toString(), 3, "0")}`; } - var ActionSet, ActionInvalidate, ActionPackageInstalled, EventTypesRegistry, EventBeginInstallTypes, EventEndInstallTypes, EventInitializationFailed, Arguments; + var ActionSet, ActionInvalidate, ActionPackageInstalled, EventTypesRegistry, EventBeginInstallTypes, EventEndInstallTypes, EventInitializationFailed, ActionWatchTypingLocations, Arguments; var init_shared = __esm({ "src/jsTyping/shared.ts" () { "use strict"; @@ -99703,6 +101618,7 @@ ${lanes.join("\n")} EventBeginInstallTypes = "event::beginInstallTypes"; EventEndInstallTypes = "event::endInstallTypes"; EventInitializationFailed = "event::initializationFailed"; + ActionWatchTypingLocations = "action::watchTypingLocations"; ((Arguments2)=>{ Arguments2.GlobalCacheLocation = "--globalTypingsCacheLocation"; Arguments2.LogFile = "--logFile"; @@ -99726,6 +101642,7 @@ ${lanes.join("\n")} ActionInvalidate: ()=>ActionInvalidate, ActionPackageInstalled: ()=>ActionPackageInstalled, ActionSet: ()=>ActionSet, + ActionWatchTypingLocations: ()=>ActionWatchTypingLocations, Arguments: ()=>Arguments, EventBeginInstallTypes: ()=>EventBeginInstallTypes, EventEndInstallTypes: ()=>EventEndInstallTypes, @@ -99774,7 +101691,8 @@ ${lanes.join("\n")} placeOpenBraceOnNewLineForFunctions: false, placeOpenBraceOnNewLineForControlBlocks: false, semicolons: "ignore" /* Ignore */ , - trimTrailingWhitespace: true + trimTrailingWhitespace: true, + indentSwitchCase: true }; } var ScriptSnapshot, PackageJsonDependencyGroup, PackageJsonAutoImportPreference, LanguageServiceMode, emptyOptions, SemanticClassificationFormat, OrganizeImportsMode, CompletionTriggerKind, InlayHintKind, HighlightSpanKind, IndentStyle, SemicolonPreference, testFormatSettings, SymbolDisplayPartKind, CompletionInfoFlags, OutliningSpanKind, OutputFileType, EndOfLineState, TokenClass, ScriptElementKind, ScriptElementKindModifier, ClassificationTypeNames, ClassificationType; @@ -99953,6 +101871,8 @@ ${lanes.join("\n")} ScriptElementKind2["enumMemberElement"] = "enum member"; ScriptElementKind2["variableElement"] = "var"; ScriptElementKind2["localVariableElement"] = "local var"; + ScriptElementKind2["variableUsingElement"] = "using"; + ScriptElementKind2["variableAwaitUsingElement"] = "await using"; ScriptElementKind2["functionElement"] = "function"; ScriptElementKind2["localFunctionElement"] = "local function"; ScriptElementKind2["memberFunctionElement"] = "method"; @@ -100065,48 +101985,48 @@ ${lanes.join("\n")} // src/services/utilities.ts function getMeaningFromDeclaration(node) { switch(node.kind){ - case 257 /* VariableDeclaration */ : + case 260 /* VariableDeclaration */ : return isInJSFile(node) && getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */ ; - case 166 /* Parameter */ : - case 205 /* BindingElement */ : - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : - case 299 /* PropertyAssignment */ : - case 300 /* ShorthandPropertyAssignment */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 173 /* Constructor */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - case 295 /* CatchClause */ : - case 288 /* JsxAttribute */ : + case 169 /* Parameter */ : + case 208 /* BindingElement */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : + case 303 /* PropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 176 /* Constructor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + case 299 /* CatchClause */ : + case 291 /* JsxAttribute */ : return 1 /* Value */ ; - case 165 /* TypeParameter */ : - case 261 /* InterfaceDeclaration */ : - case 262 /* TypeAliasDeclaration */ : - case 184 /* TypeLiteral */ : + case 168 /* TypeParameter */ : + case 264 /* InterfaceDeclaration */ : + case 265 /* TypeAliasDeclaration */ : + case 187 /* TypeLiteral */ : return 2 /* Type */ ; - case 349 /* JSDocTypedefTag */ : + case 353 /* JSDocTypedefTag */ : return node.name === void 0 ? 3 /* Type */ : 2 /* Type */ ; - case 302 /* EnumMember */ : - case 260 /* ClassDeclaration */ : + case 306 /* EnumMember */ : + case 263 /* ClassDeclaration */ : return 3 /* Type */ ; - case 264 /* ModuleDeclaration */ : + case 267 /* ModuleDeclaration */ : if (isAmbientModule(node)) return 5 /* Value */ ; else if (getModuleInstanceState(node) === 1 /* Instantiated */ ) return 5 /* Value */ ; else return 4 /* Namespace */ ; - case 263 /* EnumDeclaration */ : - case 272 /* NamedImports */ : - case 273 /* ImportSpecifier */ : - case 268 /* ImportEqualsDeclaration */ : - case 269 /* ImportDeclaration */ : - case 274 /* ExportAssignment */ : - case 275 /* ExportDeclaration */ : + case 266 /* EnumDeclaration */ : + case 275 /* NamedImports */ : + case 276 /* ImportSpecifier */ : + case 271 /* ImportEqualsDeclaration */ : + case 272 /* ImportDeclaration */ : + case 277 /* ExportAssignment */ : + case 278 /* ExportDeclaration */ : return 7 /* All */ ; - case 308 /* SourceFile */ : + case 312 /* SourceFile */ : return 5 /* Value */ ; } return 7 /* All */ ; @@ -100114,7 +102034,7 @@ ${lanes.join("\n")} function getMeaningFromLocation(node) { node = getAdjustedReferenceLocation(node); const parent2 = node.parent; - if (node.kind === 308 /* SourceFile */ ) return 1 /* Value */ ; + if (node.kind === 312 /* SourceFile */ ) return 1 /* Value */ ; else if (isExportAssignment(parent2) || isExportSpecifier(parent2) || isExternalModuleReference(parent2) || isImportSpecifier(parent2) || isImportClause(parent2) || isImportEqualsDeclaration(parent2) && node === parent2.name) return 7 /* All */ ; else if (isInRightSideOfInternalImportEqualsDeclaration(node)) return getMeaningFromRightHandSideOfImportEquals(node); else if (isDeclarationName(node)) return getMeaningFromDeclaration(parent2); @@ -100128,11 +102048,11 @@ ${lanes.join("\n")} else return 1 /* Value */ ; } function getMeaningFromRightHandSideOfImportEquals(node) { - const name = node.kind === 163 /* QualifiedName */ ? node : isQualifiedName(node.parent) && node.parent.right === node ? node.parent : void 0; - return name && name.parent.kind === 268 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */ ; + const name = node.kind === 166 /* QualifiedName */ ? node : isQualifiedName(node.parent) && node.parent.right === node ? node.parent : void 0; + return name && name.parent.kind === 271 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */ ; } function isInRightSideOfInternalImportEqualsDeclaration(node) { - while(node.parent.kind === 163 /* QualifiedName */ )node = node.parent; + while(node.parent.kind === 166 /* QualifiedName */ )node = node.parent; return isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; } function isNamespaceReference(node) { @@ -100141,39 +102061,39 @@ ${lanes.join("\n")} function isQualifiedNameNamespaceReference(node) { let root = node; let isLastClause = true; - if (root.parent.kind === 163 /* QualifiedName */ ) { - while(root.parent && root.parent.kind === 163 /* QualifiedName */ )root = root.parent; + if (root.parent.kind === 166 /* QualifiedName */ ) { + while(root.parent && root.parent.kind === 166 /* QualifiedName */ )root = root.parent; isLastClause = root.right === node; } - return root.parent.kind === 180 /* TypeReference */ && !isLastClause; + return root.parent.kind === 183 /* TypeReference */ && !isLastClause; } function isPropertyAccessNamespaceReference(node) { let root = node; let isLastClause = true; - if (root.parent.kind === 208 /* PropertyAccessExpression */ ) { - while(root.parent && root.parent.kind === 208 /* PropertyAccessExpression */ )root = root.parent; + if (root.parent.kind === 211 /* PropertyAccessExpression */ ) { + while(root.parent && root.parent.kind === 211 /* PropertyAccessExpression */ )root = root.parent; isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 230 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 294 /* HeritageClause */ ) { + if (!isLastClause && root.parent.kind === 233 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 298 /* HeritageClause */ ) { const decl = root.parent.parent.parent; - return decl.kind === 260 /* ClassDeclaration */ && root.parent.parent.token === 117 /* ImplementsKeyword */ || decl.kind === 261 /* InterfaceDeclaration */ && root.parent.parent.token === 94 /* ExtendsKeyword */ ; + return decl.kind === 263 /* ClassDeclaration */ && root.parent.parent.token === 119 /* ImplementsKeyword */ || decl.kind === 264 /* InterfaceDeclaration */ && root.parent.parent.token === 96 /* ExtendsKeyword */ ; } return false; } function isTypeReference(node) { if (isRightSideOfQualifiedNameOrPropertyAccess(node)) node = node.parent; switch(node.kind){ - case 108 /* ThisKeyword */ : + case 110 /* ThisKeyword */ : return !isExpressionNode(node); - case 194 /* ThisType */ : + case 197 /* ThisType */ : return true; } switch(node.parent.kind){ - case 180 /* TypeReference */ : + case 183 /* TypeReference */ : return true; - case 202 /* ImportType */ : + case 205 /* ImportType */ : return !node.parent.isTypeOf; - case 230 /* ExpressionWithTypeArguments */ : + case 233 /* ExpressionWithTypeArguments */ : return isPartOfTypeNode(node.parent); } return false; @@ -100218,7 +102138,7 @@ ${lanes.join("\n")} } function getTargetLabel(referenceNode, labelName) { while(referenceNode){ - if (referenceNode.kind === 253 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) return referenceNode.label; + if (referenceNode.kind === 256 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) return referenceNode.label; referenceNode = referenceNode.parent; } return void 0; @@ -100228,58 +102148,58 @@ ${lanes.join("\n")} return node.expression.name.text === funcName; } function isJumpStatementTarget(node) { - var _a2; - return isIdentifier(node) && ((_a2 = tryCast(node.parent, isBreakOrContinueStatement)) == null ? void 0 : _a2.label) === node; + var _a; + return isIdentifier(node) && ((_a = tryCast(node.parent, isBreakOrContinueStatement)) == null ? void 0 : _a.label) === node; } function isLabelOfLabeledStatement(node) { - var _a2; - return isIdentifier(node) && ((_a2 = tryCast(node.parent, isLabeledStatement)) == null ? void 0 : _a2.label) === node; + var _a; + return isIdentifier(node) && ((_a = tryCast(node.parent, isLabeledStatement)) == null ? void 0 : _a.label) === node; } function isLabelName(node) { return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); } function isTagName(node) { - var _a2; - return ((_a2 = tryCast(node.parent, isJSDocTag)) == null ? void 0 : _a2.tagName) === node; + var _a; + return ((_a = tryCast(node.parent, isJSDocTag)) == null ? void 0 : _a.tagName) === node; } function isRightSideOfQualifiedName(node) { - var _a2; - return ((_a2 = tryCast(node.parent, isQualifiedName)) == null ? void 0 : _a2.right) === node; + var _a; + return ((_a = tryCast(node.parent, isQualifiedName)) == null ? void 0 : _a.right) === node; } function isRightSideOfPropertyAccess(node) { - var _a2; - return ((_a2 = tryCast(node.parent, isPropertyAccessExpression)) == null ? void 0 : _a2.name) === node; + var _a; + return ((_a = tryCast(node.parent, isPropertyAccessExpression)) == null ? void 0 : _a.name) === node; } function isArgumentExpressionOfElementAccess(node) { - var _a2; - return ((_a2 = tryCast(node.parent, isElementAccessExpression)) == null ? void 0 : _a2.argumentExpression) === node; + var _a; + return ((_a = tryCast(node.parent, isElementAccessExpression)) == null ? void 0 : _a.argumentExpression) === node; } function isNameOfModuleDeclaration(node) { - var _a2; - return ((_a2 = tryCast(node.parent, isModuleDeclaration)) == null ? void 0 : _a2.name) === node; + var _a; + return ((_a = tryCast(node.parent, isModuleDeclaration)) == null ? void 0 : _a.name) === node; } function isNameOfFunctionDeclaration(node) { - var _a2; - return isIdentifier(node) && ((_a2 = tryCast(node.parent, isFunctionLike)) == null ? void 0 : _a2.name) === node; + var _a; + return isIdentifier(node) && ((_a = tryCast(node.parent, isFunctionLike)) == null ? void 0 : _a.name) === node; } function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { switch(node.parent.kind){ - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : - case 299 /* PropertyAssignment */ : - case 302 /* EnumMember */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 264 /* ModuleDeclaration */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : + case 303 /* PropertyAssignment */ : + case 306 /* EnumMember */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 267 /* ModuleDeclaration */ : return getNameOfDeclaration(node.parent) === node; - case 209 /* ElementAccessExpression */ : + case 212 /* ElementAccessExpression */ : return node.parent.argumentExpression === node; - case 164 /* ComputedPropertyName */ : + case 167 /* ComputedPropertyName */ : return true; - case 198 /* LiteralType */ : - return node.parent.parent.kind === 196 /* IndexedAccessType */ ; + case 201 /* LiteralType */ : + return node.parent.parent.kind === 199 /* IndexedAccessType */ ; default: return false; } @@ -100293,85 +102213,85 @@ ${lanes.join("\n")} node = node.parent; if (!node) return void 0; switch(node.kind){ - case 308 /* SourceFile */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 260 /* ClassDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 263 /* EnumDeclaration */ : - case 264 /* ModuleDeclaration */ : + case 312 /* SourceFile */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 263 /* ClassDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 266 /* EnumDeclaration */ : + case 267 /* ModuleDeclaration */ : return node; } } } function getNodeKind(node) { switch(node.kind){ - case 308 /* SourceFile */ : + case 312 /* SourceFile */ : return isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */ ; - case 264 /* ModuleDeclaration */ : + case 267 /* ModuleDeclaration */ : return "module" /* moduleElement */ ; - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : return "class" /* classElement */ ; - case 261 /* InterfaceDeclaration */ : + case 264 /* InterfaceDeclaration */ : return "interface" /* interfaceElement */ ; - case 262 /* TypeAliasDeclaration */ : - case 341 /* JSDocCallbackTag */ : - case 349 /* JSDocTypedefTag */ : + case 265 /* TypeAliasDeclaration */ : + case 345 /* JSDocCallbackTag */ : + case 353 /* JSDocTypedefTag */ : return "type" /* typeElement */ ; - case 263 /* EnumDeclaration */ : + case 266 /* EnumDeclaration */ : return "enum" /* enumElement */ ; - case 257 /* VariableDeclaration */ : + case 260 /* VariableDeclaration */ : return getKindOfVariableDeclaration(node); - case 205 /* BindingElement */ : + case 208 /* BindingElement */ : return getKindOfVariableDeclaration(getRootDeclaration(node)); - case 216 /* ArrowFunction */ : - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : return "function" /* functionElement */ ; - case 174 /* GetAccessor */ : + case 177 /* GetAccessor */ : return "getter" /* memberGetAccessorElement */ ; - case 175 /* SetAccessor */ : + case 178 /* SetAccessor */ : return "setter" /* memberSetAccessorElement */ ; - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : return "method" /* memberFunctionElement */ ; - case 299 /* PropertyAssignment */ : - const { initializer: initializer } = node; + case 303 /* PropertyAssignment */ : + const { initializer: initializer } = node; return isFunctionLike(initializer) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */ ; - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : - case 300 /* ShorthandPropertyAssignment */ : - case 301 /* SpreadAssignment */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : + case 304 /* ShorthandPropertyAssignment */ : + case 305 /* SpreadAssignment */ : return "property" /* memberVariableElement */ ; - case 178 /* IndexSignature */ : + case 181 /* IndexSignature */ : return "index" /* indexSignatureElement */ ; - case 177 /* ConstructSignature */ : + case 180 /* ConstructSignature */ : return "construct" /* constructSignatureElement */ ; - case 176 /* CallSignature */ : + case 179 /* CallSignature */ : return "call" /* callSignatureElement */ ; - case 173 /* Constructor */ : - case 172 /* ClassStaticBlockDeclaration */ : + case 176 /* Constructor */ : + case 175 /* ClassStaticBlockDeclaration */ : return "constructor" /* constructorImplementationElement */ ; - case 165 /* TypeParameter */ : + case 168 /* TypeParameter */ : return "type parameter" /* typeParameterElement */ ; - case 302 /* EnumMember */ : + case 306 /* EnumMember */ : return "enum member" /* enumMemberElement */ ; - case 166 /* Parameter */ : + case 169 /* Parameter */ : return hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */ ) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */ ; - case 268 /* ImportEqualsDeclaration */ : - case 273 /* ImportSpecifier */ : - case 278 /* ExportSpecifier */ : - case 271 /* NamespaceImport */ : - case 277 /* NamespaceExport */ : + case 271 /* ImportEqualsDeclaration */ : + case 276 /* ImportSpecifier */ : + case 281 /* ExportSpecifier */ : + case 274 /* NamespaceImport */ : + case 280 /* NamespaceExport */ : return "alias" /* alias */ ; - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : const kind = getAssignmentDeclarationKind(node); - const { right: right } = node; + const { right: right } = node; switch(kind){ case 7 /* ObjectDefinePropertyValue */ : case 8 /* ObjectDefinePropertyExports */ : @@ -100394,9 +102314,9 @@ ${lanes.join("\n")} assertType(kind); return "" /* unknown */ ; } - case 79 /* Identifier */ : + case 80 /* Identifier */ : return isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */ ; - case 274 /* ExportAssignment */ : + case 277 /* ExportAssignment */ : const scriptKind = getNodeKind(node.expression); return scriptKind === "" /* unknown */ ? "const" /* constElement */ : scriptKind; default: @@ -100408,10 +102328,10 @@ ${lanes.join("\n")} } function isThis(node) { switch(node.kind){ - case 108 /* ThisKeyword */ : + case 110 /* ThisKeyword */ : return true; - case 79 /* Identifier */ : - return identifierIsThisKeyword(node) && node.parent.kind === 166 /* Parameter */ ; + case 80 /* Identifier */ : + return identifierIsThisKeyword(node) && node.parent.kind === 169 /* Parameter */ ; default: return false; } @@ -100457,92 +102377,92 @@ ${lanes.join("\n")} function isCompletedNode(n, sourceFile) { if (n === void 0 || nodeIsMissing(n)) return false; switch(n.kind){ - case 260 /* ClassDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 263 /* EnumDeclaration */ : - case 207 /* ObjectLiteralExpression */ : - case 203 /* ObjectBindingPattern */ : - case 184 /* TypeLiteral */ : - case 238 /* Block */ : - case 265 /* ModuleBlock */ : - case 266 /* CaseBlock */ : - case 272 /* NamedImports */ : - case 276 /* NamedExports */ : - return nodeEndsWith(n, 19 /* CloseBraceToken */ , sourceFile); - case 295 /* CatchClause */ : + case 263 /* ClassDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 266 /* EnumDeclaration */ : + case 210 /* ObjectLiteralExpression */ : + case 206 /* ObjectBindingPattern */ : + case 187 /* TypeLiteral */ : + case 241 /* Block */ : + case 268 /* ModuleBlock */ : + case 269 /* CaseBlock */ : + case 275 /* NamedImports */ : + case 279 /* NamedExports */ : + return nodeEndsWith(n, 20 /* CloseBraceToken */ , sourceFile); + case 299 /* CatchClause */ : return isCompletedNode(n.block, sourceFile); - case 211 /* NewExpression */ : + case 214 /* NewExpression */ : if (!n.arguments) return true; - case 210 /* CallExpression */ : - case 214 /* ParenthesizedExpression */ : - case 193 /* ParenthesizedType */ : - return nodeEndsWith(n, 21 /* CloseParenToken */ , sourceFile); - case 181 /* FunctionType */ : - case 182 /* ConstructorType */ : + case 213 /* CallExpression */ : + case 217 /* ParenthesizedExpression */ : + case 196 /* ParenthesizedType */ : + return nodeEndsWith(n, 22 /* CloseParenToken */ , sourceFile); + case 184 /* FunctionType */ : + case 185 /* ConstructorType */ : return isCompletedNode(n.type, sourceFile); - case 173 /* Constructor */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 177 /* ConstructSignature */ : - case 176 /* CallSignature */ : - case 216 /* ArrowFunction */ : + case 176 /* Constructor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 180 /* ConstructSignature */ : + case 179 /* CallSignature */ : + case 219 /* ArrowFunction */ : if (n.body) return isCompletedNode(n.body, sourceFile); if (n.type) return isCompletedNode(n.type, sourceFile); - return hasChildOfKind(n, 21 /* CloseParenToken */ , sourceFile); - case 264 /* ModuleDeclaration */ : + return hasChildOfKind(n, 22 /* CloseParenToken */ , sourceFile); + case 267 /* ModuleDeclaration */ : return !!n.body && isCompletedNode(n.body, sourceFile); - case 242 /* IfStatement */ : + case 245 /* IfStatement */ : if (n.elseStatement) return isCompletedNode(n.elseStatement, sourceFile); return isCompletedNode(n.thenStatement, sourceFile); - case 241 /* ExpressionStatement */ : - return isCompletedNode(n.expression, sourceFile) || hasChildOfKind(n, 26 /* SemicolonToken */ , sourceFile); - case 206 /* ArrayLiteralExpression */ : - case 204 /* ArrayBindingPattern */ : - case 209 /* ElementAccessExpression */ : - case 164 /* ComputedPropertyName */ : - case 186 /* TupleType */ : - return nodeEndsWith(n, 23 /* CloseBracketToken */ , sourceFile); - case 178 /* IndexSignature */ : + case 244 /* ExpressionStatement */ : + return isCompletedNode(n.expression, sourceFile) || hasChildOfKind(n, 27 /* SemicolonToken */ , sourceFile); + case 209 /* ArrayLiteralExpression */ : + case 207 /* ArrayBindingPattern */ : + case 212 /* ElementAccessExpression */ : + case 167 /* ComputedPropertyName */ : + case 189 /* TupleType */ : + return nodeEndsWith(n, 24 /* CloseBracketToken */ , sourceFile); + case 181 /* IndexSignature */ : if (n.type) return isCompletedNode(n.type, sourceFile); - return hasChildOfKind(n, 23 /* CloseBracketToken */ , sourceFile); - case 292 /* CaseClause */ : - case 293 /* DefaultClause */ : + return hasChildOfKind(n, 24 /* CloseBracketToken */ , sourceFile); + case 296 /* CaseClause */ : + case 297 /* DefaultClause */ : return false; - case 245 /* ForStatement */ : - case 246 /* ForInStatement */ : - case 247 /* ForOfStatement */ : - case 244 /* WhileStatement */ : + case 248 /* ForStatement */ : + case 249 /* ForInStatement */ : + case 250 /* ForOfStatement */ : + case 247 /* WhileStatement */ : return isCompletedNode(n.statement, sourceFile); - case 243 /* DoStatement */ : - return hasChildOfKind(n, 115 /* WhileKeyword */ , sourceFile) ? nodeEndsWith(n, 21 /* CloseParenToken */ , sourceFile) : isCompletedNode(n.statement, sourceFile); - case 183 /* TypeQuery */ : + case 246 /* DoStatement */ : + return hasChildOfKind(n, 117 /* WhileKeyword */ , sourceFile) ? nodeEndsWith(n, 22 /* CloseParenToken */ , sourceFile) : isCompletedNode(n.statement, sourceFile); + case 186 /* TypeQuery */ : return isCompletedNode(n.exprName, sourceFile); - case 218 /* TypeOfExpression */ : - case 217 /* DeleteExpression */ : - case 219 /* VoidExpression */ : - case 226 /* YieldExpression */ : - case 227 /* SpreadElement */ : + case 221 /* TypeOfExpression */ : + case 220 /* DeleteExpression */ : + case 222 /* VoidExpression */ : + case 229 /* YieldExpression */ : + case 230 /* SpreadElement */ : const unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 212 /* TaggedTemplateExpression */ : + case 215 /* TaggedTemplateExpression */ : return isCompletedNode(n.template, sourceFile); - case 225 /* TemplateExpression */ : + case 228 /* TemplateExpression */ : const lastSpan = lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 236 /* TemplateSpan */ : + case 239 /* TemplateSpan */ : return nodeIsPresent(n.literal); - case 275 /* ExportDeclaration */ : - case 269 /* ImportDeclaration */ : + case 278 /* ExportDeclaration */ : + case 272 /* ImportDeclaration */ : return nodeIsPresent(n.moduleSpecifier); - case 221 /* PrefixUnaryExpression */ : + case 224 /* PrefixUnaryExpression */ : return isCompletedNode(n.operand, sourceFile); - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : return isCompletedNode(n.right, sourceFile); - case 224 /* ConditionalExpression */ : + case 227 /* ConditionalExpression */ : return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -100553,7 +102473,7 @@ ${lanes.join("\n")} if (children.length) { const lastChild = last(children); if (lastChild.kind === expectedLastToken) return true; - else if (lastChild.kind === 26 /* SemicolonToken */ && children.length !== 1) return children[children.length - 2].kind === expectedLastToken; + else if (lastChild.kind === 27 /* SemicolonToken */ && children.length !== 1) return children[children.length - 2].kind === expectedLastToken; } return false; } @@ -100579,13 +102499,13 @@ ${lanes.join("\n")} return syntaxList; } function isDefaultModifier2(node) { - return node.kind === 88 /* DefaultKeyword */ ; + return node.kind === 90 /* DefaultKeyword */ ; } function isClassKeyword(node) { - return node.kind === 84 /* ClassKeyword */ ; + return node.kind === 86 /* ClassKeyword */ ; } function isFunctionKeyword(node) { - return node.kind === 98 /* FunctionKeyword */ ; + return node.kind === 100 /* FunctionKeyword */ ; } function getAdjustedLocationForClass(node) { if (isNamedDeclaration(node)) return node.name; @@ -100618,7 +102538,7 @@ ${lanes.join("\n")} return lastTypeNode; } function getContextualTypeFromParentOrAncestorTypeNode(node, checker) { - if (node.flags & 8388608 /* JavaScriptFile */ ) return void 0; + if (node.flags & 16777216 /* JavaScriptFile */ ) return void 0; const contextualType = getContextualTypeFromParent(node, checker); if (contextualType) return contextualType; const ancestorTypeNode = getAncestorTypeNode(node); @@ -100626,13 +102546,13 @@ ${lanes.join("\n")} } function getAdjustedLocationForDeclaration(node, forRename) { if (!forRename) switch(node.kind){ - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : return getAdjustedLocationForClass(node); - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : return getAdjustedLocationForFunction(node); - case 173 /* Constructor */ : + case 176 /* Constructor */ : return node; } if (isNamedDeclaration(node)) return node.name; @@ -100665,16 +102585,16 @@ ${lanes.join("\n")} if (node.types.length === 1) return node.types[0].expression; } function getAdjustedLocation(node, forRename) { - const { parent: parent2 } = node; - if (isModifier(node) && (forRename || node.kind !== 88 /* DefaultKeyword */ ) ? canHaveModifiers(parent2) && contains(parent2.modifiers, node) : node.kind === 84 /* ClassKeyword */ ? isClassDeclaration(parent2) || isClassExpression(node) : node.kind === 98 /* FunctionKeyword */ ? isFunctionDeclaration(parent2) || isFunctionExpression(node) : node.kind === 118 /* InterfaceKeyword */ ? isInterfaceDeclaration(parent2) : node.kind === 92 /* EnumKeyword */ ? isEnumDeclaration(parent2) : node.kind === 154 /* TypeKeyword */ ? isTypeAliasDeclaration(parent2) : node.kind === 143 /* NamespaceKeyword */ || node.kind === 142 /* ModuleKeyword */ ? isModuleDeclaration(parent2) : node.kind === 100 /* ImportKeyword */ ? isImportEqualsDeclaration(parent2) : node.kind === 137 /* GetKeyword */ ? isGetAccessorDeclaration(parent2) : node.kind === 151 /* SetKeyword */ && isSetAccessorDeclaration(parent2)) { + const { parent: parent2 } = node; + if (isModifier(node) && (forRename || node.kind !== 90 /* DefaultKeyword */ ) ? canHaveModifiers(parent2) && contains(parent2.modifiers, node) : node.kind === 86 /* ClassKeyword */ ? isClassDeclaration(parent2) || isClassExpression(node) : node.kind === 100 /* FunctionKeyword */ ? isFunctionDeclaration(parent2) || isFunctionExpression(node) : node.kind === 120 /* InterfaceKeyword */ ? isInterfaceDeclaration(parent2) : node.kind === 94 /* EnumKeyword */ ? isEnumDeclaration(parent2) : node.kind === 156 /* TypeKeyword */ ? isTypeAliasDeclaration(parent2) : node.kind === 145 /* NamespaceKeyword */ || node.kind === 144 /* ModuleKeyword */ ? isModuleDeclaration(parent2) : node.kind === 102 /* ImportKeyword */ ? isImportEqualsDeclaration(parent2) : node.kind === 139 /* GetKeyword */ ? isGetAccessorDeclaration(parent2) : node.kind === 153 /* SetKeyword */ && isSetAccessorDeclaration(parent2)) { const location = getAdjustedLocationForDeclaration(parent2, forRename); if (location) return location; } - if ((node.kind === 113 /* VarKeyword */ || node.kind === 85 /* ConstKeyword */ || node.kind === 119 /* LetKeyword */ ) && isVariableDeclarationList(parent2) && parent2.declarations.length === 1) { + if ((node.kind === 115 /* VarKeyword */ || node.kind === 87 /* ConstKeyword */ || node.kind === 121 /* LetKeyword */ ) && isVariableDeclarationList(parent2) && parent2.declarations.length === 1) { const decl = parent2.declarations[0]; if (isIdentifier(decl.name)) return decl.name; } - if (node.kind === 154 /* TypeKeyword */ ) { + if (node.kind === 156 /* TypeKeyword */ ) { if (isImportClause(parent2) && parent2.isTypeOnly) { const location = getAdjustedLocationForImportDeclaration(parent2.parent, forRename); if (location) return location; @@ -100684,42 +102604,42 @@ ${lanes.join("\n")} if (location) return location; } } - if (node.kind === 128 /* AsKeyword */ ) { + if (node.kind === 130 /* AsKeyword */ ) { if (isImportSpecifier(parent2) && parent2.propertyName || isExportSpecifier(parent2) && parent2.propertyName || isNamespaceImport(parent2) || isNamespaceExport(parent2)) return parent2.name; if (isExportDeclaration(parent2) && parent2.exportClause && isNamespaceExport(parent2.exportClause)) return parent2.exportClause.name; } - if (node.kind === 100 /* ImportKeyword */ && isImportDeclaration(parent2)) { + if (node.kind === 102 /* ImportKeyword */ && isImportDeclaration(parent2)) { const location = getAdjustedLocationForImportDeclaration(parent2, forRename); if (location) return location; } - if (node.kind === 93 /* ExportKeyword */ ) { + if (node.kind === 95 /* ExportKeyword */ ) { if (isExportDeclaration(parent2)) { const location = getAdjustedLocationForExportDeclaration(parent2, forRename); if (location) return location; } if (isExportAssignment(parent2)) return skipOuterExpressions(parent2.expression); } - if (node.kind === 147 /* RequireKeyword */ && isExternalModuleReference(parent2)) return parent2.expression; - if (node.kind === 158 /* FromKeyword */ && (isImportDeclaration(parent2) || isExportDeclaration(parent2)) && parent2.moduleSpecifier) return parent2.moduleSpecifier; - if ((node.kind === 94 /* ExtendsKeyword */ || node.kind === 117 /* ImplementsKeyword */ ) && isHeritageClause(parent2) && parent2.token === node.kind) { + if (node.kind === 149 /* RequireKeyword */ && isExternalModuleReference(parent2)) return parent2.expression; + if (node.kind === 161 /* FromKeyword */ && (isImportDeclaration(parent2) || isExportDeclaration(parent2)) && parent2.moduleSpecifier) return parent2.moduleSpecifier; + if ((node.kind === 96 /* ExtendsKeyword */ || node.kind === 119 /* ImplementsKeyword */ ) && isHeritageClause(parent2) && parent2.token === node.kind) { const location = getAdjustedLocationForHeritageClause(parent2); if (location) return location; } - if (node.kind === 94 /* ExtendsKeyword */ ) { + if (node.kind === 96 /* ExtendsKeyword */ ) { if (isTypeParameterDeclaration(parent2) && parent2.constraint && isTypeReferenceNode(parent2.constraint)) return parent2.constraint.typeName; if (isConditionalTypeNode(parent2) && isTypeReferenceNode(parent2.extendsType)) return parent2.extendsType.typeName; } - if (node.kind === 138 /* InferKeyword */ && isInferTypeNode(parent2)) return parent2.typeParameter.name; - if (node.kind === 101 /* InKeyword */ && isTypeParameterDeclaration(parent2) && isMappedTypeNode(parent2.parent)) return parent2.name; - if (node.kind === 141 /* KeyOfKeyword */ && isTypeOperatorNode(parent2) && parent2.operator === 141 /* KeyOfKeyword */ && isTypeReferenceNode(parent2.type)) return parent2.type.typeName; - if (node.kind === 146 /* ReadonlyKeyword */ && isTypeOperatorNode(parent2) && parent2.operator === 146 /* ReadonlyKeyword */ && isArrayTypeNode(parent2.type) && isTypeReferenceNode(parent2.type.elementType)) return parent2.type.elementType.typeName; + if (node.kind === 140 /* InferKeyword */ && isInferTypeNode(parent2)) return parent2.typeParameter.name; + if (node.kind === 103 /* InKeyword */ && isTypeParameterDeclaration(parent2) && isMappedTypeNode(parent2.parent)) return parent2.name; + if (node.kind === 143 /* KeyOfKeyword */ && isTypeOperatorNode(parent2) && parent2.operator === 143 /* KeyOfKeyword */ && isTypeReferenceNode(parent2.type)) return parent2.type.typeName; + if (node.kind === 148 /* ReadonlyKeyword */ && isTypeOperatorNode(parent2) && parent2.operator === 148 /* ReadonlyKeyword */ && isArrayTypeNode(parent2.type) && isTypeReferenceNode(parent2.type.elementType)) return parent2.type.elementType.typeName; if (!forRename) { - if (node.kind === 103 /* NewKeyword */ && isNewExpression(parent2) || node.kind === 114 /* VoidKeyword */ && isVoidExpression(parent2) || node.kind === 112 /* TypeOfKeyword */ && isTypeOfExpression(parent2) || node.kind === 133 /* AwaitKeyword */ && isAwaitExpression(parent2) || node.kind === 125 /* YieldKeyword */ && isYieldExpression(parent2) || node.kind === 89 /* DeleteKeyword */ && isDeleteExpression(parent2)) { + if (node.kind === 105 /* NewKeyword */ && isNewExpression(parent2) || node.kind === 116 /* VoidKeyword */ && isVoidExpression(parent2) || node.kind === 114 /* TypeOfKeyword */ && isTypeOfExpression(parent2) || node.kind === 135 /* AwaitKeyword */ && isAwaitExpression(parent2) || node.kind === 127 /* YieldKeyword */ && isYieldExpression(parent2) || node.kind === 91 /* DeleteKeyword */ && isDeleteExpression(parent2)) { if (parent2.expression) return skipOuterExpressions(parent2.expression); } - if ((node.kind === 101 /* InKeyword */ || node.kind === 102 /* InstanceOfKeyword */ ) && isBinaryExpression(parent2) && parent2.operatorToken === node) return skipOuterExpressions(parent2.right); - if (node.kind === 128 /* AsKeyword */ && isAsExpression(parent2) && isTypeReferenceNode(parent2.type)) return parent2.type.typeName; - if (node.kind === 101 /* InKeyword */ && isForInStatement(parent2) || node.kind === 162 /* OfKeyword */ && isForOfStatement(parent2)) return skipOuterExpressions(parent2.expression); + if ((node.kind === 103 /* InKeyword */ || node.kind === 104 /* InstanceOfKeyword */ ) && isBinaryExpression(parent2) && parent2.operatorToken === node) return skipOuterExpressions(parent2.right); + if (node.kind === 130 /* AsKeyword */ && isAsExpression(parent2) && isTypeReferenceNode(parent2.type)) return parent2.type.typeName; + if (node.kind === 103 /* InKeyword */ && isForInStatement(parent2) || node.kind === 165 /* OfKeyword */ && isForOfStatement(parent2)) return skipOuterExpressions(parent2.expression); } return node; } @@ -100746,7 +102666,7 @@ ${lanes.join("\n")} const i = binarySearchKey(children, position, (_, i2)=>i2, (middle, _)=>{ const end = children[middle].getEnd(); if (end < position) return -1 /* LessThan */ ; - const start = allowPositionInLeadingTrivia ? children[middle].getFullStart() : children[middle].getStart(sourceFile, /*includeJsDoc*/ true); + const start = allowPositionInLeadingTrivia ? children[middle].getFullStart() : children[middle].getStart(sourceFile, /*includeJsDocComment*/ true); if (start > position) return 1 /* GreaterThan */ ; if (nodeContainsPosition(children[middle], start, end)) { if (children[middle - 1]) { @@ -100765,9 +102685,9 @@ ${lanes.join("\n")} return current; } function nodeContainsPosition(node, start, end) { - end != null ? end : end = node.getEnd(); + end ?? (end = node.getEnd()); if (end < position) return false; - start != null ? start : start = allowPositionInLeadingTrivia ? node.getFullStart() : node.getStart(sourceFile, /*includeJsDoc*/ true); + start ?? (start = allowPositionInLeadingTrivia ? node.getFullStart() : node.getStart(sourceFile, /*includeJsDocComment*/ true)); if (start > position) return false; if (position < end || position === end && (node.kind === 1 /* EndOfFileToken */ || includeEndPosition)) return true; else if (includePrecedingTokenAtEndPosition && end === position) { @@ -100828,11 +102748,15 @@ ${lanes.join("\n")} !nodeHasTokens(child, sourceFile) || isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { const candidate2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile, n.kind); - return candidate2 && findRightmostToken(candidate2, sourceFile); + if (candidate2) { + if (!excludeJsdoc && isJSDocCommentContainingNode(candidate2) && candidate2.getChildren(sourceFile).length) return find2(candidate2); + return findRightmostToken(candidate2, sourceFile); + } + return void 0; } else return find2(child); } } - Debug.assert(startNode2 !== void 0 || n.kind === 308 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || isJSDocCommentContainingNode(n)); + Debug.assert(startNode2 !== void 0 || n.kind === 312 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || isJSDocCommentContainingNode(n)); const candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile, n.kind); return candidate && findRightmostToken(candidate, sourceFile); } @@ -100851,7 +102775,7 @@ ${lanes.join("\n")} for(let i = exclusiveStartPosition - 1; i >= 0; i--){ const child = children[i]; if (isWhiteSpaceOnlyJsxText(child)) { - if (i === 0 && (parentKind === 11 /* JsxText */ || parentKind === 282 /* JsxSelfClosingElement */ )) Debug.fail("`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`"); + if (i === 0 && (parentKind === 12 /* JsxText */ || parentKind === 285 /* JsxSelfClosingElement */ )) Debug.fail("`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`"); } else if (nodeHasTokens(children[i], sourceFile)) return children[i]; } } @@ -100867,11 +102791,11 @@ ${lanes.join("\n")} function isInsideJsxElementOrAttribute(sourceFile, position) { const token = getTokenAtPosition(sourceFile, position); if (!token) return false; - if (token.kind === 11 /* JsxText */ ) return true; - if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 11 /* JsxText */ ) return true; - if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 291 /* JsxExpression */ ) return true; - if (token && token.kind === 19 /* CloseBraceToken */ && token.parent.kind === 291 /* JsxExpression */ ) return true; - if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 284 /* JsxClosingElement */ ) return true; + if (token.kind === 12 /* JsxText */ ) return true; + if (token.kind === 30 /* LessThanToken */ && token.parent.kind === 12 /* JsxText */ ) return true; + if (token.kind === 30 /* LessThanToken */ && token.parent.kind === 294 /* JsxExpression */ ) return true; + if (token && token.kind === 20 /* CloseBraceToken */ && token.parent.kind === 294 /* JsxExpression */ ) return true; + if (token.kind === 30 /* LessThanToken */ && token.parent.kind === 287 /* JsxClosingElement */ ) return true; return false; } function isWhiteSpaceOnlyJsxText(node) { @@ -100884,15 +102808,15 @@ ${lanes.join("\n")} function isInJSXText(sourceFile, position) { const token = getTokenAtPosition(sourceFile, position); if (isJsxText(token)) return true; - if (token.kind === 18 /* OpenBraceToken */ && isJsxExpression(token.parent) && isJsxElement(token.parent.parent)) return true; - if (token.kind === 29 /* LessThanToken */ && isJsxOpeningLikeElement(token.parent) && isJsxElement(token.parent.parent)) return true; + if (token.kind === 19 /* OpenBraceToken */ && isJsxExpression(token.parent) && isJsxElement(token.parent.parent)) return true; + if (token.kind === 30 /* LessThanToken */ && isJsxOpeningLikeElement(token.parent) && isJsxElement(token.parent.parent)) return true; return false; } function isInsideJsxElement(sourceFile, position) { function isInsideJsxElementTraversal(node) { while(node){ - if (node.kind >= 282 /* JsxSelfClosingElement */ && node.kind <= 291 /* JsxExpression */ || node.kind === 11 /* JsxText */ || node.kind === 29 /* LessThanToken */ || node.kind === 31 /* GreaterThanToken */ || node.kind === 79 /* Identifier */ || node.kind === 19 /* CloseBraceToken */ || node.kind === 18 /* OpenBraceToken */ || node.kind === 43 /* SlashToken */ ) node = node.parent; - else if (node.kind === 281 /* JsxElement */ ) { + if (node.kind >= 285 /* JsxSelfClosingElement */ && node.kind <= 294 /* JsxExpression */ || node.kind === 12 /* JsxText */ || node.kind === 30 /* LessThanToken */ || node.kind === 32 /* GreaterThanToken */ || node.kind === 80 /* Identifier */ || node.kind === 20 /* CloseBraceToken */ || node.kind === 19 /* OpenBraceToken */ || node.kind === 44 /* SlashToken */ ) node = node.parent; + else if (node.kind === 284 /* JsxElement */ ) { if (position > node.getStart(sourceFile)) return true; node = node.parent; } else return false; @@ -100943,9 +102867,9 @@ ${lanes.join("\n")} let nTypeArguments = 0; while(token){ switch(token.kind){ - case 29 /* LessThanToken */ : + case 30 /* LessThanToken */ : token = findPrecedingToken(token.getFullStart(), sourceFile); - if (token && token.kind === 28 /* QuestionDotToken */ ) token = findPrecedingToken(token.getFullStart(), sourceFile); + if (token && token.kind === 29 /* QuestionDotToken */ ) token = findPrecedingToken(token.getFullStart(), sourceFile); if (!token || !isIdentifier(token)) return void 0; if (!remainingLessThanTokens) return isDeclarationName(token) ? void 0 : { called: token, @@ -100953,44 +102877,44 @@ ${lanes.join("\n")} }; remainingLessThanTokens--; break; - case 49 /* GreaterThanGreaterThanGreaterThanToken */ : + case 50 /* GreaterThanGreaterThanGreaterThanToken */ : remainingLessThanTokens = 3; break; - case 48 /* GreaterThanGreaterThanToken */ : + case 49 /* GreaterThanGreaterThanToken */ : remainingLessThanTokens = 2; break; - case 31 /* GreaterThanToken */ : + case 32 /* GreaterThanToken */ : remainingLessThanTokens++; break; - case 19 /* CloseBraceToken */ : - token = findPrecedingMatchingToken(token, 18 /* OpenBraceToken */ , sourceFile); + case 20 /* CloseBraceToken */ : + token = findPrecedingMatchingToken(token, 19 /* OpenBraceToken */ , sourceFile); if (!token) return void 0; break; - case 21 /* CloseParenToken */ : - token = findPrecedingMatchingToken(token, 20 /* OpenParenToken */ , sourceFile); + case 22 /* CloseParenToken */ : + token = findPrecedingMatchingToken(token, 21 /* OpenParenToken */ , sourceFile); if (!token) return void 0; break; - case 23 /* CloseBracketToken */ : - token = findPrecedingMatchingToken(token, 22 /* OpenBracketToken */ , sourceFile); + case 24 /* CloseBracketToken */ : + token = findPrecedingMatchingToken(token, 23 /* OpenBracketToken */ , sourceFile); if (!token) return void 0; break; - case 27 /* CommaToken */ : + case 28 /* CommaToken */ : nTypeArguments++; break; - case 38 /* EqualsGreaterThanToken */ : - case 79 /* Identifier */ : - case 10 /* StringLiteral */ : - case 8 /* NumericLiteral */ : - case 9 /* BigIntLiteral */ : - case 110 /* TrueKeyword */ : - case 95 /* FalseKeyword */ : - case 112 /* TypeOfKeyword */ : - case 94 /* ExtendsKeyword */ : - case 141 /* KeyOfKeyword */ : - case 24 /* DotToken */ : - case 51 /* BarToken */ : - case 57 /* QuestionToken */ : - case 58 /* ColonToken */ : + case 39 /* EqualsGreaterThanToken */ : + case 80 /* Identifier */ : + case 11 /* StringLiteral */ : + case 9 /* NumericLiteral */ : + case 10 /* BigIntLiteral */ : + case 112 /* TrueKeyword */ : + case 97 /* FalseKeyword */ : + case 114 /* TypeOfKeyword */ : + case 96 /* ExtendsKeyword */ : + case 143 /* KeyOfKeyword */ : + case 25 /* DotToken */ : + case 52 /* BarToken */ : + case 58 /* QuestionToken */ : + case 59 /* ColonToken */ : break; default: if (isTypeNode(token)) break; @@ -101020,38 +102944,38 @@ ${lanes.join("\n")} if (flags & 256 /* Abstract */ ) result.push("abstract" /* abstractModifier */ ); if (flags & 1 /* Export */ ) result.push("export" /* exportedModifier */ ); if (flags & 8192 /* Deprecated */ ) result.push("deprecated" /* deprecatedModifier */ ); - if (node.flags & 16777216 /* Ambient */ ) result.push("declare" /* ambientModifier */ ); - if (node.kind === 274 /* ExportAssignment */ ) result.push("export" /* exportedModifier */ ); + if (node.flags & 33554432 /* Ambient */ ) result.push("declare" /* ambientModifier */ ); + if (node.kind === 277 /* ExportAssignment */ ) result.push("export" /* exportedModifier */ ); return result.length > 0 ? result.join(",") : "" /* none */ ; } function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 180 /* TypeReference */ || node.kind === 210 /* CallExpression */ ) return node.typeArguments; - if (isFunctionLike(node) || node.kind === 260 /* ClassDeclaration */ || node.kind === 261 /* InterfaceDeclaration */ ) return node.typeParameters; + if (node.kind === 183 /* TypeReference */ || node.kind === 213 /* CallExpression */ ) return node.typeArguments; + if (isFunctionLike(node) || node.kind === 263 /* ClassDeclaration */ || node.kind === 264 /* InterfaceDeclaration */ ) return node.typeParameters; return void 0; } function isComment(kind) { return kind === 2 /* SingleLineCommentTrivia */ || kind === 3 /* MultiLineCommentTrivia */ ; } function isStringOrRegularExpressionOrTemplateLiteral(kind) { - if (kind === 10 /* StringLiteral */ || kind === 13 /* RegularExpressionLiteral */ || isTemplateLiteralKind(kind)) return true; + if (kind === 11 /* StringLiteral */ || kind === 14 /* RegularExpressionLiteral */ || isTemplateLiteralKind(kind)) return true; return false; } + function areIntersectedTypesAvoidingStringReduction(checker, t1, t2) { + return !!(t1.flags & 4 /* String */ ) && checker.isEmptyAnonymousObjectType(t2); + } function isStringAndEmptyAnonymousObjectIntersection(type) { if (!type.isIntersection()) return false; - const { types: types , checker: checker } = type; - return types.length === 2 && types[0].flags & 4 /* String */ && checker.isEmptyAnonymousObjectType(types[1]); - } - function isPunctuation(kind) { - return 18 /* FirstPunctuation */ <= kind && kind <= 78 /* LastPunctuation */ ; + const { types: types, checker: checker } = type; + return types.length === 2 && (areIntersectedTypesAvoidingStringReduction(checker, types[0], types[1]) || areIntersectedTypesAvoidingStringReduction(checker, types[1], types[0])); } function isInsideTemplateLiteral(node, position, sourceFile) { return isTemplateLiteralKind(node.kind) && node.getStart(sourceFile) < position && position < node.end || !!node.isUnterminated && position === node.end; } function isAccessibilityModifier(kind) { switch(kind){ - case 123 /* PublicKeyword */ : - case 121 /* PrivateKeyword */ : - case 122 /* ProtectedKeyword */ : + case 125 /* PublicKeyword */ : + case 123 /* PrivateKeyword */ : + case 124 /* ProtectedKeyword */ : return true; } return false; @@ -101062,10 +102986,10 @@ ${lanes.join("\n")} return result; } function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 206 /* ArrayLiteralExpression */ || node.kind === 207 /* ObjectLiteralExpression */ ) { - if (node.parent.kind === 223 /* BinaryExpression */ && node.parent.left === node && node.parent.operatorToken.kind === 63 /* EqualsToken */ ) return true; - if (node.parent.kind === 247 /* ForOfStatement */ && node.parent.initializer === node) return true; - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 299 /* PropertyAssignment */ ? node.parent.parent : node.parent)) return true; + if (node.kind === 209 /* ArrayLiteralExpression */ || node.kind === 210 /* ObjectLiteralExpression */ ) { + if (node.parent.kind === 226 /* BinaryExpression */ && node.parent.left === node && node.parent.operatorToken.kind === 64 /* EqualsToken */ ) return true; + if (node.parent.kind === 250 /* ForOfStatement */ && node.parent.initializer === node) return true; + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 303 /* PropertyAssignment */ ? node.parent.parent : node.parent)) return true; } return false; } @@ -101082,8 +103006,8 @@ ${lanes.join("\n")} function getReplacementSpanForContextToken(contextToken) { if (!contextToken) return void 0; switch(contextToken.kind){ - case 10 /* StringLiteral */ : - case 14 /* NoSubstitutionTemplateLiteral */ : + case 11 /* StringLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : return createTextSpanFromStringLiteralLikeContent(contextToken); default: return createTextSpanFromNode(contextToken); @@ -101118,7 +103042,7 @@ ${lanes.join("\n")} return contains(typeKeywords, kind); } function isTypeKeywordToken(node) { - return node.kind === 154 /* TypeKeyword */ ; + return node.kind === 156 /* TypeKeyword */ ; } function isTypeKeywordTokenOrIdentifier(node) { return isTypeKeywordToken(node) || isIdentifier(node) && node.text === "type"; @@ -101145,7 +103069,7 @@ ${lanes.join("\n")} return type.isTypeParameter() ? type.getConstraint() || type : type; } function getNameFromPropertyName(name) { - return name.kind === 164 /* ComputedPropertyName */ ? isStringOrNumericLiteralLike(name.expression) ? name.expression.text : void 0 : isPrivateIdentifier(name) ? idText(name) : getTextOfIdentifierOrLiteral(name); + return name.kind === 167 /* ComputedPropertyName */ ? isStringOrNumericLiteralLike(name.expression) ? name.expression.text : void 0 : isPrivateIdentifier(name) ? idText(name) : getTextOfIdentifierOrLiteral(name); } function programContainsModules(program) { return program.getSourceFiles().some((s)=>!s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!(s.externalModuleIndicator || s.commonJsModuleIndicator)); @@ -101165,8 +103089,8 @@ ${lanes.join("\n")} getSymlinkCache: maybeBind(host, host.getSymlinkCache) || program.getSymlinkCache, getModuleSpecifierCache: maybeBind(host, host.getModuleSpecifierCache), getPackageJsonInfoCache: ()=>{ - var _a2; - return (_a2 = program.getModuleResolutionCache()) == null ? void 0 : _a2.getPackageJsonInfoCache(); + var _a; + return (_a = program.getModuleResolutionCache()) == null ? void 0 : _a.getPackageJsonInfoCache(); }, getGlobalTypingsCacheLocation: maybeBind(host, host.getGlobalTypingsCacheLocation), redirectTargetsMap: program.redirectTargetsMap, @@ -101222,7 +103146,7 @@ ${lanes.join("\n")} if (symbol.escapedName !== "default" /* Default */ ) return symbol.escapedName; return firstDefined(symbol.declarations, (decl)=>{ const name = getNameOfDeclaration(decl); - return name && name.kind === 79 /* Identifier */ ? name.escapedText : void 0; + return name && name.kind === 80 /* Identifier */ ? name.escapedText : void 0; }); } function isModuleSpecifierLike(node) { @@ -101250,7 +103174,7 @@ ${lanes.join("\n")} } function insertImports(changes, sourceFile, imports, blankLineBetween, preferences) { const decl = isArray(imports) ? imports[0] : imports; - const importKindPredicate = decl.kind === 240 /* VariableStatement */ ? isRequireVariableStatement : isAnyImportSyntax; + const importKindPredicate = decl.kind === 243 /* VariableStatement */ ? isRequireVariableStatement : isAnyImportSyntax; const existingImportStatements = filter(sourceFile.statements, importKindPredicate); let sortKind = isArray(imports) ? ts_OrganizeImports_exports.detectImportDeclarationSorting(imports, preferences) : 3 /* Both */ ; const comparer = ts_OrganizeImports_exports.getOrganizeImportsComparer(preferences, sortKind === 2 /* CaseInsensitive */ ); @@ -101308,7 +103232,7 @@ ${lanes.join("\n")} return mapsTo && (!fileExists || fileExists(normalizePath(mapsTo.fileName)) ? mapsTo : void 0); } function getMappedDocumentSpan(documentSpan, sourceMapper, fileExists) { - const { fileName: fileName , textSpan: textSpan } = documentSpan; + const { fileName: fileName, textSpan: textSpan } = documentSpan; const newPosition = getMappedLocation({ fileName: fileName, pos: textSpan.start @@ -101507,7 +103431,7 @@ ${lanes.join("\n")} return displayPart(text, 22 /* link */ ); } function buildLinkParts(link, checker) { - var _a2; + var _a; const prefix = isJSDocLink(link) ? "link" : isJSDocLinkCode(link) ? "linkcode" : "linkplain"; const parts = [ linkPart(`{@${prefix} `) @@ -101519,7 +103443,7 @@ ${lanes.join("\n")} const suffix = findLinkNameEnd(link.text); const name = getTextOfNode(link.name) + link.text.slice(0, suffix); const text = skipSeparatorFromLinkText(link.text.slice(suffix)); - const decl = (symbol == null ? void 0 : symbol.valueDeclaration) || ((_a2 = symbol == null ? void 0 : symbol.declarations) == null ? void 0 : _a2[0]); + const decl = (symbol == null ? void 0 : symbol.valueDeclaration) || ((_a = symbol == null ? void 0 : symbol.declarations) == null ? void 0 : _a[0]); if (decl) { parts.push(linkNamePart(name, decl)); if (text) parts.push(linkTextPart(text)); @@ -101556,8 +103480,8 @@ ${lanes.join("\n")} return 0; } function getNewLineOrDefaultFromHost(host, formatSettings) { - var _a2; - return (formatSettings == null ? void 0 : formatSettings.newLineCharacter) || ((_a2 = host.getNewLine) == null ? void 0 : _a2.call(host)) || lineFeed2; + var _a; + return (formatSettings == null ? void 0 : formatSettings.newLineCharacter) || ((_a = host.getNewLine) == null ? void 0 : _a.call(host)) || lineFeed2; } function lineBreakPart() { return displayPart("\n", 6 /* lineBreak */ ); @@ -101583,7 +103507,7 @@ ${lanes.join("\n")} function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags = 0 /* None */ ) { flags |= 25632 /* OmitParameterModifiers */ ; return mapToDisplayParts((writer)=>{ - typechecker.writeSignature(signature, enclosingDeclaration, flags, /*signatureKind*/ void 0, writer); + typechecker.writeSignature(signature, enclosingDeclaration, flags, /*kind*/ void 0, writer); }); } function nodeToDisplayParts(node, enclosingDeclaration) { @@ -101643,7 +103567,12 @@ ${lanes.join("\n")} return visited; } function getSynthesizedDeepClones(nodes, includeTrivia = true) { - return nodes && factory.createNodeArray(nodes.map((n)=>getSynthesizedDeepClone(n, includeTrivia)), nodes.hasTrailingComma); + if (nodes) { + const cloned = factory.createNodeArray(nodes.map((n)=>getSynthesizedDeepClone(n, includeTrivia)), nodes.hasTrailingComma); + setTextRange(cloned, nodes); + return cloned; + } + return nodes; } function getSynthesizedDeepClonesWithReplacements(nodes, includeTrivia, replaceNode) { return factory.createNodeArray(nodes.map((n)=>getSynthesizedDeepCloneWithReplacements(n, includeTrivia, replaceNode)), nodes.hasTrailingComma); @@ -101689,10 +103618,10 @@ ${lanes.join("\n")} function getRenameLocation(edits, renameFilename, name, preferLastLocation) { let delta = 0; let lastPos = -1; - for (const { fileName: fileName , textChanges: textChanges2 } of edits){ + for (const { fileName: fileName, textChanges: textChanges2 } of edits){ Debug.assert(fileName === renameFilename); for (const change of textChanges2){ - const { span: span , newText: newText } = change; + const { span: span, newText: newText } = change; const index = indexInTextChange(newText, escapeString(name)); if (index !== -1) { lastPos = span.start + delta + index; @@ -101731,19 +103660,19 @@ ${lanes.join("\n")} return idx === -1 ? -1 : idx + 1; } function needsParentheses(expression) { - return isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || isObjectLiteralExpression(expression) || isAsExpression(expression) && isObjectLiteralExpression(expression.expression); + return isBinaryExpression(expression) && expression.operatorToken.kind === 28 /* CommaToken */ || isObjectLiteralExpression(expression) || isAsExpression(expression) && isObjectLiteralExpression(expression.expression); } function getContextualTypeFromParent(node, checker, contextFlags) { const parent2 = walkUpParenthesizedExpressions(node.parent); switch(parent2.kind){ - case 211 /* NewExpression */ : + case 214 /* NewExpression */ : return checker.getContextualType(parent2, contextFlags); - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : { - const { left: left , operatorToken: operatorToken , right: right } = parent2; + const { left: left, operatorToken: operatorToken, right: right } = parent2; return isEqualityOperatorKind(operatorToken.kind) ? checker.getTypeAtLocation(node === right ? left : right) : checker.getContextualType(node, contextFlags); } - case 292 /* CaseClause */ : + case 296 /* CaseClause */ : return getSwitchedType(parent2, checker); default: return checker.getContextualType(node, contextFlags); @@ -101756,10 +103685,10 @@ ${lanes.join("\n")} } function isEqualityOperatorKind(kind) { switch(kind){ - case 36 /* EqualsEqualsEqualsToken */ : - case 34 /* EqualsEqualsToken */ : - case 37 /* ExclamationEqualsEqualsToken */ : - case 35 /* ExclamationEqualsToken */ : + case 37 /* EqualsEqualsEqualsToken */ : + case 35 /* EqualsEqualsToken */ : + case 38 /* ExclamationEqualsEqualsToken */ : + case 36 /* ExclamationEqualsToken */ : return true; default: return false; @@ -101767,10 +103696,10 @@ ${lanes.join("\n")} } function isStringLiteralOrTemplate(node) { switch(node.kind){ - case 10 /* StringLiteral */ : - case 14 /* NoSubstitutionTemplateLiteral */ : - case 225 /* TemplateExpression */ : - case 212 /* TaggedTemplateExpression */ : + case 11 /* StringLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + case 228 /* TemplateExpression */ : + case 215 /* TaggedTemplateExpression */ : return true; default: return false; @@ -101799,22 +103728,22 @@ ${lanes.join("\n")} return typeIsAccessible ? res : void 0; } function syntaxRequiresTrailingCommaOrSemicolonOrASI(kind) { - return kind === 176 /* CallSignature */ || kind === 177 /* ConstructSignature */ || kind === 178 /* IndexSignature */ || kind === 168 /* PropertySignature */ || kind === 170 /* MethodSignature */ ; + return kind === 179 /* CallSignature */ || kind === 180 /* ConstructSignature */ || kind === 181 /* IndexSignature */ || kind === 171 /* PropertySignature */ || kind === 173 /* MethodSignature */ ; } function syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI(kind) { - return kind === 259 /* FunctionDeclaration */ || kind === 173 /* Constructor */ || kind === 171 /* MethodDeclaration */ || kind === 174 /* GetAccessor */ || kind === 175 /* SetAccessor */ ; + return kind === 262 /* FunctionDeclaration */ || kind === 176 /* Constructor */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ ; } function syntaxRequiresTrailingModuleBlockOrSemicolonOrASI(kind) { - return kind === 264 /* ModuleDeclaration */ ; + return kind === 267 /* ModuleDeclaration */ ; } function syntaxRequiresTrailingSemicolonOrASI(kind) { - return kind === 240 /* VariableStatement */ || kind === 241 /* ExpressionStatement */ || kind === 243 /* DoStatement */ || kind === 248 /* ContinueStatement */ || kind === 249 /* BreakStatement */ || kind === 250 /* ReturnStatement */ || kind === 254 /* ThrowStatement */ || kind === 256 /* DebuggerStatement */ || kind === 169 /* PropertyDeclaration */ || kind === 262 /* TypeAliasDeclaration */ || kind === 269 /* ImportDeclaration */ || kind === 268 /* ImportEqualsDeclaration */ || kind === 275 /* ExportDeclaration */ || kind === 267 /* NamespaceExportDeclaration */ || kind === 274 /* ExportAssignment */ ; + return kind === 243 /* VariableStatement */ || kind === 244 /* ExpressionStatement */ || kind === 246 /* DoStatement */ || kind === 251 /* ContinueStatement */ || kind === 252 /* BreakStatement */ || kind === 253 /* ReturnStatement */ || kind === 257 /* ThrowStatement */ || kind === 259 /* DebuggerStatement */ || kind === 172 /* PropertyDeclaration */ || kind === 265 /* TypeAliasDeclaration */ || kind === 272 /* ImportDeclaration */ || kind === 271 /* ImportEqualsDeclaration */ || kind === 278 /* ExportDeclaration */ || kind === 270 /* NamespaceExportDeclaration */ || kind === 277 /* ExportAssignment */ ; } function nodeIsASICandidate(node, sourceFile) { const lastToken = node.getLastToken(sourceFile); - if (lastToken && lastToken.kind === 26 /* SemicolonToken */ ) return false; + if (lastToken && lastToken.kind === 27 /* SemicolonToken */ ) return false; if (syntaxRequiresTrailingCommaOrSemicolonOrASI(node.kind)) { - if (lastToken && lastToken.kind === 27 /* CommaToken */ ) return false; + if (lastToken && lastToken.kind === 28 /* CommaToken */ ) return false; } else if (syntaxRequiresTrailingModuleBlockOrSemicolonOrASI(node.kind)) { const lastChild = last(node.getChildren(sourceFile)); if (lastChild && isModuleBlock(lastChild)) return false; @@ -101822,10 +103751,10 @@ ${lanes.join("\n")} const lastChild = last(node.getChildren(sourceFile)); if (lastChild && isFunctionBlock(lastChild)) return false; } else if (!syntaxRequiresTrailingSemicolonOrASI(node.kind)) return false; - if (node.kind === 243 /* DoStatement */ ) return true; + if (node.kind === 246 /* DoStatement */ ) return true; const topNode = findAncestor(node, (ancestor)=>!ancestor.parent); const nextToken = findNextToken(node, topNode, sourceFile); - if (!nextToken || nextToken.kind === 19 /* CloseBraceToken */ ) return true; + if (!nextToken || nextToken.kind === 20 /* CloseBraceToken */ ) return true; const startLine = sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line; const endLine = sourceFile.getLineAndCharacterOfPosition(nextToken.getStart(sourceFile)).line; return startLine !== endLine; @@ -101844,12 +103773,12 @@ ${lanes.join("\n")} forEachChild(sourceFile, function visit(node) { if (syntaxRequiresTrailingSemicolonOrASI(node.kind)) { const lastToken = node.getLastToken(sourceFile); - if ((lastToken == null ? void 0 : lastToken.kind) === 26 /* SemicolonToken */ ) withSemicolon++; + if ((lastToken == null ? void 0 : lastToken.kind) === 27 /* SemicolonToken */ ) withSemicolon++; else withoutSemicolon++; } else if (syntaxRequiresTrailingCommaOrSemicolonOrASI(node.kind)) { const lastToken = node.getLastToken(sourceFile); - if ((lastToken == null ? void 0 : lastToken.kind) === 26 /* SemicolonToken */ ) withSemicolon++; - else if (lastToken && lastToken.kind !== 27 /* CommaToken */ ) { + if ((lastToken == null ? void 0 : lastToken.kind) === 27 /* SemicolonToken */ ) withSemicolon++; + else if (lastToken && lastToken.kind !== 28 /* CommaToken */ ) { const lastTokenLine = getLineAndCharacterOfPosition(sourceFile, lastToken.getStart(sourceFile)).line; const nextTokenLine = getLineAndCharacterOfPosition(sourceFile, getSpanOfTokenAtPosition(sourceFile, lastToken.end).start).line; if (lastTokenLine !== nextTokenLine) withoutSemicolon++; @@ -101876,7 +103805,7 @@ ${lanes.join("\n")} function tryAndIgnoreErrors(cb) { try { return cb(); - } catch (e) { + } catch { return void 0; } } @@ -102047,12 +103976,12 @@ ${lanes.join("\n")} function tryParseJson(text) { try { return JSON.parse(text); - } catch (e) { + } catch { return void 0; } } function consumesNodeCoreModules(sourceFile) { - return some(sourceFile.imports, ({ text: text })=>ts_JsTyping_exports.nodeCoreModules.has(text)); + return some(sourceFile.imports, ({ text: text })=>ts_JsTyping_exports.nodeCoreModules.has(text)); } function isInsideNodeModules(fileOrDirectory) { return contains(getPathComponents(fileOrDirectory), "node_modules"); @@ -102070,10 +103999,10 @@ ${lanes.join("\n")} } } function getDiagnosticsWithinSpan(span, sortedFileDiagnostics) { - var _a2; + var _a; let index = binarySearchKey(sortedFileDiagnostics, span.start, (diag2)=>diag2.start, compareValues); if (index < 0) index = ~index; - while(((_a2 = sortedFileDiagnostics[index - 1]) == null ? void 0 : _a2.start) === span.start)index--; + while(((_a = sortedFileDiagnostics[index - 1]) == null ? void 0 : _a.start) === span.start)index--; const result = []; const end = textSpanEnd(span); while(true){ @@ -102084,7 +104013,7 @@ ${lanes.join("\n")} } return result; } - function getRefactorContextSpan({ startPosition: startPosition , endPosition: endPosition }) { + function getRefactorContextSpan({ startPosition: startPosition, endPosition: endPosition }) { return createTextSpanFromBounds(startPosition, endPosition === void 0 ? startPosition : endPosition); } function getFixableErrorSpanExpression(sourceFile, span) { @@ -102105,8 +104034,8 @@ ${lanes.join("\n")} if (needsNameFromDeclaration(symbol)) { const fromDeclaration = getDefaultLikeExportNameFromDeclaration(symbol); if (fromDeclaration) return fromDeclaration; - const fileNameCase = ts_codefix_exports.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget, /*preferCapitalized*/ false); - const capitalized = ts_codefix_exports.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget, /*preferCapitalized*/ true); + const fileNameCase = ts_codefix_exports.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget, /*forceCapitalize*/ false); + const capitalized = ts_codefix_exports.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget, /*forceCapitalize*/ true); if (fileNameCase === capitalized) return fileNameCase; return [ fileNameCase, @@ -102124,16 +104053,18 @@ ${lanes.join("\n")} } function getDefaultLikeExportNameFromDeclaration(symbol) { return firstDefined(symbol.declarations, (d)=>{ - var _a2, _b; - return isExportAssignment(d) ? (_a2 = tryCast(skipOuterExpressions(d.expression), isIdentifier)) == null ? void 0 : _a2.text : (_b = tryCast(getNameOfDeclaration(d), isIdentifier)) == null ? void 0 : _b.text; + var _a, _b, _c; + if (isExportAssignment(d)) return (_a = tryCast(skipOuterExpressions(d.expression), isIdentifier)) == null ? void 0 : _a.text; + if (isExportSpecifier(d) && d.symbol.flags === 2097152 /* Alias */ ) return (_b = tryCast(d.propertyName, isIdentifier)) == null ? void 0 : _b.text; + return (_c = tryCast(getNameOfDeclaration(d), isIdentifier)) == null ? void 0 : _c.text; }); } function getSymbolParentOrFail(symbol) { - var _a2; - return Debug.checkDefined(symbol.parent, `Symbol parent was undefined. Flags: ${Debug.formatSymbolFlags(symbol.flags)}. Declarations: ${(_a2 = symbol.declarations) == null ? void 0 : _a2.map((d)=>{ + var _a; + return Debug.checkDefined(symbol.parent, `Symbol parent was undefined. Flags: ${Debug.formatSymbolFlags(symbol.flags)}. Declarations: ${(_a = symbol.declarations) == null ? void 0 : _a.map((d)=>{ const kind = Debug.formatSyntaxKind(d.kind); const inJS = isInJSFile(d); - const { expression: expression } = d; + const { expression: expression } = d; return (inJS ? "[JS]" : "") + kind + (expression ? ` (expression: ${Debug.formatSyntaxKind(expression.kind)})` : ""); }).join(", ")}.`); } @@ -102163,7 +104094,7 @@ ${lanes.join("\n")} const decisionFromFile = firstDefined(file.imports, (node)=>{ if (ts_JsTyping_exports.nodeCoreModules.has(node.text)) return startsWith(node.text, "node:"); }); - return decisionFromFile != null ? decisionFromFile : program.usesUriStyleNodeCoreModules; + return decisionFromFile ?? program.usesUriStyleNodeCoreModules; } function getNewLineKind(newLineCharacter) { return newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */ ; @@ -102171,7 +104102,7 @@ ${lanes.join("\n")} function diagnosticToString(diag2) { return isArray(diag2) ? formatStringFromArgs(getLocaleSpecificMessage(diag2[0]), diag2.slice(1)) : getLocaleSpecificMessage(diag2); } - function getFormatCodeSettingsForWriting({ options: options }, sourceFile) { + function getFormatCodeSettingsForWriting({ options: options }, sourceFile) { const shouldAutoDetectSemicolonPreference = !options.semicolons || options.semicolons === "ignore" /* Ignore */ ; const shouldRemoveSemicolons = options.semicolons === "remove" /* Remove */ || shouldAutoDetectSemicolonPreference && !probablyUsesSemicolons(sourceFile); return { @@ -102192,14 +104123,14 @@ ${lanes.join("\n")} for (const clause of clauses)if (!isDefaultClause(clause)) { const expression = skipParentheses(clause.expression); if (isLiteralExpression(expression)) switch(expression.kind){ - case 14 /* NoSubstitutionTemplateLiteral */ : - case 10 /* StringLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + case 11 /* StringLiteral */ : existingStrings.add(expression.text); break; - case 8 /* NumericLiteral */ : + case 9 /* NumericLiteral */ : existingNumbers.add(parseInt(expression.text)); break; - case 9 /* BigIntLiteral */ : + case 10 /* BigIntLiteral */ : const parsedBigInt = parseBigInt(endsWith(expression.text, "n") ? expression.text.slice(0, -1) : expression.text); if (parsedBigInt) existingBigInts.add(pseudoBigIntToString(parsedBigInt)); break; @@ -102236,6 +104167,23 @@ ${lanes.join("\n")} } } } + function fileShouldUseJavaScriptRequire(file, program, host, preferRequire) { + var _a; + const fileName = typeof file === "string" ? file : file.fileName; + if (!hasJSFileExtension(fileName)) return false; + const compilerOptions = program.getCompilerOptions(); + const moduleKind = getEmitModuleKind(compilerOptions); + const impliedNodeFormat = typeof file === "string" ? getImpliedNodeFormatForFile(toPath(file, host.getCurrentDirectory(), hostGetCanonicalFileName(host)), (_a = program.getPackageJsonInfoCache) == null ? void 0 : _a.call(program), host, compilerOptions) : file.impliedNodeFormat; + if (impliedNodeFormat === 99 /* ESNext */ ) return false; + if (impliedNodeFormat === 1 /* CommonJS */ ) return true; + if (compilerOptions.verbatimModuleSyntax && moduleKind === 1 /* CommonJS */ ) return true; + if (compilerOptions.verbatimModuleSyntax && emitModuleKindIsNonNodeESM(moduleKind)) return false; + if (typeof file === "object") { + if (file.commonJsModuleIndicator) return true; + if (file.externalModuleIndicator) return false; + } + return preferRequire; + } var scanner, SemanticMeaning, tripleSlashDirectivePrefixRegex, typeKeywords, QuotePreference, displayPartWriter, lineFeed2, ANONYMOUS, syntaxMayBeASICandidate; var init_utilities4 = __esm({ "src/services/utilities.ts" () { @@ -102252,30 +104200,31 @@ ${lanes.join("\n")} })(SemanticMeaning || {}); tripleSlashDirectivePrefixRegex = /^\/\/\/\s*{ - QuotePreference5[QuotePreference5["Single"] = 0] = "Single"; - QuotePreference5[QuotePreference5["Double"] = 1] = "Double"; - return QuotePreference5; + QuotePreference = /* @__PURE__ */ ((QuotePreference7)=>{ + QuotePreference7[QuotePreference7["Single"] = 0] = "Single"; + QuotePreference7[QuotePreference7["Double"] = 1] = "Double"; + return QuotePreference7; })(QuotePreference || {}); displayPartWriter = getDisplayPartWriter(); lineFeed2 = "\n"; @@ -102307,7 +104256,7 @@ ${lanes.join("\n")} if (moduleFile) { const nodeModulesPathParts = getNodeModulePathParts(moduleFile.fileName); if (nodeModulesPathParts) { - const { topLevelNodeModulesIndex: topLevelNodeModulesIndex , topLevelPackageNameIndex: topLevelPackageNameIndex , packageRootIndex: packageRootIndex } = nodeModulesPathParts; + const { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex } = nodeModulesPathParts; packageName = unmangleScopedPackageName(getPackageNameFromTypesPackageName(moduleFile.fileName.substring(topLevelPackageNameIndex + 1, packageRootIndex))); if (startsWith(importingFile, moduleFile.path.substring(0, topLevelNodeModulesIndex))) { const prevDeepestNodeModulesPath = packages.get(packageName); @@ -102357,7 +104306,7 @@ ${lanes.join("\n")} search: (importingFile, preferCapitalized, matches, action)=>{ if (importingFile !== usableByFileName) return; return forEachEntry(exportInfo, (info, key2)=>{ - const { symbolName: symbolName2 , ambientModuleName: ambientModuleName } = parseKey(key2); + const { symbolName: symbolName2, ambientModuleName: ambientModuleName } = parseKey(key2); const name = preferCapitalized && info[0].capitalizedSymbolName || symbolName2; if (matches(name, info[0].targetFlags)) { const rehydrated = info.map(rehydrateCachedInfo); @@ -102378,7 +104327,7 @@ ${lanes.join("\n")} // Adding or removing imports from node could change the outcome of that guess, so could change the suggestions list. typeAcquisitionEnabled && consumesNodeCoreModules(oldSourceFile) !== consumesNodeCoreModules(newSourceFile) || // Module agumentation and ambient module changes can add or remove exports available to be auto-imported. // Changes elsewhere in the file can change the *type* of an export in a module augmentation, - // but type info is gathered in getCompletionEntryDetails, which doesn’t use the cache. + // but type info is gathered in getCompletionEntryDetails, which doesn't use the cache. !arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations) || !ambientModuleDeclarationsAreEqual(oldSourceFile, newSourceFile)) { cache.clear(); return true; @@ -102393,7 +104342,7 @@ ${lanes.join("\n")} return cache; function rehydrateCachedInfo(info) { if (info.symbol && info.moduleSymbol) return info; - const { id: id , exportKind: exportKind , targetFlags: targetFlags , isFromPackageJson: isFromPackageJson , moduleFileName: moduleFileName } = info; + const { id: id, exportKind: exportKind, targetFlags: targetFlags, isFromPackageJson: isFromPackageJson, moduleFileName: moduleFileName } = info; const [cachedSymbol, cachedModuleSymbol] = symbols.get(id) || emptyArray; if (cachedSymbol && cachedModuleSymbol) return { symbol: cachedSymbol, @@ -102456,12 +104405,12 @@ ${lanes.join("\n")} } } function isImportableFile(program, from, to, preferences, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) { - var _a2; + var _a; if (from === to) return false; const cachedResult = moduleSpecifierCache == null ? void 0 : moduleSpecifierCache.get(from.path, to.path, preferences, {}); if ((cachedResult == null ? void 0 : cachedResult.isBlockedByPackageJsonDependencies) !== void 0) return !cachedResult.isBlockedByPackageJsonDependencies; const getCanonicalFileName = hostGetCanonicalFileName(moduleSpecifierResolutionHost); - const globalTypingsCache = (_a2 = moduleSpecifierResolutionHost.getGlobalTypingsCacheLocation) == null ? void 0 : _a2.call(moduleSpecifierResolutionHost); + const globalTypingsCache = (_a = moduleSpecifierResolutionHost.getGlobalTypingsCacheLocation) == null ? void 0 : _a.call(moduleSpecifierResolutionHost); const hasImportablePath = !!ts_moduleSpecifiers_exports.forEachFileNameOfModule(from.fileName, to.fileName, moduleSpecifierResolutionHost, /*preferSymlinks*/ false, (toPath3)=>{ const toFile = program.getSourceFile(toPath3); return (toFile === to || !toFile) && isImportablePath(from.fileName, toPath3, getCanonicalFileName, globalTypingsCache); @@ -102479,14 +104428,14 @@ ${lanes.join("\n")} return toNodeModulesParent === void 0 || startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) || !!globalCachePath && startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent); } function forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, cb) { - var _a2, _b; - const useCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames(host); + var _a, _b; + const useCaseSensitiveFileNames2 = hostUsesCaseSensitiveFileNames(host); const excludePatterns = preferences.autoImportFileExcludePatterns && mapDefined(preferences.autoImportFileExcludePatterns, (spec)=>{ const pattern = getPatternFromSpec(spec, "", "exclude"); - return pattern ? getRegexFromPattern(pattern, useCaseSensitiveFileNames) : void 0; + return pattern ? getRegexFromPattern(pattern, useCaseSensitiveFileNames2) : void 0; }); forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), excludePatterns, (module2, file)=>cb(module2, file, program, /*isFromPackageJson*/ false)); - const autoImportProvider = useAutoImportProvider && ((_a2 = host.getPackageJsonAutoImportProvider) == null ? void 0 : _a2.call(host)); + const autoImportProvider = useAutoImportProvider && ((_a = host.getPackageJsonAutoImportProvider) == null ? void 0 : _a.call(host)); if (autoImportProvider) { const start = timestamp(); const checker = program.getTypeChecker(); @@ -102497,24 +104446,24 @@ ${lanes.join("\n")} } } function forEachExternalModule(checker, allSourceFiles, excludePatterns, cb) { - var _a2; + var _a; const isExcluded = excludePatterns && ((fileName)=>excludePatterns.some((p)=>p.test(fileName))); - for (const ambient of checker.getAmbientModules())if (!stringContains(ambient.name, "*") && !(excludePatterns && ((_a2 = ambient.declarations) == null ? void 0 : _a2.every((d)=>isExcluded(d.getSourceFile().fileName))))) cb(ambient, /*sourceFile*/ void 0); + for (const ambient of checker.getAmbientModules())if (!stringContains(ambient.name, "*") && !(excludePatterns && ((_a = ambient.declarations) == null ? void 0 : _a.every((d)=>isExcluded(d.getSourceFile().fileName))))) cb(ambient, /*sourceFile*/ void 0); for (const sourceFile of allSourceFiles)if (isExternalOrCommonJsModule(sourceFile) && !(isExcluded == null ? void 0 : isExcluded(sourceFile.fileName))) cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile); } function getExportInfoMap(importingFile, host, program, preferences, cancellationToken) { - var _a2, _b, _c, _d, _e; + var _a, _b, _c, _d, _e; const start = timestamp(); - (_a2 = host.getPackageJsonAutoImportProvider) == null || _a2.call(host); + (_a = host.getPackageJsonAutoImportProvider) == null || _a.call(host); const cache = ((_b = host.getCachedExportInfoMap) == null ? void 0 : _b.call(host)) || createCacheableExportInfoMap({ getCurrentProgram: ()=>program, getPackageJsonAutoImportProvider: ()=>{ - var _a3; - return (_a3 = host.getPackageJsonAutoImportProvider) == null ? void 0 : _a3.call(host); + var _a2; + return (_a2 = host.getPackageJsonAutoImportProvider) == null ? void 0 : _a2.call(host); }, getGlobalTypingsCacheLocation: ()=>{ - var _a3; - return (_a3 = host.getGlobalTypingsCacheLocation) == null ? void 0 : _a3.call(host); + var _a2; + return (_a2 = host.getGlobalTypingsCacheLocation) == null ? void 0 : _a2.call(host); } }); if (cache.isUsableByFile(importingFile.path)) { @@ -102545,7 +104494,7 @@ ${lanes.join("\n")} function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { const exported = getDefaultLikeExportWorker(moduleSymbol, checker); if (!exported) return void 0; - const { symbol: symbol , exportKind: exportKind } = exported; + const { symbol: symbol, exportKind: exportKind } = exported; const info = getDefaultExportInfoWorker(symbol, checker, compilerOptions); return info && { symbol: symbol, @@ -102594,8 +104543,8 @@ ${lanes.join("\n")} } function getNameForExportDefault(symbol) { return symbol.declarations && firstDefined(symbol.declarations, (declaration)=>{ - var _a2; - if (isExportAssignment(declaration)) return (_a2 = tryCast(skipOuterExpressions(declaration.expression), isIdentifier)) == null ? void 0 : _a2.text; + var _a; + if (isExportAssignment(declaration)) return (_a = tryCast(skipOuterExpressions(declaration.expression), isIdentifier)) == null ? void 0 : _a.text; else if (isExportSpecifier(declaration)) { Debug.assert(declaration.name.text === "default" /* Default */ , "Expected the specifier to be a default export"); return declaration.propertyName && declaration.propertyName.text; @@ -102633,10 +104582,10 @@ ${lanes.join("\n")} let token = 0 /* Unknown */ ; let lastNonTriviaToken = 0 /* Unknown */ ; const templateStack = []; - const { prefix: prefix , pushTemplate: pushTemplate } = getPrefixFromLexState(lexState); + const { prefix: prefix, pushTemplate: pushTemplate } = getPrefixFromLexState(lexState); text = prefix + text; const offset = prefix.length; - if (pushTemplate) templateStack.push(15 /* TemplateHead */ ); + if (pushTemplate) templateStack.push(16 /* TemplateHead */ ); scanner2.setText(text); let endOfLineState = 0 /* None */ ; const spans = []; @@ -102647,8 +104596,8 @@ ${lanes.join("\n")} handleToken(); lastNonTriviaToken = token; } - const end = scanner2.getTextPos(); - pushEncodedClassification(scanner2.getTokenPos(), end, offset, classFromKind(token), spans); + const end = scanner2.getTokenEnd(); + pushEncodedClassification(scanner2.getTokenStart(), end, offset, classFromKind(token), spans); if (end >= text.length) { const end2 = getNewEndOfLineState(scanner2, token, lastOrUndefined(templateStack)); if (end2 !== void 0) endOfLineState = end2; @@ -102656,46 +104605,46 @@ ${lanes.join("\n")} }while (token !== 1 /* EndOfFileToken */ ); function handleToken() { switch(token){ - case 43 /* SlashToken */ : - case 68 /* SlashEqualsToken */ : - if (!noRegexTable[lastNonTriviaToken] && scanner2.reScanSlashToken() === 13 /* RegularExpressionLiteral */ ) token = 13 /* RegularExpressionLiteral */ ; + case 44 /* SlashToken */ : + case 69 /* SlashEqualsToken */ : + if (!noRegexTable[lastNonTriviaToken] && scanner2.reScanSlashToken() === 14 /* RegularExpressionLiteral */ ) token = 14 /* RegularExpressionLiteral */ ; break; - case 29 /* LessThanToken */ : - if (lastNonTriviaToken === 79 /* Identifier */ ) angleBracketStack++; + case 30 /* LessThanToken */ : + if (lastNonTriviaToken === 80 /* Identifier */ ) angleBracketStack++; break; - case 31 /* GreaterThanToken */ : + case 32 /* GreaterThanToken */ : if (angleBracketStack > 0) angleBracketStack--; break; - case 131 /* AnyKeyword */ : - case 152 /* StringKeyword */ : - case 148 /* NumberKeyword */ : - case 134 /* BooleanKeyword */ : - case 153 /* SymbolKeyword */ : - if (angleBracketStack > 0 && !syntacticClassifierAbsent) token = 79 /* Identifier */ ; + case 133 /* AnyKeyword */ : + case 154 /* StringKeyword */ : + case 150 /* NumberKeyword */ : + case 136 /* BooleanKeyword */ : + case 155 /* SymbolKeyword */ : + if (angleBracketStack > 0 && !syntacticClassifierAbsent) token = 80 /* Identifier */ ; break; - case 15 /* TemplateHead */ : + case 16 /* TemplateHead */ : templateStack.push(token); break; - case 18 /* OpenBraceToken */ : + case 19 /* OpenBraceToken */ : if (templateStack.length > 0) templateStack.push(token); break; - case 19 /* CloseBraceToken */ : + case 20 /* CloseBraceToken */ : if (templateStack.length > 0) { const lastTemplateStackToken = lastOrUndefined(templateStack); - if (lastTemplateStackToken === 15 /* TemplateHead */ ) { - token = scanner2.reScanTemplateToken(/* isTaggedTemplate */ false); - if (token === 17 /* TemplateTail */ ) templateStack.pop(); - else Debug.assertEqual(token, 16 /* TemplateMiddle */ , "Should have been a template middle."); + if (lastTemplateStackToken === 16 /* TemplateHead */ ) { + token = scanner2.reScanTemplateToken(/*isTaggedTemplate*/ false); + if (token === 18 /* TemplateTail */ ) templateStack.pop(); + else Debug.assertEqual(token, 17 /* TemplateMiddle */ , "Should have been a template middle."); } else { - Debug.assertEqual(lastTemplateStackToken, 18 /* OpenBraceToken */ , "Should have been an open brace"); + Debug.assertEqual(lastTemplateStackToken, 19 /* OpenBraceToken */ , "Should have been an open brace"); templateStack.pop(); } } break; default: if (!isKeyword(token)) break; - if (lastNonTriviaToken === 24 /* DotToken */ ) token = 79 /* Identifier */ ; - else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) token = 79 /* Identifier */ ; + if (lastNonTriviaToken === 25 /* DotToken */ ) token = 80 /* Identifier */ ; + else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) token = 80 /* Identifier */ ; } } return { @@ -102710,7 +104659,7 @@ ${lanes.join("\n")} } function getNewEndOfLineState(scanner2, token, lastOnTemplateStack) { switch(token){ - case 10 /* StringLiteral */ : + case 11 /* StringLiteral */ : { if (!scanner2.isUnterminated()) return void 0; const tokenText = scanner2.getTokenText(); @@ -102726,15 +104675,15 @@ ${lanes.join("\n")} if (isTemplateLiteralKind(token)) { if (!scanner2.isUnterminated()) return void 0; switch(token){ - case 17 /* TemplateTail */ : + case 18 /* TemplateTail */ : return 5 /* InTemplateMiddleOrTail */ ; - case 14 /* NoSubstitutionTemplateLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : return 4 /* InTemplateHeadOrNoSubstitutionTemplate */ ; default: return Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); } } - return lastOnTemplateStack === 15 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : void 0; + return lastOnTemplateStack === 16 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : void 0; } } function pushEncodedClassification(start, end, offset, classification, result) { @@ -102809,11 +104758,11 @@ ${lanes.join("\n")} function canFollow(keyword1, keyword2) { if (!isAccessibilityModifier(keyword1)) return true; switch(keyword2){ - case 137 /* GetKeyword */ : - case 151 /* SetKeyword */ : - case 135 /* ConstructorKeyword */ : - case 124 /* StaticKeyword */ : - case 127 /* AccessorKeyword */ : + case 139 /* GetKeyword */ : + case 153 /* SetKeyword */ : + case 137 /* ConstructorKeyword */ : + case 126 /* StaticKeyword */ : + case 129 /* AccessorKeyword */ : return true; default: return false; @@ -102857,48 +104806,48 @@ ${lanes.join("\n")} } function isBinaryExpressionOperatorToken(token) { switch(token){ - case 41 /* AsteriskToken */ : - case 43 /* SlashToken */ : - case 44 /* PercentToken */ : - case 39 /* PlusToken */ : - case 40 /* MinusToken */ : - case 47 /* LessThanLessThanToken */ : - case 48 /* GreaterThanGreaterThanToken */ : - case 49 /* GreaterThanGreaterThanGreaterThanToken */ : - case 29 /* LessThanToken */ : - case 31 /* GreaterThanToken */ : - case 32 /* LessThanEqualsToken */ : - case 33 /* GreaterThanEqualsToken */ : - case 102 /* InstanceOfKeyword */ : - case 101 /* InKeyword */ : - case 128 /* AsKeyword */ : - case 150 /* SatisfiesKeyword */ : - case 34 /* EqualsEqualsToken */ : - case 35 /* ExclamationEqualsToken */ : - case 36 /* EqualsEqualsEqualsToken */ : - case 37 /* ExclamationEqualsEqualsToken */ : - case 50 /* AmpersandToken */ : - case 52 /* CaretToken */ : - case 51 /* BarToken */ : - case 55 /* AmpersandAmpersandToken */ : - case 56 /* BarBarToken */ : - case 74 /* BarEqualsToken */ : - case 73 /* AmpersandEqualsToken */ : - case 78 /* CaretEqualsToken */ : - case 70 /* LessThanLessThanEqualsToken */ : - case 71 /* GreaterThanGreaterThanEqualsToken */ : - case 72 /* GreaterThanGreaterThanGreaterThanEqualsToken */ : - case 64 /* PlusEqualsToken */ : - case 65 /* MinusEqualsToken */ : - case 66 /* AsteriskEqualsToken */ : - case 68 /* SlashEqualsToken */ : - case 69 /* PercentEqualsToken */ : - case 63 /* EqualsToken */ : - case 27 /* CommaToken */ : - case 60 /* QuestionQuestionToken */ : - case 75 /* BarBarEqualsToken */ : - case 76 /* AmpersandAmpersandEqualsToken */ : - case 77 /* QuestionQuestionEqualsToken */ : + case 42 /* AsteriskToken */ : + case 44 /* SlashToken */ : + case 45 /* PercentToken */ : + case 40 /* PlusToken */ : + case 41 /* MinusToken */ : + case 48 /* LessThanLessThanToken */ : + case 49 /* GreaterThanGreaterThanToken */ : + case 50 /* GreaterThanGreaterThanGreaterThanToken */ : + case 30 /* LessThanToken */ : + case 32 /* GreaterThanToken */ : + case 33 /* LessThanEqualsToken */ : + case 34 /* GreaterThanEqualsToken */ : + case 104 /* InstanceOfKeyword */ : + case 103 /* InKeyword */ : + case 130 /* AsKeyword */ : + case 152 /* SatisfiesKeyword */ : + case 35 /* EqualsEqualsToken */ : + case 36 /* ExclamationEqualsToken */ : + case 37 /* EqualsEqualsEqualsToken */ : + case 38 /* ExclamationEqualsEqualsToken */ : + case 51 /* AmpersandToken */ : + case 53 /* CaretToken */ : + case 52 /* BarToken */ : + case 56 /* AmpersandAmpersandToken */ : + case 57 /* BarBarToken */ : + case 75 /* BarEqualsToken */ : + case 74 /* AmpersandEqualsToken */ : + case 79 /* CaretEqualsToken */ : + case 71 /* LessThanLessThanEqualsToken */ : + case 72 /* GreaterThanGreaterThanEqualsToken */ : + case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */ : + case 65 /* PlusEqualsToken */ : + case 66 /* MinusEqualsToken */ : + case 67 /* AsteriskEqualsToken */ : + case 69 /* SlashEqualsToken */ : + case 70 /* PercentEqualsToken */ : + case 64 /* EqualsToken */ : + case 28 /* CommaToken */ : + case 61 /* QuestionQuestionToken */ : + case 76 /* BarBarEqualsToken */ : + case 77 /* AmpersandAmpersandEqualsToken */ : + case 78 /* QuestionQuestionEqualsToken */ : return true; default: return false; @@ -102906,12 +104855,12 @@ ${lanes.join("\n")} } function isPrefixUnaryExpressionOperatorToken(token) { switch(token){ - case 39 /* PlusToken */ : - case 40 /* MinusToken */ : - case 54 /* TildeToken */ : - case 53 /* ExclamationToken */ : - case 45 /* PlusPlusToken */ : - case 46 /* MinusMinusToken */ : + case 40 /* PlusToken */ : + case 41 /* MinusToken */ : + case 55 /* TildeToken */ : + case 54 /* ExclamationToken */ : + case 46 /* PlusPlusToken */ : + case 47 /* MinusMinusToken */ : return true; default: return false; @@ -102920,15 +104869,15 @@ ${lanes.join("\n")} function classFromKind(token) { if (isKeyword(token)) return 3 /* keyword */ ; else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) return 5 /* operator */ ; - else if (token >= 18 /* FirstPunctuation */ && token <= 78 /* LastPunctuation */ ) return 10 /* punctuation */ ; + else if (token >= 19 /* FirstPunctuation */ && token <= 79 /* LastPunctuation */ ) return 10 /* punctuation */ ; switch(token){ - case 8 /* NumericLiteral */ : + case 9 /* NumericLiteral */ : return 4 /* numericLiteral */ ; - case 9 /* BigIntLiteral */ : + case 10 /* BigIntLiteral */ : return 25 /* bigintLiteral */ ; - case 10 /* StringLiteral */ : + case 11 /* StringLiteral */ : return 6 /* stringLiteral */ ; - case 13 /* RegularExpressionLiteral */ : + case 14 /* RegularExpressionLiteral */ : return 7 /* regularExpressionLiteral */ ; case 7 /* ConflictMarkerTrivia */ : case 3 /* MultiLineCommentTrivia */ : @@ -102937,7 +104886,7 @@ ${lanes.join("\n")} case 5 /* WhitespaceTrivia */ : case 4 /* NewLineTrivia */ : return 8 /* whiteSpace */ ; - case 79 /* Identifier */ : + case 80 /* Identifier */ : default: if (isTemplateLiteralKind(token)) return 6 /* stringLiteral */ ; return 2 /* identifier */ ; @@ -102948,13 +104897,13 @@ ${lanes.join("\n")} } function checkForClassificationCancellation(cancellationToken, kind) { switch(kind){ - case 264 /* ModuleDeclaration */ : - case 260 /* ClassDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 259 /* FunctionDeclaration */ : - case 228 /* ClassExpression */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : + case 267 /* ModuleDeclaration */ : + case 263 /* ClassDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 262 /* FunctionDeclaration */ : + case 231 /* ClassExpression */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : cancellationToken.throwIfCancellationRequested(); } } @@ -103080,12 +105029,12 @@ ${lanes.join("\n")} result.push(type); } function classifyLeadingTriviaAndGetTokenStart(token) { - triviaScanner.setTextPos(token.pos); + triviaScanner.resetTokenState(token.pos); while(true){ - const start = triviaScanner.getTextPos(); + const start = triviaScanner.getTokenEnd(); if (!couldStartTrivia(sourceFile.text, start)) return start; const kind = triviaScanner.scan(); - const end = triviaScanner.getTextPos(); + const end = triviaScanner.getTokenEnd(); const width = end - start; if (!isTrivia(kind)) return start; switch(kind){ @@ -103095,7 +105044,7 @@ ${lanes.join("\n")} case 2 /* SingleLineCommentTrivia */ : case 3 /* MultiLineCommentTrivia */ : classifyComment(token, kind, start, width); - triviaScanner.setTextPos(end); + triviaScanner.resetTokenState(end); continue; case 7 /* ConflictMarkerTrivia */ : const text = sourceFile.text; @@ -103131,7 +105080,7 @@ ${lanes.join("\n")} pushClassification(start, width, 1 /* comment */ ); } function classifyJSDocComment(docComment) { - var _a2, _b, _c, _d, _e, _f, _g, _h; + var _a, _b, _c, _d, _e, _f, _g, _h; let pos = docComment.pos; if (docComment.tags) for (const tag of docComment.tags){ if (tag.pos !== pos) pushCommentRange(pos, tag.pos - pos); @@ -103140,49 +105089,49 @@ ${lanes.join("\n")} pos = tag.tagName.end; let commentStart = tag.tagName.end; switch(tag.kind){ - case 344 /* JSDocParameterTag */ : + case 348 /* JSDocParameterTag */ : const param = tag; processJSDocParameterTag(param); - commentStart = param.isNameFirst && ((_a2 = param.typeExpression) == null ? void 0 : _a2.end) || param.name.end; + commentStart = param.isNameFirst && ((_a = param.typeExpression) == null ? void 0 : _a.end) || param.name.end; break; - case 351 /* JSDocPropertyTag */ : + case 355 /* JSDocPropertyTag */ : const prop = tag; commentStart = prop.isNameFirst && ((_b = prop.typeExpression) == null ? void 0 : _b.end) || prop.name.end; break; - case 348 /* JSDocTemplateTag */ : + case 352 /* JSDocTemplateTag */ : processJSDocTemplateTag(tag); pos = tag.end; commentStart = tag.typeParameters.end; break; - case 349 /* JSDocTypedefTag */ : + case 353 /* JSDocTypedefTag */ : const type = tag; - commentStart = ((_c = type.typeExpression) == null ? void 0 : _c.kind) === 312 /* JSDocTypeExpression */ && ((_d = type.fullName) == null ? void 0 : _d.end) || ((_e = type.typeExpression) == null ? void 0 : _e.end) || commentStart; + commentStart = ((_c = type.typeExpression) == null ? void 0 : _c.kind) === 316 /* JSDocTypeExpression */ && ((_d = type.fullName) == null ? void 0 : _d.end) || ((_e = type.typeExpression) == null ? void 0 : _e.end) || commentStart; break; - case 341 /* JSDocCallbackTag */ : + case 345 /* JSDocCallbackTag */ : commentStart = tag.typeExpression.end; break; - case 347 /* JSDocTypeTag */ : + case 351 /* JSDocTypeTag */ : processElement(tag.typeExpression); pos = tag.end; commentStart = tag.typeExpression.end; break; - case 346 /* JSDocThisTag */ : - case 343 /* JSDocEnumTag */ : + case 350 /* JSDocThisTag */ : + case 347 /* JSDocEnumTag */ : commentStart = tag.typeExpression.end; break; - case 345 /* JSDocReturnTag */ : + case 349 /* JSDocReturnTag */ : processElement(tag.typeExpression); pos = tag.end; commentStart = ((_f = tag.typeExpression) == null ? void 0 : _f.end) || commentStart; break; - case 350 /* JSDocSeeTag */ : + case 354 /* JSDocSeeTag */ : commentStart = ((_g = tag.name) == null ? void 0 : _g.end) || commentStart; break; - case 331 /* JSDocAugmentsTag */ : - case 332 /* JSDocImplementsTag */ : + case 335 /* JSDocAugmentsTag */ : + case 336 /* JSDocImplementsTag */ : commentStart = tag.class.end; break; - case 352 /* JSDocThrowsTag */ : + case 356 /* JSDocThrowsTag */ : processElement(tag.typeExpression); pos = tag.end; commentStart = ((_h = tag.typeExpression) == null ? void 0 : _h.end) || commentStart; @@ -103269,13 +105218,13 @@ ${lanes.join("\n")} if (isLineBreak(text.charCodeAt(i))) break; } pushClassification(start, i - start, 1 /* comment */ ); - mergeConflictScanner.setTextPos(i); - while(mergeConflictScanner.getTextPos() < end)classifyDisabledCodeToken(); + mergeConflictScanner.resetTokenState(i); + while(mergeConflictScanner.getTokenEnd() < end)classifyDisabledCodeToken(); } function classifyDisabledCodeToken() { - const start = mergeConflictScanner.getTextPos(); + const start = mergeConflictScanner.getTokenEnd(); const tokenKind = mergeConflictScanner.scan(); - const end = mergeConflictScanner.getTextPos(); + const end = mergeConflictScanner.getTokenEnd(); const type = classifyTokenType(tokenKind); if (type) pushClassification(start, end - start, type); } @@ -103283,8 +105232,8 @@ ${lanes.join("\n")} if (isJSDoc(node)) return true; if (nodeIsMissing(node)) return true; const classifiedElementName = tryClassifyJsxElementName(node); - if (!isToken(node) && node.kind !== 11 /* JsxText */ && classifiedElementName === void 0) return false; - const tokenStart = node.kind === 11 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); + if (!isToken(node) && node.kind !== 12 /* JsxText */ && classifiedElementName === void 0) return false; + const tokenStart = node.kind === 12 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); const tokenWidth = node.end - tokenStart; Debug.assert(tokenWidth >= 0); if (tokenWidth > 0) { @@ -103295,16 +105244,16 @@ ${lanes.join("\n")} } function tryClassifyJsxElementName(token) { switch(token.parent && token.parent.kind){ - case 283 /* JsxOpeningElement */ : + case 286 /* JsxOpeningElement */ : if (token.parent.tagName === token) return 19 /* jsxOpenTagName */ ; break; - case 284 /* JsxClosingElement */ : + case 287 /* JsxClosingElement */ : if (token.parent.tagName === token) return 20 /* jsxCloseTagName */ ; break; - case 282 /* JsxSelfClosingElement */ : + case 285 /* JsxSelfClosingElement */ : if (token.parent.tagName === token) return 21 /* jsxSelfClosingTagName */ ; break; - case 288 /* JsxAttribute */ : + case 291 /* JsxAttribute */ : if (token.parent.name === token) return 22 /* jsxAttribute */ ; break; } @@ -103312,43 +105261,43 @@ ${lanes.join("\n")} } function classifyTokenType(tokenKind, token) { if (isKeyword(tokenKind)) return 3 /* keyword */ ; - if (tokenKind === 29 /* LessThanToken */ || tokenKind === 31 /* GreaterThanToken */ ) { + if (tokenKind === 30 /* LessThanToken */ || tokenKind === 32 /* GreaterThanToken */ ) { if (token && getTypeArgumentOrTypeParameterList(token.parent)) return 10 /* punctuation */ ; } if (isPunctuation(tokenKind)) { if (token) { const parent2 = token.parent; - if (tokenKind === 63 /* EqualsToken */ ) { - if (parent2.kind === 257 /* VariableDeclaration */ || parent2.kind === 169 /* PropertyDeclaration */ || parent2.kind === 166 /* Parameter */ || parent2.kind === 288 /* JsxAttribute */ ) return 5 /* operator */ ; + if (tokenKind === 64 /* EqualsToken */ ) { + if (parent2.kind === 260 /* VariableDeclaration */ || parent2.kind === 172 /* PropertyDeclaration */ || parent2.kind === 169 /* Parameter */ || parent2.kind === 291 /* JsxAttribute */ ) return 5 /* operator */ ; } - if (parent2.kind === 223 /* BinaryExpression */ || parent2.kind === 221 /* PrefixUnaryExpression */ || parent2.kind === 222 /* PostfixUnaryExpression */ || parent2.kind === 224 /* ConditionalExpression */ ) return 5 /* operator */ ; + if (parent2.kind === 226 /* BinaryExpression */ || parent2.kind === 224 /* PrefixUnaryExpression */ || parent2.kind === 225 /* PostfixUnaryExpression */ || parent2.kind === 227 /* ConditionalExpression */ ) return 5 /* operator */ ; } return 10 /* punctuation */ ; - } else if (tokenKind === 8 /* NumericLiteral */ ) return 4 /* numericLiteral */ ; - else if (tokenKind === 9 /* BigIntLiteral */ ) return 25 /* bigintLiteral */ ; - else if (tokenKind === 10 /* StringLiteral */ ) return token && token.parent.kind === 288 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */ ; - else if (tokenKind === 13 /* RegularExpressionLiteral */ ) return 6 /* stringLiteral */ ; + } else if (tokenKind === 9 /* NumericLiteral */ ) return 4 /* numericLiteral */ ; + else if (tokenKind === 10 /* BigIntLiteral */ ) return 25 /* bigintLiteral */ ; + else if (tokenKind === 11 /* StringLiteral */ ) return token && token.parent.kind === 291 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */ ; + else if (tokenKind === 14 /* RegularExpressionLiteral */ ) return 6 /* stringLiteral */ ; else if (isTemplateLiteralKind(tokenKind)) return 6 /* stringLiteral */ ; - else if (tokenKind === 11 /* JsxText */ ) return 23 /* jsxText */ ; - else if (tokenKind === 79 /* Identifier */ ) { + else if (tokenKind === 12 /* JsxText */ ) return 23 /* jsxText */ ; + else if (tokenKind === 80 /* Identifier */ ) { if (token) { switch(token.parent.kind){ - case 260 /* ClassDeclaration */ : + case 263 /* ClassDeclaration */ : if (token.parent.name === token) return 11 /* className */ ; return; - case 165 /* TypeParameter */ : + case 168 /* TypeParameter */ : if (token.parent.name === token) return 15 /* typeParameterName */ ; return; - case 261 /* InterfaceDeclaration */ : + case 264 /* InterfaceDeclaration */ : if (token.parent.name === token) return 13 /* interfaceName */ ; return; - case 263 /* EnumDeclaration */ : + case 266 /* EnumDeclaration */ : if (token.parent.name === token) return 12 /* enumName */ ; return; - case 264 /* ModuleDeclaration */ : + case 267 /* ModuleDeclaration */ : if (token.parent.name === token) return 14 /* moduleName */ ; return; - case 166 /* Parameter */ : + case 169 /* Parameter */ : if (token.parent.name === token) return isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */ ; return; } @@ -103371,19 +105320,19 @@ ${lanes.join("\n")} "use strict"; init_ts4(); noRegexTable = arrayToNumericMap([ - 79 /* Identifier */ , - 10 /* StringLiteral */ , - 8 /* NumericLiteral */ , - 9 /* BigIntLiteral */ , - 13 /* RegularExpressionLiteral */ , - 108 /* ThisKeyword */ , - 45 /* PlusPlusToken */ , - 46 /* MinusMinusToken */ , - 21 /* CloseParenToken */ , - 23 /* CloseBracketToken */ , - 19 /* CloseBraceToken */ , - 110 /* TrueKeyword */ , - 95 /* FalseKeyword */ + 80 /* Identifier */ , + 11 /* StringLiteral */ , + 9 /* NumericLiteral */ , + 10 /* BigIntLiteral */ , + 14 /* RegularExpressionLiteral */ , + 110 /* ThisKeyword */ , + 46 /* PlusPlusToken */ , + 47 /* MinusMinusToken */ , + 22 /* CloseParenToken */ , + 24 /* CloseBracketToken */ , + 20 /* CloseBraceToken */ , + 112 /* TrueKeyword */ , + 97 /* FalseKeyword */ ], (token)=>token, ()=>true); } }); @@ -103397,11 +105346,11 @@ ${lanes.join("\n")} function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { const node = getTouchingPropertyName(sourceFile, position); if (node.parent && (isJsxOpeningElement(node.parent) && node.parent.tagName === node || isJsxClosingElement(node.parent))) { - const { openingElement: openingElement , closingElement: closingElement } = node.parent.parent; + const { openingElement: openingElement, closingElement: closingElement } = node.parent.parent; const highlightSpans = [ openingElement, closingElement - ].map(({ tagName: tagName })=>getHighlightSpanForNode(tagName, sourceFile)); + ].map(({ tagName: tagName })=>getHighlightSpanForNode(tagName, sourceFile)); return [ { fileName: sourceFile.fileName, @@ -103450,56 +105399,56 @@ ${lanes.join("\n")} } function getHighlightSpans(node, sourceFile) { switch(node.kind){ - case 99 /* IfKeyword */ : - case 91 /* ElseKeyword */ : + case 101 /* IfKeyword */ : + case 93 /* ElseKeyword */ : return isIfStatement(node.parent) ? getIfElseOccurrences(node.parent, sourceFile) : void 0; - case 105 /* ReturnKeyword */ : + case 107 /* ReturnKeyword */ : return useParent(node.parent, isReturnStatement, getReturnOccurrences); - case 109 /* ThrowKeyword */ : + case 111 /* ThrowKeyword */ : return useParent(node.parent, isThrowStatement, getThrowOccurrences); - case 111 /* TryKeyword */ : - case 83 /* CatchKeyword */ : - case 96 /* FinallyKeyword */ : - const tryStatement = node.kind === 83 /* CatchKeyword */ ? node.parent.parent : node.parent; + case 113 /* TryKeyword */ : + case 85 /* CatchKeyword */ : + case 98 /* FinallyKeyword */ : + const tryStatement = node.kind === 85 /* CatchKeyword */ ? node.parent.parent : node.parent; return useParent(tryStatement, isTryStatement, getTryCatchFinallyOccurrences); - case 107 /* SwitchKeyword */ : + case 109 /* SwitchKeyword */ : return useParent(node.parent, isSwitchStatement, getSwitchCaseDefaultOccurrences); - case 82 /* CaseKeyword */ : - case 88 /* DefaultKeyword */ : + case 84 /* CaseKeyword */ : + case 90 /* DefaultKeyword */ : if (isDefaultClause(node.parent) || isCaseClause(node.parent)) return useParent(node.parent.parent.parent, isSwitchStatement, getSwitchCaseDefaultOccurrences); return void 0; - case 81 /* BreakKeyword */ : - case 86 /* ContinueKeyword */ : + case 83 /* BreakKeyword */ : + case 88 /* ContinueKeyword */ : return useParent(node.parent, isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences); - case 97 /* ForKeyword */ : - case 115 /* WhileKeyword */ : - case 90 /* DoKeyword */ : + case 99 /* ForKeyword */ : + case 117 /* WhileKeyword */ : + case 92 /* DoKeyword */ : return useParent(node.parent, (n)=>isIterationStatement(n, /*lookInLabeledStatements*/ true), getLoopBreakContinueOccurrences); - case 135 /* ConstructorKeyword */ : + case 137 /* ConstructorKeyword */ : return getFromAllDeclarations(isConstructorDeclaration, [ - 135 /* ConstructorKeyword */ + 137 /* ConstructorKeyword */ ]); - case 137 /* GetKeyword */ : - case 151 /* SetKeyword */ : + case 139 /* GetKeyword */ : + case 153 /* SetKeyword */ : return getFromAllDeclarations(isAccessor, [ - 137 /* GetKeyword */ , - 151 /* SetKeyword */ + 139 /* GetKeyword */ , + 153 /* SetKeyword */ ]); - case 133 /* AwaitKeyword */ : + case 135 /* AwaitKeyword */ : return useParent(node.parent, isAwaitExpression, getAsyncAndAwaitOccurrences); - case 132 /* AsyncKeyword */ : + case 134 /* AsyncKeyword */ : return highlightSpans(getAsyncAndAwaitOccurrences(node)); - case 125 /* YieldKeyword */ : + case 127 /* YieldKeyword */ : return highlightSpans(getYieldOccurrences(node)); - case 101 /* InKeyword */ : + case 103 /* InKeyword */ : return void 0; default: return isModifierKind(node.kind) && (isDeclaration(node.parent) || isVariableStatement(node.parent)) ? highlightSpans(getModifierOccurrences(node.kind, node.parent)) : void 0; } function getFromAllDeclarations(nodeTest, keywords) { return useParent(node.parent, nodeTest, (decl)=>{ - var _a2; - return mapDefined((_a2 = tryCast(decl, canHaveSymbol)) == null ? void 0 : _a2.symbol.declarations, (d)=>nodeTest(d) ? find(d.getChildren(sourceFile), (c)=>contains(keywords, c.kind)) : void 0); + var _a; + return mapDefined((_a = tryCast(decl, canHaveSymbol)) == null ? void 0 : _a.symbol.declarations, (d)=>nodeTest(d) ? find(d.getChildren(sourceFile), (c)=>contains(keywords, c.kind)) : void 0); }); } function useParent(node2, nodeTest, getNodes4) { @@ -103520,7 +105469,7 @@ ${lanes.join("\n")} let child = throwStatement; while(child.parent){ const parent2 = child.parent; - if (isFunctionBlock(parent2) || parent2.kind === 308 /* SourceFile */ ) return parent2; + if (isFunctionBlock(parent2) || parent2.kind === 312 /* SourceFile */ ) return parent2; if (isTryStatement(parent2) && parent2.tryBlock === child && parent2.catchClause) return child; child = parent2; } @@ -103546,13 +105495,13 @@ ${lanes.join("\n")} function getBreakOrContinueOwner(statement) { return findAncestor(statement, (node)=>{ switch(node.kind){ - case 252 /* SwitchStatement */ : - if (statement.kind === 248 /* ContinueStatement */ ) return false; - case 245 /* ForStatement */ : - case 246 /* ForInStatement */ : - case 247 /* ForOfStatement */ : - case 244 /* WhileStatement */ : - case 243 /* DoStatement */ : + case 255 /* SwitchStatement */ : + if (statement.kind === 251 /* ContinueStatement */ ) return false; + case 248 /* ForStatement */ : + case 249 /* ForInStatement */ : + case 250 /* ForOfStatement */ : + case 247 /* WhileStatement */ : + case 246 /* DoStatement */ : return !statement.label || isLabeledBy(node, statement.label.escapedText); default: return isFunctionLike(node) && "quit"; @@ -103565,27 +105514,27 @@ ${lanes.join("\n")} function getNodesToSearchForModifier(declaration, modifierFlag) { const container = declaration.parent; switch(container.kind){ - case 265 /* ModuleBlock */ : - case 308 /* SourceFile */ : - case 238 /* Block */ : - case 292 /* CaseClause */ : - case 293 /* DefaultClause */ : + case 268 /* ModuleBlock */ : + case 312 /* SourceFile */ : + case 241 /* Block */ : + case 296 /* CaseClause */ : + case 297 /* DefaultClause */ : if (modifierFlag & 256 /* Abstract */ && isClassDeclaration(declaration)) return [ ...declaration.members, declaration ]; else return container.statements; - case 173 /* Constructor */ : - case 171 /* MethodDeclaration */ : - case 259 /* FunctionDeclaration */ : + case 176 /* Constructor */ : + case 174 /* MethodDeclaration */ : + case 262 /* FunctionDeclaration */ : return [ ...container.parameters, ...isClassLike(container.parent) ? container.parent.members : [] ]; - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : - case 261 /* InterfaceDeclaration */ : - case 184 /* TypeLiteral */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 264 /* InterfaceDeclaration */ : + case 187 /* TypeLiteral */ : const nodes = container.members; if (modifierFlag & 92 /* Readonly */ ) { const constructor = find(container.members, isConstructorDeclaration); @@ -103598,7 +105547,7 @@ ${lanes.join("\n")} container ]; return nodes; - case 207 /* ObjectLiteralExpression */ : + case 210 /* ObjectLiteralExpression */ : return void 0; default: Debug.assertNever(container, "Invalid container kind."); @@ -103613,51 +105562,51 @@ ${lanes.join("\n")} } function getLoopBreakContinueOccurrences(loopNode) { const keywords = []; - if (pushKeywordIf(keywords, loopNode.getFirstToken(), 97 /* ForKeyword */ , 115 /* WhileKeyword */ , 90 /* DoKeyword */ )) { - if (loopNode.kind === 243 /* DoStatement */ ) { + if (pushKeywordIf(keywords, loopNode.getFirstToken(), 99 /* ForKeyword */ , 117 /* WhileKeyword */ , 92 /* DoKeyword */ )) { + if (loopNode.kind === 246 /* DoStatement */ ) { const loopTokens = loopNode.getChildren(); for(let i = loopTokens.length - 1; i >= 0; i--){ - if (pushKeywordIf(keywords, loopTokens[i], 115 /* WhileKeyword */ )) break; + if (pushKeywordIf(keywords, loopTokens[i], 117 /* WhileKeyword */ )) break; } } } forEach(aggregateAllBreakAndContinueStatements(loopNode.statement), (statement)=>{ - if (ownsBreakOrContinueStatement(loopNode, statement)) pushKeywordIf(keywords, statement.getFirstToken(), 81 /* BreakKeyword */ , 86 /* ContinueKeyword */ ); + if (ownsBreakOrContinueStatement(loopNode, statement)) pushKeywordIf(keywords, statement.getFirstToken(), 83 /* BreakKeyword */ , 88 /* ContinueKeyword */ ); }); return keywords; } function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) { const owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) switch(owner.kind){ - case 245 /* ForStatement */ : - case 246 /* ForInStatement */ : - case 247 /* ForOfStatement */ : - case 243 /* DoStatement */ : - case 244 /* WhileStatement */ : + case 248 /* ForStatement */ : + case 249 /* ForInStatement */ : + case 250 /* ForOfStatement */ : + case 246 /* DoStatement */ : + case 247 /* WhileStatement */ : return getLoopBreakContinueOccurrences(owner); - case 252 /* SwitchStatement */ : + case 255 /* SwitchStatement */ : return getSwitchCaseDefaultOccurrences(owner); } return void 0; } function getSwitchCaseDefaultOccurrences(switchStatement) { const keywords = []; - pushKeywordIf(keywords, switchStatement.getFirstToken(), 107 /* SwitchKeyword */ ); + pushKeywordIf(keywords, switchStatement.getFirstToken(), 109 /* SwitchKeyword */ ); forEach(switchStatement.caseBlock.clauses, (clause)=>{ - pushKeywordIf(keywords, clause.getFirstToken(), 82 /* CaseKeyword */ , 88 /* DefaultKeyword */ ); + pushKeywordIf(keywords, clause.getFirstToken(), 84 /* CaseKeyword */ , 90 /* DefaultKeyword */ ); forEach(aggregateAllBreakAndContinueStatements(clause), (statement)=>{ - if (ownsBreakOrContinueStatement(switchStatement, statement)) pushKeywordIf(keywords, statement.getFirstToken(), 81 /* BreakKeyword */ ); + if (ownsBreakOrContinueStatement(switchStatement, statement)) pushKeywordIf(keywords, statement.getFirstToken(), 83 /* BreakKeyword */ ); }); }); return keywords; } function getTryCatchFinallyOccurrences(tryStatement, sourceFile) { const keywords = []; - pushKeywordIf(keywords, tryStatement.getFirstToken(), 111 /* TryKeyword */ ); - if (tryStatement.catchClause) pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 83 /* CatchKeyword */ ); + pushKeywordIf(keywords, tryStatement.getFirstToken(), 113 /* TryKeyword */ ); + if (tryStatement.catchClause) pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 85 /* CatchKeyword */ ); if (tryStatement.finallyBlock) { - const finallyKeyword = findChildOfKind(tryStatement, 96 /* FinallyKeyword */ , sourceFile); - pushKeywordIf(keywords, finallyKeyword, 96 /* FinallyKeyword */ ); + const finallyKeyword = findChildOfKind(tryStatement, 98 /* FinallyKeyword */ , sourceFile); + pushKeywordIf(keywords, finallyKeyword, 98 /* FinallyKeyword */ ); } return keywords; } @@ -103666,10 +105615,10 @@ ${lanes.join("\n")} if (!owner) return void 0; const keywords = []; forEach(aggregateOwnedThrowStatements(owner), (throwStatement2)=>{ - keywords.push(findChildOfKind(throwStatement2, 109 /* ThrowKeyword */ , sourceFile)); + keywords.push(findChildOfKind(throwStatement2, 111 /* ThrowKeyword */ , sourceFile)); }); if (isFunctionBlock(owner)) forEachReturnStatement(owner, (returnStatement)=>{ - keywords.push(findChildOfKind(returnStatement, 105 /* ReturnKeyword */ , sourceFile)); + keywords.push(findChildOfKind(returnStatement, 107 /* ReturnKeyword */ , sourceFile)); }); return keywords; } @@ -103678,10 +105627,10 @@ ${lanes.join("\n")} if (!func) return void 0; const keywords = []; forEachReturnStatement(cast(func.body, isBlock), (returnStatement2)=>{ - keywords.push(findChildOfKind(returnStatement2, 105 /* ReturnKeyword */ , sourceFile)); + keywords.push(findChildOfKind(returnStatement2, 107 /* ReturnKeyword */ , sourceFile)); }); forEach(aggregateOwnedThrowStatements(func.body), (throwStatement)=>{ - keywords.push(findChildOfKind(throwStatement, 109 /* ThrowKeyword */ , sourceFile)); + keywords.push(findChildOfKind(throwStatement, 111 /* ThrowKeyword */ , sourceFile)); }); return keywords; } @@ -103690,11 +105639,11 @@ ${lanes.join("\n")} if (!func) return void 0; const keywords = []; if (func.modifiers) func.modifiers.forEach((modifier)=>{ - pushKeywordIf(keywords, modifier, 132 /* AsyncKeyword */ ); + pushKeywordIf(keywords, modifier, 134 /* AsyncKeyword */ ); }); forEachChild(func, (child)=>{ traverseWithoutCrossingFunction(child, (node2)=>{ - if (isAwaitExpression(node2)) pushKeywordIf(keywords, node2.getFirstToken(), 133 /* AwaitKeyword */ ); + if (isAwaitExpression(node2)) pushKeywordIf(keywords, node2.getFirstToken(), 135 /* AwaitKeyword */ ); }); }); return keywords; @@ -103705,7 +105654,7 @@ ${lanes.join("\n")} const keywords = []; forEachChild(func, (child)=>{ traverseWithoutCrossingFunction(child, (node2)=>{ - if (isYieldExpression(node2)) pushKeywordIf(keywords, node2.getFirstToken(), 125 /* YieldKeyword */ ); + if (isYieldExpression(node2)) pushKeywordIf(keywords, node2.getFirstToken(), 127 /* YieldKeyword */ ); }); }); return keywords; @@ -103718,7 +105667,7 @@ ${lanes.join("\n")} const keywords = getIfElseKeywords(ifStatement, sourceFile); const result = []; for(let i = 0; i < keywords.length; i++){ - if (keywords[i].kind === 91 /* ElseKeyword */ && i < keywords.length - 1) { + if (keywords[i].kind === 93 /* ElseKeyword */ && i < keywords.length - 1) { const elseKeyword = keywords[i]; const ifKeyword = keywords[i + 1]; let shouldCombineElseAndIf = true; @@ -103745,9 +105694,9 @@ ${lanes.join("\n")} while(isIfStatement(ifStatement.parent) && ifStatement.parent.elseStatement === ifStatement)ifStatement = ifStatement.parent; while(true){ const children = ifStatement.getChildren(sourceFile); - pushKeywordIf(keywords, children[0], 99 /* IfKeyword */ ); + pushKeywordIf(keywords, children[0], 101 /* IfKeyword */ ); for(let i = children.length - 1; i >= 0; i--){ - if (pushKeywordIf(keywords, children[i], 91 /* ElseKeyword */ )) break; + if (pushKeywordIf(keywords, children[i], 93 /* ElseKeyword */ )) break; } if (!ifStatement.elseStatement || !isIfStatement(ifStatement.elseStatement)) break; ifStatement = ifStatement.elseStatement; @@ -103764,12 +105713,12 @@ ${lanes.join("\n")} function isDocumentRegistryEntry(entry) { return !!entry.sourceFile; } - function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { - return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); + function createDocumentRegistry(useCaseSensitiveFileNames2, currentDirectory) { + return createDocumentRegistryInternal(useCaseSensitiveFileNames2, currentDirectory); } - function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory = "", externalCache) { + function createDocumentRegistryInternal(useCaseSensitiveFileNames2, currentDirectory = "", externalCache) { const buckets = /* @__PURE__ */ new Map(); - const getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); + const getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames2); function reportStats() { const bucketInfoArray = arrayFrom(buckets.keys()).filter((name)=>name && name.charAt(0) === "_").map((name)=>{ const entries = buckets.get(name); @@ -103820,14 +105769,14 @@ ${lanes.join("\n")} return entry; } function acquireOrUpdateDocument(fileName, path, compilationSettingsOrHost, key, scriptSnapshot, version2, acquiring, scriptKind, languageVersionOrOptions) { - var _a2, _b, _c, _d; + var _a, _b, _c, _d; scriptKind = ensureScriptKind(fileName, scriptKind); const compilationSettings = getCompilationSettings(compilationSettingsOrHost); const host = compilationSettingsOrHost === compilationSettings ? void 0 : compilationSettingsOrHost; const scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : getEmitScriptTarget(compilationSettings); const sourceFileOptions = typeof languageVersionOrOptions === "object" ? languageVersionOrOptions : { languageVersion: scriptTarget, - impliedNodeFormat: host && getImpliedNodeFormatForFile(path, (_d = (_c = (_b = (_a2 = host.getCompilerHost) == null ? void 0 : _a2.call(host)) == null ? void 0 : _b.getModuleResolutionCache) == null ? void 0 : _c.call(_b)) == null ? void 0 : _d.getPackageJsonInfoCache(), host, compilationSettings), + impliedNodeFormat: host && getImpliedNodeFormatForFile(path, (_d = (_c = (_b = (_a = host.getCompilerHost) == null ? void 0 : _a.call(host)) == null ? void 0 : _b.getModuleResolutionCache) == null ? void 0 : _c.call(_b)) == null ? void 0 : _d.getPackageJsonInfoCache(), host, compilationSettings), setExternalModuleIndicator: getSetExternalModuleIndicator(compilationSettings) }; sourceFileOptions.languageVersion = scriptTarget; @@ -103905,16 +105854,6 @@ ${lanes.join("\n")} } } } - function getLanguageServiceRefCounts(path, scriptKind) { - return arrayFrom(buckets.entries(), ([key, bucket])=>{ - const bucketEntry = bucket.get(path); - const entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); - return [ - key, - entry && entry.languageServiceRefCount - ]; - }); - } return { acquireDocument: acquireDocument, acquireDocumentWithKey: acquireDocumentWithKey, @@ -103922,9 +105861,10 @@ ${lanes.join("\n")} updateDocumentWithKey: updateDocumentWithKey, releaseDocument: releaseDocument, releaseDocumentWithKey: releaseDocumentWithKey, - getLanguageServiceRefCounts: getLanguageServiceRefCounts, + getKeyForCompilationSettings: getKeyForCompilationSettings, + getDocumentRegistryBucketKeyWithMode: getDocumentRegistryBucketKeyWithMode, reportStats: reportStats, - getKeyForCompilationSettings: getKeyForCompilationSettings + getBuckets: ()=>buckets }; } function getKeyForCompilationSettings(settings) { @@ -103941,8 +105881,8 @@ ${lanes.join("\n")} }); // src/services/getEditsForFileRename.ts function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { - const useCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames(host); - const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); + const useCaseSensitiveFileNames2 = hostUsesCaseSensitiveFileNames(host); + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); const oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); const newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts_textChanges_exports.ChangeTracker.with({ @@ -103950,7 +105890,7 @@ ${lanes.join("\n")} formatContext: formatContext, preferences: preferences }, (changeTracker)=>{ - updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); + updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames2); updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } @@ -103974,8 +105914,8 @@ ${lanes.join("\n")} const rel = getRelativePathFromFile(a0, b0, getCanonicalFileName); return combinePathsSafe(getDirectoryPath(a1), rel); } - function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { - const { configFile: configFile } = program.getCompilerOptions(); + function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames2) { + const { configFile: configFile } = program.getCompilerOptions(); if (!configFile) return; const configDir = getDirectoryPath(configFile.fileName); const jsonObjectLiteral = getTsConfigObjectLiteralExpression(configFile); @@ -103990,8 +105930,8 @@ ${lanes.join("\n")} if (foundExactMatch || propertyName !== "include" || !isArrayLiteralExpression(property.initializer)) return; const includes = mapDefined(property.initializer.elements, (e)=>isStringLiteral(e) ? e.text : void 0); if (includes.length === 0) return; - const matchers = getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory); - if (getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) && !getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) changeTracker.insertNodeAfter(configFile, last(property.initializer.elements), factory.createStringLiteral(relativePath(newFileOrDirPath))); + const matchers = getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames2, currentDirectory); + if (getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames2).test(oldFileOrDirPath) && !getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames2).test(newFileOrDirPath)) changeTracker.insertNodeAfter(configFile, last(property.initializer.elements), factory.createStringLiteral(relativePath(newFileOrDirPath))); return; } case "compilerOptions": @@ -104026,14 +105966,14 @@ ${lanes.join("\n")} return false; } function relativePath(path) { - return getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); + return getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames2); } } function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { const allFiles = program.getSourceFiles(); for (const sourceFile of allFiles){ const newFromOld = oldToNew(sourceFile.fileName); - const newImportFromPath = newFromOld != null ? newFromOld : sourceFile.fileName; + const newImportFromPath = newFromOld ?? sourceFile.fileName; const newImportFromDirectory = getDirectoryPath(newImportFromPath); const oldFromNew = newToOld(sourceFile.fileName); const oldImportFromPath = oldFromNew || sourceFile.fileName; @@ -104059,7 +105999,7 @@ ${lanes.join("\n")} return ensurePathIsNonModuleName(combineNormal(pathA, pathB)); } function getSourceFileToImport(importedModuleSymbol, importLiteral, importingSourceFile, program, host, oldToNew) { - var _a2; + var _a; if (importedModuleSymbol) { const oldFileName = find(importedModuleSymbol.declarations, isSourceFile).fileName; const newFileName = oldToNew(oldFileName); @@ -104072,7 +106012,7 @@ ${lanes.join("\n")} }; } else { const mode = getModeForUsageLocation(importingSourceFile, importLiteral); - const resolved = host.resolveModuleNameLiterals || !host.resolveModuleNames ? (_a2 = importingSourceFile.resolvedModules) == null ? void 0 : _a2.get(importLiteral.text, mode) : host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName, mode); + const resolved = host.resolveModuleNameLiterals || !host.resolveModuleNames ? (_a = importingSourceFile.resolvedModules) == null ? void 0 : _a.get(importLiteral.text, mode) : host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName, mode); return getSourceFileToImportFromResolved(importLiteral, resolved, oldToNew, program.getSourceFiles()); } } @@ -104163,14 +106103,14 @@ ${lanes.join("\n")} if (index === -1) return void 0; const wordSpans = getWordSpans(candidate, stringToWordSpans); for (const span of wordSpans){ - if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) return createPatternMatch(2 /* substring */ , /*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false)); + if (partStartsWith(candidate, span, chunk.text, /*ignoreCase*/ true)) return createPatternMatch(2 /* substring */ , /*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase*/ false)); } - if (chunk.text.length < candidate.length && isUpperCaseLetter(candidate.charCodeAt(index))) return createPatternMatch(2 /* substring */ , /*isCaseSensitive:*/ false); + if (chunk.text.length < candidate.length && isUpperCaseLetter(candidate.charCodeAt(index))) return createPatternMatch(2 /* substring */ , /*isCaseSensitive*/ false); } else { - if (candidate.indexOf(chunk.text) > 0) return createPatternMatch(2 /* substring */ , /*isCaseSensitive:*/ true); + if (candidate.indexOf(chunk.text) > 0) return createPatternMatch(2 /* substring */ , /*isCaseSensitive*/ true); if (chunk.characterSpans.length > 0) { const candidateParts = getWordSpans(candidate, stringToWordSpans); - const isCaseSensitive = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ false) ? true : tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ true) ? false : void 0; + const isCaseSensitive = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase*/ false) ? true : tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase*/ true) ? false : void 0; if (isCaseSensitive !== void 0) return createPatternMatch(3 /* camelCase */ , isCaseSensitive); } } @@ -104292,10 +106232,10 @@ ${lanes.join("\n")} }; } function breakIntoCharacterSpans(identifier) { - return breakIntoSpans(identifier, /*word:*/ false); + return breakIntoSpans(identifier, /*word*/ false); } function breakIntoWordSpans(identifier) { - return breakIntoSpans(identifier, /*word:*/ true); + return breakIntoSpans(identifier, /*word*/ true); } function breakIntoSpans(identifier, word) { const result = []; @@ -104399,13 +106339,13 @@ ${lanes.join("\n")} function nextToken() { lastToken = currentToken; currentToken = scanner.scan(); - if (currentToken === 18 /* OpenBraceToken */ ) braceNesting++; - else if (currentToken === 19 /* CloseBraceToken */ ) braceNesting--; + if (currentToken === 19 /* OpenBraceToken */ ) braceNesting++; + else if (currentToken === 20 /* CloseBraceToken */ ) braceNesting--; return currentToken; } function getFileReference() { const fileName = scanner.getTokenValue(); - const pos = scanner.getTokenPos(); + const pos = scanner.getTokenStart(); return { fileName: fileName, pos: pos, @@ -104428,70 +106368,70 @@ ${lanes.join("\n")} } function tryConsumeDeclare() { let token = scanner.getToken(); - if (token === 136 /* DeclareKeyword */ ) { + if (token === 138 /* DeclareKeyword */ ) { token = nextToken(); - if (token === 142 /* ModuleKeyword */ ) { + if (token === 144 /* ModuleKeyword */ ) { token = nextToken(); - if (token === 10 /* StringLiteral */ ) recordAmbientExternalModule(); + if (token === 11 /* StringLiteral */ ) recordAmbientExternalModule(); } return true; } return false; } function tryConsumeImport() { - if (lastToken === 24 /* DotToken */ ) return false; + if (lastToken === 25 /* DotToken */ ) return false; let token = scanner.getToken(); - if (token === 100 /* ImportKeyword */ ) { + if (token === 102 /* ImportKeyword */ ) { token = nextToken(); - if (token === 20 /* OpenParenToken */ ) { + if (token === 21 /* OpenParenToken */ ) { token = nextToken(); - if (token === 10 /* StringLiteral */ || token === 14 /* NoSubstitutionTemplateLiteral */ ) { + if (token === 11 /* StringLiteral */ || token === 15 /* NoSubstitutionTemplateLiteral */ ) { recordModuleName(); return true; } - } else if (token === 10 /* StringLiteral */ ) { + } else if (token === 11 /* StringLiteral */ ) { recordModuleName(); return true; } else { - if (token === 154 /* TypeKeyword */ ) { + if (token === 156 /* TypeKeyword */ ) { const skipTypeKeyword = scanner.lookAhead(()=>{ const token2 = scanner.scan(); - return token2 !== 158 /* FromKeyword */ && (token2 === 41 /* AsteriskToken */ || token2 === 18 /* OpenBraceToken */ || token2 === 79 /* Identifier */ || isKeyword(token2)); + return token2 !== 161 /* FromKeyword */ && (token2 === 42 /* AsteriskToken */ || token2 === 19 /* OpenBraceToken */ || token2 === 80 /* Identifier */ || isKeyword(token2)); }); if (skipTypeKeyword) token = nextToken(); } - if (token === 79 /* Identifier */ || isKeyword(token)) { + if (token === 80 /* Identifier */ || isKeyword(token)) { token = nextToken(); - if (token === 158 /* FromKeyword */ ) { + if (token === 161 /* FromKeyword */ ) { token = nextToken(); - if (token === 10 /* StringLiteral */ ) { + if (token === 11 /* StringLiteral */ ) { recordModuleName(); return true; } - } else if (token === 63 /* EqualsToken */ ) { + } else if (token === 64 /* EqualsToken */ ) { if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) return true; - } else if (token === 27 /* CommaToken */ ) token = nextToken(); + } else if (token === 28 /* CommaToken */ ) token = nextToken(); else return true; } - if (token === 18 /* OpenBraceToken */ ) { + if (token === 19 /* OpenBraceToken */ ) { token = nextToken(); - while(token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */ )token = nextToken(); - if (token === 19 /* CloseBraceToken */ ) { + while(token !== 20 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */ )token = nextToken(); + if (token === 20 /* CloseBraceToken */ ) { token = nextToken(); - if (token === 158 /* FromKeyword */ ) { + if (token === 161 /* FromKeyword */ ) { token = nextToken(); - if (token === 10 /* StringLiteral */ ) recordModuleName(); + if (token === 11 /* StringLiteral */ ) recordModuleName(); } } - } else if (token === 41 /* AsteriskToken */ ) { + } else if (token === 42 /* AsteriskToken */ ) { token = nextToken(); - if (token === 128 /* AsKeyword */ ) { + if (token === 130 /* AsKeyword */ ) { token = nextToken(); - if (token === 79 /* Identifier */ || isKeyword(token)) { + if (token === 80 /* Identifier */ || isKeyword(token)) { token = nextToken(); - if (token === 158 /* FromKeyword */ ) { + if (token === 161 /* FromKeyword */ ) { token = nextToken(); - if (token === 10 /* StringLiteral */ ) recordModuleName(); + if (token === 11 /* StringLiteral */ ) recordModuleName(); } } } @@ -104503,44 +106443,44 @@ ${lanes.join("\n")} } function tryConsumeExport() { let token = scanner.getToken(); - if (token === 93 /* ExportKeyword */ ) { + if (token === 95 /* ExportKeyword */ ) { markAsExternalModuleIfTopLevel(); token = nextToken(); - if (token === 154 /* TypeKeyword */ ) { + if (token === 156 /* TypeKeyword */ ) { const skipTypeKeyword = scanner.lookAhead(()=>{ const token2 = scanner.scan(); - return token2 === 41 /* AsteriskToken */ || token2 === 18 /* OpenBraceToken */ ; + return token2 === 42 /* AsteriskToken */ || token2 === 19 /* OpenBraceToken */ ; }); if (skipTypeKeyword) token = nextToken(); } - if (token === 18 /* OpenBraceToken */ ) { + if (token === 19 /* OpenBraceToken */ ) { token = nextToken(); - while(token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */ )token = nextToken(); - if (token === 19 /* CloseBraceToken */ ) { + while(token !== 20 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */ )token = nextToken(); + if (token === 20 /* CloseBraceToken */ ) { token = nextToken(); - if (token === 158 /* FromKeyword */ ) { + if (token === 161 /* FromKeyword */ ) { token = nextToken(); - if (token === 10 /* StringLiteral */ ) recordModuleName(); + if (token === 11 /* StringLiteral */ ) recordModuleName(); } } - } else if (token === 41 /* AsteriskToken */ ) { + } else if (token === 42 /* AsteriskToken */ ) { token = nextToken(); - if (token === 158 /* FromKeyword */ ) { + if (token === 161 /* FromKeyword */ ) { token = nextToken(); - if (token === 10 /* StringLiteral */ ) recordModuleName(); + if (token === 11 /* StringLiteral */ ) recordModuleName(); } - } else if (token === 100 /* ImportKeyword */ ) { + } else if (token === 102 /* ImportKeyword */ ) { token = nextToken(); - if (token === 154 /* TypeKeyword */ ) { + if (token === 156 /* TypeKeyword */ ) { const skipTypeKeyword = scanner.lookAhead(()=>{ const token2 = scanner.scan(); - return token2 === 79 /* Identifier */ || isKeyword(token2); + return token2 === 80 /* Identifier */ || isKeyword(token2); }); if (skipTypeKeyword) token = nextToken(); } - if (token === 79 /* Identifier */ || isKeyword(token)) { + if (token === 80 /* Identifier */ || isKeyword(token)) { token = nextToken(); - if (token === 63 /* EqualsToken */ ) { + if (token === 64 /* EqualsToken */ ) { if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) return true; } } @@ -104551,11 +106491,11 @@ ${lanes.join("\n")} } function tryConsumeRequireCall(skipCurrentToken, allowTemplateLiterals = false) { let token = skipCurrentToken ? nextToken() : scanner.getToken(); - if (token === 147 /* RequireKeyword */ ) { + if (token === 149 /* RequireKeyword */ ) { token = nextToken(); - if (token === 20 /* OpenParenToken */ ) { + if (token === 21 /* OpenParenToken */ ) { token = nextToken(); - if (token === 10 /* StringLiteral */ || allowTemplateLiterals && token === 14 /* NoSubstitutionTemplateLiteral */ ) recordModuleName(); + if (token === 11 /* StringLiteral */ || allowTemplateLiterals && token === 15 /* NoSubstitutionTemplateLiteral */ ) recordModuleName(); } return true; } @@ -104563,19 +106503,19 @@ ${lanes.join("\n")} } function tryConsumeDefine() { let token = scanner.getToken(); - if (token === 79 /* Identifier */ && scanner.getTokenValue() === "define") { + if (token === 80 /* Identifier */ && scanner.getTokenValue() === "define") { token = nextToken(); - if (token !== 20 /* OpenParenToken */ ) return true; + if (token !== 21 /* OpenParenToken */ ) return true; token = nextToken(); - if (token === 10 /* StringLiteral */ || token === 14 /* NoSubstitutionTemplateLiteral */ ) { + if (token === 11 /* StringLiteral */ || token === 15 /* NoSubstitutionTemplateLiteral */ ) { token = nextToken(); - if (token === 27 /* CommaToken */ ) token = nextToken(); + if (token === 28 /* CommaToken */ ) token = nextToken(); else return true; } - if (token !== 22 /* OpenBracketToken */ ) return true; + if (token !== 23 /* OpenBracketToken */ ) return true; token = nextToken(); - while(token !== 23 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */ ){ - if (token === 10 /* StringLiteral */ || token === 14 /* NoSubstitutionTemplateLiteral */ ) recordModuleName(); + while(token !== 24 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */ ){ + if (token === 11 /* StringLiteral */ || token === 15 /* NoSubstitutionTemplateLiteral */ ) recordModuleName(); token = nextToken(); } return true; @@ -104587,7 +106527,7 @@ ${lanes.join("\n")} nextToken(); while(true){ if (scanner.getToken() === 1 /* EndOfFileToken */ ) break; - if (scanner.getToken() === 15 /* TemplateHead */ ) { + if (scanner.getToken() === 16 /* TemplateHead */ ) { const stack = [ scanner.getToken() ]; @@ -104596,19 +106536,19 @@ ${lanes.join("\n")} switch(token){ case 1 /* EndOfFileToken */ : break loop; - case 100 /* ImportKeyword */ : + case 102 /* ImportKeyword */ : tryConsumeImport(); break; - case 15 /* TemplateHead */ : + case 16 /* TemplateHead */ : stack.push(token); break; - case 18 /* OpenBraceToken */ : + case 19 /* OpenBraceToken */ : if (length(stack)) stack.push(token); break; - case 19 /* CloseBraceToken */ : + case 20 /* CloseBraceToken */ : if (length(stack)) { - if (lastOrUndefined(stack) === 15 /* TemplateHead */ ) { - if (scanner.reScanTemplateToken(/* isTaggedTemplate */ false) === 17 /* TemplateTail */ ) stack.pop(); + if (lastOrUndefined(stack) === 16 /* TemplateHead */ ) { + if (scanner.reScanTemplateToken(/*isTaggedTemplate*/ false) === 18 /* TemplateTail */ ) stack.pop(); } else stack.pop(); } break; @@ -104786,8 +106726,7 @@ ${lanes.join("\n")} "src/services/sourcemaps.ts" () { "use strict"; init_ts4(); - init_ts4(); - base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; + base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+/=]+)$)?/; } }); // src/services/suggestionDiagnostics.ts @@ -104820,8 +106759,10 @@ ${lanes.join("\n")} } else { if (isVariableStatement(node) && node.parent === sourceFile && node.declarationList.flags & 2 /* Const */ && node.declarationList.declarations.length === 1) { const init = node.declarationList.declarations[0].initializer; - if (init && isRequireCall(init, /*checkArgumentIsStringLiteralLike*/ true)) diags.push(createDiagnosticForNode(init, Diagnostics.require_call_may_be_converted_to_an_import)); + if (init && isRequireCall(init, /*requireStringLiteralLikeArgument*/ true)) diags.push(createDiagnosticForNode(init, Diagnostics.require_call_may_be_converted_to_an_import)); } + const jsdocTypedefNodes = ts_codefix_exports.getJSDocTypedefNodes(node); + for (const jsdocTypedefNode of jsdocTypedefNodes)diags.push(createDiagnosticForNode(jsdocTypedefNode, Diagnostics.JSDoc_typedef_may_be_converted_to_TypeScript_type)); if (ts_codefix_exports.parameterShouldGetTypeFromJSDoc(node)) diags.push(createDiagnosticForNode(node.name || node, Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); } if (canBeConvertedToAsync(node)) addConvertToAsyncFunctionDiagnostics(node, checker, diags); @@ -104831,12 +106772,12 @@ ${lanes.join("\n")} function containsTopLevelCommonjs(sourceFile) { return sourceFile.statements.some((statement)=>{ switch(statement.kind){ - case 240 /* VariableStatement */ : - return statement.declarationList.declarations.some((decl)=>!!decl.initializer && isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true)); - case 241 /* ExpressionStatement */ : + case 243 /* VariableStatement */ : + return statement.declarationList.declarations.some((decl)=>!!decl.initializer && isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*requireStringLiteralLikeArgument*/ true)); + case 244 /* ExpressionStatement */ : { - const { expression: expression } = statement; - if (!isBinaryExpression(expression)) return isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); + const { expression: expression } = statement; + if (!isBinaryExpression(expression)) return isRequireCall(expression, /*requireStringLiteralLikeArgument*/ true); const kind = getAssignmentDeclarationKind(expression); return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */ ; } @@ -104850,10 +106791,10 @@ ${lanes.join("\n")} } function importNameForConvertToDefaultImport(node) { switch(node.kind){ - case 269 /* ImportDeclaration */ : - const { importClause: importClause , moduleSpecifier: moduleSpecifier } = node; - return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 271 /* NamespaceImport */ && isStringLiteral(moduleSpecifier) ? importClause.namedBindings.name : void 0; - case 268 /* ImportEqualsDeclaration */ : + case 272 /* ImportDeclaration */ : + const { importClause: importClause, moduleSpecifier: moduleSpecifier } = node; + return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 274 /* NamespaceImport */ && isStringLiteral(moduleSpecifier) ? importClause.namedBindings.name : void 0; + case 271 /* ImportEqualsDeclaration */ : return node.name; default: return void 0; @@ -104897,21 +106838,21 @@ ${lanes.join("\n")} if (node.arguments.length > maxArguments) return false; if (node.arguments.length < maxArguments) return true; return maxArguments === 1 || some(node.arguments, (arg)=>{ - return arg.kind === 104 /* NullKeyword */ || isIdentifier(arg) && arg.text === "undefined"; + return arg.kind === 106 /* NullKeyword */ || isIdentifier(arg) && arg.text === "undefined"; }); } function isFixablePromiseArgument(arg, checker) { switch(arg.kind){ - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : const functionFlags = getFunctionFlags(arg); if (functionFlags & 1 /* Generator */ ) return false; - case 216 /* ArrowFunction */ : + case 219 /* ArrowFunction */ : visitedNestedConvertibleFunctions.set(getKeyFromNode(arg), true); - case 104 /* NullKeyword */ : + case 106 /* NullKeyword */ : return true; - case 79 /* Identifier */ : - case 208 /* PropertyAccessExpression */ : + case 80 /* Identifier */ : + case 211 /* PropertyAccessExpression */ : { const symbol = checker.getSymbolAtLocation(arg); if (!symbol) return false; @@ -104925,9 +106866,9 @@ ${lanes.join("\n")} return `${exp.pos.toString()}:${exp.end.toString()}`; } function canBeConvertedToClass(node, checker) { - var _a2, _b, _c, _d; + var _a, _b, _c, _d; if (isFunctionExpression(node)) { - if (isVariableDeclaration(node.parent) && ((_a2 = node.symbol.members) == null ? void 0 : _a2.size)) return true; + if (isVariableDeclaration(node.parent) && ((_a = node.symbol.members) == null ? void 0 : _a.size)) return true; const symbol = checker.getSymbolOfExpando(node, /*allowDeclaration*/ false); return !!(symbol && (((_b = symbol.exports) == null ? void 0 : _b.size) || ((_c = symbol.members) == null ? void 0 : _c.size))); } @@ -104936,10 +106877,10 @@ ${lanes.join("\n")} } function canBeConvertedToAsync(node) { switch(node.kind){ - case 259 /* FunctionDeclaration */ : - case 171 /* MethodDeclaration */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : + case 262 /* FunctionDeclaration */ : + case 174 /* MethodDeclaration */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : return true; default: return false; @@ -104990,7 +106931,7 @@ ${lanes.join("\n")} const inputFileName = transpileOptions.fileName || (transpileOptions.compilerOptions && transpileOptions.compilerOptions.jsx ? "module.tsx" : "module.ts"); const sourceFile = createSourceFile(inputFileName, input, { languageVersion: getEmitScriptTarget(options), - impliedNodeFormat: getImpliedNodeFormatForFile(toPath(inputFileName, "", compilerHost.getCanonicalFileName), /*cache*/ void 0, compilerHost, options), + impliedNodeFormat: getImpliedNodeFormatForFile(toPath(inputFileName, "", compilerHost.getCanonicalFileName), /*packageJsonInfoCache*/ void 0, compilerHost, options), setExternalModuleIndicator: getSetExternalModuleIndicator(options) }); if (transpileOptions.moduleName) sourceFile.moduleName = transpileOptions.moduleName; @@ -105085,9 +107026,9 @@ ${lanes.join("\n")} } function shouldKeepItem(declaration, checker) { switch(declaration.kind){ - case 270 /* ImportClause */ : - case 273 /* ImportSpecifier */ : - case 268 /* ImportEqualsDeclaration */ : + case 273 /* ImportClause */ : + case 276 /* ImportSpecifier */ : + case 271 /* ImportEqualsDeclaration */ : const importer = checker.getSymbolAtLocation(declaration.name); const imported = checker.getAliasedSymbol(importer); return importer.escapedName !== imported.escapedName; @@ -105097,7 +107038,7 @@ ${lanes.join("\n")} } function tryAddSingleDeclarationName(declaration, containers) { const name = getNameOfDeclaration(declaration); - return !!name && (pushLiteral(name, containers) || name.kind === 164 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); + return !!name && (pushLiteral(name, containers) || name.kind === 167 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); } function tryAddComputedPropertyName(expression, containers) { return pushLiteral(expression, containers) || isPropertyAccessExpression(expression) && (containers.push(expression.name.text), true) && tryAddComputedPropertyName(expression.expression, containers); @@ -105108,7 +107049,7 @@ ${lanes.join("\n")} function getContainers(declaration) { const containers = []; const name = getNameOfDeclaration(declaration); - if (name && name.kind === 164 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) return emptyArray; + if (name && name.kind === 167 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) return emptyArray; containers.shift(); let container = getContainerNode(declaration); while(container){ @@ -105276,79 +107217,79 @@ ${lanes.join("\n")} } else addNodeWithRecursiveChild(node, node.initializer); } function hasNavigationBarName(node) { - return !hasDynamicName(node) || node.kind !== 223 /* BinaryExpression */ && isPropertyAccessExpression(node.name.expression) && isIdentifier(node.name.expression.expression) && idText(node.name.expression.expression) === "Symbol"; + return !hasDynamicName(node) || node.kind !== 226 /* BinaryExpression */ && isPropertyAccessExpression(node.name.expression) && isIdentifier(node.name.expression.expression) && idText(node.name.expression.expression) === "Symbol"; } function addChildrenRecursively(node) { curCancellationToken.throwIfCancellationRequested(); if (!node || isToken(node)) return; switch(node.kind){ - case 173 /* Constructor */ : + case 176 /* Constructor */ : const ctr = node; addNodeWithRecursiveChild(ctr, ctr.body); for (const param of ctr.parameters)if (isParameterPropertyDeclaration(param, ctr)) addLeafNode(param); break; - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 170 /* MethodSignature */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 173 /* MethodSignature */ : if (hasNavigationBarName(node)) addNodeWithRecursiveChild(node, node.body); break; - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : if (hasNavigationBarName(node)) addNodeWithRecursiveInitializer(node); break; - case 168 /* PropertySignature */ : + case 171 /* PropertySignature */ : if (hasNavigationBarName(node)) addLeafNode(node); break; - case 270 /* ImportClause */ : + case 273 /* ImportClause */ : const importClause = node; if (importClause.name) addLeafNode(importClause.name); - const { namedBindings: namedBindings } = importClause; + const { namedBindings: namedBindings } = importClause; if (namedBindings) { - if (namedBindings.kind === 271 /* NamespaceImport */ ) addLeafNode(namedBindings); + if (namedBindings.kind === 274 /* NamespaceImport */ ) addLeafNode(namedBindings); else for (const element of namedBindings.elements)addLeafNode(element); } break; - case 300 /* ShorthandPropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : addNodeWithRecursiveChild(node, node.name); break; - case 301 /* SpreadAssignment */ : - const { expression: expression } = node; + case 305 /* SpreadAssignment */ : + const { expression: expression } = node; isIdentifier(expression) ? addLeafNode(node, expression) : addLeafNode(node); break; - case 205 /* BindingElement */ : - case 299 /* PropertyAssignment */ : - case 257 /* VariableDeclaration */ : + case 208 /* BindingElement */ : + case 303 /* PropertyAssignment */ : + case 260 /* VariableDeclaration */ : { const child = node; if (isBindingPattern(child.name)) addChildrenRecursively(child.name); else addNodeWithRecursiveInitializer(child); break; } - case 259 /* FunctionDeclaration */ : + case 262 /* FunctionDeclaration */ : const nameNode = node.name; if (nameNode && isIdentifier(nameNode)) addTrackedEs5Class(nameNode.text); addNodeWithRecursiveChild(node, node.body); break; - case 216 /* ArrowFunction */ : - case 215 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + case 218 /* FunctionExpression */ : addNodeWithRecursiveChild(node, node.body); break; - case 263 /* EnumDeclaration */ : + case 266 /* EnumDeclaration */ : startNode(node); for (const member of node.members)if (!isComputedProperty(member)) addLeafNode(member); endNode(); break; - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : - case 261 /* InterfaceDeclaration */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 264 /* InterfaceDeclaration */ : startNode(node); for (const member of node.members)addChildrenRecursively(member); endNode(); break; - case 264 /* ModuleDeclaration */ : + case 267 /* ModuleDeclaration */ : addNodeWithRecursiveChild(node, getInteriorModule(node).body); break; - case 274 /* ExportAssignment */ : + case 277 /* ExportAssignment */ : { const expression2 = node.expression; const child = isObjectLiteralExpression(expression2) || isCallExpression(expression2) ? expression2 : isArrowFunction(expression2) || isFunctionExpression(expression2) ? expression2.body : void 0; @@ -105359,16 +107300,16 @@ ${lanes.join("\n")} } else addLeafNode(node); break; } - case 278 /* ExportSpecifier */ : - case 268 /* ImportEqualsDeclaration */ : - case 178 /* IndexSignature */ : - case 176 /* CallSignature */ : - case 177 /* ConstructSignature */ : - case 262 /* TypeAliasDeclaration */ : + case 281 /* ExportSpecifier */ : + case 271 /* ImportEqualsDeclaration */ : + case 181 /* IndexSignature */ : + case 179 /* CallSignature */ : + case 180 /* ConstructSignature */ : + case 265 /* TypeAliasDeclaration */ : addLeafNode(node); break; - case 210 /* CallExpression */ : - case 223 /* BinaryExpression */ : + case 213 /* CallExpression */ : + case 226 /* BinaryExpression */ : { const special = getAssignmentDeclarationKind(node); switch(special){ @@ -105492,7 +107433,7 @@ ${lanes.join("\n")} if (!isClassDeclaration(a.node) && !isClassDeclaration(b.node) || isPossibleConstructor(a.node) || isPossibleConstructor(b.node)) { const ctorFunction = isPossibleConstructor(a.node) ? a.node : isPossibleConstructor(b.node) ? b.node : void 0; if (ctorFunction !== void 0) { - const ctorNode = setTextRange(factory.createConstructorDeclaration(/* modifiers */ void 0, [], /* body */ void 0), ctorFunction); + const ctorNode = setTextRange(factory.createConstructorDeclaration(/*modifiers*/ void 0, [], /*body*/ void 0), ctorFunction); const ctor = emptyNavigationBarNode(ctorNode); ctor.indent = a.indent + 1; ctor.children = a.node === ctorFunction ? a.children : b.children; @@ -105520,7 +107461,7 @@ ${lanes.join("\n")} sortChildren(a.children); } } - lastANode = a.node = setTextRange(factory.createClassDeclaration(/* modifiers */ void 0, a.name || factory.createIdentifier("__class__"), /* typeParameters */ void 0, /* heritageClauses */ void 0, []), a.node); + lastANode = a.node = setTextRange(factory.createClassDeclaration(/*modifiers*/ void 0, a.name || factory.createIdentifier("__class__"), /*typeParameters*/ void 0, /*heritageClauses*/ void 0, []), a.node); } else { a.children = concatenate(a.children, b.children); if (a.children) mergeChildren(a.children, a); @@ -105532,7 +107473,7 @@ ${lanes.join("\n")} }); else { if (!a.additionalNodes) a.additionalNodes = []; - a.additionalNodes.push(setTextRange(factory.createClassDeclaration(/* modifiers */ void 0, a.name || factory.createIdentifier("__class__"), /* typeParameters */ void 0, /* heritageClauses */ void 0, []), b.node)); + a.additionalNodes.push(setTextRange(factory.createClassDeclaration(/*modifiers*/ void 0, a.name || factory.createIdentifier("__class__"), /*typeParameters*/ void 0, /*heritageClauses*/ void 0, []), b.node)); } return true; } @@ -105549,19 +107490,19 @@ ${lanes.join("\n")} function shouldReallyMerge(a, b, parent2) { if (a.kind !== b.kind || a.parent !== b.parent && !(isOwnChild(a, parent2) && isOwnChild(b, parent2))) return false; switch(a.kind){ - case 169 /* PropertyDeclaration */ : - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : + case 172 /* PropertyDeclaration */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : return isStatic(a) === isStatic(b); - case 264 /* ModuleDeclaration */ : + case 267 /* ModuleDeclaration */ : return areSameModule(a, b) && getFullyQualifiedModuleName(a) === getFullyQualifiedModuleName(b); default: return true; } } function isSynthesized(node) { - return !!(node.flags & 8 /* Synthesized */ ); + return !!(node.flags & 16 /* Synthesized */ ); } function isOwnChild(n, parent2) { const par = isModuleBlock(n.parent) ? n.parent.parent : n.parent; @@ -105569,7 +107510,7 @@ ${lanes.join("\n")} } function areSameModule(a, b) { if (!a.body || !b.body) return a.body === b.body; - return a.body.kind === b.body.kind && (a.body.kind !== 264 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); + return a.body.kind === b.body.kind && (a.body.kind !== 267 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); } function merge(target, source) { target.additionalNodes = target.additionalNodes || []; @@ -105588,47 +107529,47 @@ ${lanes.join("\n")} return compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) || compareValues(navigationBarNodeKind(child1), navigationBarNodeKind(child2)); } function tryGetName(node) { - if (node.kind === 264 /* ModuleDeclaration */ ) return getModuleName(node); + if (node.kind === 267 /* ModuleDeclaration */ ) return getModuleName(node); const declName = getNameOfDeclaration(node); if (declName && isPropertyName(declName)) { const propertyName = getPropertyNameForPropertyNameNode(declName); return propertyName && unescapeLeadingUnderscores(propertyName); } switch(node.kind){ - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - case 228 /* ClassExpression */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + case 231 /* ClassExpression */ : return getFunctionOrClassName(node); default: return void 0; } } function getItemName(node, name) { - if (node.kind === 264 /* ModuleDeclaration */ ) return cleanText(getModuleName(node)); + if (node.kind === 267 /* ModuleDeclaration */ ) return cleanText(getModuleName(node)); if (name) { const text = isIdentifier(name) ? name.text : isElementAccessExpression(name) ? `[${nodeText(name.argumentExpression)}]` : nodeText(name); if (text.length > 0) return cleanText(text); } switch(node.kind){ - case 308 /* SourceFile */ : + case 312 /* SourceFile */ : const sourceFile = node; return isExternalModule(sourceFile) ? `"${escapeString(getBaseFileName(removeFileExtension(normalizePath(sourceFile.fileName))))}"` : ""; - case 274 /* ExportAssignment */ : + case 277 /* ExportAssignment */ : return isExportAssignment(node) && node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */ ; - case 216 /* ArrowFunction */ : - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : + case 219 /* ArrowFunction */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : if (getSyntacticModifierFlags(node) & 1024 /* Default */ ) return "default"; return getFunctionOrClassName(node); - case 173 /* Constructor */ : + case 176 /* Constructor */ : return "constructor"; - case 177 /* ConstructSignature */ : + case 180 /* ConstructSignature */ : return "new()"; - case 176 /* CallSignature */ : + case 179 /* CallSignature */ : return "()"; - case 178 /* IndexSignature */ : + case 181 /* IndexSignature */ : return "[]"; default: return ""; @@ -105647,19 +107588,19 @@ ${lanes.join("\n")} function shouldAppearInPrimaryNavBarMenu(item) { if (item.children) return true; switch(navigationBarNodeKind(item)){ - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : - case 263 /* EnumDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 264 /* ModuleDeclaration */ : - case 308 /* SourceFile */ : - case 262 /* TypeAliasDeclaration */ : - case 349 /* JSDocTypedefTag */ : - case 341 /* JSDocCallbackTag */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 266 /* EnumDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 267 /* ModuleDeclaration */ : + case 312 /* SourceFile */ : + case 265 /* TypeAliasDeclaration */ : + case 353 /* JSDocTypedefTag */ : + case 345 /* JSDocCallbackTag */ : return true; - case 216 /* ArrowFunction */ : - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : return isTopLevelFunctionDeclaration(item); default: return false; @@ -105667,10 +107608,10 @@ ${lanes.join("\n")} function isTopLevelFunctionDeclaration(item2) { if (!item2.node.body) return false; switch(navigationBarNodeKind(item2.parent)){ - case 265 /* ModuleBlock */ : - case 308 /* SourceFile */ : - case 171 /* MethodDeclaration */ : - case 173 /* Constructor */ : + case 268 /* ModuleBlock */ : + case 312 /* SourceFile */ : + case 174 /* MethodDeclaration */ : + case 176 /* Constructor */ : return true; default: return false; @@ -105727,7 +107668,7 @@ ${lanes.join("\n")} const result = [ getTextOfIdentifierOrLiteral(moduleDeclaration.name) ]; - while(moduleDeclaration.body && moduleDeclaration.body.kind === 264 /* ModuleDeclaration */ ){ + while(moduleDeclaration.body && moduleDeclaration.body.kind === 267 /* ModuleDeclaration */ ){ moduleDeclaration = moduleDeclaration.body; result.push(getTextOfIdentifierOrLiteral(moduleDeclaration.name)); } @@ -105737,20 +107678,20 @@ ${lanes.join("\n")} return decl.body && isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl; } function isComputedProperty(member) { - return !member.name || member.name.kind === 164 /* ComputedPropertyName */ ; + return !member.name || member.name.kind === 167 /* ComputedPropertyName */ ; } function getNodeSpan(node) { - return node.kind === 308 /* SourceFile */ ? createTextSpanFromRange(node) : createTextSpanFromNode(node, curSourceFile); + return node.kind === 312 /* SourceFile */ ? createTextSpanFromRange(node) : createTextSpanFromNode(node, curSourceFile); } function getModifiers2(node) { - if (node.parent && node.parent.kind === 257 /* VariableDeclaration */ ) node = node.parent; + if (node.parent && node.parent.kind === 260 /* VariableDeclaration */ ) node = node.parent; return getNodeModifiers(node); } function getFunctionOrClassName(node) { - const { parent: parent2 } = node; + const { parent: parent2 } = node; if (node.name && getFullWidth(node.name) > 0) return cleanText(declarationNameToString(node.name)); else if (isVariableDeclaration(parent2)) return cleanText(declarationNameToString(parent2.name)); - else if (isBinaryExpression(parent2) && parent2.operatorToken.kind === 63 /* EqualsToken */ ) return nodeText(parent2.left).replace(whiteSpaceRegex, ""); + else if (isBinaryExpression(parent2) && parent2.operatorToken.kind === 64 /* EqualsToken */ ) return nodeText(parent2.left).replace(whiteSpaceRegex, ""); else if (isPropertyAssignment(parent2)) return nodeText(parent2.name); else if (getSyntacticModifierFlags(node) & 1024 /* Default */ ) return "default"; else if (isClassLike(node)) return ""; @@ -105775,9 +107716,9 @@ ${lanes.join("\n")} } function isFunctionOrClassExpression(node) { switch(node.kind){ - case 216 /* ArrowFunction */ : - case 215 /* FunctionExpression */ : - case 228 /* ClassExpression */ : + case 219 /* ArrowFunction */ : + case 218 /* FunctionExpression */ : + case 231 /* ClassExpression */ : return true; default: return false; @@ -105823,3378 +107764,4590 @@ ${lanes.join("\n")} init_navigationBar(); } }); - // src/services/services.ts - function createNode(kind, pos, end, parent2) { - const node = isNodeKind(kind) ? new NodeObject(kind, pos, end) : kind === 79 /* Identifier */ ? new IdentifierObject(79 /* Identifier */ , pos, end) : kind === 80 /* PrivateIdentifier */ ? new PrivateIdentifierObject(80 /* PrivateIdentifier */ , pos, end) : new TokenObject(kind, pos, end); - node.parent = parent2; - node.flags = parent2.flags & 50720768 /* ContextFlags */ ; - return node; + // src/services/refactorProvider.ts + function registerRefactor(name, refactor) { + refactors.set(name, refactor); } - function createChildren(node, sourceFile) { - if (!isNodeKind(node.kind)) return emptyArray; - const children = []; - if (isJSDocCommentContainingNode(node)) { - node.forEachChild((child)=>{ - children.push(child); - }); - return children; + function getApplicableRefactors(context, includeInteractiveActions) { + return arrayFrom(flatMapIterator(refactors.values(), (refactor)=>{ + var _a; + return context.cancellationToken && context.cancellationToken.isCancellationRequested() || !((_a = refactor.kinds) == null ? void 0 : _a.some((kind)=>refactorKindBeginsWith(kind, context.kind))) ? void 0 : refactor.getAvailableActions(context, includeInteractiveActions); + })); + } + function getEditsForRefactor(context, refactorName14, actionName2, interactiveRefactorArguments) { + const refactor = refactors.get(refactorName14); + return refactor && refactor.getEditsForAction(context, actionName2, interactiveRefactorArguments); + } + var refactors; + var init_refactorProvider = __esm({ + "src/services/refactorProvider.ts" () { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactors = /* @__PURE__ */ new Map(); } - scanner.setText((sourceFile || node.getSourceFile()).text); - let pos = node.pos; - const processNode = (child)=>{ - addSyntheticNodes(children, pos, child.pos, node); - children.push(child); - pos = child.end; + }); + // src/services/refactors/convertExport.ts + function getInfo2(context, considerPartialSpans = true) { + const { file: file, program: program } = context; + const span = getRefactorContextSpan(context); + const token = getTokenAtPosition(file, span.start); + const exportNode = !!(token.parent && getSyntacticModifierFlags(token.parent) & 1 /* Export */ ) && considerPartialSpans ? token.parent : getParentNodeInSpan(token, file, span); + if (!exportNode || !isSourceFile(exportNode.parent) && !(isModuleBlock(exportNode.parent) && isAmbientModule(exportNode.parent.parent))) return { + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_export_statement) }; - const processNodes = (nodes)=>{ - addSyntheticNodes(children, pos, nodes.pos, node); - children.push(createSyntaxList(nodes, node)); - pos = nodes.end; + const checker = program.getTypeChecker(); + const exportingModuleSymbol = getExportingModuleSymbol(exportNode.parent, checker); + const flags = getSyntacticModifierFlags(exportNode) || (isExportAssignment(exportNode) && !exportNode.isExportEquals ? 1025 /* ExportDefault */ : 0 /* None */ ); + const wasDefault = !!(flags & 1024 /* Default */ ); + if (!(flags & 1 /* Export */ ) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */ )) return { + error: getLocaleSpecificMessage(Diagnostics.This_file_already_has_a_default_export) }; - forEach(node.jsDoc, processNode); - pos = node.pos; - node.forEachChild(processNode, processNodes); - addSyntheticNodes(children, pos, node.end, node); - scanner.setText(void 0); - return children; - } - function addSyntheticNodes(nodes, pos, end, parent2) { - scanner.setTextPos(pos); - while(pos < end){ - const token = scanner.scan(); - const textPos = scanner.getTextPos(); - if (textPos <= end) { - if (token === 79 /* Identifier */ ) { - if (hasTabstop(parent2)) continue; - Debug.fail(`Did not expect ${Debug.formatSyntaxKind(parent2.kind)} to have an Identifier in its trivia`); + const noSymbolError = (id)=>isIdentifier(id) && checker.getSymbolAtLocation(id) ? void 0 : { + error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_named_export) + }; + switch(exportNode.kind){ + case 262 /* FunctionDeclaration */ : + case 263 /* ClassDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 266 /* EnumDeclaration */ : + case 265 /* TypeAliasDeclaration */ : + case 267 /* ModuleDeclaration */ : + { + const node = exportNode; + if (!node.name) return void 0; + return noSymbolError(node.name) || { + exportNode: node, + exportName: node.name, + wasDefault: wasDefault, + exportingModuleSymbol: exportingModuleSymbol + }; } - nodes.push(createNode(token, pos, textPos, parent2)); - } - pos = textPos; - if (token === 1 /* EndOfFileToken */ ) break; - } - } - function createSyntaxList(nodes, parent2) { - const list = createNode(354 /* SyntaxList */ , nodes.pos, nodes.end, parent2); - list._children = []; - let pos = nodes.pos; - for (const node of nodes){ - addSyntheticNodes(list._children, pos, node.pos, parent2); - list._children.push(node); - pos = node.end; + case 243 /* VariableStatement */ : + { + const vs = exportNode; + if (!(vs.declarationList.flags & 2 /* Const */ ) || vs.declarationList.declarations.length !== 1) return void 0; + const decl = first(vs.declarationList.declarations); + if (!decl.initializer) return void 0; + Debug.assert(!wasDefault, "Can't have a default flag here"); + return noSymbolError(decl.name) || { + exportNode: vs, + exportName: decl.name, + wasDefault: wasDefault, + exportingModuleSymbol: exportingModuleSymbol + }; + } + case 277 /* ExportAssignment */ : + { + const node = exportNode; + if (node.isExportEquals) return void 0; + return noSymbolError(node.expression) || { + exportNode: node, + exportName: node.expression, + wasDefault: wasDefault, + exportingModuleSymbol: exportingModuleSymbol + }; + } + default: + return void 0; } - addSyntheticNodes(list._children, pos, nodes.end, parent2); - return list; - } - function hasJSDocInheritDocTag(node) { - return getJSDocTags(node).some((tag)=>tag.tagName.text === "inheritDoc" || tag.tagName.text === "inheritdoc"); } - function getJsDocTagsOfDeclarations(declarations, checker) { - if (!declarations) return emptyArray; - let tags = ts_JsDoc_exports.getJsDocTagsFromDeclarations(declarations, checker); - if (checker && (tags.length === 0 || declarations.some(hasJSDocInheritDocTag))) { - const seenSymbols = /* @__PURE__ */ new Set(); - for (const declaration of declarations){ - const inheritedTags = findBaseOfDeclaration(checker, declaration, (symbol)=>{ - var _a2; - if (!seenSymbols.has(symbol)) { - seenSymbols.add(symbol); - if (declaration.kind === 174 /* GetAccessor */ || declaration.kind === 175 /* SetAccessor */ ) return symbol.getContextualJsDocTags(declaration, checker); - return ((_a2 = symbol.declarations) == null ? void 0 : _a2.length) === 1 ? symbol.getJsDocTags() : void 0; - } - }); - if (inheritedTags) tags = [ - ...inheritedTags, - ...tags - ]; - } - } - return tags; + function doChange(exportingSourceFile, program, info, changes, cancellationToken) { + changeExport(exportingSourceFile, info, changes, program.getTypeChecker()); + changeImports(program, info, changes, cancellationToken); } - function getDocumentationComment(declarations, checker) { - if (!declarations) return emptyArray; - let doc = ts_JsDoc_exports.getJsDocCommentsFromDeclarations(declarations, checker); - if (checker && (doc.length === 0 || declarations.some(hasJSDocInheritDocTag))) { - const seenSymbols = /* @__PURE__ */ new Set(); - for (const declaration of declarations){ - const inheritedDocs = findBaseOfDeclaration(checker, declaration, (symbol)=>{ - if (!seenSymbols.has(symbol)) { - seenSymbols.add(symbol); - if (declaration.kind === 174 /* GetAccessor */ || declaration.kind === 175 /* SetAccessor */ ) return symbol.getContextualDocumentationComment(declaration, checker); - return symbol.getDocumentationComment(checker); + function changeExport(exportingSourceFile, { wasDefault: wasDefault, exportNode: exportNode, exportName: exportName }, changes, checker) { + if (wasDefault) { + if (isExportAssignment(exportNode) && !exportNode.isExportEquals) { + const exp = exportNode.expression; + const spec = makeExportSpecifier(exp.text, exp.text); + changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, factory.createNamedExports([ + spec + ]))); + } else changes.delete(exportingSourceFile, Debug.checkDefined(findModifier(exportNode, 90 /* DefaultKeyword */ ), "Should find a default keyword in modifier list")); + } else { + const exportKeyword = Debug.checkDefined(findModifier(exportNode, 95 /* ExportKeyword */ ), "Should find an export keyword in modifier list"); + switch(exportNode.kind){ + case 262 /* FunctionDeclaration */ : + case 263 /* ClassDeclaration */ : + case 264 /* InterfaceDeclaration */ : + changes.insertNodeAfter(exportingSourceFile, exportKeyword, factory.createToken(90 /* DefaultKeyword */ )); + break; + case 243 /* VariableStatement */ : + const decl = first(exportNode.declarationList.declarations); + if (!ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile) && !decl.type) { + changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDefault(Debug.checkDefined(decl.initializer, "Initializer was previously known to be present"))); + break; } - }); - if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(lineBreakPart(), doc); + case 266 /* EnumDeclaration */ : + case 265 /* TypeAliasDeclaration */ : + case 267 /* ModuleDeclaration */ : + changes.deleteModifier(exportingSourceFile, exportKeyword); + changes.insertNodeAfter(exportingSourceFile, exportNode, factory.createExportDefault(factory.createIdentifier(exportName.text))); + break; + default: + Debug.fail(`Unexpected exportNode kind ${exportNode.kind}`); } } - return doc; } - function findBaseOfDeclaration(checker, declaration, cb) { - var _a2; - const classOrInterfaceDeclaration = ((_a2 = declaration.parent) == null ? void 0 : _a2.kind) === 173 /* Constructor */ ? declaration.parent.parent : declaration.parent; - if (!classOrInterfaceDeclaration) return; - const isStaticMember = hasStaticModifier(declaration); - return firstDefined(getAllSuperTypeNodes(classOrInterfaceDeclaration), (superTypeNode)=>{ - const baseType = checker.getTypeAtLocation(superTypeNode); - const type = isStaticMember && baseType.symbol ? checker.getTypeOfSymbol(baseType.symbol) : baseType; - const symbol = checker.getPropertyOfType(type, declaration.symbol.name); - return symbol ? cb(symbol) : void 0; + function changeImports(program, { wasDefault: wasDefault, exportName: exportName, exportingModuleSymbol: exportingModuleSymbol }, changes, cancellationToken) { + const checker = program.getTypeChecker(); + const exportSymbol = Debug.checkDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol"); + ts_FindAllReferences_exports.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, (ref)=>{ + if (exportName === ref) return; + const importingSourceFile = ref.getSourceFile(); + if (wasDefault) changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text); + else changeNamedToDefaultImport(importingSourceFile, ref, changes); }); } - function getServicesObjectAllocator() { - return { - getNodeConstructor: ()=>NodeObject, - getTokenConstructor: ()=>TokenObject, - getIdentifierConstructor: ()=>IdentifierObject, - getPrivateIdentifierConstructor: ()=>PrivateIdentifierObject, - getSourceFileConstructor: ()=>SourceFileObject, - getSymbolConstructor: ()=>SymbolObject, - getTypeConstructor: ()=>TypeObject, - getSignatureConstructor: ()=>SignatureObject, - getSourceMapSourceConstructor: ()=>SourceMapSourceObject - }; - } - function toEditorSettings(optionsAsMap) { - let allPropertiesAreCamelCased = true; - for(const key in optionsAsMap)if (hasProperty(optionsAsMap, key) && !isCamelCase(key)) { - allPropertiesAreCamelCased = false; - break; + function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { + const { parent: parent2 } = ref; + switch(parent2.kind){ + case 211 /* PropertyAccessExpression */ : + changes.replaceNode(importingSourceFile, ref, factory.createIdentifier(exportName)); + break; + case 276 /* ImportSpecifier */ : + case 281 /* ExportSpecifier */ : + { + const spec = parent2; + changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text)); + break; + } + case 273 /* ImportClause */ : + { + const clause = parent2; + Debug.assert(clause.name === ref, "Import clause name should match provided ref"); + const spec = makeImportSpecifier(exportName, ref.text); + const { namedBindings: namedBindings } = clause; + if (!namedBindings) changes.replaceNode(importingSourceFile, ref, factory.createNamedImports([ + spec + ])); + else if (namedBindings.kind === 274 /* NamespaceImport */ ) { + changes.deleteRange(importingSourceFile, { + pos: ref.getStart(importingSourceFile), + end: namedBindings.getStart(importingSourceFile) + }); + const quotePreference = isStringLiteral(clause.parent.moduleSpecifier) ? quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */ ; + const newImport = makeImport(/*defaultImport*/ void 0, [ + makeImportSpecifier(exportName, ref.text) + ], clause.parent.moduleSpecifier, quotePreference); + changes.insertNodeAfter(importingSourceFile, clause.parent, newImport); + } else { + changes.delete(importingSourceFile, ref); + changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec); + } + break; + } + case 205 /* ImportType */ : + const importTypeNode = parent2; + changes.replaceNode(importingSourceFile, parent2, factory.createImportTypeNode(importTypeNode.argument, importTypeNode.assertions, factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf)); + break; + default: + Debug.failBadSyntaxKind(parent2); } - if (allPropertiesAreCamelCased) return optionsAsMap; - const settings = {}; - for(const key in optionsAsMap)if (hasProperty(optionsAsMap, key)) { - const newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1); - settings[newKey] = optionsAsMap[key]; + } + function changeNamedToDefaultImport(importingSourceFile, ref, changes) { + const parent2 = ref.parent; + switch(parent2.kind){ + case 211 /* PropertyAccessExpression */ : + changes.replaceNode(importingSourceFile, ref, factory.createIdentifier("default")); + break; + case 276 /* ImportSpecifier */ : + { + const defaultImport = factory.createIdentifier(parent2.name.text); + if (parent2.parent.elements.length === 1) changes.replaceNode(importingSourceFile, parent2.parent, defaultImport); + else { + changes.delete(importingSourceFile, parent2); + changes.insertNodeBefore(importingSourceFile, parent2.parent, defaultImport); + } + break; + } + case 281 /* ExportSpecifier */ : + changes.replaceNode(importingSourceFile, parent2, makeExportSpecifier("default", parent2.name.text)); + break; + default: + Debug.assertNever(parent2, `Unexpected parent kind ${parent2.kind}`); } - return settings; } - function isCamelCase(s) { - return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); + function makeImportSpecifier(propertyName, name) { + return factory.createImportSpecifier(/*isTypeOnly*/ false, propertyName === name ? void 0 : factory.createIdentifier(propertyName), factory.createIdentifier(name)); } - function displayPartsToString(displayParts) { - if (displayParts) return map(displayParts, (displayPart2)=>displayPart2.text).join(""); - return ""; + function makeExportSpecifier(propertyName, name) { + return factory.createExportSpecifier(/*isTypeOnly*/ false, propertyName === name ? void 0 : factory.createIdentifier(propertyName), factory.createIdentifier(name)); } - function getDefaultCompilerOptions2() { - return { - target: 1 /* ES5 */ , - jsx: 1 /* Preserve */ - }; + function getExportingModuleSymbol(parent2, checker) { + if (isSourceFile(parent2)) return parent2.symbol; + const symbol = parent2.parent.symbol; + if (symbol.valueDeclaration && isExternalModuleAugmentation(symbol.valueDeclaration)) return checker.getMergedSymbol(symbol); + return symbol; } - function getSupportedCodeFixes() { - return ts_codefix_exports.getSupportedErrorCodes(); + var refactorName, defaultToNamedAction, namedToDefaultAction; + var init_convertExport = __esm({ + "src/services/refactors/convertExport.ts" () { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName = "Convert export"; + defaultToNamedAction = { + name: "Convert default export to named export", + description: getLocaleSpecificMessage(Diagnostics.Convert_default_export_to_named_export), + kind: "refactor.rewrite.export.named" + }; + namedToDefaultAction = { + name: "Convert named export to default export", + description: getLocaleSpecificMessage(Diagnostics.Convert_named_export_to_default_export), + kind: "refactor.rewrite.export.default" + }; + registerRefactor(refactorName, { + kinds: [ + defaultToNamedAction.kind, + namedToDefaultAction.kind + ], + getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndDefaultExports(context) { + const info = getInfo2(context, context.triggerReason === "invoked"); + if (!info) return emptyArray; + if (!isRefactorErrorInfo(info)) { + const action = info.wasDefault ? defaultToNamedAction : namedToDefaultAction; + return [ + { + name: refactorName, + description: action.description, + actions: [ + action + ] + } + ]; + } + if (context.preferences.provideRefactorNotApplicableReason) return [ + { + name: refactorName, + description: getLocaleSpecificMessage(Diagnostics.Convert_default_export_to_named_export), + actions: [ + { + ...defaultToNamedAction, + notApplicableReason: info.error + }, + { + ...namedToDefaultAction, + notApplicableReason: info.error + } + ] + } + ]; + return emptyArray; + }, + getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndDefaultExports(context, actionName2) { + Debug.assert(actionName2 === defaultToNamedAction.name || actionName2 === namedToDefaultAction.name, "Unexpected action name"); + const info = getInfo2(context); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange(context.file, context.program, info, t, context.cancellationToken)); + return { + edits: edits, + renameFilename: void 0, + renameLocation: void 0 + }; + } + }); + } + }); + // src/services/refactors/convertImport.ts + function getImportConversionInfo(context, considerPartialSpans = true) { + const { file: file } = context; + const span = getRefactorContextSpan(context); + const token = getTokenAtPosition(file, span.start); + const importDecl = considerPartialSpans ? findAncestor(token, isImportDeclaration) : getParentNodeInSpan(token, file, span); + if (!importDecl || !isImportDeclaration(importDecl)) return { + error: "Selection is not an import declaration." + }; + const end = span.start + span.length; + const nextToken = findNextToken(importDecl, importDecl.parent, file); + if (nextToken && end > nextToken.getStart()) return void 0; + const { importClause: importClause } = importDecl; + if (!importClause) return { + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_import_clause) + }; + if (!importClause.namedBindings) return { + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_namespace_import_or_named_imports) + }; + if (importClause.namedBindings.kind === 274 /* NamespaceImport */ ) return { + convertTo: 0 /* Named */ , + import: importClause.namedBindings + }; + const shouldUseDefault = getShouldUseDefault(context.program, importClause); + return shouldUseDefault ? { + convertTo: 1 /* Default */ , + import: importClause.namedBindings + } : { + convertTo: 2 /* Namespace */ , + import: importClause.namedBindings + }; } - function setSourceFileFields(sourceFile, scriptSnapshot, version2) { - sourceFile.version = version2; - sourceFile.scriptSnapshot = scriptSnapshot; + function getShouldUseDefault(program, importClause) { + return getAllowSyntheticDefaultImports(program.getCompilerOptions()) && isExportEqualsModule(importClause.parent.moduleSpecifier, program.getTypeChecker()); } - function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTargetOrOptions, version2, setNodeParents, scriptKind) { - const sourceFile = createSourceFile(fileName, getSnapshotText(scriptSnapshot), scriptTargetOrOptions, setNodeParents, scriptKind); - setSourceFileFields(sourceFile, scriptSnapshot, version2); - return sourceFile; + function doChange2(sourceFile, program, changes, info) { + const checker = program.getTypeChecker(); + if (info.convertTo === 0 /* Named */ ) doChangeNamespaceToNamed(sourceFile, checker, changes, info.import, getAllowSyntheticDefaultImports(program.getCompilerOptions())); + else doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, info.import, info.convertTo === 1 /* Default */ ); } - function updateLanguageServiceSourceFile(sourceFile, scriptSnapshot, version2, textChangeRange, aggressiveChecks) { - if (textChangeRange) { - if (version2 !== sourceFile.version) { - let newText; - const prefix = textChangeRange.span.start !== 0 ? sourceFile.text.substr(0, textChangeRange.span.start) : ""; - const suffix = textSpanEnd(textChangeRange.span) !== sourceFile.text.length ? sourceFile.text.substr(textSpanEnd(textChangeRange.span)) : ""; - if (textChangeRange.newLength === 0) newText = prefix && suffix ? prefix + suffix : prefix || suffix; - else { - const changedText = scriptSnapshot.getText(textChangeRange.span.start, textChangeRange.span.start + textChangeRange.newLength); - newText = prefix && suffix ? prefix + changedText + suffix : prefix ? prefix + changedText : changedText + suffix; - } - const newSourceFile = updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); - setSourceFileFields(newSourceFile, scriptSnapshot, version2); - newSourceFile.nameTable = void 0; - if (sourceFile !== newSourceFile && sourceFile.scriptSnapshot) { - if (sourceFile.scriptSnapshot.dispose) sourceFile.scriptSnapshot.dispose(); - sourceFile.scriptSnapshot = void 0; - } - return newSourceFile; + function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) { + let usedAsNamespaceOrDefault = false; + const nodesToReplace = []; + const conflictingNames = /* @__PURE__ */ new Map(); + ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, (id)=>{ + if (!isPropertyAccessOrQualifiedName(id.parent)) usedAsNamespaceOrDefault = true; + else { + const exportName = getRightOfPropertyAccessOrQualifiedName(id.parent).text; + if (checker.resolveName(exportName, id, 67108863 /* All */ , /*excludeGlobals*/ true)) conflictingNames.set(exportName, true); + Debug.assert(getLeftOfPropertyAccessOrQualifiedName(id.parent) === id, "Parent expression should match id"); + nodesToReplace.push(id.parent); } + }); + const exportNameToImportName = /* @__PURE__ */ new Map(); + for (const propertyAccessOrQualifiedName of nodesToReplace){ + const exportName = getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName).text; + let importName = exportNameToImportName.get(exportName); + if (importName === void 0) exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? getUniqueName(exportName, sourceFile) : exportName); + changes.replaceNode(sourceFile, propertyAccessOrQualifiedName, factory.createIdentifier(importName)); } - const options = { - languageVersion: sourceFile.languageVersion, - impliedNodeFormat: sourceFile.impliedNodeFormat, - setExternalModuleIndicator: sourceFile.setExternalModuleIndicator - }; - return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, options, version2, /*setNodeParents*/ true, sourceFile.scriptKind); + const importSpecifiers = []; + exportNameToImportName.forEach((name, propertyName)=>{ + importSpecifiers.push(factory.createImportSpecifier(/*isTypeOnly*/ false, name === propertyName ? void 0 : factory.createIdentifier(propertyName), factory.createIdentifier(name))); + }); + const importDecl = toConvert.parent.parent; + if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) changes.insertNodeAfter(sourceFile, importDecl, updateImport(importDecl, /*defaultImportName*/ void 0, importSpecifiers)); + else changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? factory.createIdentifier(toConvert.name.text) : void 0, importSpecifiers)); } - function createLanguageService(host, documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()), syntaxOnlyOrLanguageServiceMode) { - var _a2; - let languageServiceMode; - if (syntaxOnlyOrLanguageServiceMode === void 0) languageServiceMode = 0 /* Semantic */ ; - else if (typeof syntaxOnlyOrLanguageServiceMode === "boolean") languageServiceMode = syntaxOnlyOrLanguageServiceMode ? 2 /* Syntactic */ : 0 /* Semantic */ ; - else languageServiceMode = syntaxOnlyOrLanguageServiceMode; - const syntaxTreeCache = new SyntaxTreeCache(host); - let program; - let lastProjectVersion; - let lastTypesRootVersion = 0; - const cancellationToken = host.getCancellationToken ? new CancellationTokenObject(host.getCancellationToken()) : NoopCancellationToken; - const currentDirectory = host.getCurrentDirectory(); - maybeSetLocalizedDiagnosticMessages((_a2 = host.getLocalizedDiagnosticMessages) == null ? void 0 : _a2.bind(host)); - function log(message) { - if (host.log) host.log(message); - } - const useCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames(host); - const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); - const sourceMapper = getSourceMapper({ - useCaseSensitiveFileNames: ()=>useCaseSensitiveFileNames, - getCurrentDirectory: ()=>currentDirectory, - getProgram: getProgram, - fileExists: maybeBind(host, host.fileExists), - readFile: maybeBind(host, host.readFile), - getDocumentPositionMapper: maybeBind(host, host.getDocumentPositionMapper), - getSourceFileLike: maybeBind(host, host.getSourceFileLike), - log: log + function getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) { + return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.name : propertyAccessOrQualifiedName.right; + } + function getLeftOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) { + return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.expression : propertyAccessOrQualifiedName.left; + } + function doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, toConvert, shouldUseDefault = getShouldUseDefault(program, toConvert.parent)) { + const checker = program.getTypeChecker(); + const importDecl = toConvert.parent.parent; + const { moduleSpecifier: moduleSpecifier } = importDecl; + const toConvertSymbols = /* @__PURE__ */ new Set(); + toConvert.elements.forEach((namedImport)=>{ + const symbol = checker.getSymbolAtLocation(namedImport.name); + if (symbol) toConvertSymbols.add(symbol); }); - function getValidSourceFile(fileName) { - const sourceFile = program.getSourceFile(fileName); - if (!sourceFile) { - const error = new Error(`Could not find source file: '${fileName}'.`); - error.ProgramFiles = program.getSourceFiles().map((f)=>f.fileName); - throw error; - } - return sourceFile; - } - function synchronizeHostData() { - var _a3, _b, _c; - Debug.assert(languageServiceMode !== 2 /* Syntactic */ ); - if (host.getProjectVersion) { - const hostProjectVersion = host.getProjectVersion(); - if (hostProjectVersion) { - if (lastProjectVersion === hostProjectVersion && !((_a3 = host.hasChangedAutomaticTypeDirectiveNames) == null ? void 0 : _a3.call(host))) return; - lastProjectVersion = hostProjectVersion; + const preferredName = moduleSpecifier && isStringLiteral(moduleSpecifier) ? ts_codefix_exports.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 99 /* ESNext */ ) : "module"; + function hasNamespaceNameConflict(namedImport) { + return !!ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(namedImport.name, checker, sourceFile, (id)=>{ + const symbol = checker.resolveName(preferredName, id, 67108863 /* All */ , /*excludeGlobals*/ true); + if (symbol) { + if (toConvertSymbols.has(symbol)) return isExportSpecifier(id.parent); + return true; } - } - const typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; - if (lastTypesRootVersion !== typeRootsVersion) { - log("TypeRoots version has changed; provide new program"); - program = void 0; - lastTypesRootVersion = typeRootsVersion; - } - const rootFileNames = host.getScriptFileNames().slice(); - const newSettings = host.getCompilationSettings() || getDefaultCompilerOptions2(); - const hasInvalidatedResolutions = host.hasInvalidatedResolutions || returnFalse; - const hasChangedAutomaticTypeDirectiveNames = maybeBind(host, host.hasChangedAutomaticTypeDirectiveNames); - const projectReferences = (_b = host.getProjectReferences) == null ? void 0 : _b.call(host); - let parsedCommandLines; - let compilerHost = { - getSourceFile: getOrCreateSourceFile, - getSourceFileByPath: getOrCreateSourceFileByPath, - getCancellationToken: ()=>cancellationToken, - getCanonicalFileName: getCanonicalFileName, - useCaseSensitiveFileNames: ()=>useCaseSensitiveFileNames, - getNewLine: ()=>getNewLineCharacter(newSettings), - getDefaultLibFileName: (options2)=>host.getDefaultLibFileName(options2), - writeFile: noop, - getCurrentDirectory: ()=>currentDirectory, - fileExists: (fileName)=>host.fileExists(fileName), - readFile: (fileName)=>host.readFile && host.readFile(fileName), - getSymlinkCache: maybeBind(host, host.getSymlinkCache), - realpath: maybeBind(host, host.realpath), - directoryExists: (directoryName)=>{ - return directoryProbablyExists(directoryName, host); - }, - getDirectories: (path)=>{ - return host.getDirectories ? host.getDirectories(path) : []; + return false; + }); + } + const namespaceNameConflicts = toConvert.elements.some(hasNamespaceNameConflict); + const namespaceImportName = namespaceNameConflicts ? getUniqueName(preferredName, sourceFile) : preferredName; + const neededNamedImports = /* @__PURE__ */ new Set(); + for (const element of toConvert.elements){ + const propertyName = (element.propertyName || element.name).text; + ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, (id)=>{ + const access = factory.createPropertyAccessExpression(factory.createIdentifier(namespaceImportName), propertyName); + if (isShorthandPropertyAssignment(id.parent)) changes.replaceNode(sourceFile, id.parent, factory.createPropertyAssignment(id.text, access)); + else if (isExportSpecifier(id.parent)) neededNamedImports.add(element); + else changes.replaceNode(sourceFile, id, access); + }); + } + changes.replaceNode(sourceFile, toConvert, shouldUseDefault ? factory.createIdentifier(namespaceImportName) : factory.createNamespaceImport(factory.createIdentifier(namespaceImportName))); + if (neededNamedImports.size) { + const newNamedImports = arrayFrom(neededNamedImports.values(), (element)=>factory.createImportSpecifier(element.isTypeOnly, element.propertyName && factory.createIdentifier(element.propertyName.text), factory.createIdentifier(element.name.text))); + changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport(importDecl, /*defaultImportName*/ void 0, newNamedImports)); + } + } + function isExportEqualsModule(moduleSpecifier, checker) { + const externalModule = checker.resolveExternalModuleName(moduleSpecifier); + if (!externalModule) return false; + const exportEquals = checker.resolveExternalModuleSymbol(externalModule); + return externalModule !== exportEquals; + } + function updateImport(old, defaultImportName, elements) { + return factory.createImportDeclaration(/*modifiers*/ void 0, factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, elements && elements.length ? factory.createNamedImports(elements) : void 0), old.moduleSpecifier, /*assertClause*/ void 0); + } + var refactorName2, actions; + var init_convertImport = __esm({ + "src/services/refactors/convertImport.ts" () { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName2 = "Convert import"; + actions = { + [0 /* Named */ ]: { + name: "Convert namespace import to named imports", + description: getLocaleSpecificMessage(Diagnostics.Convert_namespace_import_to_named_imports), + kind: "refactor.rewrite.import.named" }, - readDirectory: (path, extensions, exclude, include, depth)=>{ - Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); - return host.readDirectory(path, extensions, exclude, include, depth); + [2 /* Namespace */ ]: { + name: "Convert named imports to namespace import", + description: getLocaleSpecificMessage(Diagnostics.Convert_named_imports_to_namespace_import), + kind: "refactor.rewrite.import.namespace" }, - onReleaseOldSourceFile: onReleaseOldSourceFile, - onReleaseParsedCommandLine: onReleaseParsedCommandLine, - hasInvalidatedResolutions: hasInvalidatedResolutions, - hasChangedAutomaticTypeDirectiveNames: hasChangedAutomaticTypeDirectiveNames, - trace: maybeBind(host, host.trace), - resolveModuleNames: maybeBind(host, host.resolveModuleNames), - getModuleResolutionCache: maybeBind(host, host.getModuleResolutionCache), - createHash: maybeBind(host, host.createHash), - resolveTypeReferenceDirectives: maybeBind(host, host.resolveTypeReferenceDirectives), - resolveModuleNameLiterals: maybeBind(host, host.resolveModuleNameLiterals), - resolveTypeReferenceDirectiveReferences: maybeBind(host, host.resolveTypeReferenceDirectiveReferences), - useSourceOfProjectReferenceRedirect: maybeBind(host, host.useSourceOfProjectReferenceRedirect), - getParsedCommandLine: getParsedCommandLine - }; - const originalGetSourceFile = compilerHost.getSourceFile; - const { getSourceFileWithCache: getSourceFileWithCache } = changeCompilerHostLikeToUseCache(compilerHost, (fileName)=>toPath(fileName, currentDirectory, getCanonicalFileName), (...args)=>originalGetSourceFile.call(compilerHost, ...args)); - compilerHost.getSourceFile = getSourceFileWithCache; - (_c = host.setCompilerHost) == null || _c.call(host, compilerHost); - const parseConfigHost = { - useCaseSensitiveFileNames: useCaseSensitiveFileNames, - fileExists: (fileName)=>compilerHost.fileExists(fileName), - readFile: (fileName)=>compilerHost.readFile(fileName), - readDirectory: (...args)=>compilerHost.readDirectory(...args), - trace: compilerHost.trace, - getCurrentDirectory: compilerHost.getCurrentDirectory, - onUnRecoverableConfigFileDiagnostic: noop - }; - const documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); - if (isProgramUptoDate(program, rootFileNames, newSettings, (_path, fileName)=>host.getScriptVersion(fileName), (fileName)=>compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) return; - const options = { - rootNames: rootFileNames, - options: newSettings, - host: compilerHost, - oldProgram: program, - projectReferences: projectReferences + [1 /* Default */ ]: { + name: "Convert named imports to default import", + description: getLocaleSpecificMessage(Diagnostics.Convert_named_imports_to_default_import), + kind: "refactor.rewrite.import.default" + } }; - program = createProgram(options); - compilerHost = void 0; - parsedCommandLines = void 0; - sourceMapper.clearCache(); - program.getTypeChecker(); - return; - function getParsedCommandLine(fileName) { - const path = toPath(fileName, currentDirectory, getCanonicalFileName); - const existing = parsedCommandLines == null ? void 0 : parsedCommandLines.get(path); - if (existing !== void 0) return existing || void 0; - const result = host.getParsedCommandLine ? host.getParsedCommandLine(fileName) : getParsedCommandLineOfConfigFileUsingSourceFile(fileName); - (parsedCommandLines || (parsedCommandLines = /* @__PURE__ */ new Map())).set(path, result || false); - return result; - } - function getParsedCommandLineOfConfigFileUsingSourceFile(configFileName) { - const result = getOrCreateSourceFile(configFileName, 100 /* JSON */ ); - if (!result) return void 0; - result.path = toPath(configFileName, currentDirectory, getCanonicalFileName); - result.resolvedPath = result.path; - result.originalFileName = result.fileName; - return parseJsonSourceFileConfigFileContent(result, parseConfigHost, getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), /*optionsToExtend*/ void 0, getNormalizedAbsolutePath(configFileName, currentDirectory)); - } - function onReleaseParsedCommandLine(configFileName, oldResolvedRef, oldOptions) { - var _a4; - if (host.getParsedCommandLine) (_a4 = host.onReleaseParsedCommandLine) == null || _a4.call(host, configFileName, oldResolvedRef, oldOptions); - else if (oldResolvedRef) onReleaseOldSourceFile(oldResolvedRef.sourceFile, oldOptions); - } - function onReleaseOldSourceFile(oldSourceFile, oldOptions) { - const oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); - documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind, oldSourceFile.impliedNodeFormat); - } - function getOrCreateSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile) { - return getOrCreateSourceFileByPath(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), languageVersionOrOptions, onError, shouldCreateNewSourceFile); - } - function getOrCreateSourceFileByPath(fileName, path, languageVersionOrOptions, _onError, shouldCreateNewSourceFile) { - Debug.assert(compilerHost, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host."); - const scriptSnapshot = host.getScriptSnapshot(fileName); - if (!scriptSnapshot) return void 0; - const scriptKind = getScriptKind(fileName, host); - const scriptVersion = host.getScriptVersion(fileName); - if (!shouldCreateNewSourceFile) { - const oldSourceFile = program && program.getSourceFileByPath(path); - if (oldSourceFile) { - if (scriptKind === oldSourceFile.scriptKind) return documentRegistry.updateDocumentWithKey(fileName, path, host, documentRegistryBucketKey, scriptSnapshot, scriptVersion, scriptKind, languageVersionOrOptions); - else documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()), oldSourceFile.scriptKind, oldSourceFile.impliedNodeFormat); + registerRefactor(refactorName2, { + kinds: getOwnValues(actions).map((a)=>a.kind), + getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndNamespacedImports(context) { + const info = getImportConversionInfo(context, context.triggerReason === "invoked"); + if (!info) return emptyArray; + if (!isRefactorErrorInfo(info)) { + const action = actions[info.convertTo]; + return [ + { + name: refactorName2, + description: action.description, + actions: [ + action + ] + } + ]; } + if (context.preferences.provideRefactorNotApplicableReason) return getOwnValues(actions).map((action)=>({ + name: refactorName2, + description: action.description, + actions: [ + { + ...action, + notApplicableReason: info.error + } + ] + })); + return emptyArray; + }, + getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndNamespacedImports(context, actionName2) { + Debug.assert(some(getOwnValues(actions), (action)=>action.name === actionName2), "Unexpected action name"); + const info = getImportConversionInfo(context); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange2(context.file, context.program, t, info)); + return { + edits: edits, + renameFilename: void 0, + renameLocation: void 0 + }; } - return documentRegistry.acquireDocumentWithKey(fileName, path, host, documentRegistryBucketKey, scriptSnapshot, scriptVersion, scriptKind, languageVersionOrOptions); - } - } - function getProgram() { - if (languageServiceMode === 2 /* Syntactic */ ) { - Debug.assert(program === void 0); - return void 0; - } - synchronizeHostData(); - return program; - } - function getAutoImportProvider() { - var _a3; - return (_a3 = host.getPackageJsonAutoImportProvider) == null ? void 0 : _a3.call(host); + }); } - function updateIsDefinitionOfReferencedSymbols(referencedSymbols, knownSymbolSpans) { - const checker = program.getTypeChecker(); - const symbol = getSymbolForProgram(); - if (!symbol) return false; - for (const referencedSymbol of referencedSymbols)for (const ref of referencedSymbol.references){ - const refNode = getNodeForSpan(ref); - Debug.assertIsDefined(refNode); - if (knownSymbolSpans.has(ref) || ts_FindAllReferences_exports.isDeclarationOfSymbol(refNode, symbol)) { - knownSymbolSpans.add(ref); - ref.isDefinition = true; - const mappedSpan = getMappedDocumentSpan(ref, sourceMapper, maybeBind(host, host.fileExists)); - if (mappedSpan) knownSymbolSpans.add(mappedSpan); - } else ref.isDefinition = false; + }); + // src/services/refactors/extractType.ts + function getRangeToExtract(context, considerEmptySpans = true) { + const { file: file, startPosition: startPosition } = context; + const isJS = isSourceFileJS(file); + const current = getTokenAtPosition(file, startPosition); + const range = createTextRangeFromSpan(getRefactorContextSpan(context)); + const cursorRequest = range.pos === range.end && considerEmptySpans; + const selection = findAncestor(current, (node)=>node.parent && isTypeNode(node) && !rangeContainsSkipTrivia(range, node.parent, file) && (cursorRequest || nodeOverlapsWithStartEnd(current, file, range.pos, range.end))); + if (!selection || !isTypeNode(selection)) return { + error: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_type_node) + }; + const checker = context.program.getTypeChecker(); + const enclosingNode = getEnclosingNode(selection, isJS); + if (enclosingNode === void 0) return { + error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) + }; + const typeParameters = collectTypeParameters(checker, selection, enclosingNode, file); + if (!typeParameters) return { + error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) + }; + const typeElements = flattenTypeLiteralNodeReference(checker, selection); + return { + isJS: isJS, + selection: selection, + enclosingNode: enclosingNode, + typeParameters: typeParameters, + typeElements: typeElements + }; + } + function flattenTypeLiteralNodeReference(checker, node) { + if (!node) return void 0; + if (isIntersectionTypeNode(node)) { + const result = []; + const seen = /* @__PURE__ */ new Map(); + for (const type of node.types){ + const flattenedTypeMembers = flattenTypeLiteralNodeReference(checker, type); + if (!flattenedTypeMembers || !flattenedTypeMembers.every((type2)=>type2.name && addToSeen(seen, getNameFromPropertyName(type2.name)))) return void 0; + addRange(result, flattenedTypeMembers); } - return true; - function getSymbolForProgram() { - for (const referencedSymbol of referencedSymbols)for (const ref of referencedSymbol.references){ - if (knownSymbolSpans.has(ref)) { - const refNode = getNodeForSpan(ref); - Debug.assertIsDefined(refNode); - return checker.getSymbolAtLocation(refNode); - } - const mappedSpan = getMappedDocumentSpan(ref, sourceMapper, maybeBind(host, host.fileExists)); - if (mappedSpan && knownSymbolSpans.has(mappedSpan)) { - const refNode = getNodeForSpan(mappedSpan); - if (refNode) return checker.getSymbolAtLocation(refNode); + return result; + } else if (isParenthesizedTypeNode(node)) return flattenTypeLiteralNodeReference(checker, node.type); + else if (isTypeLiteralNode(node)) return node.members; + return void 0; + } + function rangeContainsSkipTrivia(r1, node, file) { + return rangeContainsStartEnd(r1, skipTrivia(file.text, node.pos), node.end); + } + function collectTypeParameters(checker, selection, enclosingNode, file) { + const result = []; + return visitor(selection) ? void 0 : result; + function visitor(node) { + if (isTypeReferenceNode(node)) { + if (isIdentifier(node.typeName)) { + const typeName = node.typeName; + const symbol = checker.resolveName(typeName.text, typeName, 262144 /* TypeParameter */ , /*excludeGlobals*/ true); + for (const decl of (symbol == null ? void 0 : symbol.declarations) || emptyArray)if (isTypeParameterDeclaration(decl) && decl.getSourceFile() === file) { + if (decl.name.escapedText === typeName.escapedText && rangeContainsSkipTrivia(decl, selection, file)) return true; + if (rangeContainsSkipTrivia(enclosingNode, decl, file) && !rangeContainsSkipTrivia(selection, decl, file)) { + pushIfUnique(result, decl); + break; + } } } - return void 0; - } - function getNodeForSpan(docSpan) { - const sourceFile = program.getSourceFile(docSpan.fileName); - if (!sourceFile) return void 0; - const rawNode = getTouchingPropertyName(sourceFile, docSpan.textSpan.start); - const adjustedNode = ts_FindAllReferences_exports.Core.getAdjustedNode(rawNode, { - use: ts_FindAllReferences_exports.FindReferencesUse.References - }); - return adjustedNode; - } - } - function cleanupSemanticCache() { - program = void 0; - } - function dispose() { - if (program) { - const key = documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()); - forEach(program.getSourceFiles(), (f)=>documentRegistry.releaseDocumentWithKey(f.resolvedPath, key, f.scriptKind, f.impliedNodeFormat)); - program = void 0; + } else if (isInferTypeNode(node)) { + const conditionalTypeNode = findAncestor(node, (n)=>isConditionalTypeNode(n) && rangeContainsSkipTrivia(n.extendsType, node, file)); + if (!conditionalTypeNode || !rangeContainsSkipTrivia(selection, conditionalTypeNode, file)) return true; + } else if (isTypePredicateNode(node) || isThisTypeNode(node)) { + const functionLikeNode = findAncestor(node.parent, isFunctionLike); + if (functionLikeNode && functionLikeNode.type && rangeContainsSkipTrivia(functionLikeNode.type, node, file) && !rangeContainsSkipTrivia(selection, functionLikeNode, file)) return true; + } else if (isTypeQueryNode(node)) { + if (isIdentifier(node.exprName)) { + const symbol = checker.resolveName(node.exprName.text, node.exprName, 111551 /* Value */ , /*excludeGlobals*/ false); + if ((symbol == null ? void 0 : symbol.valueDeclaration) && rangeContainsSkipTrivia(enclosingNode, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) return true; + } else { + if (isThisIdentifier(node.exprName.left) && !rangeContainsSkipTrivia(selection, node.parent, file)) return true; + } } - host = void 0; - } - function getSyntacticDiagnostics(fileName) { - synchronizeHostData(); - return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken).slice(); + if (file && isTupleTypeNode(node) && getLineAndCharacterOfPosition(file, node.pos).line === getLineAndCharacterOfPosition(file, node.end).line) setEmitFlags(node, 1 /* SingleLine */ ); + return forEachChild(node, visitor); } - function getSemanticDiagnostics(fileName) { - synchronizeHostData(); - const targetSourceFile = getValidSourceFile(fileName); - const semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); - if (!getEmitDeclarations(program.getCompilerOptions())) return semanticDiagnostics.slice(); - const declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); - return [ - ...semanticDiagnostics, - ...declarationDiagnostics - ]; + } + function doTypeAliasChange(changes, file, name, info) { + const { enclosingNode: enclosingNode, selection: selection, typeParameters: typeParameters } = info; + const newTypeNode = factory.createTypeAliasDeclaration(/*modifiers*/ void 0, name, typeParameters.map((id)=>factory.updateTypeParameterDeclaration(id, id.modifiers, id.name, id.constraint, /*defaultType*/ void 0)), selection); + changes.insertNodeBefore(file, enclosingNode, ignoreSourceNewlines(newTypeNode), /*blankLineBetween*/ true); + changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id)=>factory.createTypeReferenceNode(id.name, /*typeArguments*/ void 0))), { + leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, + trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace + }); + } + function doInterfaceChange(changes, file, name, info) { + var _a; + const { enclosingNode: enclosingNode, selection: selection, typeParameters: typeParameters, typeElements: typeElements } = info; + const newTypeNode = factory.createInterfaceDeclaration(/*modifiers*/ void 0, name, typeParameters, /*heritageClauses*/ void 0, typeElements); + setTextRange(newTypeNode, (_a = typeElements[0]) == null ? void 0 : _a.parent); + changes.insertNodeBefore(file, enclosingNode, ignoreSourceNewlines(newTypeNode), /*blankLineBetween*/ true); + changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id)=>factory.createTypeReferenceNode(id.name, /*typeArguments*/ void 0))), { + leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, + trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace + }); + } + function doTypedefChange(changes, context, file, name, info) { + var _a; + const { enclosingNode: enclosingNode, selection: selection, typeParameters: typeParameters } = info; + setEmitFlags(selection, 7168 /* NoNestedComments */ ); + const node = factory.createJSDocTypedefTag(factory.createIdentifier("typedef"), factory.createJSDocTypeExpression(selection), factory.createIdentifier(name)); + const templates = []; + forEach(typeParameters, (typeParameter)=>{ + const constraint = getEffectiveConstraintOfTypeParameter(typeParameter); + const parameter = factory.createTypeParameterDeclaration(/*modifiers*/ void 0, typeParameter.name); + const template = factory.createJSDocTemplateTag(factory.createIdentifier("template"), constraint && cast(constraint, isJSDocTypeExpression), [ + parameter + ]); + templates.push(template); + }); + const jsDoc = factory.createJSDocComment(/*comment*/ void 0, factory.createNodeArray(concatenate(templates, [ + node + ]))); + if (isJSDoc(enclosingNode)) { + const pos = enclosingNode.getStart(file); + const newLineCharacter = getNewLineOrDefaultFromHost(context.host, (_a = context.formatContext) == null ? void 0 : _a.options); + changes.insertNodeAt(file, enclosingNode.getStart(file), jsDoc, { + suffix: newLineCharacter + newLineCharacter + file.text.slice(getPrecedingNonSpaceCharacterPosition(file.text, pos - 1), pos) + }); + } else changes.insertNodeBefore(file, enclosingNode, jsDoc, /*blankLineBetween*/ true); + changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id)=>factory.createTypeReferenceNode(id.name, /*typeArguments*/ void 0)))); + } + function getEnclosingNode(node, isJS) { + return findAncestor(node, isStatement) || (isJS ? findAncestor(node, isJSDoc) : void 0); + } + var refactorName3, extractToTypeAliasAction, extractToInterfaceAction, extractToTypeDefAction; + var init_extractType = __esm({ + "src/services/refactors/extractType.ts" () { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName3 = "Extract type"; + extractToTypeAliasAction = { + name: "Extract to type alias", + description: getLocaleSpecificMessage(Diagnostics.Extract_to_type_alias), + kind: "refactor.extract.type" + }; + extractToInterfaceAction = { + name: "Extract to interface", + description: getLocaleSpecificMessage(Diagnostics.Extract_to_interface), + kind: "refactor.extract.interface" + }; + extractToTypeDefAction = { + name: "Extract to typedef", + description: getLocaleSpecificMessage(Diagnostics.Extract_to_typedef), + kind: "refactor.extract.typedef" + }; + registerRefactor(refactorName3, { + kinds: [ + extractToTypeAliasAction.kind, + extractToInterfaceAction.kind, + extractToTypeDefAction.kind + ], + getAvailableActions: function getRefactorActionsToExtractType(context) { + const info = getRangeToExtract(context, context.triggerReason === "invoked"); + if (!info) return emptyArray; + if (!isRefactorErrorInfo(info)) return [ + { + name: refactorName3, + description: getLocaleSpecificMessage(Diagnostics.Extract_type), + actions: info.isJS ? [ + extractToTypeDefAction + ] : append([ + extractToTypeAliasAction + ], info.typeElements && extractToInterfaceAction) + } + ]; + if (context.preferences.provideRefactorNotApplicableReason) return [ + { + name: refactorName3, + description: getLocaleSpecificMessage(Diagnostics.Extract_type), + actions: [ + { + ...extractToTypeDefAction, + notApplicableReason: info.error + }, + { + ...extractToTypeAliasAction, + notApplicableReason: info.error + }, + { + ...extractToInterfaceAction, + notApplicableReason: info.error + } + ] + } + ]; + return emptyArray; + }, + getEditsForAction: function getRefactorEditsToExtractType(context, actionName2) { + const { file: file } = context; + const info = getRangeToExtract(context); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected to find a range to extract"); + const name = getUniqueName("NewType", file); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (changes)=>{ + switch(actionName2){ + case extractToTypeAliasAction.name: + Debug.assert(!info.isJS, "Invalid actionName/JS combo"); + return doTypeAliasChange(changes, file, name, info); + case extractToTypeDefAction.name: + Debug.assert(info.isJS, "Invalid actionName/JS combo"); + return doTypedefChange(changes, context, file, name, info); + case extractToInterfaceAction.name: + Debug.assert(!info.isJS && !!info.typeElements, "Invalid actionName/JS combo"); + return doInterfaceChange(changes, file, name, info); + default: + Debug.fail("Unexpected action name"); + } + }); + const renameFilename = file.fileName; + const renameLocation = getRenameLocation(edits, renameFilename, name, /*preferLastLocation*/ false); + return { + edits: edits, + renameFilename: renameFilename, + renameLocation: renameLocation + }; + } + }); } - function getSuggestionDiagnostics(fileName) { - synchronizeHostData(); - return computeSuggestionDiagnostics(getValidSourceFile(fileName), program, cancellationToken); + }); + // src/services/refactors/helpers.ts + function isRefactorErrorInfo(info) { + return info.error !== void 0; + } + function refactorKindBeginsWith(known, requested) { + if (!requested) return true; + return known.substr(0, requested.length) === requested; + } + var init_helpers = __esm({ + "src/services/refactors/helpers.ts" () { + "use strict"; } - function getCompilerOptionsDiagnostics() { - synchronizeHostData(); - return [ - ...program.getOptionsDiagnostics(cancellationToken), - ...program.getGlobalDiagnostics(cancellationToken) - ]; + }); + // src/services/refactors/inlineVariable.ts + function getInliningInfo(file, startPosition, tryWithReferenceToken, program) { + var _a, _b; + const checker = program.getTypeChecker(); + const token = getTouchingPropertyName(file, startPosition); + const parent2 = token.parent; + if (!isIdentifier(token)) return void 0; + if (isInitializedVariable(parent2) && isVariableDeclarationInVariableStatement(parent2) && isIdentifier(parent2.name)) { + if (((_a = checker.getMergedSymbol(parent2.symbol).declarations) == null ? void 0 : _a.length) !== 1) return { + error: getLocaleSpecificMessage(Diagnostics.Variables_with_multiple_declarations_cannot_be_inlined) + }; + if (isDeclarationExported(parent2)) return void 0; + const references = getReferenceNodes(parent2, checker, file); + return references && { + references: references, + declaration: parent2, + replacement: parent2.initializer + }; } - function getCompletionsAtPosition2(fileName, position, options = emptyOptions, formattingSettings) { - const fullPreferences = { - ...identity(options), - // avoid excess property check - includeCompletionsForModuleExports: options.includeCompletionsForModuleExports || options.includeExternalModuleExports, - includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions + if (tryWithReferenceToken) { + let definition = checker.resolveName(token.text, token, 111551 /* Value */ , /*excludeGlobals*/ false); + definition = definition && checker.getMergedSymbol(definition); + if (((_b = definition == null ? void 0 : definition.declarations) == null ? void 0 : _b.length) !== 1) return { + error: getLocaleSpecificMessage(Diagnostics.Variables_with_multiple_declarations_cannot_be_inlined) + }; + const declaration = definition.declarations[0]; + if (!isInitializedVariable(declaration) || !isVariableDeclarationInVariableStatement(declaration) || !isIdentifier(declaration.name)) return void 0; + if (isDeclarationExported(declaration)) return void 0; + const references = getReferenceNodes(declaration, checker, file); + return references && { + references: references, + declaration: declaration, + replacement: declaration.initializer }; - synchronizeHostData(); - return ts_Completions_exports.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter, options.triggerKind, cancellationToken, formattingSettings && ts_formatting_exports.getFormatContext(formattingSettings, host), options.includeSymbol); - } - function getCompletionEntryDetails2(fileName, position, name, formattingOptions, source, preferences = emptyOptions, data) { - synchronizeHostData(); - return ts_Completions_exports.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { - name: name, - source: source, - data: data - }, host, formattingOptions && ts_formatting_exports.getFormatContext(formattingOptions, host), // TODO: GH#18217 - preferences, cancellationToken); - } - function getCompletionEntrySymbol2(fileName, position, name, source, preferences = emptyOptions) { - synchronizeHostData(); - return ts_Completions_exports.getCompletionEntrySymbol(program, log, getValidSourceFile(fileName), position, { - name: name, - source: source - }, host, preferences); } - function getQuickInfoAtPosition(fileName, position) { - synchronizeHostData(); - const sourceFile = getValidSourceFile(fileName); - const node = getTouchingPropertyName(sourceFile, position); - if (node === sourceFile) return void 0; - const typeChecker = program.getTypeChecker(); - const nodeForQuickInfo = getNodeForQuickInfo(node); - const symbol = getSymbolAtLocationForQuickInfo(nodeForQuickInfo, typeChecker); - if (!symbol || typeChecker.isUnknownSymbol(symbol)) { - const type = shouldGetType(sourceFile, nodeForQuickInfo, position) ? typeChecker.getTypeAtLocation(nodeForQuickInfo) : void 0; - return type && { - kind: "" /* unknown */ , - kindModifiers: "" /* none */ , - textSpan: createTextSpanFromNode(nodeForQuickInfo, sourceFile), - displayParts: typeChecker.runWithCancellationToken(cancellationToken, (typeChecker2)=>typeToDisplayParts(typeChecker2, type, getContainerNode(nodeForQuickInfo))), - documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : void 0, - tags: type.symbol ? type.symbol.getJsDocTags(typeChecker) : void 0 - }; - } - const { symbolKind: symbolKind , displayParts: displayParts , documentation: documentation , tags: tags } = typeChecker.runWithCancellationToken(cancellationToken, (typeChecker2)=>ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker2, symbol, sourceFile, getContainerNode(nodeForQuickInfo), nodeForQuickInfo)); - return { - kind: symbolKind, - kindModifiers: ts_SymbolDisplay_exports.getSymbolModifiers(typeChecker, symbol), - textSpan: createTextSpanFromNode(nodeForQuickInfo, sourceFile), - displayParts: displayParts, - documentation: documentation, - tags: tags + return { + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_variable_to_inline) + }; + } + function isDeclarationExported(declaration) { + const variableStatement = cast(declaration.parent.parent, isVariableStatement); + return some(variableStatement.modifiers, isExportModifier); + } + function getReferenceNodes(declaration, checker, file) { + const references = []; + const cannotInline = ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(declaration.name, checker, file, (ref)=>{ + if (ts_FindAllReferences_exports.isWriteAccessForReference(ref)) return true; + if (isExportSpecifier(ref.parent) || isExportAssignment(ref.parent)) return true; + if (isTypeQueryNode(ref.parent)) return true; + if (textRangeContainsPositionInclusive(declaration, ref.pos)) return true; + references.push(ref); + }); + return references.length === 0 || cannotInline ? void 0 : references; + } + function getReplacementExpression(reference, replacement) { + replacement = getSynthesizedDeepClone(replacement); + const { parent: parent2 } = reference; + if (isExpression(parent2) && (getExpressionPrecedence(replacement) < getExpressionPrecedence(parent2) || needsParentheses(parent2))) return factory.createParenthesizedExpression(replacement); + if (isFunctionLike(replacement) && (isCallLikeExpression(parent2) || isPropertyAccessExpression(parent2))) return factory.createParenthesizedExpression(replacement); + if (isPropertyAccessExpression(parent2) && (isNumericLiteral(replacement) || isObjectLiteralExpression(replacement))) return factory.createParenthesizedExpression(replacement); + return replacement; + } + var refactorName4, refactorDescription, inlineVariableAction; + var init_inlineVariable = __esm({ + "src/services/refactors/inlineVariable.ts" () { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName4 = "Inline variable"; + refactorDescription = getLocaleSpecificMessage(Diagnostics.Inline_variable); + inlineVariableAction = { + name: refactorName4, + description: refactorDescription, + kind: "refactor.inline.variable" }; + registerRefactor(refactorName4, { + kinds: [ + inlineVariableAction.kind + ], + getAvailableActions (context) { + const { file: file, program: program, preferences: preferences, startPosition: startPosition, triggerReason: triggerReason } = context; + const info = getInliningInfo(file, startPosition, triggerReason === "invoked", program); + if (!info) return emptyArray; + if (!ts_refactor_exports.isRefactorErrorInfo(info)) return [ + { + name: refactorName4, + description: refactorDescription, + actions: [ + inlineVariableAction + ] + } + ]; + if (preferences.provideRefactorNotApplicableReason) return [ + { + name: refactorName4, + description: refactorDescription, + actions: [ + { + ...inlineVariableAction, + notApplicableReason: info.error + } + ] + } + ]; + return emptyArray; + }, + getEditsForAction (context, actionName2) { + Debug.assert(actionName2 === refactorName4, "Unexpected refactor invoked"); + const { file: file, program: program, startPosition: startPosition } = context; + const info = getInliningInfo(file, startPosition, /*tryWithReferenceToken*/ true, program); + if (!info || ts_refactor_exports.isRefactorErrorInfo(info)) return void 0; + const { references: references, declaration: declaration, replacement: replacement } = info; + const edits = ts_textChanges_exports.ChangeTracker.with(context, (tracker)=>{ + for (const node of references)tracker.replaceNode(file, node, getReplacementExpression(node, replacement)); + tracker.delete(file, declaration); + }); + return { + edits: edits + }; + } + }); } - function getNodeForQuickInfo(node) { - if (isNewExpression(node.parent) && node.pos === node.parent.pos) return node.parent.expression; - if (isNamedTupleMember(node.parent) && node.pos === node.parent.pos) return node.parent; - if (isImportMeta(node.parent) && node.parent.name === node) return node.parent; - return node; + }); + // src/services/refactors/moveToNewFile.ts + function doChange3(oldFile, program, toMove, changes, host, preferences, context) { + const checker = program.getTypeChecker(); + const usage = getUsageInfo(oldFile, toMove.all, checker); + const newFilename = createNewFileName(oldFile, program, context, host); + changes.createNewFile(oldFile, newFilename, getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, host, newFilename, preferences)); + addNewFileToTsconfig(program, changes, oldFile.fileName, newFilename, hostGetCanonicalFileName(host)); + } + function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, host, newFilename, preferences) { + const checker = program.getTypeChecker(); + const prologueDirectives = takeWhile(oldFile.statements, isPrologueDirective); + if (oldFile.externalModuleIndicator === void 0 && oldFile.commonJsModuleIndicator === void 0 && usage.oldImportsNeededByTargetFile.size === 0) { + deleteMovedStatements(oldFile, toMove.ranges, changes); + return [ + ...prologueDirectives, + ...toMove.all + ]; } - function shouldGetType(sourceFile, node, position) { - switch(node.kind){ - case 79 /* Identifier */ : - return !isLabelName(node) && !isTagName(node) && !isConstTypeReference(node.parent); - case 208 /* PropertyAccessExpression */ : - case 163 /* QualifiedName */ : - return !isInComment(sourceFile, position); - case 108 /* ThisKeyword */ : - case 194 /* ThisType */ : - case 106 /* SuperKeyword */ : - case 199 /* NamedTupleMember */ : - return true; - case 233 /* MetaProperty */ : - return isImportMeta(node); - default: - return false; + const useEsModuleSyntax = !fileShouldUseJavaScriptRequire(newFilename, program, host, !!oldFile.commonJsModuleIndicator); + const quotePreference = getQuotePreference(oldFile, preferences); + const importsFromNewFile = createOldFileImportsFromTargetFile(oldFile, usage.oldFileImportsFromTargetFile, newFilename, program, host, useEsModuleSyntax, quotePreference); + if (importsFromNewFile) insertImports(changes, oldFile, importsFromNewFile, /*blankLineBetween*/ true, preferences); + deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); + deleteMovedStatements(oldFile, toMove.ranges, changes); + updateImportsInOtherFiles(changes, program, host, oldFile, usage.movedSymbols, newFilename, quotePreference); + const imports = getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByTargetFile, usage.targetFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference); + const body = addExports(oldFile, toMove.all, usage.oldFileImportsFromTargetFile, useEsModuleSyntax); + if (imports.length && body.length) return [ + ...prologueDirectives, + ...imports, + 4 /* NewLineTrivia */ , + ...body + ]; + return [ + ...prologueDirectives, + ...imports, + ...body + ]; + } + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference) { + const copiedOldImports = []; + for (const oldStatement of oldFile.statements)forEachImportInStatement(oldStatement, (i)=>{ + append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), (name)=>importsToCopy.has(checker.getSymbolAtLocation(name)))); + }); + let oldFileDefault; + const oldFileNamedImports = []; + const markSeenTop = nodeSeenTracker(); + newFileImportsFromOldFile.forEach((symbol)=>{ + if (!symbol.declarations) return; + for (const decl of symbol.declarations){ + if (!isTopLevelDeclaration(decl)) continue; + const name = nameOfTopLevelDeclaration(decl); + if (!name) continue; + const top = getTopLevelDeclarationStatement(decl); + if (markSeenTop(top)) addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); + if (hasSyntacticModifier(decl, 1024 /* Default */ )) oldFileDefault = name; + else oldFileNamedImports.push(name.text); } - } - function getDefinitionAtPosition2(fileName, position, searchOtherFilesOnly, stopAtAlias) { - synchronizeHostData(); - return ts_GoToDefinition_exports.getDefinitionAtPosition(program, getValidSourceFile(fileName), position, searchOtherFilesOnly, stopAtAlias); - } - function getDefinitionAndBoundSpan2(fileName, position) { - synchronizeHostData(); - return ts_GoToDefinition_exports.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); - } - function getTypeDefinitionAtPosition2(fileName, position) { - synchronizeHostData(); - return ts_GoToDefinition_exports.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); - } - function getImplementationAtPosition(fileName, position) { - synchronizeHostData(); - return ts_FindAllReferences_exports.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); - } - function getOccurrencesAtPosition(fileName, position) { - return flatMap(getDocumentHighlights(fileName, position, [ - fileName - ]), (entry)=>entry.highlightSpans.map((highlightSpan)=>({ - fileName: entry.fileName, - textSpan: highlightSpan.textSpan, - isWriteAccess: highlightSpan.kind === "writtenReference" /* writtenReference */ , - ...highlightSpan.isInString && { - isInString: true - }, - ...highlightSpan.contextSpan && { - contextSpan: highlightSpan.contextSpan + }); + append(copiedOldImports, makeImportOrRequire(oldFile, oldFileDefault, oldFileNamedImports, getBaseFileName(oldFile.fileName), program, host, useEsModuleSyntax, quotePreference)); + return copiedOldImports; + } + var refactorName5, description, moveToNewFileAction; + var init_moveToNewFile = __esm({ + "src/services/refactors/moveToNewFile.ts" () { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName5 = "Move to a new file"; + description = getLocaleSpecificMessage(Diagnostics.Move_to_a_new_file); + moveToNewFileAction = { + name: refactorName5, + description: description, + kind: "refactor.move.newFile" + }; + registerRefactor(refactorName5, { + kinds: [ + moveToNewFileAction.kind + ], + getAvailableActions: function getRefactorActionsToMoveToNewFile(context) { + const statements = getStatementsToMove(context); + if (context.preferences.allowTextChangesInNewFiles && statements) return [ + { + name: refactorName5, + description: description, + actions: [ + moveToNewFileAction + ] } - }))); - } - function getDocumentHighlights(fileName, position, filesToSearch) { - const normalizedFileName = normalizePath(fileName); - Debug.assert(filesToSearch.some((f)=>normalizePath(f) === normalizedFileName)); - synchronizeHostData(); - const sourceFilesToSearch = mapDefined(filesToSearch, (fileName2)=>program.getSourceFile(fileName2)); - const sourceFile = getValidSourceFile(fileName); - return DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); - } - function findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) { - synchronizeHostData(); - const sourceFile = getValidSourceFile(fileName); - const node = getAdjustedRenameLocation(getTouchingPropertyName(sourceFile, position)); - if (!ts_Rename_exports.nodeIsEligibleForRename(node)) return void 0; - if (isIdentifier(node) && (isJsxOpeningElement(node.parent) || isJsxClosingElement(node.parent)) && isIntrinsicJsxName(node.escapedText)) { - const { openingElement: openingElement , closingElement: closingElement } = node.parent.parent; - return [ - openingElement, - closingElement - ].map((node2)=>{ - const textSpan = createTextSpanFromNode(node2.tagName, sourceFile); + ]; + if (context.preferences.provideRefactorNotApplicableReason) return [ + { + name: refactorName5, + description: description, + actions: [ + { + ...moveToNewFileAction, + notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) + } + ] + } + ]; + return emptyArray; + }, + getEditsForAction: function getRefactorEditsToMoveToNewFile(context, actionName2) { + Debug.assert(actionName2 === refactorName5, "Wrong refactor invoked"); + const statements = Debug.checkDefined(getStatementsToMove(context)); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange3(context.file, context.program, statements, t, context.host, context.preferences, context)); return { - fileName: sourceFile.fileName, - textSpan: textSpan, - ...ts_FindAllReferences_exports.toContextSpan(textSpan, sourceFile, node2.parent) + edits: edits, + renameFilename: void 0, + renameLocation: void 0 }; - }); - } else return getReferencesWorker(node, position, { - findInStrings: findInStrings, - findInComments: findInComments, - providePrefixAndSuffixTextForRename: providePrefixAndSuffixTextForRename, - use: ts_FindAllReferences_exports.FindReferencesUse.Rename - }, (entry, originalNode, checker)=>ts_FindAllReferences_exports.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false)); - } - function getReferencesAtPosition(fileName, position) { - synchronizeHostData(); - return getReferencesWorker(getTouchingPropertyName(getValidSourceFile(fileName), position), position, { - use: ts_FindAllReferences_exports.FindReferencesUse.References - }, ts_FindAllReferences_exports.toReferenceEntry); - } - function getReferencesWorker(node, position, options, cb) { - synchronizeHostData(); - const sourceFiles = options && options.use === ts_FindAllReferences_exports.FindReferencesUse.Rename ? program.getSourceFiles().filter((sourceFile)=>!program.isSourceFileDefaultLibrary(sourceFile)) : program.getSourceFiles(); - return ts_FindAllReferences_exports.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); - } - function findReferences(fileName, position) { - synchronizeHostData(); - return ts_FindAllReferences_exports.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); - } - function getFileReferences(fileName) { - synchronizeHostData(); - return ts_FindAllReferences_exports.Core.getReferencesForFileName(fileName, program, program.getSourceFiles()).map(ts_FindAllReferences_exports.toReferenceEntry); - } - function getNavigateToItems2(searchValue, maxResultCount, fileName, excludeDtsFiles = false) { - synchronizeHostData(); - const sourceFiles = fileName ? [ - getValidSourceFile(fileName) - ] : program.getSourceFiles(); - return getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); - } - function getEmitOutput(fileName, emitOnlyDtsFiles, forceDtsEmit) { - synchronizeHostData(); - const sourceFile = getValidSourceFile(fileName); - const customTransformers = host.getCustomTransformers && host.getCustomTransformers(); - return getFileEmitOutput(program, sourceFile, !!emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit); + } + }); } - function getSignatureHelpItems2(fileName, position, { triggerReason: triggerReason } = emptyOptions) { - synchronizeHostData(); - const sourceFile = getValidSourceFile(fileName); - return ts_SignatureHelp_exports.getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken); + }); + // src/services/refactors/moveToFile.ts + function error(notApplicableReason) { + return { + edits: [], + renameFilename: void 0, + renameLocation: void 0, + notApplicableReason: notApplicableReason + }; + } + function doChange4(context, oldFile, targetFile, program, toMove, changes, host, preferences) { + const checker = program.getTypeChecker(); + const usage = getUsageInfo(oldFile, toMove.all, checker); + if (!host.fileExists(targetFile)) { + changes.createNewFile(oldFile, targetFile, getNewStatementsAndRemoveFromOldFile2(oldFile, targetFile, usage, changes, toMove, program, host, preferences)); + addNewFileToTsconfig(program, changes, oldFile.fileName, targetFile, hostGetCanonicalFileName(host)); + } else { + const targetSourceFile = Debug.checkDefined(program.getSourceFile(targetFile)); + const importAdder = ts_codefix_exports.createImportAdder(targetSourceFile, context.program, context.preferences, context.host); + getNewStatementsAndRemoveFromOldFile2(oldFile, targetSourceFile, usage, changes, toMove, program, host, preferences, importAdder); } - function getNonBoundSourceFile(fileName) { - return syntaxTreeCache.getCurrentSourceFile(fileName); + } + function getNewStatementsAndRemoveFromOldFile2(oldFile, targetFile, usage, changes, toMove, program, host, preferences, importAdder) { + const checker = program.getTypeChecker(); + const prologueDirectives = takeWhile(oldFile.statements, isPrologueDirective); + if (oldFile.externalModuleIndicator === void 0 && oldFile.commonJsModuleIndicator === void 0 && usage.oldImportsNeededByTargetFile.size === 0 && usage.targetFileImportsFromOldFile.size === 0 && typeof targetFile === "string") { + deleteMovedStatements(oldFile, toMove.ranges, changes); + return [ + ...prologueDirectives, + ...toMove.all + ]; } - function getNameOrDottedNameSpan(fileName, startPos, _endPos) { - const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - const node = getTouchingPropertyName(sourceFile, startPos); - if (node === sourceFile) return void 0; - switch(node.kind){ - case 208 /* PropertyAccessExpression */ : - case 163 /* QualifiedName */ : - case 10 /* StringLiteral */ : - case 95 /* FalseKeyword */ : - case 110 /* TrueKeyword */ : - case 104 /* NullKeyword */ : - case 106 /* SuperKeyword */ : - case 108 /* ThisKeyword */ : - case 194 /* ThisType */ : - case 79 /* Identifier */ : - break; - default: - return void 0; + const targetFileName = typeof targetFile === "string" ? targetFile : targetFile.fileName; + const useEsModuleSyntax = !fileShouldUseJavaScriptRequire(targetFileName, program, host, !!oldFile.commonJsModuleIndicator); + const quotePreference = getQuotePreference(oldFile, preferences); + const importsFromTargetFile = createOldFileImportsFromTargetFile(oldFile, usage.oldFileImportsFromTargetFile, targetFileName, program, host, useEsModuleSyntax, quotePreference); + if (importsFromTargetFile) insertImports(changes, oldFile, importsFromTargetFile, /*blankLineBetween*/ true, preferences); + deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); + deleteMovedStatements(oldFile, toMove.ranges, changes); + updateImportsInOtherFiles(changes, program, host, oldFile, usage.movedSymbols, targetFileName, quotePreference); + const imports = getTargetFileImportsAndAddExportInOldFile(oldFile, targetFileName, usage.oldImportsNeededByTargetFile, usage.targetFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference, importAdder); + const body = addExports(oldFile, toMove.all, usage.oldFileImportsFromTargetFile, useEsModuleSyntax); + if (typeof targetFile !== "string") { + if (targetFile.statements.length > 0) moveStatementsToTargetFile(changes, program, body, targetFile, toMove); + else changes.insertNodesAtEndOfFile(targetFile, body, /*blankLineBetween*/ false); + if (imports.length > 0) insertImports(changes, targetFile, imports, /*blankLineBetween*/ true, preferences); + } + if (importAdder) importAdder.writeFixes(changes, quotePreference); + if (imports.length && body.length) return [ + ...prologueDirectives, + ...imports, + 4 /* NewLineTrivia */ , + ...body + ]; + return [ + ...prologueDirectives, + ...imports, + ...body + ]; + } + function getTargetFileImportsAndAddExportInOldFile(oldFile, targetFile, importsToCopy, targetFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference, importAdder) { + const copiedOldImports = []; + if (importAdder) importsToCopy.forEach((isValidTypeOnlyUseSite, symbol)=>{ + try { + importAdder.addImportFromExportedSymbol(skipAlias(symbol, checker), isValidTypeOnlyUseSite); + } catch { + for (const oldStatement of oldFile.statements)forEachImportInStatement(oldStatement, (i)=>{ + append(copiedOldImports, filterImport(i, factory.createStringLiteral(moduleSpecifierFromImport(i).text), (name)=>importsToCopy.has(checker.getSymbolAtLocation(name)))); + }); } - let nodeForStartPos = node; - while(true){ - if (isRightSideOfPropertyAccess(nodeForStartPos) || isRightSideOfQualifiedName(nodeForStartPos)) nodeForStartPos = nodeForStartPos.parent; - else if (isNameOfModuleDeclaration(nodeForStartPos)) { - if (nodeForStartPos.parent.parent.kind === 264 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) nodeForStartPos = nodeForStartPos.parent.parent.name; - else break; - } else break; + }); + else { + const targetSourceFile = program.getSourceFile(targetFile); + for (const oldStatement of oldFile.statements)forEachImportInStatement(oldStatement, (i)=>{ + var _a, _b; + const moduleSpecifier = moduleSpecifierFromImport(i); + const resolved = (_a = oldFile.resolvedModules) == null ? void 0 : _a.get(moduleSpecifier.text, getModeForUsageLocation(oldFile, moduleSpecifier)); + const fileName = (_b = resolved == null ? void 0 : resolved.resolvedModule) == null ? void 0 : _b.resolvedFileName; + if (fileName && targetSourceFile) { + const newModuleSpecifier = getModuleSpecifier(program.getCompilerOptions(), targetSourceFile, targetSourceFile.path, fileName, createModuleSpecifierResolutionHost(program, host)); + append(copiedOldImports, filterImport(i, makeStringLiteral(newModuleSpecifier, quotePreference), (name)=>importsToCopy.has(checker.getSymbolAtLocation(name)))); + } else append(copiedOldImports, filterImport(i, factory.createStringLiteral(moduleSpecifierFromImport(i).text), (name)=>importsToCopy.has(checker.getSymbolAtLocation(name)))); + }); + } + const targetFileSourceFile = program.getSourceFile(targetFile); + let oldFileDefault; + const oldFileNamedImports = []; + const markSeenTop = nodeSeenTracker(); + targetFileImportsFromOldFile.forEach((symbol)=>{ + if (!symbol.declarations) return; + for (const decl of symbol.declarations){ + if (!isTopLevelDeclaration(decl)) continue; + const name = nameOfTopLevelDeclaration(decl); + if (!name) continue; + const top = getTopLevelDeclarationStatement(decl); + if (markSeenTop(top)) addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); + if (importAdder && checker.isUnknownSymbol(symbol)) importAdder.addImportFromExportedSymbol(skipAlias(symbol, checker)); + else if (hasSyntacticModifier(decl, 1024 /* Default */ )) oldFileDefault = name; + else oldFileNamedImports.push(name.text); } - return createTextSpanFromBounds(nodeForStartPos.getStart(), node.getEnd()); + }); + return targetFileSourceFile ? append(copiedOldImports, makeImportOrRequire(targetFileSourceFile, oldFileDefault, oldFileNamedImports, oldFile.fileName, program, host, useEsModuleSyntax, quotePreference)) : append(copiedOldImports, makeImportOrRequire(oldFile, oldFileDefault, oldFileNamedImports, oldFile.fileName, program, host, useEsModuleSyntax, quotePreference)); + } + function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) { + const cfg = program.getCompilerOptions().configFile; + if (!cfg) return; + const newFileAbsolutePath = normalizePath(combinePaths(oldFileName, "..", newFileNameWithExtension)); + const newFilePath = getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName); + const cfgObject = cfg.statements[0] && tryCast(cfg.statements[0].expression, isObjectLiteralExpression); + const filesProp = cfgObject && find(cfgObject.properties, (prop)=>isPropertyAssignment(prop) && isStringLiteral(prop.name) && prop.name.text === "files"); + if (filesProp && isArrayLiteralExpression(filesProp.initializer)) changes.insertNodeInListAfter(cfg, last(filesProp.initializer.elements), factory.createStringLiteral(newFilePath), filesProp.initializer.elements); + } + function deleteMovedStatements(sourceFile, moved, changes) { + for (const { first: first2, afterLast: afterLast } of moved)changes.deleteNodeRangeExcludingEnd(sourceFile, first2, afterLast); + } + function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { + for (const statement of oldFile.statements){ + if (contains(toMove, statement)) continue; + forEachImportInStatement(statement, (i)=>deleteUnusedImports(oldFile, i, changes, (name)=>toDelete.has(checker.getSymbolAtLocation(name)))); } - function getBreakpointStatementAtPosition(fileName, position) { - const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts_BreakpointResolver_exports.spanInSourceFileAtLocation(sourceFile, position); + } + function updateImportsInOtherFiles(changes, program, host, oldFile, movedSymbols, targetFileName, quotePreference) { + const checker = program.getTypeChecker(); + for (const sourceFile of program.getSourceFiles()){ + if (sourceFile === oldFile) continue; + for (const statement of sourceFile.statements)forEachImportInStatement(statement, (importNode)=>{ + if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; + const shouldMove = (name)=>{ + const symbol = isBindingElement(name.parent) ? getPropertySymbolFromBindingElement(checker, name.parent) : skipAlias(checker.getSymbolAtLocation(name), checker); + return !!symbol && movedSymbols.has(symbol); + }; + deleteUnusedImports(sourceFile, importNode, changes, shouldMove); + const pathToTargetFileWithExtension = resolvePath(getDirectoryPath(oldFile.path), targetFileName); + const newModuleSpecifier = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.path, pathToTargetFileWithExtension, createModuleSpecifierResolutionHost(program, host)); + const newImportDeclaration = filterImport(importNode, makeStringLiteral(newModuleSpecifier, quotePreference), shouldMove); + if (newImportDeclaration) changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); + const ns = getNamespaceLikeImport(importNode); + if (ns) updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, ns, importNode, quotePreference); + }); } - function getNavigationBarItems2(fileName) { - return getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken); + } + function getNamespaceLikeImport(node) { + switch(node.kind){ + case 272 /* ImportDeclaration */ : + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 274 /* NamespaceImport */ ? node.importClause.namedBindings.name : void 0; + case 271 /* ImportEqualsDeclaration */ : + return node.name; + case 260 /* VariableDeclaration */ : + return tryCast(node.name, isIdentifier); + default: + return Debug.assertNever(node, `Unexpected node kind ${node.kind}`); } - function getNavigationTree2(fileName) { - return getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken); + } + function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, oldImportId, oldImportNode, quotePreference) { + const preferredNewNamespaceName = ts_codefix_exports.moduleSpecifierToValidIdentifier(newModuleSpecifier, 99 /* ESNext */ ); + let needUniqueName = false; + const toChange = []; + ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, (ref)=>{ + if (!isPropertyAccessExpression(ref.parent)) return; + needUniqueName = needUniqueName || !!checker.resolveName(preferredNewNamespaceName, ref, 67108863 /* All */ , /*excludeGlobals*/ true); + if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) toChange.push(ref); + }); + if (toChange.length) { + const newNamespaceName = needUniqueName ? getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName; + for (const ref of toChange)changes.replaceNode(sourceFile, ref, factory.createIdentifier(newNamespaceName)); + changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, preferredNewNamespaceName, newModuleSpecifier, quotePreference)); } - function getSemanticClassifications3(fileName, span, format) { - synchronizeHostData(); - const responseFormat = format || "original" /* Original */ ; - if (responseFormat === "2020" /* TwentyTwenty */ ) return ts_classifier_exports.v2020.getSemanticClassifications(program, cancellationToken, getValidSourceFile(fileName), span); - else return getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); + } + function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier, quotePreference) { + const newNamespaceId = factory.createIdentifier(newNamespaceName); + const newModuleString = makeStringLiteral(newModuleSpecifier, quotePreference); + switch(node.kind){ + case 272 /* ImportDeclaration */ : + return factory.createImportDeclaration(/*modifiers*/ void 0, factory.createImportClause(/*isTypeOnly*/ false, /*name*/ void 0, factory.createNamespaceImport(newNamespaceId)), newModuleString, /*assertClause*/ void 0); + case 271 /* ImportEqualsDeclaration */ : + return factory.createImportEqualsDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, newNamespaceId, factory.createExternalModuleReference(newModuleString)); + case 260 /* VariableDeclaration */ : + return factory.createVariableDeclaration(newNamespaceId, /*exclamationToken*/ void 0, /*type*/ void 0, createRequireCall(newModuleString)); + default: + return Debug.assertNever(node, `Unexpected node kind ${node.kind}`); } - function getEncodedSemanticClassifications3(fileName, span, format) { - synchronizeHostData(); - const responseFormat = format || "original" /* Original */ ; - if (responseFormat === "original" /* Original */ ) return getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); - else return ts_classifier_exports.v2020.getEncodedSemanticClassifications(program, cancellationToken, getValidSourceFile(fileName), span); + } + function createRequireCall(moduleSpecifier) { + return factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ void 0, [ + moduleSpecifier + ]); + } + function moduleSpecifierFromImport(i) { + return i.kind === 272 /* ImportDeclaration */ ? i.moduleSpecifier : i.kind === 271 /* ImportEqualsDeclaration */ ? i.moduleReference.expression : i.initializer.arguments[0]; + } + function forEachImportInStatement(statement, cb) { + if (isImportDeclaration(statement)) { + if (isStringLiteral(statement.moduleSpecifier)) cb(statement); + } else if (isImportEqualsDeclaration(statement)) { + if (isExternalModuleReference(statement.moduleReference) && isStringLiteralLike(statement.moduleReference.expression)) cb(statement); + } else if (isVariableStatement(statement)) { + for (const decl of statement.declarationList.declarations)if (decl.initializer && isRequireCall(decl.initializer, /*requireStringLiteralLikeArgument*/ true)) cb(decl); } - function getSyntacticClassifications2(fileName, span) { - return getSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span); + } + function createOldFileImportsFromTargetFile(sourceFile, targetFileNeedExport, targetFileNameWithExtension, program, host, useEs6Imports, quotePreference) { + let defaultImport; + const imports = []; + targetFileNeedExport.forEach((symbol)=>{ + if (symbol.escapedName === "default" /* Default */ ) defaultImport = factory.createIdentifier(symbolNameNoDefault(symbol)); + else imports.push(symbol.name); + }); + return makeImportOrRequire(sourceFile, defaultImport, imports, targetFileNameWithExtension, program, host, useEs6Imports, quotePreference); + } + function makeImportOrRequire(sourceFile, defaultImport, imports, targetFileNameWithExtension, program, host, useEs6Imports, quotePreference) { + const pathToTargetFile = resolvePath(getDirectoryPath(sourceFile.path), targetFileNameWithExtension); + const pathToTargetFileWithCorrectExtension = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.path, pathToTargetFile, createModuleSpecifierResolutionHost(program, host)); + if (useEs6Imports) { + const specifiers = imports.map((i)=>factory.createImportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ void 0, factory.createIdentifier(i))); + return makeImportIfNecessary(defaultImport, specifiers, pathToTargetFileWithCorrectExtension, quotePreference); + } else { + Debug.assert(!defaultImport, "No default import should exist"); + const bindingElements = imports.map((i)=>factory.createBindingElement(/*dotDotDotToken*/ void 0, /*propertyName*/ void 0, i)); + return bindingElements.length ? makeVariableStatement(factory.createObjectBindingPattern(bindingElements), /*type*/ void 0, createRequireCall(makeStringLiteral(pathToTargetFileWithCorrectExtension, quotePreference))) : void 0; } - function getEncodedSyntacticClassifications2(fileName, span) { - return getEncodedSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span); + } + function makeVariableStatement(name, type, initializer, flags = 2 /* Const */ ) { + return factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ + factory.createVariableDeclaration(name, /*exclamationToken*/ void 0, type, initializer) + ], flags)); + } + function addExports(sourceFile, toMove, needExport, useEs6Exports) { + return flatMap(toMove, (statement)=>{ + if (isTopLevelDeclarationStatement(statement) && !isExported(sourceFile, statement, useEs6Exports) && forEachTopLevelDeclaration(statement, (d)=>{ + var _a; + return needExport.has(Debug.checkDefined((_a = tryCast(d, canHaveSymbol)) == null ? void 0 : _a.symbol)); + })) { + const exports = addExport(getSynthesizedDeepClone(statement), useEs6Exports); + if (exports) return exports; + } + return getSynthesizedDeepClone(statement); + }); + } + function isExported(sourceFile, decl, useEs6Exports, name) { + var _a; + if (useEs6Exports) return !isExpressionStatement(decl) && hasSyntacticModifier(decl, 1 /* Export */ ) || !!(name && sourceFile.symbol && ((_a = sourceFile.symbol.exports) == null ? void 0 : _a.has(name.escapedText))); + return !!sourceFile.symbol && !!sourceFile.symbol.exports && getNamesToExportInCommonJS(decl).some((name2)=>sourceFile.symbol.exports.has(escapeLeadingUnderscores(name2))); + } + function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { + switch(importDecl.kind){ + case 272 /* ImportDeclaration */ : + deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); + break; + case 271 /* ImportEqualsDeclaration */ : + if (isUnused(importDecl.name)) changes.delete(sourceFile, importDecl); + break; + case 260 /* VariableDeclaration */ : + deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); + break; + default: + Debug.assertNever(importDecl, `Unexpected import decl kind ${importDecl.kind}`); } - function getOutliningSpans(fileName) { - const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts_OutliningElementsCollector_exports.collectElements(sourceFile, cancellationToken); + } + function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) { + if (!importDecl.importClause) return; + const { name: name, namedBindings: namedBindings } = importDecl.importClause; + const defaultUnused = !name || isUnused(name); + const namedBindingsUnused = !namedBindings || (namedBindings.kind === 274 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every((e)=>isUnused(e.name))); + if (defaultUnused && namedBindingsUnused) changes.delete(sourceFile, importDecl); + else { + if (name && defaultUnused) changes.delete(sourceFile, name); + if (namedBindings) { + if (namedBindingsUnused) changes.replaceNode(sourceFile, importDecl.importClause, factory.updateImportClause(importDecl.importClause, importDecl.importClause.isTypeOnly, name, /*namedBindings*/ void 0)); + else if (namedBindings.kind === 275 /* NamedImports */ ) { + for (const element of namedBindings.elements)if (isUnused(element.name)) changes.delete(sourceFile, element); + } + } } - const braceMatching = new Map(Object.entries({ - [18 /* OpenBraceToken */ ]: 19 /* CloseBraceToken */ , - [20 /* OpenParenToken */ ]: 21 /* CloseParenToken */ , - [22 /* OpenBracketToken */ ]: 23 /* CloseBracketToken */ , - [31 /* GreaterThanToken */ ]: 29 /* LessThanToken */ - })); - braceMatching.forEach((value1, key)=>braceMatching.set(value1.toString(), Number(key))); - function getBraceMatchingAtPosition(fileName, position) { - const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - const token = getTouchingToken(sourceFile, position); - const matchKind = token.getStart(sourceFile) === position ? braceMatching.get(token.kind.toString()) : void 0; - const match = matchKind && findChildOfKind(token.parent, matchKind, sourceFile); - return match ? [ - createTextSpanFromNode(token, sourceFile), - createTextSpanFromNode(match, sourceFile) - ].sort((a, b)=>a.start - b.start) : emptyArray; + } + function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { + const { name: name } = varDecl; + switch(name.kind){ + case 80 /* Identifier */ : + if (isUnused(name)) { + if (varDecl.initializer && isRequireCall(varDecl.initializer, /*requireStringLiteralLikeArgument*/ true)) changes.delete(sourceFile, isVariableDeclarationList(varDecl.parent) && length(varDecl.parent.declarations) === 1 ? varDecl.parent.parent : varDecl); + else changes.delete(sourceFile, name); + } + break; + case 207 /* ArrayBindingPattern */ : + break; + case 206 /* ObjectBindingPattern */ : + if (name.elements.every((e)=>isIdentifier(e.name) && isUnused(e.name))) changes.delete(sourceFile, isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); + else { + for (const element of name.elements)if (isIdentifier(element.name) && isUnused(element.name)) changes.delete(sourceFile, element.name); + } + break; } - function getIndentationAtPosition(fileName, position, editorOptions) { - let start = timestamp(); - const settings = toEditorSettings(editorOptions); - const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - log("getIndentationAtPosition: getCurrentSourceFile: " + (timestamp() - start)); - start = timestamp(); - const result = ts_formatting_exports.SmartIndenter.getIndentation(position, sourceFile, settings); - log("getIndentationAtPosition: computeIndentation : " + (timestamp() - start)); - return result; + } + function isTopLevelDeclarationStatement(node) { + Debug.assert(isSourceFile(node.parent), "Node parent should be a SourceFile"); + return isNonVariableTopLevelDeclaration(node) || isVariableStatement(node); + } + function addExport(decl, useEs6Exports) { + return useEs6Exports ? [ + addEs6Export(decl) + ] : addCommonjsExport(decl); + } + function addEs6Export(d) { + const modifiers = canHaveModifiers(d) ? concatenate([ + factory.createModifier(95 /* ExportKeyword */ ) + ], getModifiers(d)) : void 0; + switch(d.kind){ + case 262 /* FunctionDeclaration */ : + return factory.updateFunctionDeclaration(d, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); + case 263 /* ClassDeclaration */ : + const decorators = canHaveDecorators(d) ? getDecorators(d) : void 0; + return factory.updateClassDeclaration(d, concatenate(decorators, modifiers), d.name, d.typeParameters, d.heritageClauses, d.members); + case 243 /* VariableStatement */ : + return factory.updateVariableStatement(d, modifiers, d.declarationList); + case 267 /* ModuleDeclaration */ : + return factory.updateModuleDeclaration(d, modifiers, d.name, d.body); + case 266 /* EnumDeclaration */ : + return factory.updateEnumDeclaration(d, modifiers, d.name, d.members); + case 265 /* TypeAliasDeclaration */ : + return factory.updateTypeAliasDeclaration(d, modifiers, d.name, d.typeParameters, d.type); + case 264 /* InterfaceDeclaration */ : + return factory.updateInterfaceDeclaration(d, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 271 /* ImportEqualsDeclaration */ : + return factory.updateImportEqualsDeclaration(d, modifiers, d.isTypeOnly, d.name, d.moduleReference); + case 244 /* ExpressionStatement */ : + return Debug.fail(); + default: + return Debug.assertNever(d, `Unexpected declaration kind ${d.kind}`); } - function getFormattingEditsForRange(fileName, start, end, options) { - const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts_formatting_exports.formatSelection(start, end, sourceFile, ts_formatting_exports.getFormatContext(toEditorSettings(options), host)); + } + function addCommonjsExport(decl) { + return [ + decl, + ...getNamesToExportInCommonJS(decl).map(createExportAssignment) + ]; + } + function createExportAssignment(name) { + return factory.createExpressionStatement(factory.createBinaryExpression(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(name)), 64 /* EqualsToken */ , factory.createIdentifier(name))); + } + function getNamesToExportInCommonJS(decl) { + switch(decl.kind){ + case 262 /* FunctionDeclaration */ : + case 263 /* ClassDeclaration */ : + return [ + decl.name.text + ]; + case 243 /* VariableStatement */ : + return mapDefined(decl.declarationList.declarations, (d)=>isIdentifier(d.name) ? d.name.text : void 0); + case 267 /* ModuleDeclaration */ : + case 266 /* EnumDeclaration */ : + case 265 /* TypeAliasDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : + return emptyArray; + case 244 /* ExpressionStatement */ : + return Debug.fail("Can't export an ExpressionStatement"); + default: + return Debug.assertNever(decl, `Unexpected decl kind ${decl.kind}`); } - function getFormattingEditsForDocument(fileName, options) { - return ts_formatting_exports.formatDocument(syntaxTreeCache.getCurrentSourceFile(fileName), ts_formatting_exports.getFormatContext(toEditorSettings(options), host)); + } + function filterImport(i, moduleSpecifier, keep) { + switch(i.kind){ + case 272 /* ImportDeclaration */ : + { + const clause = i.importClause; + if (!clause) return void 0; + const defaultImport = clause.name && keep(clause.name) ? clause.name : void 0; + const namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); + return defaultImport || namedBindings ? factory.createImportDeclaration(/*modifiers*/ void 0, factory.createImportClause(clause.isTypeOnly, defaultImport, namedBindings), getSynthesizedDeepClone(moduleSpecifier), /*assertClause*/ void 0) : void 0; + } + case 271 /* ImportEqualsDeclaration */ : + return keep(i.name) ? i : void 0; + case 260 /* VariableDeclaration */ : + { + const name = filterBindingName(i.name, keep); + return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : void 0; + } + default: + return Debug.assertNever(i, `Unexpected import kind ${i.kind}`); } - function getFormattingEditsAfterKeystroke(fileName, position, key, options) { - const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - const formatContext = ts_formatting_exports.getFormatContext(toEditorSettings(options), host); - if (!isInComment(sourceFile, position)) switch(key){ - case "{": - return ts_formatting_exports.formatOnOpeningCurly(position, sourceFile, formatContext); - case "}": - return ts_formatting_exports.formatOnClosingCurly(position, sourceFile, formatContext); - case ";": - return ts_formatting_exports.formatOnSemicolon(position, sourceFile, formatContext); - case "\n": - return ts_formatting_exports.formatOnEnter(position, sourceFile, formatContext); - } - return []; + } + function filterNamedBindings(namedBindings, keep) { + if (namedBindings.kind === 274 /* NamespaceImport */ ) return keep(namedBindings.name) ? namedBindings : void 0; + else { + const newElements = namedBindings.elements.filter((e)=>keep(e.name)); + return newElements.length ? factory.createNamedImports(newElements) : void 0; } - function getCodeFixesAtPosition(fileName, start, end, errorCodes63, formatOptions, preferences = emptyOptions) { - synchronizeHostData(); - const sourceFile = getValidSourceFile(fileName); - const span = createTextSpanFromBounds(start, end); - const formatContext = ts_formatting_exports.getFormatContext(formatOptions, host); - return flatMap(deduplicate(errorCodes63, equateValues, compareValues), (errorCode)=>{ - cancellationToken.throwIfCancellationRequested(); - return ts_codefix_exports.getFixes({ - errorCode: errorCode, - sourceFile: sourceFile, - span: span, - program: program, - host: host, - cancellationToken: cancellationToken, - formatContext: formatContext, - preferences: preferences - }); + } + function filterBindingName(name, keep) { + switch(name.kind){ + case 80 /* Identifier */ : + return keep(name) ? name : void 0; + case 207 /* ArrayBindingPattern */ : + return name; + case 206 /* ObjectBindingPattern */ : + { + const newElements = name.elements.filter((prop)=>prop.propertyName || !isIdentifier(prop.name) || keep(prop.name)); + return newElements.length ? factory.createObjectBindingPattern(newElements) : void 0; + } + } + } + function nameOfTopLevelDeclaration(d) { + return isExpressionStatement(d) ? tryCast(d.expression.left.name, isIdentifier) : tryCast(d.name, isIdentifier); + } + function getTopLevelDeclarationStatement(d) { + switch(d.kind){ + case 260 /* VariableDeclaration */ : + return d.parent.parent; + case 208 /* BindingElement */ : + return getTopLevelDeclarationStatement(cast(d.parent.parent, (p)=>isVariableDeclaration(p) || isBindingElement(p))); + default: + return d; + } + } + function addExportToChanges(sourceFile, decl, name, changes, useEs6Exports) { + if (isExported(sourceFile, decl, useEs6Exports, name)) return; + if (useEs6Exports) { + if (!isExpressionStatement(decl)) changes.insertExportModifier(sourceFile, decl); + } else { + const names = getNamesToExportInCommonJS(decl); + if (names.length !== 0) changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment)); + } + } + function createNewFileName(oldFile, program, context, host) { + const checker = program.getTypeChecker(); + const toMove = getStatementsToMove(context); + let usage; + if (toMove) { + usage = getUsageInfo(oldFile, toMove.all, checker); + const currentDirectory = getDirectoryPath(oldFile.fileName); + const extension = extensionFromPath(oldFile.fileName); + const newFileName = combinePaths(// new file is always placed in the same directory as the old file + currentDirectory, // ensures the filename computed below isn't already taken + makeUniqueFilename(// infers a name for the new file from the symbols being moved + inferNewFileName(usage.oldFileImportsFromTargetFile, usage.movedSymbols), extension, currentDirectory, host)) + extension; + return newFileName; + } + return ""; + } + function getRangeToMove(context) { + const { file: file } = context; + const range = createTextRangeFromSpan(getRefactorContextSpan(context)); + const { statements: statements } = file; + let startNodeIndex = findIndex(statements, (s)=>s.end > range.pos); + if (startNodeIndex === -1) return void 0; + const startStatement = statements[startNodeIndex]; + const overloadRangeToMove = getOverloadRangeToMove(file, startStatement); + if (overloadRangeToMove) startNodeIndex = overloadRangeToMove.start; + let endNodeIndex = findIndex(statements, (s)=>s.end >= range.end, startNodeIndex); + if (endNodeIndex !== -1 && range.end <= statements[endNodeIndex].getStart()) endNodeIndex--; + const endingOverloadRangeToMove = getOverloadRangeToMove(file, statements[endNodeIndex]); + if (endingOverloadRangeToMove) endNodeIndex = endingOverloadRangeToMove.end; + return { + toMove: statements.slice(startNodeIndex, endNodeIndex === -1 ? statements.length : endNodeIndex + 1), + afterLast: endNodeIndex === -1 ? void 0 : statements[endNodeIndex + 1] + }; + } + function getStatementsToMove(context) { + const rangeToMove = getRangeToMove(context); + if (rangeToMove === void 0) return void 0; + const all = []; + const ranges = []; + const { toMove: toMove, afterLast: afterLast } = rangeToMove; + getRangesWhere(toMove, isAllowedStatementToMove, (start, afterEndIndex)=>{ + for(let i = start; i < afterEndIndex; i++)all.push(toMove[i]); + ranges.push({ + first: toMove[start], + afterLast: afterLast }); + }); + return all.length === 0 ? void 0 : { + all: all, + ranges: ranges + }; + } + function isAllowedStatementToMove(statement) { + return !isPureImport(statement) && !isPrologueDirective(statement); + } + function isPureImport(node) { + switch(node.kind){ + case 272 /* ImportDeclaration */ : + return true; + case 271 /* ImportEqualsDeclaration */ : + return !hasSyntacticModifier(node, 1 /* Export */ ); + case 243 /* VariableStatement */ : + return node.declarationList.declarations.every((d)=>!!d.initializer && isRequireCall(d.initializer, /*requireStringLiteralLikeArgument*/ true)); + default: + return false; } - function getCombinedCodeFix(scope, fixId51, formatOptions, preferences = emptyOptions) { - synchronizeHostData(); - Debug.assert(scope.type === "file"); - const sourceFile = getValidSourceFile(scope.fileName); - const formatContext = ts_formatting_exports.getFormatContext(formatOptions, host); - return ts_codefix_exports.getAllFixes({ - fixId: fixId51, - sourceFile: sourceFile, - program: program, - host: host, - cancellationToken: cancellationToken, - formatContext: formatContext, - preferences: preferences + } + function getUsageInfo(oldFile, toMove, checker) { + const movedSymbols = /* @__PURE__ */ new Set(); + const oldImportsNeededByTargetFile = /* @__PURE__ */ new Map(); + const targetFileImportsFromOldFile = /* @__PURE__ */ new Set(); + const containsJsx = find(toMove, (statement)=>!!(statement.transformFlags & 2 /* ContainsJsx */ )); + const jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx); + if (jsxNamespaceSymbol) oldImportsNeededByTargetFile.set(jsxNamespaceSymbol, false); + for (const statement of toMove)forEachTopLevelDeclaration(statement, (decl)=>{ + movedSymbols.add(Debug.checkDefined(isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol, "Need a symbol here")); + }); + for (const statement of toMove)forEachReference(statement, checker, (symbol, isValidTypeOnlyUseSite)=>{ + if (!symbol.declarations) return; + for (const decl of symbol.declarations){ + if (isInImport(decl)) { + const prevIsTypeOnly = oldImportsNeededByTargetFile.get(symbol); + oldImportsNeededByTargetFile.set(symbol, prevIsTypeOnly === void 0 ? isValidTypeOnlyUseSite : prevIsTypeOnly && isValidTypeOnlyUseSite); + } else if (isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile && !movedSymbols.has(symbol)) targetFileImportsFromOldFile.add(symbol); + } + }); + const unusedImportsFromOldFile = new Set(oldImportsNeededByTargetFile.keys()); + const oldFileImportsFromTargetFile = /* @__PURE__ */ new Set(); + for (const statement of oldFile.statements){ + if (contains(toMove, statement)) continue; + if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */ )) unusedImportsFromOldFile.delete(jsxNamespaceSymbol); + forEachReference(statement, checker, (symbol)=>{ + if (movedSymbols.has(symbol)) oldFileImportsFromTargetFile.add(symbol); + unusedImportsFromOldFile.delete(symbol); }); } - function organizeImports2(args, formatOptions, preferences = emptyOptions) { - var _a3; - synchronizeHostData(); - Debug.assert(args.type === "file"); - const sourceFile = getValidSourceFile(args.fileName); - const formatContext = ts_formatting_exports.getFormatContext(formatOptions, host); - const mode = (_a3 = args.mode) != null ? _a3 : args.skipDestructiveCodeActions ? "SortAndCombine" /* SortAndCombine */ : "All" /* All */ ; - return ts_OrganizeImports_exports.organizeImports(sourceFile, formatContext, host, program, preferences, mode); + return { + movedSymbols: movedSymbols, + targetFileImportsFromOldFile: targetFileImportsFromOldFile, + oldFileImportsFromTargetFile: oldFileImportsFromTargetFile, + oldImportsNeededByTargetFile: oldImportsNeededByTargetFile, + unusedImportsFromOldFile: unusedImportsFromOldFile + }; + function getJsxNamespaceSymbol(containsJsx2) { + if (containsJsx2 === void 0) return void 0; + const jsxNamespace = checker.getJsxNamespace(containsJsx2); + const jsxNamespaceSymbol2 = checker.resolveName(jsxNamespace, containsJsx2, 1920 /* Namespace */ , /*excludeGlobals*/ true); + return !!jsxNamespaceSymbol2 && some(jsxNamespaceSymbol2.declarations, isInImport) ? jsxNamespaceSymbol2 : void 0; } - function getEditsForFileRename2(oldFilePath, newFilePath, formatOptions, preferences = emptyOptions) { - return getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts_formatting_exports.getFormatContext(formatOptions, host), preferences, sourceMapper); + } + function makeUniqueFilename(proposedFilename, extension, inDirectory, host) { + let newFilename = proposedFilename; + for(let i = 1;; i++){ + const name = combinePaths(inDirectory, newFilename + extension); + if (!host.fileExists(name)) return newFilename; + newFilename = `${proposedFilename}.${i}`; } - function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { - const action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; - return isArray(action) ? Promise.all(action.map((a)=>applySingleCodeActionCommand(a))) : applySingleCodeActionCommand(action); + } + function inferNewFileName(importsFromNewFile, movedSymbols) { + return forEachKey(importsFromNewFile, symbolNameNoDefault) || forEachKey(movedSymbols, symbolNameNoDefault) || "newFile"; + } + function forEachReference(node, checker, onReference) { + node.forEachChild(function cb(node2) { + if (isIdentifier(node2) && !isDeclarationName(node2)) { + const sym = checker.getSymbolAtLocation(node2); + if (sym) onReference(sym, isValidTypeOnlyAliasUseSite(node2)); + } else node2.forEachChild(cb); + }); + } + function forEachTopLevelDeclaration(statement, cb) { + switch(statement.kind){ + case 262 /* FunctionDeclaration */ : + case 263 /* ClassDeclaration */ : + case 267 /* ModuleDeclaration */ : + case 266 /* EnumDeclaration */ : + case 265 /* TypeAliasDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : + return cb(statement); + case 243 /* VariableStatement */ : + return firstDefined(statement.declarationList.declarations, (decl)=>forEachTopLevelDeclarationInBindingName(decl.name, cb)); + case 244 /* ExpressionStatement */ : + { + const { expression: expression } = statement; + return isBinaryExpression(expression) && getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : void 0; + } } - function applySingleCodeActionCommand(action) { - const getPath = (path)=>toPath(path, currentDirectory, getCanonicalFileName); - Debug.assertEqual(action.type, "install package"); - return host.installPackage ? host.installPackage({ - fileName: getPath(action.file), - packageName: action.packageName - }) : Promise.reject("Host does not implement `installPackage`"); + } + function isInImport(decl) { + switch(decl.kind){ + case 271 /* ImportEqualsDeclaration */ : + case 276 /* ImportSpecifier */ : + case 273 /* ImportClause */ : + case 274 /* NamespaceImport */ : + return true; + case 260 /* VariableDeclaration */ : + return isVariableDeclarationInImport(decl); + case 208 /* BindingElement */ : + return isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); + default: + return false; } - function getDocCommentTemplateAtPosition2(fileName, position, options, formatOptions) { - const formatSettings = formatOptions ? ts_formatting_exports.getFormatContext(formatOptions, host).options : void 0; - return ts_JsDoc_exports.getDocCommentTemplateAtPosition(getNewLineOrDefaultFromHost(host, formatSettings), syntaxTreeCache.getCurrentSourceFile(fileName), position, options); + } + function isVariableDeclarationInImport(decl) { + return isSourceFile(decl.parent.parent.parent) && !!decl.initializer && isRequireCall(decl.initializer, /*requireStringLiteralLikeArgument*/ true); + } + function isTopLevelDeclaration(node) { + return isNonVariableTopLevelDeclaration(node) && isSourceFile(node.parent) || isVariableDeclaration(node) && isSourceFile(node.parent.parent.parent); + } + function sourceFileOfTopLevelDeclaration(node) { + return isVariableDeclaration(node) ? node.parent.parent.parent : node.parent; + } + function forEachTopLevelDeclarationInBindingName(name, cb) { + switch(name.kind){ + case 80 /* Identifier */ : + return cb(cast(name.parent, (x)=>isVariableDeclaration(x) || isBindingElement(x))); + case 207 /* ArrayBindingPattern */ : + case 206 /* ObjectBindingPattern */ : + return firstDefined(name.elements, (em)=>isOmittedExpression(em) ? void 0 : forEachTopLevelDeclarationInBindingName(em.name, cb)); + default: + return Debug.assertNever(name, `Unexpected name kind ${name.kind}`); } - function isValidBraceCompletionAtPosition(fileName, position, openingBrace) { - if (openingBrace === 60 /* lessThan */ ) return false; - const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - if (isInString(sourceFile, position)) return false; - if (isInsideJsxElementOrAttribute(sourceFile, position)) return openingBrace === 123 /* openBrace */ ; - if (isInTemplateString(sourceFile, position)) return false; - switch(openingBrace){ - case 39 /* singleQuote */ : - case 34 /* doubleQuote */ : - case 96 /* backtick */ : - return !isInComment(sourceFile, position); - } - return true; + } + function isNonVariableTopLevelDeclaration(node) { + switch(node.kind){ + case 262 /* FunctionDeclaration */ : + case 263 /* ClassDeclaration */ : + case 267 /* ModuleDeclaration */ : + case 266 /* EnumDeclaration */ : + case 265 /* TypeAliasDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : + return true; + default: + return false; } - function getJsxClosingTagAtPosition(fileName, position) { - const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - const token = findPrecedingToken(position, sourceFile); - if (!token) return void 0; - const element = token.kind === 31 /* GreaterThanToken */ && isJsxOpeningElement(token.parent) ? token.parent.parent : isJsxText(token) && isJsxElement(token.parent) ? token.parent : void 0; - if (element && isUnclosedTag(element)) return { - newText: `` - }; - const fragment = token.kind === 31 /* GreaterThanToken */ && isJsxOpeningFragment(token.parent) ? token.parent.parent : isJsxText(token) && isJsxFragment(token.parent) ? token.parent : void 0; - if (fragment && isUnclosedFragment(fragment)) return { - newText: "" - }; + } + function moveStatementsToTargetFile(changes, program, statements, targetFile, toMove) { + var _a; + const removedExports = /* @__PURE__ */ new Set(); + const targetExports = (_a = targetFile.symbol) == null ? void 0 : _a.exports; + if (targetExports) { + const checker = program.getTypeChecker(); + const targetToSourceExports = /* @__PURE__ */ new Map(); + for (const node of toMove.all)if (isTopLevelDeclarationStatement(node) && hasSyntacticModifier(node, 1 /* Export */ )) forEachTopLevelDeclaration(node, (declaration)=>{ + var _a2; + const targetDeclarations = canHaveSymbol(declaration) ? (_a2 = targetExports.get(declaration.symbol.escapedName)) == null ? void 0 : _a2.declarations : void 0; + const exportDeclaration = firstDefined(targetDeclarations, (d)=>isExportDeclaration(d) ? d : isExportSpecifier(d) ? tryCast(d.parent.parent, isExportDeclaration) : void 0); + if (exportDeclaration && exportDeclaration.moduleSpecifier) targetToSourceExports.set(exportDeclaration, (targetToSourceExports.get(exportDeclaration) || /* @__PURE__ */ new Set()).add(declaration)); + }); + for (const [exportDeclaration, topLevelDeclarations] of arrayFrom(targetToSourceExports))if (exportDeclaration.exportClause && isNamedExports(exportDeclaration.exportClause) && length(exportDeclaration.exportClause.elements)) { + const elements = exportDeclaration.exportClause.elements; + const updatedElements = filter(elements, (elem)=>find(skipAlias(elem.symbol, checker).declarations, (d)=>isTopLevelDeclaration(d) && topLevelDeclarations.has(d)) === void 0); + if (length(updatedElements) === 0) { + changes.deleteNode(targetFile, exportDeclaration); + removedExports.add(exportDeclaration); + continue; + } + if (length(updatedElements) < length(elements)) changes.replaceNode(targetFile, exportDeclaration, factory.updateExportDeclaration(exportDeclaration, exportDeclaration.modifiers, exportDeclaration.isTypeOnly, factory.updateNamedExports(exportDeclaration.exportClause, factory.createNodeArray(updatedElements, elements.hasTrailingComma)), exportDeclaration.moduleSpecifier, exportDeclaration.assertClause)); + } } - function getLinesForRange(sourceFile, textRange) { + const lastReExport = findLast(targetFile.statements, (n)=>isExportDeclaration(n) && !!n.moduleSpecifier && !removedExports.has(n)); + if (lastReExport) changes.insertNodesBefore(targetFile, lastReExport, statements, /*blankLineBetween*/ true); + else changes.insertNodesAfter(targetFile, targetFile.statements[targetFile.statements.length - 1], statements); + } + function getOverloadRangeToMove(sourceFile, statement) { + if (isFunctionLikeDeclaration(statement)) { + const declarations = statement.symbol.declarations; + if (declarations === void 0 || length(declarations) <= 1 || !contains(declarations, statement)) return void 0; + const firstDecl = declarations[0]; + const lastDecl = declarations[length(declarations) - 1]; + const statementsToMove = mapDefined(declarations, (d)=>getSourceFileOfNode(d) === sourceFile && isStatement(d) ? d : void 0); + const end = findIndex(sourceFile.statements, (s)=>s.end >= lastDecl.end); + const start = findIndex(sourceFile.statements, (s)=>s.end >= firstDecl.end); return { - lineStarts: sourceFile.getLineStarts(), - firstLine: sourceFile.getLineAndCharacterOfPosition(textRange.pos).line, - lastLine: sourceFile.getLineAndCharacterOfPosition(textRange.end).line + toMove: statementsToMove, + start: start, + end: end }; } - function toggleLineComment(fileName, textRange, insertComment) { - const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - const textChanges2 = []; - const { lineStarts: lineStarts , firstLine: firstLine , lastLine: lastLine } = getLinesForRange(sourceFile, textRange); - let isCommenting = insertComment || false; - let leftMostPosition = Number.MAX_VALUE; - const lineTextStarts = /* @__PURE__ */ new Map(); - const firstNonWhitespaceCharacterRegex = new RegExp(/\S/); - const isJsx = isInsideJsxElement(sourceFile, lineStarts[firstLine]); - const openComment = isJsx ? "{/*" : "//"; - for(let i = firstLine; i <= lastLine; i++){ - const lineText = sourceFile.text.substring(lineStarts[i], sourceFile.getLineEndOfPosition(lineStarts[i])); - const regExec = firstNonWhitespaceCharacterRegex.exec(lineText); - if (regExec) { - leftMostPosition = Math.min(leftMostPosition, regExec.index); - lineTextStarts.set(i.toString(), regExec.index); - if (lineText.substr(regExec.index, openComment.length) !== openComment) isCommenting = insertComment === void 0 || insertComment; - } - } - for(let i = firstLine; i <= lastLine; i++){ - if (firstLine !== lastLine && lineStarts[i] === textRange.end) continue; - const lineTextStart = lineTextStarts.get(i.toString()); - if (lineTextStart !== void 0) { - if (isJsx) textChanges2.push.apply(textChanges2, toggleMultilineComment(fileName, { - pos: lineStarts[i] + leftMostPosition, - end: sourceFile.getLineEndOfPosition(lineStarts[i]) - }, isCommenting, isJsx)); - else if (isCommenting) textChanges2.push({ - newText: openComment, - span: { - length: 0, - start: lineStarts[i] + leftMostPosition + return void 0; + } + var refactorNameForMoveToFile, description2, moveToFileAction; + var init_moveToFile = __esm({ + "src/services/refactors/moveToFile.ts" () { + "use strict"; + init_moduleSpecifiers(); + init_ts4(); + init_refactorProvider(); + refactorNameForMoveToFile = "Move to file"; + description2 = getLocaleSpecificMessage(Diagnostics.Move_to_file); + moveToFileAction = { + name: "Move to file", + description: description2, + kind: "refactor.move.file" + }; + registerRefactor(refactorNameForMoveToFile, { + kinds: [ + moveToFileAction.kind + ], + getAvailableActions: function getRefactorActionsToMoveToFile(context, interactiveRefactorArguments) { + const statements = getStatementsToMove(context); + if (!interactiveRefactorArguments) return emptyArray; + if (context.preferences.allowTextChangesInNewFiles && statements) return [ + { + name: refactorNameForMoveToFile, + description: description2, + actions: [ + moveToFileAction + ] } - }); - else if (sourceFile.text.substr(lineStarts[i] + lineTextStart, openComment.length) === openComment) textChanges2.push({ - newText: "", - span: { - length: openComment.length, - start: lineStarts[i] + lineTextStart + ]; + if (context.preferences.provideRefactorNotApplicableReason) return [ + { + name: refactorNameForMoveToFile, + description: description2, + actions: [ + { + ...moveToFileAction, + notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) + } + ] } - }); + ]; + return emptyArray; + }, + getEditsForAction: function getRefactorEditsToMoveToFile(context, actionName2, interactiveRefactorArguments) { + Debug.assert(actionName2 === refactorNameForMoveToFile, "Wrong refactor invoked"); + const statements = Debug.checkDefined(getStatementsToMove(context)); + const { host: host, program: program } = context; + Debug.assert(interactiveRefactorArguments, "No interactive refactor arguments available"); + const targetFile = interactiveRefactorArguments.targetFile; + if (hasJSFileExtension(targetFile) || hasTSFileExtension(targetFile)) { + if (host.fileExists(targetFile) && program.getSourceFile(targetFile) === void 0) return error(getLocaleSpecificMessage(Diagnostics.Cannot_move_statements_to_the_selected_file)); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange4(context, context.file, interactiveRefactorArguments.targetFile, context.program, statements, t, context.host, context.preferences)); + return { + edits: edits, + renameFilename: void 0, + renameLocation: void 0 + }; + } + return error(getLocaleSpecificMessage(Diagnostics.Cannot_move_to_file_selected_file_is_invalid)); } + }); + } + }); + // src/services/refactors/convertOverloadListToSingleSignature.ts + function getRefactorActionsToConvertOverloadsToOneSignature(context) { + const { file: file, startPosition: startPosition, program: program } = context; + const info = getConvertableOverloadListAtPosition(file, startPosition, program); + if (!info) return emptyArray; + return [ + { + name: refactorName6, + description: refactorDescription2, + actions: [ + functionOverloadAction + ] } - return textChanges2; + ]; + } + function getRefactorEditsToConvertOverloadsToOneSignature(context) { + const { file: file, startPosition: startPosition, program: program } = context; + const signatureDecls = getConvertableOverloadListAtPosition(file, startPosition, program); + if (!signatureDecls) return void 0; + const checker = program.getTypeChecker(); + const lastDeclaration = signatureDecls[signatureDecls.length - 1]; + let updated = lastDeclaration; + switch(lastDeclaration.kind){ + case 173 /* MethodSignature */ : + updated = factory.updateMethodSignature(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); + break; + case 174 /* MethodDeclaration */ : + updated = factory.updateMethodDeclaration(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); + break; + case 179 /* CallSignature */ : + updated = factory.updateCallSignature(lastDeclaration, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); + break; + case 176 /* Constructor */ : + updated = factory.updateConstructorDeclaration(lastDeclaration, lastDeclaration.modifiers, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.body); + break; + case 180 /* ConstructSignature */ : + updated = factory.updateConstructSignature(lastDeclaration, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); + break; + case 262 /* FunctionDeclaration */ : + updated = factory.updateFunctionDeclaration(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); + break; + default: + return Debug.failBadSyntaxKind(lastDeclaration, "Unhandled signature kind in overload list conversion refactoring"); } - function toggleMultilineComment(fileName, textRange, insertComment, isInsideJsx) { - var _a3; - const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - const textChanges2 = []; - const { text: text } = sourceFile; - let hasComment = false; - let isCommenting = insertComment || false; - const positions = []; - let { pos: pos } = textRange; - const isJsx = isInsideJsx !== void 0 ? isInsideJsx : isInsideJsxElement(sourceFile, pos); - const openMultiline = isJsx ? "{/*" : "/*"; - const closeMultiline = isJsx ? "*/}" : "*/"; - const openMultilineRegex = isJsx ? "\\{\\/\\*" : "\\/\\*"; - const closeMultilineRegex = isJsx ? "\\*\\/\\}" : "\\*\\/"; - while(pos <= textRange.end){ - const offset = text.substr(pos, openMultiline.length) === openMultiline ? openMultiline.length : 0; - const commentRange = isInComment(sourceFile, pos + offset); - if (commentRange) { - if (isJsx) { - commentRange.pos--; - commentRange.end++; + if (updated === lastDeclaration) return; + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t)=>{ + t.replaceNodeRange(file, signatureDecls[0], signatureDecls[signatureDecls.length - 1], updated); + }); + return { + renameFilename: void 0, + renameLocation: void 0, + edits: edits + }; + function getNewParametersForCombinedSignature(signatureDeclarations) { + const lastSig = signatureDeclarations[signatureDeclarations.length - 1]; + if (isFunctionLikeDeclaration(lastSig) && lastSig.body) signatureDeclarations = signatureDeclarations.slice(0, signatureDeclarations.length - 1); + return factory.createNodeArray([ + factory.createParameterDeclaration(/*modifiers*/ void 0, factory.createToken(26 /* DotDotDotToken */ ), "args", /*questionToken*/ void 0, factory.createUnionTypeNode(map(signatureDeclarations, convertSignatureParametersToTuple))) + ]); + } + function convertSignatureParametersToTuple(decl) { + const members = map(decl.parameters, convertParameterToNamedTupleMember); + return setEmitFlags(factory.createTupleTypeNode(members), some(members, (m)=>!!length(getSyntheticLeadingComments(m))) ? 0 /* None */ : 1 /* SingleLine */ ); + } + function convertParameterToNamedTupleMember(p) { + Debug.assert(isIdentifier(p.name)); + const result = setTextRange(factory.createNamedTupleMember(p.dotDotDotToken, p.name, p.questionToken, p.type || factory.createKeywordTypeNode(133 /* AnyKeyword */ )), p); + const parameterDocComment = p.symbol && p.symbol.getDocumentationComment(checker); + if (parameterDocComment) { + const newComment = displayPartsToString(parameterDocComment); + if (newComment.length) setSyntheticLeadingComments(result, [ + { + text: `* +${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} + `, + kind: 3 /* MultiLineCommentTrivia */ , + pos: -1, + end: -1, + hasTrailingNewLine: true, + hasLeadingNewline: true } - positions.push(commentRange.pos); - if (commentRange.kind === 3 /* MultiLineCommentTrivia */ ) positions.push(commentRange.end); - hasComment = true; - pos = commentRange.end + 1; - } else { - const newPos = text.substring(pos, textRange.end).search(`(${openMultilineRegex})|(${closeMultilineRegex})`); - isCommenting = insertComment !== void 0 ? insertComment : isCommenting || !isTextWhiteSpaceLike(text, pos, newPos === -1 ? textRange.end : pos + newPos); - pos = newPos === -1 ? textRange.end + 1 : pos + newPos + closeMultiline.length; - } + ]); } - if (isCommenting || !hasComment) { - if (((_a3 = isInComment(sourceFile, textRange.pos)) == null ? void 0 : _a3.kind) !== 2 /* SingleLineCommentTrivia */ ) insertSorted(positions, textRange.pos, compareValues); - insertSorted(positions, textRange.end, compareValues); - const firstPos = positions[0]; - if (text.substr(firstPos, openMultiline.length) !== openMultiline) textChanges2.push({ - newText: openMultiline, - span: { - length: 0, - start: firstPos - } - }); - for(let i = 1; i < positions.length - 1; i++){ - if (text.substr(positions[i] - closeMultiline.length, closeMultiline.length) !== closeMultiline) textChanges2.push({ - newText: closeMultiline, - span: { - length: 0, - start: positions[i] - } - }); - if (text.substr(positions[i], openMultiline.length) !== openMultiline) textChanges2.push({ - newText: openMultiline, - span: { - length: 0, - start: positions[i] - } - }); - } - if (textChanges2.length % 2 !== 0) textChanges2.push({ - newText: closeMultiline, - span: { - length: 0, - start: positions[positions.length - 1] - } - }); - } else for (const pos2 of positions){ - const from = pos2 - closeMultiline.length > 0 ? pos2 - closeMultiline.length : 0; - const offset = text.substr(from, closeMultiline.length) === closeMultiline ? closeMultiline.length : 0; - textChanges2.push({ - newText: "", - span: { - length: openMultiline.length, - start: pos2 - offset - } - }); - } - return textChanges2; - } - function commentSelection(fileName, textRange) { - const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - const { firstLine: firstLine , lastLine: lastLine } = getLinesForRange(sourceFile, textRange); - return firstLine === lastLine && textRange.pos !== textRange.end ? toggleMultilineComment(fileName, textRange, /*insertComment*/ true) : toggleLineComment(fileName, textRange, /*insertComment*/ true); - } - function uncommentSelection(fileName, textRange) { - const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - const textChanges2 = []; - const { pos: pos } = textRange; - let { end: end } = textRange; - if (pos === end) end += isInsideJsxElement(sourceFile, pos) ? 2 : 1; - for(let i = pos; i <= end; i++){ - const commentRange = isInComment(sourceFile, i); - if (commentRange) { - switch(commentRange.kind){ - case 2 /* SingleLineCommentTrivia */ : - textChanges2.push.apply(textChanges2, toggleLineComment(fileName, { - end: commentRange.end, - pos: commentRange.pos + 1 - }, /*insertComment*/ false)); - break; - case 3 /* MultiLineCommentTrivia */ : - textChanges2.push.apply(textChanges2, toggleMultilineComment(fileName, { - end: commentRange.end, - pos: commentRange.pos + 1 - }, /*insertComment*/ false)); - } - i = commentRange.end + 1; - } - } - return textChanges2; - } - function isUnclosedTag({ openingElement: openingElement , closingElement: closingElement , parent: parent2 }) { - return !tagNamesAreEquivalent(openingElement.tagName, closingElement.tagName) || isJsxElement(parent2) && tagNamesAreEquivalent(openingElement.tagName, parent2.openingElement.tagName) && isUnclosedTag(parent2); + return result; } - function isUnclosedFragment({ closingFragment: closingFragment , parent: parent2 }) { - return !!(closingFragment.flags & 131072 /* ThisNodeHasError */ ) || isJsxFragment(parent2) && isUnclosedFragment(parent2); + } + function isConvertableSignatureDeclaration(d) { + switch(d.kind){ + case 173 /* MethodSignature */ : + case 174 /* MethodDeclaration */ : + case 179 /* CallSignature */ : + case 176 /* Constructor */ : + case 180 /* ConstructSignature */ : + case 262 /* FunctionDeclaration */ : + return true; } - function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) { - const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - const range = ts_formatting_exports.getRangeOfEnclosingComment(sourceFile, position); - return range && (!onlyMultiLine || range.kind === 3 /* MultiLineCommentTrivia */ ) ? createTextSpanFromRange(range) : void 0; + return false; + } + function getConvertableOverloadListAtPosition(file, startPosition, program) { + const node = getTokenAtPosition(file, startPosition); + const containingDecl = findAncestor(node, isConvertableSignatureDeclaration); + if (!containingDecl) return; + if (isFunctionLikeDeclaration(containingDecl) && containingDecl.body && rangeContainsPosition(containingDecl.body, startPosition)) return; + const checker = program.getTypeChecker(); + const signatureSymbol = containingDecl.symbol; + if (!signatureSymbol) return; + const decls = signatureSymbol.declarations; + if (length(decls) <= 1) return; + if (!every(decls, (d)=>getSourceFileOfNode(d) === file)) return; + if (!isConvertableSignatureDeclaration(decls[0])) return; + const kindOne = decls[0].kind; + if (!every(decls, (d)=>d.kind === kindOne)) return; + const signatureDecls = decls; + if (some(signatureDecls, (d)=>!!d.typeParameters || some(d.parameters, (p)=>!!p.modifiers || !isIdentifier(p.name)))) return; + const signatures = mapDefined(signatureDecls, (d)=>checker.getSignatureFromDeclaration(d)); + if (length(signatures) !== length(decls)) return; + const returnOne = checker.getReturnTypeOfSignature(signatures[0]); + if (!every(signatures, (s)=>checker.getReturnTypeOfSignature(s) === returnOne)) return; + return signatureDecls; + } + var refactorName6, refactorDescription2, functionOverloadAction; + var init_convertOverloadListToSingleSignature = __esm({ + "src/services/refactors/convertOverloadListToSingleSignature.ts" () { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName6 = "Convert overload list to single signature"; + refactorDescription2 = getLocaleSpecificMessage(Diagnostics.Convert_overload_list_to_single_signature); + functionOverloadAction = { + name: refactorName6, + description: refactorDescription2, + kind: "refactor.rewrite.function.overloadList" + }; + registerRefactor(refactorName6, { + kinds: [ + functionOverloadAction.kind + ], + getEditsForAction: getRefactorEditsToConvertOverloadsToOneSignature, + getAvailableActions: getRefactorActionsToConvertOverloadsToOneSignature + }); } - function getTodoComments(fileName, descriptors) { - synchronizeHostData(); - const sourceFile = getValidSourceFile(fileName); - cancellationToken.throwIfCancellationRequested(); - const fileContents = sourceFile.text; - const result = []; - if (descriptors.length > 0 && !isNodeModulesFile(sourceFile.fileName)) { - const regExp = getTodoCommentsRegExp(); - let matchArray; - while(matchArray = regExp.exec(fileContents)){ - cancellationToken.throwIfCancellationRequested(); - const firstDescriptorCaptureIndex = 3; - Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex); - const preamble = matchArray[1]; - const matchPosition = matchArray.index + preamble.length; - if (!isInComment(sourceFile, matchPosition)) continue; - let descriptor; - for(let i = 0; i < descriptors.length; i++)if (matchArray[i + firstDescriptorCaptureIndex]) descriptor = descriptors[i]; - if (descriptor === void 0) return Debug.fail(); - if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) continue; - const message = matchArray[2]; - result.push({ - descriptor: descriptor, - message: message, - position: matchPosition - }); - } - } - return result; - function escapeRegExp(str) { - return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); - } - function getTodoCommentsRegExp() { - const singleLineCommentStart = /(?:\/\/+\s*)/.source; - const multiLineCommentStart = /(?:\/\*+\s*)/.source; - const anyNumberOfSpacesAndAsterisksAtStartOfLine = /(?:^(?:\s|\*)*)/.source; - const preamble = "(" + anyNumberOfSpacesAndAsterisksAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")"; - const literals = "(?:" + map(descriptors, (d)=>"(" + escapeRegExp(d.text) + ")").join("|") + ")"; - const endOfLineOrEndOfComment = /(?:$|\*\/)/.source; - const messageRemainder = /(?:.*?)/.source; - const messagePortion = "(" + literals + messageRemainder + ")"; - const regExpString = preamble + messagePortion + endOfLineOrEndOfComment; - return new RegExp(regExpString, "gim"); - } - function isLetterOrDigit(char) { - return char >= 97 /* a */ && char <= 122 /* z */ || char >= 65 /* A */ && char <= 90 /* Z */ || char >= 48 /* _0 */ && char <= 57 /* _9 */ ; + }); + // src/services/refactors/addOrRemoveBracesToArrowFunction.ts + function getRefactorActionsToRemoveFunctionBraces(context) { + const { file: file, startPosition: startPosition, triggerReason: triggerReason } = context; + const info = getConvertibleArrowFunctionAtPosition(file, startPosition, triggerReason === "invoked"); + if (!info) return emptyArray; + if (!isRefactorErrorInfo(info)) return [ + { + name: refactorName7, + description: refactorDescription3, + actions: [ + info.addBraces ? addBracesAction : removeBracesAction + ] } - function isNodeModulesFile(path) { - return stringContains(path, "/node_modules/"); + ]; + if (context.preferences.provideRefactorNotApplicableReason) return [ + { + name: refactorName7, + description: refactorDescription3, + actions: [ + { + ...addBracesAction, + notApplicableReason: info.error + }, + { + ...removeBracesAction, + notApplicableReason: info.error + } + ] } - } - function getRenameInfo2(fileName, position, preferences) { - synchronizeHostData(); - return ts_Rename_exports.getRenameInfo(program, getValidSourceFile(fileName), position, preferences || {}); - } - function getRefactorContext(file, positionOrRange, preferences, formatOptions, triggerReason, kind) { - const [startPosition, endPosition] = typeof positionOrRange === "number" ? [ - positionOrRange, - void 0 - ] : [ - positionOrRange.pos, - positionOrRange.end - ]; - return { - file: file, - startPosition: startPosition, - endPosition: endPosition, - program: getProgram(), - host: host, - formatContext: ts_formatting_exports.getFormatContext(formatOptions, host), - cancellationToken: // TODO: GH#18217 - cancellationToken, - preferences: preferences, - triggerReason: triggerReason, - kind: kind + ]; + return emptyArray; + } + function getRefactorEditsToRemoveFunctionBraces(context, actionName2) { + const { file: file, startPosition: startPosition } = context; + const info = getConvertibleArrowFunctionAtPosition(file, startPosition); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); + const { expression: expression, returnStatement: returnStatement, func: func } = info; + let body; + if (actionName2 === addBracesAction.name) { + const returnStatement2 = factory.createReturnStatement(expression); + body = factory.createBlock([ + returnStatement2 + ], /*multiLine*/ true); + copyLeadingComments(expression, returnStatement2, file, 3 /* MultiLineCommentTrivia */ , /*hasTrailingNewLine*/ true); + } else if (actionName2 === removeBracesAction.name && returnStatement) { + const actualExpression = expression || factory.createVoidZero(); + body = needsParentheses(actualExpression) ? factory.createParenthesizedExpression(actualExpression) : actualExpression; + copyTrailingAsLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */ , /*hasTrailingNewLine*/ false); + copyLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */ , /*hasTrailingNewLine*/ false); + copyTrailingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */ , /*hasTrailingNewLine*/ false); + } else Debug.fail("invalid action"); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t)=>{ + t.replaceNode(file, func.body, body); + }); + return { + renameFilename: void 0, + renameLocation: void 0, + edits: edits + }; + } + function getConvertibleArrowFunctionAtPosition(file, startPosition, considerFunctionBodies = true, kind) { + const node = getTokenAtPosition(file, startPosition); + const func = getContainingFunction(node); + if (!func) return { + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_a_containing_arrow_function) + }; + if (!isArrowFunction(func)) return { + error: getLocaleSpecificMessage(Diagnostics.Containing_function_is_not_an_arrow_function) + }; + if (!rangeContainsRange(func, node) || rangeContainsRange(func.body, node) && !considerFunctionBodies) return void 0; + if (refactorKindBeginsWith(addBracesAction.kind, kind) && isExpression(func.body)) return { + func: func, + addBraces: true, + expression: func.body + }; + else if (refactorKindBeginsWith(removeBracesAction.kind, kind) && isBlock(func.body) && func.body.statements.length === 1) { + const firstStatement = first(func.body.statements); + if (isReturnStatement(firstStatement)) return { + func: func, + addBraces: false, + expression: firstStatement.expression, + returnStatement: firstStatement }; } - function getInlayHintsContext(file, span, preferences) { - return { - file: file, - program: getProgram(), - host: host, - span: span, - preferences: preferences, - cancellationToken: cancellationToken + return void 0; + } + var refactorName7, refactorDescription3, addBracesAction, removeBracesAction; + var init_addOrRemoveBracesToArrowFunction = __esm({ + "src/services/refactors/addOrRemoveBracesToArrowFunction.ts" () { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName7 = "Add or remove braces in an arrow function"; + refactorDescription3 = getLocaleSpecificMessage(Diagnostics.Add_or_remove_braces_in_an_arrow_function); + addBracesAction = { + name: "Add braces to arrow function", + description: getLocaleSpecificMessage(Diagnostics.Add_braces_to_arrow_function), + kind: "refactor.rewrite.arrow.braces.add" }; - } - function getSmartSelectionRange2(fileName, position) { - return ts_SmartSelectionRange_exports.getSmartSelectionRange(position, syntaxTreeCache.getCurrentSourceFile(fileName)); - } - function getApplicableRefactors2(fileName, positionOrRange, preferences = emptyOptions, triggerReason, kind) { - synchronizeHostData(); - const file = getValidSourceFile(fileName); - return ts_refactor_exports.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences, emptyOptions, triggerReason, kind)); - } - function getEditsForRefactor2(fileName, formatOptions, positionOrRange, refactorName13, actionName2, preferences = emptyOptions) { - synchronizeHostData(); - const file = getValidSourceFile(fileName); - return ts_refactor_exports.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName13, actionName2); - } - function toLineColumnOffset(fileName, position) { - if (position === 0) return { - line: 0, - character: 0 + removeBracesAction = { + name: "Remove braces from arrow function", + description: getLocaleSpecificMessage(Diagnostics.Remove_braces_from_arrow_function), + kind: "refactor.rewrite.arrow.braces.remove" }; - return sourceMapper.toLineColumnOffset(fileName, position); + registerRefactor(refactorName7, { + kinds: [ + removeBracesAction.kind + ], + getEditsForAction: getRefactorEditsToRemoveFunctionBraces, + getAvailableActions: getRefactorActionsToRemoveFunctionBraces + }); } - function prepareCallHierarchy(fileName, position) { - synchronizeHostData(); - const declarations = ts_CallHierarchy_exports.resolveCallHierarchyDeclaration(program, getTouchingPropertyName(getValidSourceFile(fileName), position)); - return declarations && mapOneOrMany(declarations, (declaration)=>ts_CallHierarchy_exports.createCallHierarchyItem(program, declaration)); + }); + // src/services/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.ts + var ts_refactor_addOrRemoveBracesToArrowFunction_exports = {}; + var init_ts_refactor_addOrRemoveBracesToArrowFunction = __esm({ + "src/services/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.ts" () { + "use strict"; + init_convertOverloadListToSingleSignature(); + init_addOrRemoveBracesToArrowFunction(); } - function provideCallHierarchyIncomingCalls(fileName, position) { - synchronizeHostData(); - const sourceFile = getValidSourceFile(fileName); - const declaration = firstOrOnly(ts_CallHierarchy_exports.resolveCallHierarchyDeclaration(program, position === 0 ? sourceFile : getTouchingPropertyName(sourceFile, position))); - return declaration ? ts_CallHierarchy_exports.getIncomingCalls(program, declaration, cancellationToken) : []; + }); + // src/services/refactors/convertArrowFunctionOrFunctionExpression.ts + function getRefactorActionsToConvertFunctionExpressions(context) { + const { file: file, startPosition: startPosition, program: program, kind: kind } = context; + const info = getFunctionInfo(file, startPosition, program); + if (!info) return emptyArray; + const { selectedVariableDeclaration: selectedVariableDeclaration, func: func } = info; + const possibleActions = []; + const errors = []; + if (refactorKindBeginsWith(toNamedFunctionAction.kind, kind)) { + const error2 = selectedVariableDeclaration || isArrowFunction(func) && isVariableDeclaration(func.parent) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_named_function); + if (error2) errors.push({ + ...toNamedFunctionAction, + notApplicableReason: error2 + }); + else possibleActions.push(toNamedFunctionAction); } - function provideCallHierarchyOutgoingCalls(fileName, position) { - synchronizeHostData(); - const sourceFile = getValidSourceFile(fileName); - const declaration = firstOrOnly(ts_CallHierarchy_exports.resolveCallHierarchyDeclaration(program, position === 0 ? sourceFile : getTouchingPropertyName(sourceFile, position))); - return declaration ? ts_CallHierarchy_exports.getOutgoingCalls(program, declaration) : []; + if (refactorKindBeginsWith(toAnonymousFunctionAction.kind, kind)) { + const error2 = !selectedVariableDeclaration && isArrowFunction(func) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_anonymous_function); + if (error2) errors.push({ + ...toAnonymousFunctionAction, + notApplicableReason: error2 + }); + else possibleActions.push(toAnonymousFunctionAction); } - function provideInlayHints2(fileName, span, preferences = emptyOptions) { - synchronizeHostData(); - const sourceFile = getValidSourceFile(fileName); - return ts_InlayHints_exports.provideInlayHints(getInlayHintsContext(sourceFile, span, preferences)); + if (refactorKindBeginsWith(toArrowFunctionAction.kind, kind)) { + const error2 = isFunctionExpression(func) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_arrow_function); + if (error2) errors.push({ + ...toArrowFunctionAction, + notApplicableReason: error2 + }); + else possibleActions.push(toArrowFunctionAction); } - const ls = { - dispose: dispose, - cleanupSemanticCache: cleanupSemanticCache, - getSyntacticDiagnostics: getSyntacticDiagnostics, - getSemanticDiagnostics: getSemanticDiagnostics, - getSuggestionDiagnostics: getSuggestionDiagnostics, - getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, - getSyntacticClassifications: getSyntacticClassifications2, - getSemanticClassifications: getSemanticClassifications3, - getEncodedSyntacticClassifications: getEncodedSyntacticClassifications2, - getEncodedSemanticClassifications: getEncodedSemanticClassifications3, - getCompletionsAtPosition: getCompletionsAtPosition2, - getCompletionEntryDetails: getCompletionEntryDetails2, - getCompletionEntrySymbol: getCompletionEntrySymbol2, - getSignatureHelpItems: getSignatureHelpItems2, - getQuickInfoAtPosition: getQuickInfoAtPosition, - getDefinitionAtPosition: getDefinitionAtPosition2, - getDefinitionAndBoundSpan: getDefinitionAndBoundSpan2, - getImplementationAtPosition: getImplementationAtPosition, - getTypeDefinitionAtPosition: getTypeDefinitionAtPosition2, - getReferencesAtPosition: getReferencesAtPosition, - findReferences: findReferences, - getFileReferences: getFileReferences, - getOccurrencesAtPosition: getOccurrencesAtPosition, - getDocumentHighlights: getDocumentHighlights, - getNameOrDottedNameSpan: getNameOrDottedNameSpan, - getBreakpointStatementAtPosition: getBreakpointStatementAtPosition, - getNavigateToItems: getNavigateToItems2, - getRenameInfo: getRenameInfo2, - getSmartSelectionRange: getSmartSelectionRange2, - findRenameLocations: findRenameLocations, - getNavigationBarItems: getNavigationBarItems2, - getNavigationTree: getNavigationTree2, - getOutliningSpans: getOutliningSpans, - getTodoComments: getTodoComments, - getBraceMatchingAtPosition: getBraceMatchingAtPosition, - getIndentationAtPosition: getIndentationAtPosition, - getFormattingEditsForRange: getFormattingEditsForRange, - getFormattingEditsForDocument: getFormattingEditsForDocument, - getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, - getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition2, - isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, - getJsxClosingTagAtPosition: getJsxClosingTagAtPosition, - getSpanOfEnclosingComment: getSpanOfEnclosingComment, - getCodeFixesAtPosition: getCodeFixesAtPosition, - getCombinedCodeFix: getCombinedCodeFix, - applyCodeActionCommand: applyCodeActionCommand, - organizeImports: organizeImports2, - getEditsForFileRename: getEditsForFileRename2, - getEmitOutput: getEmitOutput, - getNonBoundSourceFile: getNonBoundSourceFile, - getProgram: getProgram, - getCurrentProgram: ()=>program, - getAutoImportProvider: getAutoImportProvider, - updateIsDefinitionOfReferencedSymbols: updateIsDefinitionOfReferencedSymbols, - getApplicableRefactors: getApplicableRefactors2, - getEditsForRefactor: getEditsForRefactor2, - toLineColumnOffset: toLineColumnOffset, - getSourceMapper: ()=>sourceMapper, - clearSourceMapperCache: ()=>sourceMapper.clearCache(), - prepareCallHierarchy: prepareCallHierarchy, - provideCallHierarchyIncomingCalls: provideCallHierarchyIncomingCalls, - provideCallHierarchyOutgoingCalls: provideCallHierarchyOutgoingCalls, - toggleLineComment: toggleLineComment, - toggleMultilineComment: toggleMultilineComment, - commentSelection: commentSelection, - uncommentSelection: uncommentSelection, - provideInlayHints: provideInlayHints2, - getSupportedCodeFixes: getSupportedCodeFixes - }; - switch(languageServiceMode){ - case 0 /* Semantic */ : + return [ + { + name: refactorName8, + description: refactorDescription4, + actions: possibleActions.length === 0 && context.preferences.provideRefactorNotApplicableReason ? errors : possibleActions + } + ]; + } + function getRefactorEditsToConvertFunctionExpressions(context, actionName2) { + const { file: file, startPosition: startPosition, program: program } = context; + const info = getFunctionInfo(file, startPosition, program); + if (!info) return void 0; + const { func: func } = info; + const edits = []; + switch(actionName2){ + case toAnonymousFunctionAction.name: + edits.push(...getEditInfoForConvertToAnonymousFunction(context, func)); break; - case 1 /* PartialSemantic */ : - invalidOperationsInPartialSemanticMode.forEach((key)=>ls[key] = ()=>{ - throw new Error(`LanguageService Operation: ${key} not allowed in LanguageServiceMode.PartialSemantic`); - }); + case toNamedFunctionAction.name: + const variableInfo = getVariableInfo(func); + if (!variableInfo) return void 0; + edits.push(...getEditInfoForConvertToNamedFunction(context, func, variableInfo)); break; - case 2 /* Syntactic */ : - invalidOperationsInSyntacticMode.forEach((key)=>ls[key] = ()=>{ - throw new Error(`LanguageService Operation: ${key} not allowed in LanguageServiceMode.Syntactic`); - }); + case toArrowFunctionAction.name: + if (!isFunctionExpression(func)) return void 0; + edits.push(...getEditInfoForConvertToArrowFunction(context, func)); break; default: - Debug.assertNever(languageServiceMode); + return Debug.fail("invalid action"); } - return ls; - } - function getNameTable(sourceFile) { - if (!sourceFile.nameTable) initializeNameTable(sourceFile); - return sourceFile.nameTable; + return { + renameFilename: void 0, + renameLocation: void 0, + edits: edits + }; } - function initializeNameTable(sourceFile) { - const nameTable = sourceFile.nameTable = /* @__PURE__ */ new Map(); - sourceFile.forEachChild(function walk(node) { - if (isIdentifier(node) && !isTagName(node) && node.escapedText || isStringOrNumericLiteralLike(node) && literalIsName(node)) { - const text = getEscapedTextOfIdentifierOrLiteral(node); - nameTable.set(text, nameTable.get(text) === void 0 ? node.pos : -1); - } else if (isPrivateIdentifier(node)) { - const text = node.escapedText; - nameTable.set(text, nameTable.get(text) === void 0 ? node.pos : -1); + function containingThis(node) { + let containsThis = false; + node.forEachChild(function checkThis(child) { + if (isThis(child)) { + containsThis = true; + return; } - forEachChild(node, walk); - if (hasJSDocNodes(node)) for (const jsDoc of node.jsDoc)forEachChild(jsDoc, walk); + if (!isClassLike(child) && !isFunctionDeclaration(child) && !isFunctionExpression(child)) forEachChild(child, checkThis); }); + return containsThis; } - function literalIsName(node) { - return isDeclarationName(node) || node.parent.kind === 280 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node) || isLiteralComputedPropertyDeclarationName(node); - } - function getContainingObjectLiteralElement(node) { - const element = getContainingObjectLiteralElementWorker(node); - return element && (isObjectLiteralExpression(element.parent) || isJsxAttributes(element.parent)) ? element : void 0; - } - function getContainingObjectLiteralElementWorker(node) { - switch(node.kind){ - case 10 /* StringLiteral */ : - case 14 /* NoSubstitutionTemplateLiteral */ : - case 8 /* NumericLiteral */ : - if (node.parent.kind === 164 /* ComputedPropertyName */ ) return isObjectLiteralElement(node.parent.parent) ? node.parent.parent : void 0; - case 79 /* Identifier */ : - return isObjectLiteralElement(node.parent) && (node.parent.parent.kind === 207 /* ObjectLiteralExpression */ || node.parent.parent.kind === 289 /* JsxAttributes */ ) && node.parent.name === node ? node.parent : void 0; + function getFunctionInfo(file, startPosition, program) { + const token = getTokenAtPosition(file, startPosition); + const typeChecker = program.getTypeChecker(); + const func = tryGetFunctionFromVariableDeclaration(file, typeChecker, token.parent); + if (func && !containingThis(func.body) && !typeChecker.containsArgumentsReference(func)) return { + selectedVariableDeclaration: true, + func: func + }; + const maybeFunc = getContainingFunction(token); + if (maybeFunc && (isFunctionExpression(maybeFunc) || isArrowFunction(maybeFunc)) && !rangeContainsRange(maybeFunc.body, token) && !containingThis(maybeFunc.body) && !typeChecker.containsArgumentsReference(maybeFunc)) { + if (isFunctionExpression(maybeFunc) && isFunctionReferencedInFile(file, typeChecker, maybeFunc)) return void 0; + return { + selectedVariableDeclaration: false, + func: maybeFunc + }; } return void 0; } - function getSymbolAtLocationForQuickInfo(node, checker) { - const object = getContainingObjectLiteralElement(node); - if (object) { - const contextualType = checker.getContextualType(object.parent); - const properties = contextualType && getPropertySymbolsFromContextualType(object, checker, contextualType, /*unionSymbolOk*/ false); - if (properties && properties.length === 1) return first(properties); - } - return checker.getSymbolAtLocation(node); + function isSingleVariableDeclaration(parent2) { + return isVariableDeclaration(parent2) || isVariableDeclarationList(parent2) && parent2.declarations.length === 1; } - function getPropertySymbolsFromContextualType(node, checker, contextualType, unionSymbolOk) { - const name = getNameFromPropertyName(node.name); - if (!name) return emptyArray; - if (!contextualType.isUnion()) { - const symbol = contextualType.getProperty(name); - return symbol ? [ - symbol - ] : emptyArray; - } - const discriminatedPropertySymbols = mapDefined(contextualType.types, (t)=>(isObjectLiteralExpression(node.parent) || isJsxAttributes(node.parent)) && checker.isTypeInvalidDueToUnionDiscriminant(t, node.parent) ? void 0 : t.getProperty(name)); - if (unionSymbolOk && (discriminatedPropertySymbols.length === 0 || discriminatedPropertySymbols.length === contextualType.types.length)) { - const symbol = contextualType.getProperty(name); - if (symbol) return [ - symbol - ]; - } - if (discriminatedPropertySymbols.length === 0) return mapDefined(contextualType.types, (t)=>t.getProperty(name)); - return discriminatedPropertySymbols; + function tryGetFunctionFromVariableDeclaration(sourceFile, typeChecker, parent2) { + if (!isSingleVariableDeclaration(parent2)) return void 0; + const variableDeclaration = isVariableDeclaration(parent2) ? parent2 : first(parent2.declarations); + const initializer = variableDeclaration.initializer; + if (initializer && (isArrowFunction(initializer) || isFunctionExpression(initializer) && !isFunctionReferencedInFile(sourceFile, typeChecker, initializer))) return initializer; + return void 0; } - function isArgumentOfElementAccessExpression(node) { - return node && node.parent && node.parent.kind === 209 /* ElementAccessExpression */ && node.parent.argumentExpression === node; + function convertToBlock(body) { + if (isExpression(body)) { + const returnStatement = factory.createReturnStatement(body); + const file = body.getSourceFile(); + setTextRange(returnStatement, body); + suppressLeadingAndTrailingTrivia(returnStatement); + copyTrailingAsLeadingComments(body, returnStatement, file, /*commentKind*/ void 0, /*hasTrailingNewLine*/ true); + return factory.createBlock([ + returnStatement + ], /*multiLine*/ true); + } else return body; } - function getDefaultLibFilePath(options) { - if (sys) return combinePaths(getDirectoryPath(normalizePath(sys.getExecutingFilePath())), getDefaultLibFileName(options)); - throw new Error("getDefaultLibFilePath is only supported when consumed as a node module. "); + function getVariableInfo(func) { + const variableDeclaration = func.parent; + if (!isVariableDeclaration(variableDeclaration) || !isVariableDeclarationInVariableStatement(variableDeclaration)) return void 0; + const variableDeclarationList = variableDeclaration.parent; + const statement = variableDeclarationList.parent; + if (!isVariableDeclarationList(variableDeclarationList) || !isVariableStatement(statement) || !isIdentifier(variableDeclaration.name)) return void 0; + return { + variableDeclaration: variableDeclaration, + variableDeclarationList: variableDeclarationList, + statement: statement, + name: variableDeclaration.name + }; } - var servicesVersion, NodeObject, TokenOrIdentifierObject, SymbolObject, TokenObject, IdentifierObject, PrivateIdentifierObject, TypeObject, SignatureObject, SourceFileObject, SourceMapSourceObject, SyntaxTreeCache, NoopCancellationToken, CancellationTokenObject, ThrottledCancellationToken, invalidOperationsInPartialSemanticMode, invalidOperationsInSyntacticMode; - var init_services = __esm({ - "src/services/services.ts" () { + function getEditInfoForConvertToAnonymousFunction(context, func) { + const { file: file } = context; + const body = convertToBlock(func.body); + const newNode = factory.createFunctionExpression(func.modifiers, func.asteriskToken, /*name*/ void 0, func.typeParameters, func.parameters, func.type, body); + return ts_textChanges_exports.ChangeTracker.with(context, (t)=>t.replaceNode(file, func, newNode)); + } + function getEditInfoForConvertToNamedFunction(context, func, variableInfo) { + const { file: file } = context; + const body = convertToBlock(func.body); + const { variableDeclaration: variableDeclaration, variableDeclarationList: variableDeclarationList, statement: statement, name: name } = variableInfo; + suppressLeadingTrivia(statement); + const modifiersFlags = getCombinedModifierFlags(variableDeclaration) & 1 /* Export */ | getEffectiveModifierFlags(func); + const modifiers = factory.createModifiersFromModifierFlags(modifiersFlags); + const newNode = factory.createFunctionDeclaration(length(modifiers) ? modifiers : void 0, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); + if (variableDeclarationList.declarations.length === 1) return ts_textChanges_exports.ChangeTracker.with(context, (t)=>t.replaceNode(file, statement, newNode)); + else return ts_textChanges_exports.ChangeTracker.with(context, (t)=>{ + t.delete(file, variableDeclaration); + t.insertNodeAfter(file, statement, newNode); + }); + } + function getEditInfoForConvertToArrowFunction(context, func) { + const { file: file } = context; + const statements = func.body.statements; + const head = statements[0]; + let body; + if (canBeConvertedToExpression(func.body, head)) { + body = head.expression; + suppressLeadingAndTrailingTrivia(body); + copyComments(head, body); + } else body = func.body; + const newNode = factory.createArrowFunction(func.modifiers, func.typeParameters, func.parameters, func.type, factory.createToken(39 /* EqualsGreaterThanToken */ ), body); + return ts_textChanges_exports.ChangeTracker.with(context, (t)=>t.replaceNode(file, func, newNode)); + } + function canBeConvertedToExpression(body, head) { + return body.statements.length === 1 && isReturnStatement(head) && !!head.expression; + } + function isFunctionReferencedInFile(sourceFile, typeChecker, node) { + return !!node.name && ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(node.name, typeChecker, sourceFile); + } + var refactorName8, refactorDescription4, toAnonymousFunctionAction, toNamedFunctionAction, toArrowFunctionAction; + var init_convertArrowFunctionOrFunctionExpression = __esm({ + "src/services/refactors/convertArrowFunctionOrFunctionExpression.ts" () { "use strict"; init_ts4(); - init_ts4(); - init_ts_NavigateTo(); - init_ts_NavigationBar(); - servicesVersion = "0.8"; - NodeObject = class { - constructor(kind, pos, end){ - this.pos = pos; - this.end = end; - this.flags = 0 /* None */ ; - this.modifierFlagsCache = 0 /* None */ ; - this.transformFlags = 0 /* None */ ; - this.parent = void 0; - this.kind = kind; - } - assertHasRealPosition(message) { - Debug.assert(!positionIsSynthesized(this.pos) && !positionIsSynthesized(this.end), message || "Node must have a real position for this operation"); - } - getSourceFile() { - return getSourceFileOfNode(this); - } - getStart(sourceFile, includeJsDocComment) { - this.assertHasRealPosition(); - return getTokenPosOfNode(this, sourceFile, includeJsDocComment); - } - getFullStart() { - this.assertHasRealPosition(); - return this.pos; - } - getEnd() { - this.assertHasRealPosition(); - return this.end; - } - getWidth(sourceFile) { - this.assertHasRealPosition(); - return this.getEnd() - this.getStart(sourceFile); - } - getFullWidth() { - this.assertHasRealPosition(); - return this.end - this.pos; - } - getLeadingTriviaWidth(sourceFile) { - this.assertHasRealPosition(); - return this.getStart(sourceFile) - this.pos; - } - getFullText(sourceFile) { - this.assertHasRealPosition(); - return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); - } - getText(sourceFile) { - this.assertHasRealPosition(); - if (!sourceFile) sourceFile = this.getSourceFile(); - return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); - } - getChildCount(sourceFile) { - return this.getChildren(sourceFile).length; - } - getChildAt(index, sourceFile) { - return this.getChildren(sourceFile)[index]; - } - getChildren(sourceFile) { - this.assertHasRealPosition("Node without a real position cannot be scanned and thus has no token nodes - use forEachChild and collect the result if that's fine"); - return this._children || (this._children = createChildren(this, sourceFile)); - } - getFirstToken(sourceFile) { - this.assertHasRealPosition(); - const children = this.getChildren(sourceFile); - if (!children.length) return void 0; - const child = find(children, (kid)=>kid.kind < 312 /* FirstJSDocNode */ || kid.kind > 353 /* LastJSDocNode */ ); - return child.kind < 163 /* FirstNode */ ? child : child.getFirstToken(sourceFile); - } - getLastToken(sourceFile) { - this.assertHasRealPosition(); - const children = this.getChildren(sourceFile); - const child = lastOrUndefined(children); - if (!child) return void 0; - return child.kind < 163 /* FirstNode */ ? child : child.getLastToken(sourceFile); - } - forEachChild(cbNode, cbNodeArray) { - return forEachChild(this, cbNode, cbNodeArray); - } + init_ts_refactor(); + refactorName8 = "Convert arrow function or function expression"; + refactorDescription4 = getLocaleSpecificMessage(Diagnostics.Convert_arrow_function_or_function_expression); + toAnonymousFunctionAction = { + name: "Convert to anonymous function", + description: getLocaleSpecificMessage(Diagnostics.Convert_to_anonymous_function), + kind: "refactor.rewrite.function.anonymous" }; - TokenOrIdentifierObject = class { - constructor(pos, end){ - this.pos = pos; - this.end = end; - this.flags = 0 /* None */ ; - this.modifierFlagsCache = 0 /* None */ ; - this.transformFlags = 0 /* None */ ; - this.parent = void 0; - } - getSourceFile() { - return getSourceFileOfNode(this); - } - getStart(sourceFile, includeJsDocComment) { - return getTokenPosOfNode(this, sourceFile, includeJsDocComment); - } - getFullStart() { - return this.pos; - } - getEnd() { - return this.end; - } - getWidth(sourceFile) { - return this.getEnd() - this.getStart(sourceFile); - } - getFullWidth() { - return this.end - this.pos; - } - getLeadingTriviaWidth(sourceFile) { - return this.getStart(sourceFile) - this.pos; - } - getFullText(sourceFile) { - return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); - } - getText(sourceFile) { - if (!sourceFile) sourceFile = this.getSourceFile(); - return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); - } - getChildCount() { - return this.getChildren().length; - } - getChildAt(index) { - return this.getChildren()[index]; - } - getChildren() { - return this.kind === 1 /* EndOfFileToken */ ? this.jsDoc || emptyArray : emptyArray; - } - getFirstToken() { - return void 0; - } - getLastToken() { - return void 0; - } - forEachChild() { - return void 0; - } + toNamedFunctionAction = { + name: "Convert to named function", + description: getLocaleSpecificMessage(Diagnostics.Convert_to_named_function), + kind: "refactor.rewrite.function.named" }; - SymbolObject = class { - constructor(flags, name){ - this.id = 0; - this.mergeId = 0; - this.flags = flags; - this.escapedName = name; - } - getFlags() { - return this.flags; - } - get name() { - return symbolName(this); - } - getEscapedName() { - return this.escapedName; - } - getName() { - return this.name; - } - getDeclarations() { - return this.declarations; - } - getDocumentationComment(checker) { - if (!this.documentationComment) { - this.documentationComment = emptyArray; - if (!this.declarations && isTransientSymbol(this) && this.links.target && isTransientSymbol(this.links.target) && this.links.target.links.tupleLabelDeclaration) { - const labelDecl = this.links.target.links.tupleLabelDeclaration; - this.documentationComment = getDocumentationComment([ - labelDecl - ], checker); - } else this.documentationComment = getDocumentationComment(this.declarations, checker); - } - return this.documentationComment; - } - getContextualDocumentationComment(context, checker) { - if (context) { - if (isGetAccessor(context)) { - if (!this.contextualGetAccessorDocumentationComment) this.contextualGetAccessorDocumentationComment = getDocumentationComment(filter(this.declarations, isGetAccessor), checker); - if (length(this.contextualGetAccessorDocumentationComment)) return this.contextualGetAccessorDocumentationComment; - } - if (isSetAccessor(context)) { - if (!this.contextualSetAccessorDocumentationComment) this.contextualSetAccessorDocumentationComment = getDocumentationComment(filter(this.declarations, isSetAccessor), checker); - if (length(this.contextualSetAccessorDocumentationComment)) return this.contextualSetAccessorDocumentationComment; - } - } - return this.getDocumentationComment(checker); - } - getJsDocTags(checker) { - if (this.tags === void 0) this.tags = getJsDocTagsOfDeclarations(this.declarations, checker); - return this.tags; - } - getContextualJsDocTags(context, checker) { - if (context) { - if (isGetAccessor(context)) { - if (!this.contextualGetAccessorTags) this.contextualGetAccessorTags = getJsDocTagsOfDeclarations(filter(this.declarations, isGetAccessor), checker); - if (length(this.contextualGetAccessorTags)) return this.contextualGetAccessorTags; - } - if (isSetAccessor(context)) { - if (!this.contextualSetAccessorTags) this.contextualSetAccessorTags = getJsDocTagsOfDeclarations(filter(this.declarations, isSetAccessor), checker); - if (length(this.contextualSetAccessorTags)) return this.contextualSetAccessorTags; - } - } - return this.getJsDocTags(checker); - } + toArrowFunctionAction = { + name: "Convert to arrow function", + description: getLocaleSpecificMessage(Diagnostics.Convert_to_arrow_function), + kind: "refactor.rewrite.function.arrow" }; - TokenObject = class extends TokenOrIdentifierObject { - constructor(kind, pos, end){ - super(pos, end); - this.kind = kind; - } + registerRefactor(refactorName8, { + kinds: [ + toAnonymousFunctionAction.kind, + toNamedFunctionAction.kind, + toArrowFunctionAction.kind + ], + getEditsForAction: getRefactorEditsToConvertFunctionExpressions, + getAvailableActions: getRefactorActionsToConvertFunctionExpressions + }); + } + }); + // src/services/_namespaces/ts.refactor.convertArrowFunctionOrFunctionExpression.ts + var ts_refactor_convertArrowFunctionOrFunctionExpression_exports = {}; + var init_ts_refactor_convertArrowFunctionOrFunctionExpression = __esm({ + "src/services/_namespaces/ts.refactor.convertArrowFunctionOrFunctionExpression.ts" () { + "use strict"; + init_convertArrowFunctionOrFunctionExpression(); + } + }); + // src/services/refactors/convertParamsToDestructuredObject.ts + function getRefactorActionsToConvertParametersToDestructuredObject(context) { + const { file: file, startPosition: startPosition } = context; + const isJSFile = isSourceFileJS(file); + if (isJSFile) return emptyArray; + const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker()); + if (!functionDeclaration) return emptyArray; + return [ + { + name: refactorName9, + description: refactorDescription5, + actions: [ + toDestructuredAction + ] + } + ]; + } + function getRefactorEditsToConvertParametersToDestructuredObject(context, actionName2) { + Debug.assert(actionName2 === refactorName9, "Unexpected action name"); + const { file: file, startPosition: startPosition, program: program, cancellationToken: cancellationToken, host: host } = context; + const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker()); + if (!functionDeclaration || !cancellationToken) return void 0; + const groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken); + if (groupedReferences.valid) { + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange5(file, program, host, t, functionDeclaration, groupedReferences)); + return { + renameFilename: void 0, + renameLocation: void 0, + edits: edits }; - IdentifierObject = class extends TokenOrIdentifierObject { - constructor(_kind, pos, end){ - super(pos, end); - this.kind = 79 /* Identifier */ ; - } - get text() { - return idText(this); - } + } + return { + edits: [] + }; + } + function doChange5(sourceFile, program, host, changes, functionDeclaration, groupedReferences) { + const signature = groupedReferences.signature; + const newFunctionDeclarationParams = map(createNewParameters(functionDeclaration, program, host), (param)=>getSynthesizedDeepClone(param)); + if (signature) { + const newSignatureParams = map(createNewParameters(signature, program, host), (param)=>getSynthesizedDeepClone(param)); + replaceParameters(signature, newSignatureParams); + } + replaceParameters(functionDeclaration, newFunctionDeclarationParams); + const functionCalls = sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ (a, b)=>compareValues(a.pos, b.pos)); + for (const call of functionCalls)if (call.arguments && call.arguments.length) { + const newArgument = getSynthesizedDeepClone(createNewArgument(functionDeclaration, call.arguments), /*includeTrivia*/ true); + changes.replaceNodeRange(getSourceFileOfNode(call), first(call.arguments), last(call.arguments), newArgument, { + leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include + }); + } + function replaceParameters(declarationOrSignature, parameterDeclarations) { + changes.replaceNodeRangeWithNodes(sourceFile, first(declarationOrSignature.parameters), last(declarationOrSignature.parameters), parameterDeclarations, { + joiner: ", ", + // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter + indentation: 0, + leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include + }); + } + } + function getGroupedReferences(functionDeclaration, program, cancellationToken) { + const functionNames = getFunctionNames(functionDeclaration); + const classNames = isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : []; + const names = deduplicate([ + ...functionNames, + ...classNames + ], equateValues); + const checker = program.getTypeChecker(); + const references = flatMap(names, /*mapfn*/ (name)=>ts_FindAllReferences_exports.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken)); + const groupedReferences = groupReferences(references); + if (!every(groupedReferences.declarations, /*callback*/ (decl)=>contains(names, decl))) groupedReferences.valid = false; + return groupedReferences; + function groupReferences(referenceEntries) { + const classReferences = { + accessExpressions: [], + typeUsages: [] }; - IdentifierObject.prototype.kind = 79 /* Identifier */ ; - PrivateIdentifierObject = class extends TokenOrIdentifierObject { - constructor(_kind, pos, end){ - super(pos, end); - this.kind = 80 /* PrivateIdentifier */ ; - } - get text() { - return idText(this); - } + const groupedReferences2 = { + functionCalls: [], + declarations: [], + classReferences: classReferences, + valid: true }; - PrivateIdentifierObject.prototype.kind = 80 /* PrivateIdentifier */ ; - TypeObject = class { - constructor(checker, flags){ - this.checker = checker; - this.flags = flags; - } - getFlags() { - return this.flags; - } - getSymbol() { - return this.symbol; - } - getProperties() { - return this.checker.getPropertiesOfType(this); - } - getProperty(propertyName) { - return this.checker.getPropertyOfType(this, propertyName); - } - getApparentProperties() { - return this.checker.getAugmentedPropertiesOfType(this); - } - getCallSignatures() { - return this.checker.getSignaturesOfType(this, 0 /* Call */ ); - } - getConstructSignatures() { - return this.checker.getSignaturesOfType(this, 1 /* Construct */ ); - } - getStringIndexType() { - return this.checker.getIndexTypeOfType(this, 0 /* String */ ); - } - getNumberIndexType() { - return this.checker.getIndexTypeOfType(this, 1 /* Number */ ); - } - getBaseTypes() { - return this.isClassOrInterface() ? this.checker.getBaseTypes(this) : void 0; - } - isNullableType() { - return this.checker.isNullableType(this); - } - getNonNullableType() { - return this.checker.getNonNullableType(this); - } - getNonOptionalType() { - return this.checker.getNonOptionalType(this); - } - getConstraint() { - return this.checker.getBaseConstraintOfType(this); + const functionSymbols = map(functionNames, getSymbolTargetAtLocation); + const classSymbols = map(classNames, getSymbolTargetAtLocation); + const isConstructor = isConstructorDeclaration(functionDeclaration); + const contextualSymbols = map(functionNames, (name)=>getSymbolForContextualType(name, checker)); + for (const entry of referenceEntries){ + if (entry.kind === ts_FindAllReferences_exports.EntryKind.Span) { + groupedReferences2.valid = false; + continue; } - getDefault() { - return this.checker.getDefaultFromTypeParameter(this); + if (contains(contextualSymbols, getSymbolTargetAtLocation(entry.node))) { + if (isValidMethodSignature(entry.node.parent)) { + groupedReferences2.signature = entry.node.parent; + continue; + } + const call = entryToFunctionCall(entry); + if (call) { + groupedReferences2.functionCalls.push(call); + continue; + } } - isUnion() { - return !!(this.flags & 1048576 /* Union */ ); + const contextualSymbol = getSymbolForContextualType(entry.node, checker); + if (contextualSymbol && contains(contextualSymbols, contextualSymbol)) { + const decl = entryToDeclaration(entry); + if (decl) { + groupedReferences2.declarations.push(decl); + continue; + } } - isIntersection() { - return !!(this.flags & 2097152 /* Intersection */ ); + if (contains(functionSymbols, getSymbolTargetAtLocation(entry.node)) || isNewExpressionTarget(entry.node)) { + const importOrExportReference = entryToImportOrExport(entry); + if (importOrExportReference) continue; + const decl = entryToDeclaration(entry); + if (decl) { + groupedReferences2.declarations.push(decl); + continue; + } + const call = entryToFunctionCall(entry); + if (call) { + groupedReferences2.functionCalls.push(call); + continue; + } } - isUnionOrIntersection() { - return !!(this.flags & 3145728 /* UnionOrIntersection */ ); + if (isConstructor && contains(classSymbols, getSymbolTargetAtLocation(entry.node))) { + const importOrExportReference = entryToImportOrExport(entry); + if (importOrExportReference) continue; + const decl = entryToDeclaration(entry); + if (decl) { + groupedReferences2.declarations.push(decl); + continue; + } + const accessExpression = entryToAccessExpression(entry); + if (accessExpression) { + classReferences.accessExpressions.push(accessExpression); + continue; + } + if (isClassDeclaration(functionDeclaration.parent)) { + const type = entryToType(entry); + if (type) { + classReferences.typeUsages.push(type); + continue; + } + } } - isLiteral() { - return !!(this.flags & 2432 /* BigIntLiteral */ ); - } - isStringLiteral() { - return !!(this.flags & 128 /* StringLiteral */ ); - } - isNumberLiteral() { - return !!(this.flags & 256 /* NumberLiteral */ ); - } - isTypeParameter() { - return !!(this.flags & 262144 /* TypeParameter */ ); - } - isClassOrInterface() { - return !!(getObjectFlags(this) & 3 /* ClassOrInterface */ ); - } - isClass() { - return !!(getObjectFlags(this) & 1 /* Class */ ); - } - isIndexType() { - return !!(this.flags & 4194304 /* Index */ ); - } - /** - * This polyfills `referenceType.typeArguments` for API consumers - */ get typeArguments() { - if (getObjectFlags(this) & 4 /* Reference */ ) return this.checker.getTypeArguments(this); - return void 0; - } - }; - SignatureObject = class { - // same - constructor(checker, flags){ - this.checker = checker; - this.flags = flags; - } - getDeclaration() { - return this.declaration; - } - getTypeParameters() { - return this.typeParameters; - } - getParameters() { - return this.parameters; - } - getReturnType() { - return this.checker.getReturnTypeOfSignature(this); - } - getTypeParameterAtPosition(pos) { - const type = this.checker.getParameterType(this, pos); - if (type.isIndexType() && isThisTypeParameter(type.type)) { - const constraint = type.type.getConstraint(); - if (constraint) return this.checker.getIndexType(constraint); - } - return type; - } - getDocumentationComment() { - return this.documentationComment || (this.documentationComment = getDocumentationComment(singleElementArray(this.declaration), this.checker)); - } - getJsDocTags() { - return this.jsDocTags || (this.jsDocTags = getJsDocTagsOfDeclarations(singleElementArray(this.declaration), this.checker)); - } - }; - SourceFileObject = class extends NodeObject { - constructor(kind, pos, end){ - super(kind, pos, end); - this.kind = 308 /* SourceFile */ ; - } - update(newText, textChangeRange) { - return updateSourceFile(this, newText, textChangeRange); - } - getLineAndCharacterOfPosition(position) { - return getLineAndCharacterOfPosition(this, position); - } - getLineStarts() { - return getLineStarts(this); - } - getPositionOfLineAndCharacter(line, character, allowEdits) { - return computePositionOfLineAndCharacter(getLineStarts(this), line, character, this.text, allowEdits); - } - getLineEndOfPosition(pos) { - const { line: line } = this.getLineAndCharacterOfPosition(pos); - const lineStarts = this.getLineStarts(); - let lastCharPos; - if (line + 1 >= lineStarts.length) lastCharPos = this.getEnd(); - if (!lastCharPos) lastCharPos = lineStarts[line + 1] - 1; - const fullText = this.getFullText(); - return fullText[lastCharPos] === "\n" && fullText[lastCharPos - 1] === "\r" ? lastCharPos - 1 : lastCharPos; - } - getNamedDeclarations() { - if (!this.namedDeclarations) this.namedDeclarations = this.computeNamedDeclarations(); - return this.namedDeclarations; - } - computeNamedDeclarations() { - const result = createMultiMap(); - this.forEachChild(visit); - return result; - function addDeclaration(declaration) { - const name = getDeclarationName(declaration); - if (name) result.add(name, declaration); - } - function getDeclarations(name) { - let declarations = result.get(name); - if (!declarations) result.set(name, declarations = []); - return declarations; - } - function getDeclarationName(declaration) { - const name = getNonAssignedNameOfDeclaration(declaration); - return name && (isComputedPropertyName(name) && isPropertyAccessExpression(name.expression) ? name.expression.name.text : isPropertyName(name) ? getNameFromPropertyName(name) : void 0); - } - function visit(node) { - switch(node.kind){ - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - const functionDeclaration = node; - const declarationName = getDeclarationName(functionDeclaration); - if (declarationName) { - const declarations = getDeclarations(declarationName); - const lastDeclaration = lastOrUndefined(declarations); - if (lastDeclaration && functionDeclaration.parent === lastDeclaration.parent && functionDeclaration.symbol === lastDeclaration.symbol) { - if (functionDeclaration.body && !lastDeclaration.body) declarations[declarations.length - 1] = functionDeclaration; - } else declarations.push(functionDeclaration); - } - forEachChild(node, visit); - break; - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : - case 261 /* InterfaceDeclaration */ : - case 262 /* TypeAliasDeclaration */ : - case 263 /* EnumDeclaration */ : - case 264 /* ModuleDeclaration */ : - case 268 /* ImportEqualsDeclaration */ : - case 278 /* ExportSpecifier */ : - case 273 /* ImportSpecifier */ : - case 270 /* ImportClause */ : - case 271 /* NamespaceImport */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 184 /* TypeLiteral */ : - addDeclaration(node); - forEachChild(node, visit); - break; - case 166 /* Parameter */ : - if (!hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */ )) break; - case 257 /* VariableDeclaration */ : - case 205 /* BindingElement */ : - { - const decl = node; - if (isBindingPattern(decl.name)) { - forEachChild(decl.name, visit); - break; - } - if (decl.initializer) visit(decl.initializer); - } - case 302 /* EnumMember */ : - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : - addDeclaration(node); - break; - case 275 /* ExportDeclaration */ : - const exportDeclaration = node; - if (exportDeclaration.exportClause) { - if (isNamedExports(exportDeclaration.exportClause)) forEach(exportDeclaration.exportClause.elements, visit); - else visit(exportDeclaration.exportClause.name); - } - break; - case 269 /* ImportDeclaration */ : - const importClause = node.importClause; - if (importClause) { - if (importClause.name) addDeclaration(importClause.name); - if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 271 /* NamespaceImport */ ) addDeclaration(importClause.namedBindings); - else forEach(importClause.namedBindings.elements, visit); - } - } - break; - case 223 /* BinaryExpression */ : - if (getAssignmentDeclarationKind(node) !== 0 /* None */ ) addDeclaration(node); - default: - forEachChild(node, visit); - } - } - } - }; - SourceMapSourceObject = class { - constructor(fileName, text, skipTrivia2){ - this.fileName = fileName; - this.text = text; - this.skipTrivia = skipTrivia2; - } - getLineAndCharacterOfPosition(pos) { - return getLineAndCharacterOfPosition(this, pos); - } - }; - SyntaxTreeCache = class { - constructor(host){ - this.host = host; - } - getCurrentSourceFile(fileName) { - var _a2, _b, _c, _d, _e, _f, _g, _h; - const scriptSnapshot = this.host.getScriptSnapshot(fileName); - if (!scriptSnapshot) throw new Error("Could not find file: '" + fileName + "'."); - const scriptKind = getScriptKind(fileName, this.host); - const version2 = this.host.getScriptVersion(fileName); - let sourceFile; - if (this.currentFileName !== fileName) { - const options = { - languageVersion: 99 /* Latest */ , - impliedNodeFormat: getImpliedNodeFormatForFile(toPath(fileName, this.host.getCurrentDirectory(), ((_c = (_b = (_a2 = this.host).getCompilerHost) == null ? void 0 : _b.call(_a2)) == null ? void 0 : _c.getCanonicalFileName) || hostGetCanonicalFileName(this.host)), (_h = (_g = (_f = (_e = (_d = this.host).getCompilerHost) == null ? void 0 : _e.call(_d)) == null ? void 0 : _f.getModuleResolutionCache) == null ? void 0 : _g.call(_f)) == null ? void 0 : _h.getPackageJsonInfoCache(), this.host, this.host.getCompilationSettings()), - setExternalModuleIndicator: getSetExternalModuleIndicator(this.host.getCompilationSettings()) - }; - sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, options, version2, /*setNodeParents*/ true, scriptKind); - } else if (this.currentFileVersion !== version2) { - const editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot); - sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version2, editRange); - } - if (sourceFile) { - this.currentFileVersion = version2; - this.currentFileName = fileName; - this.currentFileScriptSnapshot = scriptSnapshot; - this.currentSourceFile = sourceFile; - } - return this.currentSourceFile; - } - }; - NoopCancellationToken = { - isCancellationRequested: returnFalse, - throwIfCancellationRequested: noop - }; - CancellationTokenObject = class { - constructor(cancellationToken){ - this.cancellationToken = cancellationToken; - } - isCancellationRequested() { - return this.cancellationToken.isCancellationRequested(); - } - throwIfCancellationRequested() { - var _a2; - if (this.isCancellationRequested()) { - (_a2 = tracing) == null || _a2.instant(tracing.Phase.Session, "cancellationThrown", { - kind: "CancellationTokenObject" - }); - throw new OperationCanceledException(); - } - } - }; - ThrottledCancellationToken = class { - constructor(hostCancellationToken, throttleWaitMilliseconds = 20){ - this.hostCancellationToken = hostCancellationToken; - this.throttleWaitMilliseconds = throttleWaitMilliseconds; - // Store when we last tried to cancel. Checking cancellation can be expensive (as we have - // to marshall over to the host layer). So we only bother actually checking once enough - // time has passed. - this.lastCancellationCheckTime = 0; - } - isCancellationRequested() { - const time = timestamp(); - const duration = Math.abs(time - this.lastCancellationCheckTime); - if (duration >= this.throttleWaitMilliseconds) { - this.lastCancellationCheckTime = time; - return this.hostCancellationToken.isCancellationRequested(); + groupedReferences2.valid = false; + } + return groupedReferences2; + } + function getSymbolTargetAtLocation(node) { + const symbol = checker.getSymbolAtLocation(node); + return symbol && getSymbolTarget(symbol, checker); + } + } + function getSymbolForContextualType(node, checker) { + const element = getContainingObjectLiteralElement(node); + if (element) { + const contextualType = checker.getContextualTypeForObjectLiteralElement(element); + const symbol = contextualType == null ? void 0 : contextualType.getSymbol(); + if (symbol && !(getCheckFlags(symbol) & 6 /* Synthetic */ )) return symbol; + } + } + function entryToImportOrExport(entry) { + const node = entry.node; + if (isImportSpecifier(node.parent) || isImportClause(node.parent) || isImportEqualsDeclaration(node.parent) || isNamespaceImport(node.parent)) return node; + if (isExportSpecifier(node.parent) || isExportAssignment(node.parent)) return node; + return void 0; + } + function entryToDeclaration(entry) { + if (isDeclaration(entry.node.parent)) return entry.node; + return void 0; + } + function entryToFunctionCall(entry) { + if (entry.node.parent) { + const functionReference = entry.node; + const parent2 = functionReference.parent; + switch(parent2.kind){ + case 213 /* CallExpression */ : + case 214 /* NewExpression */ : + const callOrNewExpression = tryCast(parent2, isCallOrNewExpression); + if (callOrNewExpression && callOrNewExpression.expression === functionReference) return callOrNewExpression; + break; + case 211 /* PropertyAccessExpression */ : + const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression); + if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) { + const callOrNewExpression2 = tryCast(propertyAccessExpression.parent, isCallOrNewExpression); + if (callOrNewExpression2 && callOrNewExpression2.expression === propertyAccessExpression) return callOrNewExpression2; } - return false; - } - throwIfCancellationRequested() { - var _a2; - if (this.isCancellationRequested()) { - (_a2 = tracing) == null || _a2.instant(tracing.Phase.Session, "cancellationThrown", { - kind: "ThrottledCancellationToken" - }); - throw new OperationCanceledException(); + break; + case 212 /* ElementAccessExpression */ : + const elementAccessExpression = tryCast(parent2, isElementAccessExpression); + if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) { + const callOrNewExpression2 = tryCast(elementAccessExpression.parent, isCallOrNewExpression); + if (callOrNewExpression2 && callOrNewExpression2.expression === elementAccessExpression) return callOrNewExpression2; } - } - }; - invalidOperationsInPartialSemanticMode = [ - "getSemanticDiagnostics", - "getSuggestionDiagnostics", - "getCompilerOptionsDiagnostics", - "getSemanticClassifications", - "getEncodedSemanticClassifications", - "getCodeFixesAtPosition", - "getCombinedCodeFix", - "applyCodeActionCommand", - "organizeImports", - "getEditsForFileRename", - "getEmitOutput", - "getApplicableRefactors", - "getEditsForRefactor", - "prepareCallHierarchy", - "provideCallHierarchyIncomingCalls", - "provideCallHierarchyOutgoingCalls", - "provideInlayHints", - "getSupportedCodeFixes" - ]; - invalidOperationsInSyntacticMode = [ - ...invalidOperationsInPartialSemanticMode, - "getCompletionsAtPosition", - "getCompletionEntryDetails", - "getCompletionEntrySymbol", - "getSignatureHelpItems", - "getQuickInfoAtPosition", - "getDefinitionAtPosition", - "getDefinitionAndBoundSpan", - "getImplementationAtPosition", - "getTypeDefinitionAtPosition", - "getReferencesAtPosition", - "findReferences", - "getOccurrencesAtPosition", - "getDocumentHighlights", - "getNavigateToItems", - "getRenameInfo", - "findRenameLocations", - "getApplicableRefactors" - ]; - setObjectAllocator(getServicesObjectAllocator()); + break; + } } - }); - // src/services/transform.ts - function transform(source, transformers, compilerOptions) { - const diagnostics = []; - compilerOptions = fixupCompilerOptions(compilerOptions, diagnostics); - const nodes = isArray(source) ? source : [ - source - ]; - const result = transformNodes(/*resolver*/ void 0, /*emitHost*/ void 0, factory, compilerOptions, nodes, transformers, /*allowDtsFiles*/ true); - result.diagnostics = concatenate(result.diagnostics, diagnostics); - return result; + return void 0; } - var init_transform = __esm({ - "src/services/transform.ts" () { - "use strict"; - init_ts4(); + function entryToAccessExpression(entry) { + if (entry.node.parent) { + const reference = entry.node; + const parent2 = reference.parent; + switch(parent2.kind){ + case 211 /* PropertyAccessExpression */ : + const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression); + if (propertyAccessExpression && propertyAccessExpression.expression === reference) return propertyAccessExpression; + break; + case 212 /* ElementAccessExpression */ : + const elementAccessExpression = tryCast(parent2, isElementAccessExpression); + if (elementAccessExpression && elementAccessExpression.expression === reference) return elementAccessExpression; + break; + } } - }); - // src/services/shims.ts - function logInternalError(logger, err) { - if (logger) logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message); + return void 0; } - function simpleForwardCall(logger, actionDescription2, action, logPerformance) { - let start; - if (logPerformance) { - logger.log(actionDescription2); - start = timestamp(); + function entryToType(entry) { + const reference = entry.node; + if (getMeaningFromLocation(reference) === 2 /* Type */ || isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) return reference; + return void 0; + } + function getFunctionDeclarationAtPosition(file, startPosition, checker) { + const node = getTouchingToken(file, startPosition); + const functionDeclaration = getContainingFunctionDeclaration(node); + if (isTopLevelJSDoc(node)) return void 0; + if (functionDeclaration && isValidFunctionDeclaration(functionDeclaration, checker) && rangeContainsRange(functionDeclaration, node) && !(functionDeclaration.body && rangeContainsRange(functionDeclaration.body, node))) return functionDeclaration; + return void 0; + } + function isTopLevelJSDoc(node) { + const containingJSDoc = findAncestor(node, isJSDocNode); + if (containingJSDoc) { + const containingNonJSDoc = findAncestor(containingJSDoc, (n)=>!isJSDocNode(n)); + return !!containingNonJSDoc && isFunctionLikeDeclaration(containingNonJSDoc); } - const result = action(); - if (logPerformance) { - const end = timestamp(); - logger.log(`${actionDescription2} completed in ${end - start} msec`); - if (isString(result)) { - let str = result; - if (str.length > 128) str = str.substring(0, 128) + "..."; - logger.log(` result.length=${str.length}, result='${JSON.stringify(str)}'`); - } + return false; + } + function isValidMethodSignature(node) { + return isMethodSignature(node) && (isInterfaceDeclaration(node.parent) || isTypeLiteralNode(node.parent)); + } + function isValidFunctionDeclaration(functionDeclaration, checker) { + var _a; + if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) return false; + switch(functionDeclaration.kind){ + case 262 /* FunctionDeclaration */ : + return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker); + case 174 /* MethodDeclaration */ : + if (isObjectLiteralExpression(functionDeclaration.parent)) { + const contextualSymbol = getSymbolForContextualType(functionDeclaration.name, checker); + return ((_a = contextualSymbol == null ? void 0 : contextualSymbol.declarations) == null ? void 0 : _a.length) === 1 && isSingleImplementation(functionDeclaration, checker); + } + return isSingleImplementation(functionDeclaration, checker); + case 176 /* Constructor */ : + if (isClassDeclaration(functionDeclaration.parent)) return hasNameOrDefault(functionDeclaration.parent) && isSingleImplementation(functionDeclaration, checker); + else return isValidVariableDeclaration(functionDeclaration.parent.parent) && isSingleImplementation(functionDeclaration, checker); + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + return isValidVariableDeclaration(functionDeclaration.parent); } - return result; + return false; } - function forwardJSONCall(logger, actionDescription2, action, logPerformance) { - return forwardCall(logger, actionDescription2, /*returnJson*/ true, action, logPerformance); + function isSingleImplementation(functionDeclaration, checker) { + return !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); } - function forwardCall(logger, actionDescription2, returnJson, action, logPerformance) { - try { - const result = simpleForwardCall(logger, actionDescription2, action, logPerformance); - return returnJson ? JSON.stringify({ - result: result - }) : result; - } catch (err) { - if (err instanceof OperationCanceledException) return JSON.stringify({ - canceled: true - }); - logInternalError(logger, err); - err.description = actionDescription2; - return JSON.stringify({ - error: err - }); + function hasNameOrDefault(functionOrClassDeclaration) { + if (!functionOrClassDeclaration.name) { + const defaultKeyword = findModifier(functionOrClassDeclaration, 90 /* DefaultKeyword */ ); + return !!defaultKeyword; } + return true; } - function realizeDiagnostics(diagnostics, newLine) { - return diagnostics.map((d)=>realizeDiagnostic(d, newLine)); + function isValidParameterNodeArray(parameters, checker) { + return getRefactorableParametersLength(parameters) >= minimumParameterLength && every(parameters, /*callback*/ (paramDecl)=>isValidParameterDeclaration(paramDecl, checker)); } - function realizeDiagnostic(diagnostic, newLine) { - return { - message: flattenDiagnosticMessageText(diagnostic.messageText, newLine), - start: diagnostic.start, - // TODO: GH#18217 - length: diagnostic.length, - // TODO: GH#18217 - category: diagnosticCategoryName(diagnostic), - code: diagnostic.code, - reportsUnnecessary: diagnostic.reportsUnnecessary, - reportsDeprecated: diagnostic.reportsDeprecated - }; + function isValidParameterDeclaration(parameterDeclaration, checker) { + if (isRestParameter(parameterDeclaration)) { + const type = checker.getTypeAtLocation(parameterDeclaration); + if (!checker.isArrayType(type) && !checker.isTupleType(type)) return false; + } + return !parameterDeclaration.modifiers && isIdentifier(parameterDeclaration.name); } - function convertClassifications(classifications) { - return { - spans: classifications.spans.join(","), - endOfLineState: classifications.endOfLineState - }; + function isValidVariableDeclaration(node) { + return isVariableDeclaration(node) && isVarConst(node) && isIdentifier(node.name) && !node.type; } - var debugObjectHost, ScriptSnapshotShimAdapter, LanguageServiceShimHostAdapter, CoreServicesShimHostAdapter, ShimBase, LanguageServiceShimObject, ClassifierShimObject, CoreServicesShimObject, TypeScriptServicesFactory; - var init_shims = __esm({ - "src/services/shims.ts" () { - "use strict"; - init_ts4(); - debugObjectHost = function() { - return this; - }(); - ScriptSnapshotShimAdapter = class { - constructor(scriptSnapshotShim){ - this.scriptSnapshotShim = scriptSnapshotShim; - } - getText(start, end) { - return this.scriptSnapshotShim.getText(start, end); - } - getLength() { - return this.scriptSnapshotShim.getLength(); - } - getChangeRange(oldSnapshot) { - const oldSnapshotShim = oldSnapshot; - const encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim); - if (encoded === null) return null; - const decoded = JSON.parse(encoded); - return createTextChangeRange(createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength); - } - dispose() { - if ("dispose" in this.scriptSnapshotShim) this.scriptSnapshotShim.dispose(); - } - }; - LanguageServiceShimHostAdapter = class { - constructor(shimHost){ - this.shimHost = shimHost; - this.loggingEnabled = false; - this.tracingEnabled = false; - if ("getModuleResolutionsForFile" in this.shimHost) this.resolveModuleNames = (moduleNames, containingFile)=>{ - const resolutionsInFile = JSON.parse(this.shimHost.getModuleResolutionsForFile(containingFile)); - return map(moduleNames, (name)=>{ - const result = getProperty(resolutionsInFile, name); - return result ? { - resolvedFileName: result, - extension: extensionFromPath(result), - isExternalLibraryImport: false - } : void 0; - }); - }; - if ("directoryExists" in this.shimHost) this.directoryExists = (directoryName)=>this.shimHost.directoryExists(directoryName); - if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) this.resolveTypeReferenceDirectives = (typeDirectiveNames, containingFile)=>{ - const typeDirectivesForFile = JSON.parse(this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); - return map(typeDirectiveNames, (name)=>getProperty(typeDirectivesForFile, isString(name) ? name : toFileNameLowerCase(name.fileName))); - }; - } - log(s) { - if (this.loggingEnabled) this.shimHost.log(s); - } - trace(s) { - if (this.tracingEnabled) this.shimHost.trace(s); - } - error(s) { - this.shimHost.error(s); - } - getProjectVersion() { - if (!this.shimHost.getProjectVersion) return void 0; - return this.shimHost.getProjectVersion(); - } - getTypeRootsVersion() { - if (!this.shimHost.getTypeRootsVersion) return 0; - return this.shimHost.getTypeRootsVersion(); - } - useCaseSensitiveFileNames() { - return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; - } - getCompilationSettings() { - const settingsJson = this.shimHost.getCompilationSettings(); - if (settingsJson === null || settingsJson === "") throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings"); - const compilerOptions = JSON.parse(settingsJson); - compilerOptions.allowNonTsExtensions = true; - return compilerOptions; - } - getScriptFileNames() { - const encoded = this.shimHost.getScriptFileNames(); - return JSON.parse(encoded); - } - getScriptSnapshot(fileName) { - const scriptSnapshot = this.shimHost.getScriptSnapshot(fileName); - return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot); - } - getScriptKind(fileName) { - if ("getScriptKind" in this.shimHost) return this.shimHost.getScriptKind(fileName); - else return 0 /* Unknown */ ; - } - getScriptVersion(fileName) { - return this.shimHost.getScriptVersion(fileName); - } - getLocalizedDiagnosticMessages() { - const diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages(); - if (diagnosticMessagesJson === null || diagnosticMessagesJson === "") return null; - try { - return JSON.parse(diagnosticMessagesJson); - } catch (e) { - this.log(e.description || "diagnosticMessages.generated.json has invalid JSON format"); - return null; - } - } - getCancellationToken() { - const hostCancellationToken = this.shimHost.getCancellationToken(); - return new ThrottledCancellationToken(hostCancellationToken); - } - getCurrentDirectory() { - return this.shimHost.getCurrentDirectory(); - } - getDirectories(path) { - return JSON.parse(this.shimHost.getDirectories(path)); - } - getDefaultLibFileName(options) { - return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); - } - readDirectory(path, extensions, exclude, include, depth) { - const pattern = getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); - return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); - } - readFile(path, encoding) { - return this.shimHost.readFile(path, encoding); - } - fileExists(path) { - return this.shimHost.fileExists(path); + function hasThisParameter(parameters) { + return parameters.length > 0 && isThis(parameters[0].name); + } + function getRefactorableParametersLength(parameters) { + if (hasThisParameter(parameters)) return parameters.length - 1; + return parameters.length; + } + function getRefactorableParameters(parameters) { + if (hasThisParameter(parameters)) parameters = factory.createNodeArray(parameters.slice(1), parameters.hasTrailingComma); + return parameters; + } + function createPropertyOrShorthandAssignment(name, initializer) { + if (isIdentifier(initializer) && getTextOfIdentifierOrLiteral(initializer) === name) return factory.createShorthandPropertyAssignment(name); + return factory.createPropertyAssignment(name, initializer); + } + function createNewArgument(functionDeclaration, functionArguments) { + const parameters = getRefactorableParameters(functionDeclaration.parameters); + const hasRestParameter2 = isRestParameter(last(parameters)); + const nonRestArguments = hasRestParameter2 ? functionArguments.slice(0, parameters.length - 1) : functionArguments; + const properties = map(nonRestArguments, (arg, i)=>{ + const parameterName = getParameterName(parameters[i]); + const property = createPropertyOrShorthandAssignment(parameterName, arg); + suppressLeadingAndTrailingTrivia(property.name); + if (isPropertyAssignment(property)) suppressLeadingAndTrailingTrivia(property.initializer); + copyComments(arg, property); + return property; + }); + if (hasRestParameter2 && functionArguments.length >= parameters.length) { + const restArguments = functionArguments.slice(parameters.length - 1); + const restProperty = factory.createPropertyAssignment(getParameterName(last(parameters)), factory.createArrayLiteralExpression(restArguments)); + properties.push(restProperty); + } + const objectLiteral = factory.createObjectLiteralExpression(properties, /*multiLine*/ false); + return objectLiteral; + } + function createNewParameters(functionDeclaration, program, host) { + const checker = program.getTypeChecker(); + const refactorableParameters = getRefactorableParameters(functionDeclaration.parameters); + const bindingElements = map(refactorableParameters, createBindingElementFromParameterDeclaration); + const objectParameterName = factory.createObjectBindingPattern(bindingElements); + const objectParameterType = createParameterTypeNode(refactorableParameters); + let objectInitializer; + if (every(refactorableParameters, isOptionalParameter)) objectInitializer = factory.createObjectLiteralExpression(); + const objectParameter = factory.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, objectParameterName, /*questionToken*/ void 0, objectParameterType, objectInitializer); + if (hasThisParameter(functionDeclaration.parameters)) { + const thisParameter = functionDeclaration.parameters[0]; + const newThisParameter = factory.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, thisParameter.name, /*questionToken*/ void 0, thisParameter.type); + suppressLeadingAndTrailingTrivia(newThisParameter.name); + copyComments(thisParameter.name, newThisParameter.name); + if (thisParameter.type) { + suppressLeadingAndTrailingTrivia(newThisParameter.type); + copyComments(thisParameter.type, newThisParameter.type); + } + return factory.createNodeArray([ + newThisParameter, + objectParameter + ]); + } + return factory.createNodeArray([ + objectParameter + ]); + function createBindingElementFromParameterDeclaration(parameterDeclaration) { + const element = factory.createBindingElement(/*dotDotDotToken*/ void 0, /*propertyName*/ void 0, getParameterName(parameterDeclaration), isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? factory.createArrayLiteralExpression() : parameterDeclaration.initializer); + suppressLeadingAndTrailingTrivia(element); + if (parameterDeclaration.initializer && element.initializer) copyComments(parameterDeclaration.initializer, element.initializer); + return element; + } + function createParameterTypeNode(parameters) { + const members = map(parameters, createPropertySignatureFromParameterDeclaration); + const typeNode = addEmitFlags(factory.createTypeLiteralNode(members), 1 /* SingleLine */ ); + return typeNode; + } + function createPropertySignatureFromParameterDeclaration(parameterDeclaration) { + let parameterType = parameterDeclaration.type; + if (!parameterType && (parameterDeclaration.initializer || isRestParameter(parameterDeclaration))) parameterType = getTypeNode3(parameterDeclaration); + const propertySignature = factory.createPropertySignature(/*modifiers*/ void 0, getParameterName(parameterDeclaration), isOptionalParameter(parameterDeclaration) ? factory.createToken(58 /* QuestionToken */ ) : parameterDeclaration.questionToken, parameterType); + suppressLeadingAndTrailingTrivia(propertySignature); + copyComments(parameterDeclaration.name, propertySignature.name); + if (parameterDeclaration.type && propertySignature.type) copyComments(parameterDeclaration.type, propertySignature.type); + return propertySignature; + } + function getTypeNode3(node) { + const type = checker.getTypeAtLocation(node); + return getTypeNodeIfAccessible(type, node, program, host); + } + function isOptionalParameter(parameterDeclaration) { + if (isRestParameter(parameterDeclaration)) { + const type = checker.getTypeAtLocation(parameterDeclaration); + return !checker.isTupleType(type); + } + return checker.isOptionalParameter(parameterDeclaration); + } + } + function getParameterName(paramDeclaration) { + return getTextOfIdentifierOrLiteral(paramDeclaration.name); + } + function getClassNames(constructorDeclaration) { + switch(constructorDeclaration.parent.kind){ + case 263 /* ClassDeclaration */ : + const classDeclaration = constructorDeclaration.parent; + if (classDeclaration.name) return [ + classDeclaration.name + ]; + const defaultModifier = Debug.checkDefined(findModifier(classDeclaration, 90 /* DefaultKeyword */ ), "Nameless class declaration should be a default export"); + return [ + defaultModifier + ]; + case 231 /* ClassExpression */ : + const classExpression = constructorDeclaration.parent; + const variableDeclaration = constructorDeclaration.parent.parent; + const className = classExpression.name; + if (className) return [ + className, + variableDeclaration.name + ]; + return [ + variableDeclaration.name + ]; + } + } + function getFunctionNames(functionDeclaration) { + switch(functionDeclaration.kind){ + case 262 /* FunctionDeclaration */ : + if (functionDeclaration.name) return [ + functionDeclaration.name + ]; + const defaultModifier = Debug.checkDefined(findModifier(functionDeclaration, 90 /* DefaultKeyword */ ), "Nameless function declaration should be a default export"); + return [ + defaultModifier + ]; + case 174 /* MethodDeclaration */ : + return [ + functionDeclaration.name + ]; + case 176 /* Constructor */ : + const ctrKeyword = Debug.checkDefined(findChildOfKind(functionDeclaration, 137 /* ConstructorKeyword */ , functionDeclaration.getSourceFile()), "Constructor declaration should have constructor keyword"); + if (functionDeclaration.parent.kind === 231 /* ClassExpression */ ) { + const variableDeclaration = functionDeclaration.parent.parent; + return [ + variableDeclaration.name, + ctrKeyword + ]; } + return [ + ctrKeyword + ]; + case 219 /* ArrowFunction */ : + return [ + functionDeclaration.parent.name + ]; + case 218 /* FunctionExpression */ : + if (functionDeclaration.name) return [ + functionDeclaration.name, + functionDeclaration.parent.name + ]; + return [ + functionDeclaration.parent.name + ]; + default: + return Debug.assertNever(functionDeclaration, `Unexpected function declaration kind ${functionDeclaration.kind}`); + } + } + var refactorName9, minimumParameterLength, refactorDescription5, toDestructuredAction; + var init_convertParamsToDestructuredObject = __esm({ + "src/services/refactors/convertParamsToDestructuredObject.ts" () { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName9 = "Convert parameters to destructured object"; + minimumParameterLength = 1; + refactorDescription5 = getLocaleSpecificMessage(Diagnostics.Convert_parameters_to_destructured_object); + toDestructuredAction = { + name: refactorName9, + description: refactorDescription5, + kind: "refactor.rewrite.parameters.toDestructured" }; - CoreServicesShimHostAdapter = class { - constructor(shimHost){ - this.shimHost = shimHost; - this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; - if ("directoryExists" in this.shimHost) this.directoryExists = (directoryName)=>this.shimHost.directoryExists(directoryName); - else this.directoryExists = void 0; - if ("realpath" in this.shimHost) this.realpath = (path)=>this.shimHost.realpath(path); - else this.realpath = void 0; - } - readDirectory(rootDir, extensions, exclude, include, depth) { - const pattern = getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); - return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); - } - fileExists(fileName) { - return this.shimHost.fileExists(fileName); - } - readFile(fileName) { - return this.shimHost.readFile(fileName); - } - getDirectories(path) { - return JSON.parse(this.shimHost.getDirectories(path)); - } + registerRefactor(refactorName9, { + kinds: [ + toDestructuredAction.kind + ], + getEditsForAction: getRefactorEditsToConvertParametersToDestructuredObject, + getAvailableActions: getRefactorActionsToConvertParametersToDestructuredObject + }); + } + }); + // src/services/_namespaces/ts.refactor.convertParamsToDestructuredObject.ts + var ts_refactor_convertParamsToDestructuredObject_exports = {}; + var init_ts_refactor_convertParamsToDestructuredObject = __esm({ + "src/services/_namespaces/ts.refactor.convertParamsToDestructuredObject.ts" () { + "use strict"; + init_convertParamsToDestructuredObject(); + } + }); + // src/services/refactors/convertStringOrTemplateLiteral.ts + function getRefactorActionsToConvertToTemplateString(context) { + const { file: file, startPosition: startPosition } = context; + const node = getNodeOrParentOfParentheses(file, startPosition); + const maybeBinary = getParentBinaryExpression(node); + const refactorInfo = { + name: refactorName10, + description: refactorDescription6, + actions: [] + }; + if (isBinaryExpression(maybeBinary) && treeToArray(maybeBinary).isValidConcatenation) { + refactorInfo.actions.push(convertStringAction); + return [ + refactorInfo + ]; + } else if (context.preferences.provideRefactorNotApplicableReason) { + refactorInfo.actions.push({ + ...convertStringAction, + notApplicableReason: getLocaleSpecificMessage(Diagnostics.Can_only_convert_string_concatenation) + }); + return [ + refactorInfo + ]; + } + return emptyArray; + } + function getNodeOrParentOfParentheses(file, startPosition) { + const node = getTokenAtPosition(file, startPosition); + const nestedBinary = getParentBinaryExpression(node); + const isNonStringBinary = !treeToArray(nestedBinary).isValidConcatenation; + if (isNonStringBinary && isParenthesizedExpression(nestedBinary.parent) && isBinaryExpression(nestedBinary.parent.parent)) return nestedBinary.parent.parent; + return node; + } + function getRefactorEditsToConvertToTemplateString(context, actionName2) { + const { file: file, startPosition: startPosition } = context; + const node = getNodeOrParentOfParentheses(file, startPosition); + switch(actionName2){ + case refactorDescription6: + return { + edits: getEditsForToTemplateLiteral(context, node) + }; + default: + return Debug.fail("invalid action"); + } + } + function getEditsForToTemplateLiteral(context, node) { + const maybeBinary = getParentBinaryExpression(node); + const file = context.file; + const templateLiteral = nodesToTemplate(treeToArray(maybeBinary), file); + const trailingCommentRanges = getTrailingCommentRanges(file.text, maybeBinary.end); + if (trailingCommentRanges) { + const lastComment = trailingCommentRanges[trailingCommentRanges.length - 1]; + const trailingRange = { + pos: trailingCommentRanges[0].pos, + end: lastComment.end }; - ShimBase = class { - constructor(factory2){ - this.factory = factory2; - factory2.registerShim(this); - } - dispose(_dummy) { - this.factory.unregisterShim(this); - } + return ts_textChanges_exports.ChangeTracker.with(context, (t)=>{ + t.deleteRange(file, trailingRange); + t.replaceNode(file, maybeBinary, templateLiteral); + }); + } else return ts_textChanges_exports.ChangeTracker.with(context, (t)=>t.replaceNode(file, maybeBinary, templateLiteral)); + } + function isNotEqualsOperator(node) { + return !(node.operatorToken.kind === 64 /* EqualsToken */ || node.operatorToken.kind === 65 /* PlusEqualsToken */ ); + } + function getParentBinaryExpression(expr) { + const container = findAncestor(expr.parent, (n)=>{ + switch(n.kind){ + case 211 /* PropertyAccessExpression */ : + case 212 /* ElementAccessExpression */ : + return false; + case 228 /* TemplateExpression */ : + case 226 /* BinaryExpression */ : + return !(isBinaryExpression(n.parent) && isNotEqualsOperator(n.parent)); + default: + return "quit"; + } + }); + return container || expr; + } + function treeToArray(current) { + const loop = (current2)=>{ + if (!isBinaryExpression(current2)) return { + nodes: [ + current2 + ], + operators: [], + validOperators: true, + hasString: isStringLiteral(current2) || isNoSubstitutionTemplateLiteral(current2) }; - LanguageServiceShimObject = class extends ShimBase { - constructor(factory2, host, languageService){ - super(factory2); - this.host = host; - this.languageService = languageService; - this.logPerformance = false; - this.logger = this.host; - } - forwardJSONCall(actionDescription2, action) { - return forwardJSONCall(this.logger, actionDescription2, action, this.logPerformance); - } - /// DISPOSE - /** - * Ensure (almost) deterministic release of internal Javascript resources when - * some external native objects holds onto us (e.g. Com/Interop). - */ dispose(dummy) { - this.logger.log("dispose()"); - this.languageService.dispose(); - this.languageService = null; - if (debugObjectHost && debugObjectHost.CollectGarbage) { - debugObjectHost.CollectGarbage(); - this.logger.log("CollectGarbage()"); + const { nodes: nodes2, operators: operators2, hasString: leftHasString, validOperators: leftOperatorValid } = loop(current2.left); + if (!(leftHasString || isStringLiteral(current2.right) || isTemplateExpression(current2.right))) return { + nodes: [ + current2 + ], + operators: [], + hasString: false, + validOperators: true + }; + const currentOperatorValid = current2.operatorToken.kind === 40 /* PlusToken */ ; + const validOperators2 = leftOperatorValid && currentOperatorValid; + nodes2.push(current2.right); + operators2.push(current2.operatorToken); + return { + nodes: nodes2, + operators: operators2, + hasString: true, + validOperators: validOperators2 + }; + }; + const { nodes: nodes, operators: operators, validOperators: validOperators, hasString: hasString } = loop(current); + return { + nodes: nodes, + operators: operators, + isValidConcatenation: validOperators && hasString + }; + } + function escapeRawStringForTemplate(s) { + return s.replace(/\\.|[$`]/g, (m)=>m[0] === "\\" ? m : "\\" + m); + } + function getRawTextOfTemplate(node) { + const rightShaving = isTemplateHead(node) || isTemplateMiddle(node) ? -2 : -1; + return getTextOfNode(node).slice(1, rightShaving); + } + function concatConsecutiveString(index, nodes) { + const indexes = []; + let text = "", rawText = ""; + while(index < nodes.length){ + const node = nodes[index]; + if (isStringLiteralLike(node)) { + text += node.text; + rawText += escapeRawStringForTemplate(getTextOfNode(node).slice(1, -1)); + indexes.push(index); + index++; + } else if (isTemplateExpression(node)) { + text += node.head.text; + rawText += getRawTextOfTemplate(node.head); + break; + } else break; + } + return [ + index, + text, + rawText, + indexes + ]; + } + function nodesToTemplate({ nodes: nodes, operators: operators }, file) { + const copyOperatorComments = copyTrailingOperatorComments(operators, file); + const copyCommentFromStringLiterals = copyCommentFromMultiNode(nodes, file, copyOperatorComments); + const [begin, headText, rawHeadText, headIndexes] = concatConsecutiveString(0, nodes); + if (begin === nodes.length) { + const noSubstitutionTemplateLiteral = factory.createNoSubstitutionTemplateLiteral(headText, rawHeadText); + copyCommentFromStringLiterals(headIndexes, noSubstitutionTemplateLiteral); + return noSubstitutionTemplateLiteral; + } + const templateSpans = []; + const templateHead = factory.createTemplateHead(headText, rawHeadText); + copyCommentFromStringLiterals(headIndexes, templateHead); + for(let i = begin; i < nodes.length; i++){ + const currentNode = getExpressionFromParenthesesOrExpression(nodes[i]); + copyOperatorComments(i, currentNode); + const [newIndex, subsequentText, rawSubsequentText, stringIndexes] = concatConsecutiveString(i + 1, nodes); + i = newIndex - 1; + const isLast = i === nodes.length - 1; + if (isTemplateExpression(currentNode)) { + const spans = map(currentNode.templateSpans, (span, index)=>{ + copyExpressionComments(span); + const isLastSpan = index === currentNode.templateSpans.length - 1; + const text = span.literal.text + (isLastSpan ? subsequentText : ""); + const rawText = getRawTextOfTemplate(span.literal) + (isLastSpan ? rawSubsequentText : ""); + return factory.createTemplateSpan(span.expression, isLast && isLastSpan ? factory.createTemplateTail(text, rawText) : factory.createTemplateMiddle(text, rawText)); + }); + templateSpans.push(...spans); + } else { + const templatePart = isLast ? factory.createTemplateTail(subsequentText, rawSubsequentText) : factory.createTemplateMiddle(subsequentText, rawSubsequentText); + copyCommentFromStringLiterals(stringIndexes, templatePart); + templateSpans.push(factory.createTemplateSpan(currentNode, templatePart)); + } + } + return factory.createTemplateExpression(templateHead, templateSpans); + } + function copyExpressionComments(node) { + const file = node.getSourceFile(); + copyTrailingComments(node, node.expression, file, 3 /* MultiLineCommentTrivia */ , /*hasTrailingNewLine*/ false); + copyTrailingAsLeadingComments(node.expression, node.expression, file, 3 /* MultiLineCommentTrivia */ , /*hasTrailingNewLine*/ false); + } + function getExpressionFromParenthesesOrExpression(node) { + if (isParenthesizedExpression(node)) { + copyExpressionComments(node); + node = node.expression; + } + return node; + } + var refactorName10, refactorDescription6, convertStringAction, copyTrailingOperatorComments, copyCommentFromMultiNode; + var init_convertStringOrTemplateLiteral = __esm({ + "src/services/refactors/convertStringOrTemplateLiteral.ts" () { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName10 = "Convert to template string"; + refactorDescription6 = getLocaleSpecificMessage(Diagnostics.Convert_to_template_string); + convertStringAction = { + name: refactorName10, + description: refactorDescription6, + kind: "refactor.rewrite.string" + }; + registerRefactor(refactorName10, { + kinds: [ + convertStringAction.kind + ], + getEditsForAction: getRefactorEditsToConvertToTemplateString, + getAvailableActions: getRefactorActionsToConvertToTemplateString + }); + copyTrailingOperatorComments = (operators, file)=>(index, targetNode)=>{ + if (index < operators.length) copyTrailingComments(operators[index], targetNode, file, 3 /* MultiLineCommentTrivia */ , /*hasTrailingNewLine*/ false); + }; + copyCommentFromMultiNode = (nodes, file, copyOperatorComments)=>(indexes, targetNode)=>{ + while(indexes.length > 0){ + const index = indexes.shift(); + copyTrailingComments(nodes[index], targetNode, file, 3 /* MultiLineCommentTrivia */ , /*hasTrailingNewLine*/ false); + copyOperatorComments(index, targetNode); } - this.logger = null; - super.dispose(dummy); - } - /// REFRESH - /** - * Update the list of scripts known to the compiler - */ refresh(throwOnError) { - this.forwardJSONCall(`refresh(${throwOnError})`, ()=>null); - } - cleanupSemanticCache() { - this.forwardJSONCall("cleanupSemanticCache()", ()=>{ - this.languageService.cleanupSemanticCache(); - return null; - }); - } - realizeDiagnostics(diagnostics) { - const newLine = getNewLineOrDefaultFromHost(this.host, /*formatSettings*/ void 0); - return realizeDiagnostics(diagnostics, newLine); - } - getSyntacticClassifications(fileName, start, length2) { - return this.forwardJSONCall(`getSyntacticClassifications('${fileName}', ${start}, ${length2})`, ()=>this.languageService.getSyntacticClassifications(fileName, createTextSpan(start, length2))); - } - getSemanticClassifications(fileName, start, length2) { - return this.forwardJSONCall(`getSemanticClassifications('${fileName}', ${start}, ${length2})`, ()=>this.languageService.getSemanticClassifications(fileName, createTextSpan(start, length2))); + }; + } + }); + // src/services/_namespaces/ts.refactor.convertStringOrTemplateLiteral.ts + var ts_refactor_convertStringOrTemplateLiteral_exports = {}; + var init_ts_refactor_convertStringOrTemplateLiteral = __esm({ + "src/services/_namespaces/ts.refactor.convertStringOrTemplateLiteral.ts" () { + "use strict"; + init_convertStringOrTemplateLiteral(); + } + }); + // src/services/refactors/convertToOptionalChainExpression.ts + function getRefactorActionsToConvertToOptionalChain(context) { + const info = getInfo3(context, context.triggerReason === "invoked"); + if (!info) return emptyArray; + if (!isRefactorErrorInfo(info)) return [ + { + name: refactorName11, + description: convertToOptionalChainExpressionMessage, + actions: [ + toOptionalChainAction + ] + } + ]; + if (context.preferences.provideRefactorNotApplicableReason) return [ + { + name: refactorName11, + description: convertToOptionalChainExpressionMessage, + actions: [ + { + ...toOptionalChainAction, + notApplicableReason: info.error + } + ] + } + ]; + return emptyArray; + } + function getRefactorEditsToConvertToOptionalChain(context, actionName2) { + const info = getInfo3(context); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange6(context.file, context.program.getTypeChecker(), t, info, actionName2)); + return { + edits: edits, + renameFilename: void 0, + renameLocation: void 0 + }; + } + function isValidExpression(node) { + return isBinaryExpression(node) || isConditionalExpression(node); + } + function isValidStatement(node) { + return isExpressionStatement(node) || isReturnStatement(node) || isVariableStatement(node); + } + function isValidExpressionOrStatement(node) { + return isValidExpression(node) || isValidStatement(node); + } + function getInfo3(context, considerEmptySpans = true) { + const { file: file, program: program } = context; + const span = getRefactorContextSpan(context); + const forEmptySpan = span.length === 0; + if (forEmptySpan && !considerEmptySpans) return void 0; + const startToken = getTokenAtPosition(file, span.start); + const endToken = findTokenOnLeftOfPosition(file, span.start + span.length); + const adjustedSpan = createTextSpanFromBounds(startToken.pos, endToken && endToken.end >= startToken.pos ? endToken.getEnd() : startToken.getEnd()); + const parent2 = forEmptySpan ? getValidParentNodeOfEmptySpan(startToken) : getValidParentNodeContainingSpan(startToken, adjustedSpan); + const expression = parent2 && isValidExpressionOrStatement(parent2) ? getExpression(parent2) : void 0; + if (!expression) return { + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) + }; + const checker = program.getTypeChecker(); + return isConditionalExpression(expression) ? getConditionalInfo(expression, checker) : getBinaryInfo(expression); + } + function getConditionalInfo(expression, checker) { + const condition = expression.condition; + const finalExpression = getFinalExpressionInChain(expression.whenTrue); + if (!finalExpression || checker.isNullableType(checker.getTypeAtLocation(finalExpression))) return { + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) + }; + if ((isPropertyAccessExpression(condition) || isIdentifier(condition)) && getMatchingStart(condition, finalExpression.expression)) return { + finalExpression: finalExpression, + occurrences: [ + condition + ], + expression: expression + }; + else if (isBinaryExpression(condition)) { + const occurrences = getOccurrencesInExpression(finalExpression.expression, condition); + return occurrences ? { + finalExpression: finalExpression, + occurrences: occurrences, + expression: expression + } : { + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) + }; + } + } + function getBinaryInfo(expression) { + if (expression.operatorToken.kind !== 56 /* AmpersandAmpersandToken */ ) return { + error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_logical_AND_access_chains) + }; + const finalExpression = getFinalExpressionInChain(expression.right); + if (!finalExpression) return { + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) + }; + const occurrences = getOccurrencesInExpression(finalExpression.expression, expression.left); + return occurrences ? { + finalExpression: finalExpression, + occurrences: occurrences, + expression: expression + } : { + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) + }; + } + function getOccurrencesInExpression(matchTo, expression) { + const occurrences = []; + while(isBinaryExpression(expression) && expression.operatorToken.kind === 56 /* AmpersandAmpersandToken */ ){ + const match = getMatchingStart(skipParentheses(matchTo), skipParentheses(expression.right)); + if (!match) break; + occurrences.push(match); + matchTo = match; + expression = expression.left; + } + const finalMatch = getMatchingStart(matchTo, expression); + if (finalMatch) occurrences.push(finalMatch); + return occurrences.length > 0 ? occurrences : void 0; + } + function getMatchingStart(chain, subchain) { + if (!isIdentifier(subchain) && !isPropertyAccessExpression(subchain) && !isElementAccessExpression(subchain)) return void 0; + return chainStartsWith(chain, subchain) ? subchain : void 0; + } + function chainStartsWith(chain, subchain) { + while(isCallExpression(chain) || isPropertyAccessExpression(chain) || isElementAccessExpression(chain)){ + if (getTextOfChainNode(chain) === getTextOfChainNode(subchain)) break; + chain = chain.expression; + } + while(isPropertyAccessExpression(chain) && isPropertyAccessExpression(subchain) || isElementAccessExpression(chain) && isElementAccessExpression(subchain)){ + if (getTextOfChainNode(chain) !== getTextOfChainNode(subchain)) return false; + chain = chain.expression; + subchain = subchain.expression; + } + return isIdentifier(chain) && isIdentifier(subchain) && chain.getText() === subchain.getText(); + } + function getTextOfChainNode(node) { + if (isIdentifier(node) || isStringOrNumericLiteralLike(node)) return node.getText(); + if (isPropertyAccessExpression(node)) return getTextOfChainNode(node.name); + if (isElementAccessExpression(node)) return getTextOfChainNode(node.argumentExpression); + return void 0; + } + function getValidParentNodeContainingSpan(node, span) { + while(node.parent){ + if (isValidExpressionOrStatement(node) && span.length !== 0 && node.end >= span.start + span.length) return node; + node = node.parent; + } + return void 0; + } + function getValidParentNodeOfEmptySpan(node) { + while(node.parent){ + if (isValidExpressionOrStatement(node) && !isValidExpressionOrStatement(node.parent)) return node; + node = node.parent; + } + return void 0; + } + function getExpression(node) { + if (isValidExpression(node)) return node; + if (isVariableStatement(node)) { + const variable = getSingleVariableOfVariableStatement(node); + const initializer = variable == null ? void 0 : variable.initializer; + return initializer && isValidExpression(initializer) ? initializer : void 0; + } + return node.expression && isValidExpression(node.expression) ? node.expression : void 0; + } + function getFinalExpressionInChain(node) { + node = skipParentheses(node); + if (isBinaryExpression(node)) return getFinalExpressionInChain(node.left); + else if ((isPropertyAccessExpression(node) || isElementAccessExpression(node) || isCallExpression(node)) && !isOptionalChain(node)) return node; + return void 0; + } + function convertOccurrences(checker, toConvert, occurrences) { + if (isPropertyAccessExpression(toConvert) || isElementAccessExpression(toConvert) || isCallExpression(toConvert)) { + const chain = convertOccurrences(checker, toConvert.expression, occurrences); + const lastOccurrence = occurrences.length > 0 ? occurrences[occurrences.length - 1] : void 0; + const isOccurrence = (lastOccurrence == null ? void 0 : lastOccurrence.getText()) === toConvert.expression.getText(); + if (isOccurrence) occurrences.pop(); + if (isCallExpression(toConvert)) return isOccurrence ? factory.createCallChain(chain, factory.createToken(29 /* QuestionDotToken */ ), toConvert.typeArguments, toConvert.arguments) : factory.createCallChain(chain, toConvert.questionDotToken, toConvert.typeArguments, toConvert.arguments); + else if (isPropertyAccessExpression(toConvert)) return isOccurrence ? factory.createPropertyAccessChain(chain, factory.createToken(29 /* QuestionDotToken */ ), toConvert.name) : factory.createPropertyAccessChain(chain, toConvert.questionDotToken, toConvert.name); + else if (isElementAccessExpression(toConvert)) return isOccurrence ? factory.createElementAccessChain(chain, factory.createToken(29 /* QuestionDotToken */ ), toConvert.argumentExpression) : factory.createElementAccessChain(chain, toConvert.questionDotToken, toConvert.argumentExpression); + } + return toConvert; + } + function doChange6(sourceFile, checker, changes, info, _actionName) { + const { finalExpression: finalExpression, occurrences: occurrences, expression: expression } = info; + const firstOccurrence = occurrences[occurrences.length - 1]; + const convertedChain = convertOccurrences(checker, finalExpression, occurrences); + if (convertedChain && (isPropertyAccessExpression(convertedChain) || isElementAccessExpression(convertedChain) || isCallExpression(convertedChain))) { + if (isBinaryExpression(expression)) changes.replaceNodeRange(sourceFile, firstOccurrence, finalExpression, convertedChain); + else if (isConditionalExpression(expression)) changes.replaceNode(sourceFile, expression, factory.createBinaryExpression(convertedChain, factory.createToken(61 /* QuestionQuestionToken */ ), expression.whenFalse)); + } + } + var refactorName11, convertToOptionalChainExpressionMessage, toOptionalChainAction; + var init_convertToOptionalChainExpression = __esm({ + "src/services/refactors/convertToOptionalChainExpression.ts" () { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName11 = "Convert to optional chain expression"; + convertToOptionalChainExpressionMessage = getLocaleSpecificMessage(Diagnostics.Convert_to_optional_chain_expression); + toOptionalChainAction = { + name: refactorName11, + description: convertToOptionalChainExpressionMessage, + kind: "refactor.rewrite.expression.optionalChain" + }; + registerRefactor(refactorName11, { + kinds: [ + toOptionalChainAction.kind + ], + getEditsForAction: getRefactorEditsToConvertToOptionalChain, + getAvailableActions: getRefactorActionsToConvertToOptionalChain + }); + } + }); + // src/services/_namespaces/ts.refactor.convertToOptionalChainExpression.ts + var ts_refactor_convertToOptionalChainExpression_exports = {}; + var init_ts_refactor_convertToOptionalChainExpression = __esm({ + "src/services/_namespaces/ts.refactor.convertToOptionalChainExpression.ts" () { + "use strict"; + init_convertToOptionalChainExpression(); + } + }); + // src/services/refactors/extractSymbol.ts + function getRefactorActionsToExtractSymbol(context) { + const requestedRefactor = context.kind; + const rangeToExtract = getRangeToExtract2(context.file, getRefactorContextSpan(context), context.triggerReason === "invoked"); + const targetRange = rangeToExtract.targetRange; + if (targetRange === void 0) { + if (!rangeToExtract.errors || rangeToExtract.errors.length === 0 || !context.preferences.provideRefactorNotApplicableReason) return emptyArray; + const errors = []; + if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) errors.push({ + name: refactorName12, + description: extractFunctionAction.description, + actions: [ + { + ...extractFunctionAction, + notApplicableReason: getStringError(rangeToExtract.errors) + } + ] + }); + if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) errors.push({ + name: refactorName12, + description: extractConstantAction.description, + actions: [ + { + ...extractConstantAction, + notApplicableReason: getStringError(rangeToExtract.errors) + } + ] + }); + return errors; + } + const extractions = getPossibleExtractions(targetRange, context); + if (extractions === void 0) return emptyArray; + const functionActions = []; + const usedFunctionNames = /* @__PURE__ */ new Map(); + let innermostErrorFunctionAction; + const constantActions = []; + const usedConstantNames = /* @__PURE__ */ new Map(); + let innermostErrorConstantAction; + let i = 0; + for (const { functionExtraction: functionExtraction, constantExtraction: constantExtraction } of extractions){ + if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) { + const description3 = functionExtraction.description; + if (functionExtraction.errors.length === 0) { + if (!usedFunctionNames.has(description3)) { + usedFunctionNames.set(description3, true); + functionActions.push({ + description: description3, + name: `function_scope_${i}`, + kind: extractFunctionAction.kind + }); + } + } else if (!innermostErrorFunctionAction) innermostErrorFunctionAction = { + description: description3, + name: `function_scope_${i}`, + notApplicableReason: getStringError(functionExtraction.errors), + kind: extractFunctionAction.kind + }; + } + if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { + const description3 = constantExtraction.description; + if (constantExtraction.errors.length === 0) { + if (!usedConstantNames.has(description3)) { + usedConstantNames.set(description3, true); + constantActions.push({ + description: description3, + name: `constant_scope_${i}`, + kind: extractConstantAction.kind + }); + } + } else if (!innermostErrorConstantAction) innermostErrorConstantAction = { + description: description3, + name: `constant_scope_${i}`, + notApplicableReason: getStringError(constantExtraction.errors), + kind: extractConstantAction.kind + }; + } + i++; + } + const infos = []; + if (functionActions.length) infos.push({ + name: refactorName12, + description: getLocaleSpecificMessage(Diagnostics.Extract_function), + actions: functionActions + }); + else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorFunctionAction) infos.push({ + name: refactorName12, + description: getLocaleSpecificMessage(Diagnostics.Extract_function), + actions: [ + innermostErrorFunctionAction + ] + }); + if (constantActions.length) infos.push({ + name: refactorName12, + description: getLocaleSpecificMessage(Diagnostics.Extract_constant), + actions: constantActions + }); + else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorConstantAction) infos.push({ + name: refactorName12, + description: getLocaleSpecificMessage(Diagnostics.Extract_constant), + actions: [ + innermostErrorConstantAction + ] + }); + return infos.length ? infos : emptyArray; + function getStringError(errors) { + let error2 = errors[0].messageText; + if (typeof error2 !== "string") error2 = error2.messageText; + return error2; + } + } + function getRefactorEditsToExtractSymbol(context, actionName2) { + const rangeToExtract = getRangeToExtract2(context.file, getRefactorContextSpan(context)); + const targetRange = rangeToExtract.targetRange; + const parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName2); + if (parsedFunctionIndexMatch) { + const index = +parsedFunctionIndexMatch[1]; + Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index"); + return getFunctionExtractionAtIndex(targetRange, context, index); + } + const parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName2); + if (parsedConstantIndexMatch) { + const index = +parsedConstantIndexMatch[1]; + Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index"); + return getConstantExtractionAtIndex(targetRange, context, index); + } + Debug.fail("Unrecognized action name"); + } + function getRangeToExtract2(sourceFile, span, invoked = true) { + const { length: length2 } = span; + if (length2 === 0 && !invoked) return { + errors: [ + createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractEmpty) + ] + }; + const cursorRequest = length2 === 0 && invoked; + const startToken = findFirstNonJsxWhitespaceToken(sourceFile, span.start); + const endToken = findTokenOnLeftOfPosition(sourceFile, textSpanEnd(span)); + const adjustedSpan = startToken && endToken && invoked ? getAdjustedSpanFromNodes(startToken, endToken, sourceFile) : span; + const start = cursorRequest ? getExtractableParent(startToken) : getParentNodeInSpan(startToken, sourceFile, adjustedSpan); + const end = cursorRequest ? start : getParentNodeInSpan(endToken, sourceFile, adjustedSpan); + let rangeFacts = 0 /* None */ ; + let thisNode; + if (!start || !end) return { + errors: [ + createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange) + ] + }; + if (start.flags & 16777216 /* JSDoc */ ) return { + errors: [ + createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractJSDoc) + ] + }; + if (start.parent !== end.parent) return { + errors: [ + createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange) + ] + }; + if (start !== end) { + if (!isBlockLike(start.parent)) return { + errors: [ + createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange) + ] + }; + const statements = []; + for (const statement of start.parent.statements){ + if (statement === start || statements.length) { + const errors2 = checkNode(statement); + if (errors2) return { + errors: errors2 + }; + statements.push(statement); } - getEncodedSyntacticClassifications(fileName, start, length2) { - return this.forwardJSONCall(`getEncodedSyntacticClassifications('${fileName}', ${start}, ${length2})`, // directly serialize the spans out to a string. This is much faster to decode - // on the managed side versus a full JSON array. - ()=>convertClassifications(this.languageService.getEncodedSyntacticClassifications(fileName, createTextSpan(start, length2)))); + if (statement === end) break; + } + if (!statements.length) return { + errors: [ + createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange) + ] + }; + return { + targetRange: { + range: statements, + facts: rangeFacts, + thisNode: thisNode } - getEncodedSemanticClassifications(fileName, start, length2) { - return this.forwardJSONCall(`getEncodedSemanticClassifications('${fileName}', ${start}, ${length2})`, // directly serialize the spans out to a string. This is much faster to decode - // on the managed side versus a full JSON array. - ()=>convertClassifications(this.languageService.getEncodedSemanticClassifications(fileName, createTextSpan(start, length2)))); + }; + } + if (isReturnStatement(start) && !start.expression) return { + errors: [ + createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange) + ] + }; + const node = refineNode(start); + const errors = checkRootNode(node) || checkNode(node); + if (errors) return { + errors: errors + }; + return { + targetRange: { + range: getStatementOrExpressionRange(node), + facts: rangeFacts, + thisNode: thisNode + } + }; + function refineNode(node2) { + if (isReturnStatement(node2)) { + if (node2.expression) return node2.expression; + } else if (isVariableStatement(node2) || isVariableDeclarationList(node2)) { + const declarations = isVariableStatement(node2) ? node2.declarationList.declarations : node2.declarations; + let numInitializers = 0; + let lastInitializer; + for (const declaration of declarations)if (declaration.initializer) { + numInitializers++; + lastInitializer = declaration.initializer; } - getSyntacticDiagnostics(fileName) { - return this.forwardJSONCall(`getSyntacticDiagnostics('${fileName}')`, ()=>{ - const diagnostics = this.languageService.getSyntacticDiagnostics(fileName); - return this.realizeDiagnostics(diagnostics); - }); + if (numInitializers === 1) return lastInitializer; + } else if (isVariableDeclaration(node2)) { + if (node2.initializer) return node2.initializer; + } + return node2; + } + function checkRootNode(node2) { + if (isIdentifier(isExpressionStatement(node2) ? node2.expression : node2)) return [ + createDiagnosticForNode(node2, Messages.cannotExtractIdentifier) + ]; + return void 0; + } + function checkForStaticContext(nodeToCheck, containingClass) { + let current = nodeToCheck; + while(current !== containingClass){ + if (current.kind === 172 /* PropertyDeclaration */ ) { + if (isStatic(current)) rangeFacts |= 32 /* InStaticRegion */ ; + break; + } else if (current.kind === 169 /* Parameter */ ) { + const ctorOrMethod = getContainingFunction(current); + if (ctorOrMethod.kind === 176 /* Constructor */ ) rangeFacts |= 32 /* InStaticRegion */ ; + break; + } else if (current.kind === 174 /* MethodDeclaration */ ) { + if (isStatic(current)) rangeFacts |= 32 /* InStaticRegion */ ; } - getSemanticDiagnostics(fileName) { - return this.forwardJSONCall(`getSemanticDiagnostics('${fileName}')`, ()=>{ - const diagnostics = this.languageService.getSemanticDiagnostics(fileName); - return this.realizeDiagnostics(diagnostics); - }); + current = current.parent; + } + } + function checkNode(nodeToCheck) { + let PermittedJumps; + ((PermittedJumps2)=>{ + PermittedJumps2[PermittedJumps2["None"] = 0] = "None"; + PermittedJumps2[PermittedJumps2["Break"] = 1] = "Break"; + PermittedJumps2[PermittedJumps2["Continue"] = 2] = "Continue"; + PermittedJumps2[PermittedJumps2["Return"] = 4] = "Return"; + })(PermittedJumps || (PermittedJumps = {})); + Debug.assert(nodeToCheck.pos <= nodeToCheck.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (1)"); + Debug.assert(!positionIsSynthesized(nodeToCheck.pos), "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (2)"); + if (!isStatement(nodeToCheck) && !(isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck)) && !isStringLiteralJsxAttribute(nodeToCheck)) return [ + createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected) + ]; + if (nodeToCheck.flags & 33554432 /* Ambient */ ) return [ + createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock) + ]; + const containingClass = getContainingClass(nodeToCheck); + if (containingClass) checkForStaticContext(nodeToCheck, containingClass); + let errors2; + let permittedJumps = 4 /* Return */ ; + let seenLabels; + visit(nodeToCheck); + if (rangeFacts & 8 /* UsesThis */ ) { + const container = getThisContainer(nodeToCheck, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false); + if (container.kind === 262 /* FunctionDeclaration */ || container.kind === 174 /* MethodDeclaration */ && container.parent.kind === 210 /* ObjectLiteralExpression */ || container.kind === 218 /* FunctionExpression */ ) rangeFacts |= 16 /* UsesThisInFunction */ ; + } + return errors2; + function visit(node2) { + if (errors2) return true; + if (isDeclaration(node2)) { + const declaringNode = node2.kind === 260 /* VariableDeclaration */ ? node2.parent.parent : node2; + if (hasSyntacticModifier(declaringNode, 1 /* Export */ )) { + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractExportedEntity)); + return true; + } } - getSuggestionDiagnostics(fileName) { - return this.forwardJSONCall(`getSuggestionDiagnostics('${fileName}')`, ()=>this.realizeDiagnostics(this.languageService.getSuggestionDiagnostics(fileName))); + switch(node2.kind){ + case 272 /* ImportDeclaration */ : + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractImport)); + return true; + case 277 /* ExportAssignment */ : + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractExportedEntity)); + return true; + case 108 /* SuperKeyword */ : + if (node2.parent.kind === 213 /* CallExpression */ ) { + const containingClass2 = getContainingClass(node2); + if (containingClass2 === void 0 || containingClass2.pos < span.start || containingClass2.end >= span.start + span.length) { + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractSuper)); + return true; + } + } else { + rangeFacts |= 8 /* UsesThis */ ; + thisNode = node2; + } + break; + case 219 /* ArrowFunction */ : + forEachChild(node2, function check(n) { + if (isThis(n)) { + rangeFacts |= 8 /* UsesThis */ ; + thisNode = node2; + } else if (isClassLike(n) || isFunctionLike(n) && !isArrowFunction(n)) return false; + else forEachChild(n, check); + }); + case 263 /* ClassDeclaration */ : + case 262 /* FunctionDeclaration */ : + if (isSourceFile(node2.parent) && node2.parent.externalModuleIndicator === void 0) (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.functionWillNotBeVisibleInTheNewScope)); + case 231 /* ClassExpression */ : + case 218 /* FunctionExpression */ : + case 174 /* MethodDeclaration */ : + case 176 /* Constructor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + return false; } - getCompilerOptionsDiagnostics() { - return this.forwardJSONCall("getCompilerOptionsDiagnostics()", ()=>{ - const diagnostics = this.languageService.getCompilerOptionsDiagnostics(); - return this.realizeDiagnostics(diagnostics); - }); - } - /// QUICKINFO - /** - * Computes a string representation of the type at the requested position - * in the active file. - */ getQuickInfoAtPosition(fileName, position) { - return this.forwardJSONCall(`getQuickInfoAtPosition('${fileName}', ${position})`, ()=>this.languageService.getQuickInfoAtPosition(fileName, position)); - } - /// NAMEORDOTTEDNAMESPAN - /** - * Computes span information of the name or dotted name at the requested position - * in the active file. - */ getNameOrDottedNameSpan(fileName, startPos, endPos) { - return this.forwardJSONCall(`getNameOrDottedNameSpan('${fileName}', ${startPos}, ${endPos})`, ()=>this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos)); - } - /** - * STATEMENTSPAN - * Computes span information of statement at the requested position in the active file. - */ getBreakpointStatementAtPosition(fileName, position) { - return this.forwardJSONCall(`getBreakpointStatementAtPosition('${fileName}', ${position})`, ()=>this.languageService.getBreakpointStatementAtPosition(fileName, position)); - } - /// SIGNATUREHELP - getSignatureHelpItems(fileName, position, options) { - return this.forwardJSONCall(`getSignatureHelpItems('${fileName}', ${position})`, ()=>this.languageService.getSignatureHelpItems(fileName, position, options)); - } - /// GOTO DEFINITION - /** - * Computes the definition location and file for the symbol - * at the requested position. - */ getDefinitionAtPosition(fileName, position) { - return this.forwardJSONCall(`getDefinitionAtPosition('${fileName}', ${position})`, ()=>this.languageService.getDefinitionAtPosition(fileName, position)); + const savedPermittedJumps = permittedJumps; + switch(node2.kind){ + case 245 /* IfStatement */ : + permittedJumps &= -5 /* Return */ ; + break; + case 258 /* TryStatement */ : + permittedJumps = 0 /* None */ ; + break; + case 241 /* Block */ : + if (node2.parent && node2.parent.kind === 258 /* TryStatement */ && node2.parent.finallyBlock === node2) permittedJumps = 4 /* Return */ ; + break; + case 297 /* DefaultClause */ : + case 296 /* CaseClause */ : + permittedJumps |= 1 /* Break */ ; + break; + default: + if (isIterationStatement(node2, /*lookInLabeledStatements*/ false)) permittedJumps |= 3 /* Continue */ ; + break; } - /** - * Computes the definition location and file for the symbol - * at the requested position. - */ getDefinitionAndBoundSpan(fileName, position) { - return this.forwardJSONCall(`getDefinitionAndBoundSpan('${fileName}', ${position})`, ()=>this.languageService.getDefinitionAndBoundSpan(fileName, position)); + switch(node2.kind){ + case 197 /* ThisType */ : + case 110 /* ThisKeyword */ : + rangeFacts |= 8 /* UsesThis */ ; + thisNode = node2; + break; + case 256 /* LabeledStatement */ : + { + const label = node2.label; + (seenLabels || (seenLabels = [])).push(label.escapedText); + forEachChild(node2, visit); + seenLabels.pop(); + break; + } + case 252 /* BreakStatement */ : + case 251 /* ContinueStatement */ : + { + const label = node2.label; + if (label) { + if (!contains(seenLabels, label.escapedText)) (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); + } else if (!(permittedJumps & (node2.kind === 252 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */ ))) (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); + break; + } + case 223 /* AwaitExpression */ : + rangeFacts |= 4 /* IsAsyncFunction */ ; + break; + case 229 /* YieldExpression */ : + rangeFacts |= 2 /* IsGenerator */ ; + break; + case 253 /* ReturnStatement */ : + if (permittedJumps & 4 /* Return */ ) rangeFacts |= 1 /* HasReturn */ ; + else (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingConditionalReturnStatement)); + break; + default: + forEachChild(node2, visit); + break; } - /// GOTO Type - /** - * Computes the definition location of the type of the symbol - * at the requested position. - */ getTypeDefinitionAtPosition(fileName, position) { - return this.forwardJSONCall(`getTypeDefinitionAtPosition('${fileName}', ${position})`, ()=>this.languageService.getTypeDefinitionAtPosition(fileName, position)); + permittedJumps = savedPermittedJumps; + } + } + } + function getAdjustedSpanFromNodes(startNode2, endNode2, sourceFile) { + const start = startNode2.getStart(sourceFile); + let end = endNode2.getEnd(); + if (sourceFile.text.charCodeAt(end) === 59 /* semicolon */ ) end++; + return { + start: start, + length: end - start + }; + } + function getStatementOrExpressionRange(node) { + if (isStatement(node)) return [ + node + ]; + if (isExpressionNode(node)) return isExpressionStatement(node.parent) ? [ + node.parent + ] : node; + if (isStringLiteralJsxAttribute(node)) return node; + return void 0; + } + function isScope(node) { + return isArrowFunction(node) ? isFunctionBody(node.body) : isFunctionLikeDeclaration(node) || isSourceFile(node) || isModuleBlock(node) || isClassLike(node); + } + function collectEnclosingScopes(range) { + let current = isReadonlyArray(range.range) ? first(range.range) : range.range; + if (range.facts & 8 /* UsesThis */ && !(range.facts & 16 /* UsesThisInFunction */ )) { + const containingClass = getContainingClass(current); + if (containingClass) { + const containingFunction = findAncestor(current, isFunctionLikeDeclaration); + return containingFunction ? [ + containingFunction, + containingClass + ] : [ + containingClass + ]; + } + } + const scopes = []; + while(true){ + current = current.parent; + if (current.kind === 169 /* Parameter */ ) current = findAncestor(current, (parent2)=>isFunctionLikeDeclaration(parent2)).parent; + if (isScope(current)) { + scopes.push(current); + if (current.kind === 312 /* SourceFile */ ) return scopes; + } + } + } + function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { + const { scopes: scopes, readsAndWrites: { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context); + Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + context.cancellationToken.throwIfCancellationRequested(); + return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); + } + function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { + const { scopes: scopes, readsAndWrites: { target: target, usagesPerScope: usagesPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context); + Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?"); + context.cancellationToken.throwIfCancellationRequested(); + const expression = isExpression(target) ? target : target.statements[0].expression; + return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context); + } + function getPossibleExtractions(targetRange, context) { + const { scopes: scopes, readsAndWrites: { functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope } } = getPossibleExtractionsWorker(targetRange, context); + const extractions = scopes.map((scope, i)=>{ + const functionDescriptionPart = getDescriptionForFunctionInScope(scope); + const constantDescriptionPart = getDescriptionForConstantInScope(scope); + const scopeDescription = isFunctionLikeDeclaration(scope) ? getDescriptionForFunctionLikeDeclaration(scope) : isClassLike(scope) ? getDescriptionForClassLikeDeclaration(scope) : getDescriptionForModuleLikeDeclaration(scope); + let functionDescription; + let constantDescription; + if (scopeDescription === 1 /* Global */ ) { + functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [ + functionDescriptionPart, + "global" + ]); + constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [ + constantDescriptionPart, + "global" + ]); + } else if (scopeDescription === 0 /* Module */ ) { + functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [ + functionDescriptionPart, + "module" + ]); + constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [ + constantDescriptionPart, + "module" + ]); + } else { + functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1), [ + functionDescriptionPart, + scopeDescription + ]); + constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1), [ + constantDescriptionPart, + scopeDescription + ]); + } + if (i === 0 && !isClassLike(scope)) constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_enclosing_scope), [ + constantDescriptionPart + ]); + return { + functionExtraction: { + description: functionDescription, + errors: functionErrorsPerScope[i] + }, + constantExtraction: { + description: constantDescription, + errors: constantErrorsPerScope[i] } - /// GOTO Implementation - /** - * Computes the implementation location of the symbol - * at the requested position. - */ getImplementationAtPosition(fileName, position) { - return this.forwardJSONCall(`getImplementationAtPosition('${fileName}', ${position})`, ()=>this.languageService.getImplementationAtPosition(fileName, position)); + }; + }); + return extractions; + } + function getPossibleExtractionsWorker(targetRange, context) { + const { file: sourceFile } = context; + const scopes = collectEnclosingScopes(targetRange); + const enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); + const readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken); + return { + scopes: scopes, + readsAndWrites: readsAndWrites + }; + } + function getDescriptionForFunctionInScope(scope) { + return isFunctionLikeDeclaration(scope) ? "inner function" : isClassLike(scope) ? "method" : "function"; + } + function getDescriptionForConstantInScope(scope) { + return isClassLike(scope) ? "readonly field" : "constant"; + } + function getDescriptionForFunctionLikeDeclaration(scope) { + switch(scope.kind){ + case 176 /* Constructor */ : + return "constructor"; + case 218 /* FunctionExpression */ : + case 262 /* FunctionDeclaration */ : + return scope.name ? `function '${scope.name.text}'` : ANONYMOUS; + case 219 /* ArrowFunction */ : + return "arrow function"; + case 174 /* MethodDeclaration */ : + return `method '${scope.name.getText()}'`; + case 177 /* GetAccessor */ : + return `'get ${scope.name.getText()}'`; + case 178 /* SetAccessor */ : + return `'set ${scope.name.getText()}'`; + default: + Debug.assertNever(scope, `Unexpected scope kind ${scope.kind}`); + } + } + function getDescriptionForClassLikeDeclaration(scope) { + return scope.kind === 263 /* ClassDeclaration */ ? scope.name ? `class '${scope.name.text}'` : "anonymous class declaration" : scope.name ? `class expression '${scope.name.text}'` : "anonymous class expression"; + } + function getDescriptionForModuleLikeDeclaration(scope) { + return scope.kind === 268 /* ModuleBlock */ ? `namespace '${scope.parent.name.getText()}'` : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */ ; + } + function extractFunctionInScope(node, scope, { usages: usagesInScope, typeParameterUsages: typeParameterUsages, substitutions: substitutions }, exposedVariableDeclarations, range, context) { + const checker = context.program.getTypeChecker(); + const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions()); + const importAdder = ts_codefix_exports.createImportAdder(context.file, context.program, context.preferences, context.host); + const file = scope.getSourceFile(); + const functionNameText = getUniqueName(isClassLike(scope) ? "newMethod" : "newFunction", file); + const isJS = isInJSFile(scope); + const functionName = factory.createIdentifier(functionNameText); + let returnType; + const parameters = []; + const callArguments = []; + let writes; + usagesInScope.forEach((usage, name)=>{ + let typeNode; + if (!isJS) { + let type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); + type = checker.getBaseTypeOfLiteralType(type); + typeNode = ts_codefix_exports.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NoTruncation */ ); + } + const paramDecl = factory.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, /*name*/ name, /*questionToken*/ void 0, typeNode); + parameters.push(paramDecl); + if (usage.usage === 2 /* Write */ ) (writes || (writes = [])).push(usage); + callArguments.push(factory.createIdentifier(name)); + }); + const typeParametersAndDeclarations = arrayFrom(typeParameterUsages.values(), (type)=>({ + type: type, + declaration: getFirstDeclarationBeforePosition(type, context.startPosition) + })); + const sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); + const typeParameters = sortedTypeParametersAndDeclarations.length === 0 ? void 0 : mapDefined(sortedTypeParametersAndDeclarations, ({ declaration: declaration })=>declaration); + const callTypeArguments = typeParameters !== void 0 ? typeParameters.map((decl)=>factory.createTypeReferenceNode(decl.name, /*typeArguments*/ void 0)) : void 0; + if (isExpression(node) && !isJS) { + const contextualType = checker.getContextualType(node); + returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */ ); + } + const { body: body, returnValueProperty: returnValueProperty } = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & 1 /* HasReturn */ )); + suppressLeadingAndTrailingTrivia(body); + let newFunction; + const callThis = !!(range.facts & 16 /* UsesThisInFunction */ ); + if (isClassLike(scope)) { + const modifiers = isJS ? [] : [ + factory.createModifier(123 /* PrivateKeyword */ ) + ]; + if (range.facts & 32 /* InStaticRegion */ ) modifiers.push(factory.createModifier(126 /* StaticKeyword */ )); + if (range.facts & 4 /* IsAsyncFunction */ ) modifiers.push(factory.createModifier(134 /* AsyncKeyword */ )); + newFunction = factory.createMethodDeclaration(modifiers.length ? modifiers : void 0, range.facts & 2 /* IsGenerator */ ? factory.createToken(42 /* AsteriskToken */ ) : void 0, functionName, /*questionToken*/ void 0, typeParameters, parameters, returnType, body); + } else { + if (callThis) parameters.unshift(factory.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, /*name*/ "this", /*questionToken*/ void 0, checker.typeToTypeNode(checker.getTypeAtLocation(range.thisNode), scope, 1 /* NoTruncation */ ), /*initializer*/ void 0)); + newFunction = factory.createFunctionDeclaration(range.facts & 4 /* IsAsyncFunction */ ? [ + factory.createToken(134 /* AsyncKeyword */ ) + ] : void 0, range.facts & 2 /* IsGenerator */ ? factory.createToken(42 /* AsteriskToken */ ) : void 0, functionName, typeParameters, parameters, returnType, body); + } + const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context); + const minInsertionPos = (isReadonlyArray(range.range) ? last(range.range) : range.range).end; + const nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope); + if (nodeToInsertBefore) changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, /*blankLineBetween*/ true); + else changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); + importAdder.writeFixes(changeTracker); + const newNodes = []; + const called = getCalledExpression(scope, range, functionNameText); + if (callThis) callArguments.unshift(factory.createIdentifier("this")); + let call = factory.createCallExpression(callThis ? factory.createPropertyAccessExpression(called, "call") : called, callTypeArguments, // Note that no attempt is made to take advantage of type argument inference + callArguments); + if (range.facts & 2 /* IsGenerator */ ) call = factory.createYieldExpression(factory.createToken(42 /* AsteriskToken */ ), call); + if (range.facts & 4 /* IsAsyncFunction */ ) call = factory.createAwaitExpression(call); + if (isInJSXContent(node)) call = factory.createJsxExpression(/*dotDotDotToken*/ void 0, call); + if (exposedVariableDeclarations.length && !writes) { + Debug.assert(!returnValueProperty, "Expected no returnValueProperty"); + Debug.assert(!(range.facts & 1 /* HasReturn */ ), "Expected RangeFacts.HasReturn flag to be unset"); + if (exposedVariableDeclarations.length === 1) { + const variableDeclaration = exposedVariableDeclarations[0]; + newNodes.push(factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ + factory.createVariableDeclaration(getSynthesizedDeepClone(variableDeclaration.name), /*exclamationToken*/ void 0, /*type*/ getSynthesizedDeepClone(variableDeclaration.type), /*initializer*/ call) + ], variableDeclaration.parent.flags))); + } else { + const bindingElements = []; + const typeElements = []; + let commonNodeFlags = exposedVariableDeclarations[0].parent.flags; + let sawExplicitType = false; + for (const variableDeclaration of exposedVariableDeclarations){ + bindingElements.push(factory.createBindingElement(/*dotDotDotToken*/ void 0, /*propertyName*/ void 0, /*name*/ getSynthesizedDeepClone(variableDeclaration.name))); + const variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */ ); + typeElements.push(factory.createPropertySignature(/*modifiers*/ void 0, /*name*/ variableDeclaration.symbol.name, /*questionToken*/ void 0, /*type*/ variableType)); + sawExplicitType = sawExplicitType || variableDeclaration.type !== void 0; + commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; } - getRenameInfo(fileName, position, preferences) { - return this.forwardJSONCall(`getRenameInfo('${fileName}', ${position})`, ()=>this.languageService.getRenameInfo(fileName, position, preferences)); + const typeLiteral = sawExplicitType ? factory.createTypeLiteralNode(typeElements) : void 0; + if (typeLiteral) setEmitFlags(typeLiteral, 1 /* SingleLine */ ); + newNodes.push(factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ + factory.createVariableDeclaration(factory.createObjectBindingPattern(bindingElements), /*exclamationToken*/ void 0, /*type*/ typeLiteral, /*initializer*/ call) + ], commonNodeFlags))); + } + } else if (exposedVariableDeclarations.length || writes) { + if (exposedVariableDeclarations.length) for (const variableDeclaration of exposedVariableDeclarations){ + let flags = variableDeclaration.parent.flags; + if (flags & 2 /* Const */ ) flags = flags & -3 /* Const */ | 1 /* Let */ ; + newNodes.push(factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ + factory.createVariableDeclaration(variableDeclaration.symbol.name, /*exclamationToken*/ void 0, getTypeDeepCloneUnionUndefined(variableDeclaration.type)) + ], flags))); + } + if (returnValueProperty) newNodes.push(factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ + factory.createVariableDeclaration(returnValueProperty, /*exclamationToken*/ void 0, getTypeDeepCloneUnionUndefined(returnType)) + ], 1 /* Let */ ))); + const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (returnValueProperty) assignments.unshift(factory.createShorthandPropertyAssignment(returnValueProperty)); + if (assignments.length === 1) { + Debug.assert(!returnValueProperty, "Shouldn't have returnValueProperty here"); + newNodes.push(factory.createExpressionStatement(factory.createAssignment(assignments[0].name, call))); + if (range.facts & 1 /* HasReturn */ ) newNodes.push(factory.createReturnStatement()); + } else { + newNodes.push(factory.createExpressionStatement(factory.createAssignment(factory.createObjectLiteralExpression(assignments), call))); + if (returnValueProperty) newNodes.push(factory.createReturnStatement(factory.createIdentifier(returnValueProperty))); + } + } else { + if (range.facts & 1 /* HasReturn */ ) newNodes.push(factory.createReturnStatement(call)); + else if (isReadonlyArray(range.range)) newNodes.push(factory.createExpressionStatement(call)); + else newNodes.push(call); + } + if (isReadonlyArray(range.range)) changeTracker.replaceNodeRangeWithNodes(context.file, first(range.range), last(range.range), newNodes); + else changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes); + const edits = changeTracker.getChanges(); + const renameRange = isReadonlyArray(range.range) ? first(range.range) : range.range; + const renameFilename = renameRange.getSourceFile().fileName; + const renameLocation = getRenameLocation(edits, renameFilename, functionNameText, /*preferLastLocation*/ false); + return { + renameFilename: renameFilename, + renameLocation: renameLocation, + edits: edits + }; + function getTypeDeepCloneUnionUndefined(typeNode) { + if (typeNode === void 0) return void 0; + const clone2 = getSynthesizedDeepClone(typeNode); + let withoutParens = clone2; + while(isParenthesizedTypeNode(withoutParens))withoutParens = withoutParens.type; + return isUnionTypeNode(withoutParens) && find(withoutParens.types, (t)=>t.kind === 157 /* UndefinedKeyword */ ) ? clone2 : factory.createUnionTypeNode([ + clone2, + factory.createKeywordTypeNode(157 /* UndefinedKeyword */ ) + ]); + } + } + function extractConstantInScope(node, scope, { substitutions: substitutions }, rangeFacts, context) { + const checker = context.program.getTypeChecker(); + const file = scope.getSourceFile(); + const localNameText = isPropertyAccessExpression(node) && !isClassLike(scope) && !checker.resolveName(node.name.text, node, 111551 /* Value */ , /*excludeGlobals*/ false) && !isPrivateIdentifier(node.name) && !identifierToKeywordKind(node.name) ? node.name.text : getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file); + const isJS = isInJSFile(scope); + let variableType = isJS || !checker.isContextSensitive(node) ? void 0 : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */ ); + let initializer = transformConstantInitializer(skipParentheses(node), substitutions); + ({ variableType: variableType, initializer: initializer } = transformFunctionInitializerAndType(variableType, initializer)); + suppressLeadingAndTrailingTrivia(initializer); + const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context); + if (isClassLike(scope)) { + Debug.assert(!isJS, "Cannot extract to a JS class"); + const modifiers = []; + modifiers.push(factory.createModifier(123 /* PrivateKeyword */ )); + if (rangeFacts & 32 /* InStaticRegion */ ) modifiers.push(factory.createModifier(126 /* StaticKeyword */ )); + modifiers.push(factory.createModifier(148 /* ReadonlyKeyword */ )); + const newVariable = factory.createPropertyDeclaration(modifiers, localNameText, /*questionOrExclamationToken*/ void 0, variableType, initializer); + let localReference = factory.createPropertyAccessExpression(rangeFacts & 32 /* InStaticRegion */ ? factory.createIdentifier(scope.name.getText()) : factory.createThis(), factory.createIdentifier(localNameText)); + if (isInJSXContent(node)) localReference = factory.createJsxExpression(/*dotDotDotToken*/ void 0, localReference); + const maxInsertionPos = node.pos; + const nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, /*blankLineBetween*/ true); + changeTracker.replaceNode(context.file, node, localReference); + } else { + const newVariableDeclaration = factory.createVariableDeclaration(localNameText, /*exclamationToken*/ void 0, variableType, initializer); + const oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope); + if (oldVariableDeclaration) { + changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); + const localReference = factory.createIdentifier(localNameText); + changeTracker.replaceNode(context.file, node, localReference); + } else if (node.parent.kind === 244 /* ExpressionStatement */ && scope === findAncestor(node, isScope)) { + const newVariableStatement = factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ + newVariableDeclaration + ], 2 /* Const */ )); + changeTracker.replaceNode(context.file, node.parent, newVariableStatement); + } else { + const newVariableStatement = factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ + newVariableDeclaration + ], 2 /* Const */ )); + const nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); + if (nodeToInsertBefore.pos === 0) changeTracker.insertNodeAtTopOfFile(context.file, newVariableStatement, /*blankLineBetween*/ false); + else changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false); + if (node.parent.kind === 244 /* ExpressionStatement */ ) changeTracker.delete(context.file, node.parent); + else { + let localReference = factory.createIdentifier(localNameText); + if (isInJSXContent(node)) localReference = factory.createJsxExpression(/*dotDotDotToken*/ void 0, localReference); + changeTracker.replaceNode(context.file, node, localReference); } - getSmartSelectionRange(fileName, position) { - return this.forwardJSONCall(`getSmartSelectionRange('${fileName}', ${position})`, ()=>this.languageService.getSmartSelectionRange(fileName, position)); + } + } + const edits = changeTracker.getChanges(); + const renameFilename = node.getSourceFile().fileName; + const renameLocation = getRenameLocation(edits, renameFilename, localNameText, /*preferLastLocation*/ true); + return { + renameFilename: renameFilename, + renameLocation: renameLocation, + edits: edits + }; + function transformFunctionInitializerAndType(variableType2, initializer2) { + if (variableType2 === void 0) return { + variableType: variableType2, + initializer: initializer2 + }; + if (!isFunctionExpression(initializer2) && !isArrowFunction(initializer2) || !!initializer2.typeParameters) return { + variableType: variableType2, + initializer: initializer2 + }; + const functionType = checker.getTypeAtLocation(node); + const functionSignature = singleOrUndefined(checker.getSignaturesOfType(functionType, 0 /* Call */ )); + if (!functionSignature) return { + variableType: variableType2, + initializer: initializer2 + }; + if (!!functionSignature.getTypeParameters()) return { + variableType: variableType2, + initializer: initializer2 + }; + const parameters = []; + let hasAny = false; + for (const p of initializer2.parameters)if (p.type) parameters.push(p); + else { + const paramType = checker.getTypeAtLocation(p); + if (paramType === checker.getAnyType()) hasAny = true; + parameters.push(factory.updateParameterDeclaration(p, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, p.type || checker.typeToTypeNode(paramType, scope, 1 /* NoTruncation */ ), p.initializer)); + } + if (hasAny) return { + variableType: variableType2, + initializer: initializer2 + }; + variableType2 = void 0; + if (isArrowFunction(initializer2)) initializer2 = factory.updateArrowFunction(initializer2, canHaveModifiers(node) ? getModifiers(node) : void 0, initializer2.typeParameters, parameters, initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */ ), initializer2.equalsGreaterThanToken, initializer2.body); + else { + if (functionSignature && !!functionSignature.thisParameter) { + const firstParameter = firstOrUndefined(parameters); + if (!firstParameter || isIdentifier(firstParameter.name) && firstParameter.name.escapedText !== "this") { + const thisType = checker.getTypeOfSymbolAtLocation(functionSignature.thisParameter, node); + parameters.splice(0, 0, factory.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, "this", /*questionToken*/ void 0, checker.typeToTypeNode(thisType, scope, 1 /* NoTruncation */ ))); + } } - findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) { - return this.forwardJSONCall(`findRenameLocations('${fileName}', ${position}, ${findInStrings}, ${findInComments}, ${providePrefixAndSuffixTextForRename})`, ()=>this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename)); + initializer2 = factory.updateFunctionExpression(initializer2, canHaveModifiers(node) ? getModifiers(node) : void 0, initializer2.asteriskToken, initializer2.name, initializer2.typeParameters, parameters, initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */ ), initializer2.body); + } + return { + variableType: variableType2, + initializer: initializer2 + }; + } + } + function getContainingVariableDeclarationIfInList(node, scope) { + let prevNode; + while(node !== void 0 && node !== scope){ + if (isVariableDeclaration(node) && node.initializer === prevNode && isVariableDeclarationList(node.parent) && node.parent.declarations.length > 1) return node; + prevNode = node; + node = node.parent; + } + } + function getFirstDeclarationBeforePosition(type, position) { + let firstDeclaration; + const symbol = type.symbol; + if (symbol && symbol.declarations) { + for (const declaration of symbol.declarations)if ((firstDeclaration === void 0 || declaration.pos < firstDeclaration.pos) && declaration.pos < position) firstDeclaration = declaration; + } + return firstDeclaration; + } + function compareTypesByDeclarationOrder({ type: type1, declaration: declaration1 }, { type: type2, declaration: declaration2 }) { + return compareProperties(declaration1, declaration2, "pos", compareValues) || compareStringsCaseSensitive(type1.symbol ? type1.symbol.getName() : "", type2.symbol ? type2.symbol.getName() : "") || compareValues(type1.id, type2.id); + } + function getCalledExpression(scope, range, functionNameText) { + const functionReference = factory.createIdentifier(functionNameText); + if (isClassLike(scope)) { + const lhs = range.facts & 32 /* InStaticRegion */ ? factory.createIdentifier(scope.name.text) : factory.createThis(); + return factory.createPropertyAccessExpression(lhs, functionReference); + } else return functionReference; + } + function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn2) { + const hasWritesOrVariableDeclarations = writes !== void 0 || exposedVariableDeclarations.length > 0; + if (isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) return { + body: factory.createBlock(body.statements, /*multiLine*/ true), + returnValueProperty: void 0 + }; + let returnValueProperty; + let ignoreReturns = false; + const statements = factory.createNodeArray(isBlock(body) ? body.statements.slice(0) : [ + isStatement(body) ? body : factory.createReturnStatement(skipParentheses(body)) + ]); + if (hasWritesOrVariableDeclarations || substitutions.size) { + const rewrittenStatements = visitNodes2(statements, visitor, isStatement).slice(); + if (hasWritesOrVariableDeclarations && !hasReturn2 && isStatement(body)) { + const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (assignments.length === 1) rewrittenStatements.push(factory.createReturnStatement(assignments[0].name)); + else rewrittenStatements.push(factory.createReturnStatement(factory.createObjectLiteralExpression(assignments))); + } + return { + body: factory.createBlock(rewrittenStatements, /*multiLine*/ true), + returnValueProperty: returnValueProperty + }; + } else return { + body: factory.createBlock(statements, /*multiLine*/ true), + returnValueProperty: void 0 + }; + function visitor(node) { + if (!ignoreReturns && isReturnStatement(node) && hasWritesOrVariableDeclarations) { + const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (node.expression) { + if (!returnValueProperty) returnValueProperty = "__return"; + assignments.unshift(factory.createPropertyAssignment(returnValueProperty, visitNode(node.expression, visitor, isExpression))); } - /// GET BRACE MATCHING - getBraceMatchingAtPosition(fileName, position) { - return this.forwardJSONCall(`getBraceMatchingAtPosition('${fileName}', ${position})`, ()=>this.languageService.getBraceMatchingAtPosition(fileName, position)); - } - isValidBraceCompletionAtPosition(fileName, position, openingBrace) { - return this.forwardJSONCall(`isValidBraceCompletionAtPosition('${fileName}', ${position}, ${openingBrace})`, ()=>this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace)); - } - getSpanOfEnclosingComment(fileName, position, onlyMultiLine) { - return this.forwardJSONCall(`getSpanOfEnclosingComment('${fileName}', ${position})`, ()=>this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine)); - } - /// GET SMART INDENT - getIndentationAtPosition(fileName, position, options) { - return this.forwardJSONCall(`getIndentationAtPosition('${fileName}', ${position})`, ()=>{ - const localOptions = JSON.parse(options); - return this.languageService.getIndentationAtPosition(fileName, position, localOptions); - }); - } - /// GET REFERENCES - getReferencesAtPosition(fileName, position) { - return this.forwardJSONCall(`getReferencesAtPosition('${fileName}', ${position})`, ()=>this.languageService.getReferencesAtPosition(fileName, position)); - } - findReferences(fileName, position) { - return this.forwardJSONCall(`findReferences('${fileName}', ${position})`, ()=>this.languageService.findReferences(fileName, position)); - } - getFileReferences(fileName) { - return this.forwardJSONCall(`getFileReferences('${fileName})`, ()=>this.languageService.getFileReferences(fileName)); - } - getOccurrencesAtPosition(fileName, position) { - return this.forwardJSONCall(`getOccurrencesAtPosition('${fileName}', ${position})`, ()=>this.languageService.getOccurrencesAtPosition(fileName, position)); - } - getDocumentHighlights(fileName, position, filesToSearch) { - return this.forwardJSONCall(`getDocumentHighlights('${fileName}', ${position})`, ()=>{ - const results = this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch)); - const normalizedName = toFileNameLowerCase(normalizeSlashes(fileName)); - return filter(results, (r)=>toFileNameLowerCase(normalizeSlashes(r.fileName)) === normalizedName); - }); + if (assignments.length === 1) return factory.createReturnStatement(assignments[0].name); + else return factory.createReturnStatement(factory.createObjectLiteralExpression(assignments)); + } else { + const oldIgnoreReturns = ignoreReturns; + ignoreReturns = ignoreReturns || isFunctionLikeDeclaration(node) || isClassLike(node); + const substitution = substitutions.get(getNodeId(node).toString()); + const result = substitution ? getSynthesizedDeepClone(substitution) : visitEachChild(node, visitor, nullTransformationContext); + ignoreReturns = oldIgnoreReturns; + return result; + } + } + } + function transformConstantInitializer(initializer, substitutions) { + return substitutions.size ? visitor(initializer) : initializer; + function visitor(node) { + const substitution = substitutions.get(getNodeId(node).toString()); + return substitution ? getSynthesizedDeepClone(substitution) : visitEachChild(node, visitor, nullTransformationContext); + } + } + function getStatementsOrClassElements(scope) { + if (isFunctionLikeDeclaration(scope)) { + const body = scope.body; + if (isBlock(body)) return body.statements; + } else if (isModuleBlock(scope) || isSourceFile(scope)) return scope.statements; + else if (isClassLike(scope)) return scope.members; + else assertType(scope); + return emptyArray; + } + function getNodeToInsertFunctionBefore(minPos, scope) { + return find(getStatementsOrClassElements(scope), (child)=>child.pos >= minPos && isFunctionLikeDeclaration(child) && !isConstructorDeclaration(child)); + } + function getNodeToInsertPropertyBefore(maxPos, scope) { + const members = scope.members; + Debug.assert(members.length > 0, "Found no members"); + let prevMember; + let allProperties = true; + for (const member of members){ + if (member.pos > maxPos) return prevMember || members[0]; + if (allProperties && !isPropertyDeclaration(member)) { + if (prevMember !== void 0) return member; + allProperties = false; + } + prevMember = member; + } + if (prevMember === void 0) return Debug.fail(); + return prevMember; + } + function getNodeToInsertConstantBefore(node, scope) { + Debug.assert(!isClassLike(scope)); + let prevScope; + for(let curr = node; curr !== scope; curr = curr.parent)if (isScope(curr)) prevScope = curr; + for(let curr = (prevScope || node).parent;; curr = curr.parent){ + if (isBlockLike(curr)) { + let prevStatement; + for (const statement of curr.statements){ + if (statement.pos > node.pos) break; + prevStatement = statement; } - /// COMPLETION LISTS - /** - * Get a string based representation of the completions - * to provide at the given source position and providing a member completion - * list if requested. - */ getCompletionsAtPosition(fileName, position, preferences, formattingSettings) { - return this.forwardJSONCall(`getCompletionsAtPosition('${fileName}', ${position}, ${preferences}, ${formattingSettings})`, ()=>this.languageService.getCompletionsAtPosition(fileName, position, preferences, formattingSettings)); + if (!prevStatement && isCaseClause(curr)) { + Debug.assert(isSwitchStatement(curr.parent.parent), "Grandparent isn't a switch statement"); + return curr.parent.parent; } - /** Get a string based representation of a completion list entry details */ getCompletionEntryDetails(fileName, position, entryName, formatOptions, source, preferences, data) { - return this.forwardJSONCall(`getCompletionEntryDetails('${fileName}', ${position}, '${entryName}')`, ()=>{ - const localOptions = formatOptions === void 0 ? void 0 : JSON.parse(formatOptions); - return this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences, data); + return Debug.checkDefined(prevStatement, "prevStatement failed to get set"); + } + Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope"); + } + } + function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { + const variableAssignments = map(exposedVariableDeclarations, (v)=>factory.createShorthandPropertyAssignment(v.symbol.name)); + const writeAssignments = map(writes, (w)=>factory.createShorthandPropertyAssignment(w.symbol.name)); + return variableAssignments === void 0 ? writeAssignments : writeAssignments === void 0 ? variableAssignments : variableAssignments.concat(writeAssignments); + } + function isReadonlyArray(v) { + return isArray(v); + } + function getEnclosingTextRange(targetRange, sourceFile) { + return isReadonlyArray(targetRange.range) ? { + pos: first(targetRange.range).getStart(sourceFile), + end: last(targetRange.range).getEnd() + } : targetRange.range; + } + function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) { + const allTypeParameterUsages = /* @__PURE__ */ new Map(); + const usagesPerScope = []; + const substitutionsPerScope = []; + const functionErrorsPerScope = []; + const constantErrorsPerScope = []; + const visibleDeclarationsInExtractedRange = []; + const exposedVariableSymbolSet = /* @__PURE__ */ new Map(); + const exposedVariableDeclarations = []; + let firstExposedNonVariableDeclaration; + const expression = !isReadonlyArray(targetRange.range) ? targetRange.range : targetRange.range.length === 1 && isExpressionStatement(targetRange.range[0]) ? targetRange.range[0].expression : void 0; + let expressionDiagnostic; + if (expression === void 0) { + const statements = targetRange.range; + const start = first(statements).getStart(); + const end = last(statements).end; + expressionDiagnostic = createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); + } else if (checker.getTypeAtLocation(expression).flags & 147456 /* Never */ ) expressionDiagnostic = createDiagnosticForNode(expression, Messages.uselessConstantType); + for (const scope of scopes){ + usagesPerScope.push({ + usages: /* @__PURE__ */ new Map(), + typeParameterUsages: /* @__PURE__ */ new Map(), + substitutions: /* @__PURE__ */ new Map() + }); + substitutionsPerScope.push(/* @__PURE__ */ new Map()); + functionErrorsPerScope.push([]); + const constantErrors = []; + if (expressionDiagnostic) constantErrors.push(expressionDiagnostic); + if (isClassLike(scope) && isInJSFile(scope)) constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); + if (isArrowFunction(scope) && !isBlock(scope.body)) constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction)); + constantErrorsPerScope.push(constantErrors); + } + const seenUsages = /* @__PURE__ */ new Map(); + const target = isReadonlyArray(targetRange.range) ? factory.createBlock(targetRange.range) : targetRange.range; + const unmodifiedNode = isReadonlyArray(targetRange.range) ? first(targetRange.range) : targetRange.range; + const inGenericContext = isInGenericContext(unmodifiedNode); + collectUsages(target); + if (inGenericContext && !isReadonlyArray(targetRange.range) && !isJsxAttribute(targetRange.range)) { + const contextualType = checker.getContextualType(targetRange.range); + recordTypeParameterUsages(contextualType); + } + if (allTypeParameterUsages.size > 0) { + const seenTypeParameterUsages = /* @__PURE__ */ new Map(); + let i = 0; + for(let curr = unmodifiedNode; curr !== void 0 && i < scopes.length; curr = curr.parent){ + if (curr === scopes[i]) { + seenTypeParameterUsages.forEach((typeParameter, id)=>{ + usagesPerScope[i].typeParameterUsages.set(id, typeParameter); }); + i++; } - getFormattingEditsForRange(fileName, start, end, options) { - return this.forwardJSONCall(`getFormattingEditsForRange('${fileName}', ${start}, ${end})`, ()=>{ - const localOptions = JSON.parse(options); - return this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); - }); + if (isDeclarationWithTypeParameters(curr)) for (const typeParameterDecl of getEffectiveTypeParameterDeclarations(curr)){ + const typeParameter = checker.getTypeAtLocation(typeParameterDecl); + if (allTypeParameterUsages.has(typeParameter.id.toString())) seenTypeParameterUsages.set(typeParameter.id.toString(), typeParameter); } - getFormattingEditsForDocument(fileName, options) { - return this.forwardJSONCall(`getFormattingEditsForDocument('${fileName}')`, ()=>{ - const localOptions = JSON.parse(options); - return this.languageService.getFormattingEditsForDocument(fileName, localOptions); - }); + } + Debug.assert(i === scopes.length, "Should have iterated all scopes"); + } + if (visibleDeclarationsInExtractedRange.length) { + const containingLexicalScopeOfExtraction = isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : getEnclosingBlockScopeContainer(scopes[0]); + forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + } + for(let i = 0; i < scopes.length; i++){ + const scopeUsages = usagesPerScope[i]; + if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) { + const errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; + constantErrorsPerScope[i].push(createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes)); + } + if (targetRange.facts & 16 /* UsesThisInFunction */ && isClassLike(scopes[i])) functionErrorsPerScope[i].push(createDiagnosticForNode(targetRange.thisNode, Messages.cannotExtractFunctionsContainingThisToMethod)); + let hasWrite = false; + let readonlyClassPropertyWrite; + usagesPerScope[i].usages.forEach((value1)=>{ + if (value1.usage === 2 /* Write */ ) { + hasWrite = true; + if (value1.symbol.flags & 106500 /* ClassMember */ && value1.symbol.valueDeclaration && hasEffectiveModifier(value1.symbol.valueDeclaration, 64 /* Readonly */ )) readonlyClassPropertyWrite = value1.symbol.valueDeclaration; } - getFormattingEditsAfterKeystroke(fileName, position, key, options) { - return this.forwardJSONCall(`getFormattingEditsAfterKeystroke('${fileName}', ${position}, '${key}')`, ()=>{ - const localOptions = JSON.parse(options); - return this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); + }); + Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0, "No variable declarations expected if something was extracted"); + if (hasWrite && !isReadonlyArray(targetRange.range)) { + const diag2 = createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression); + functionErrorsPerScope[i].push(diag2); + constantErrorsPerScope[i].push(diag2); + } else if (readonlyClassPropertyWrite && i > 0) { + const diag2 = createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor); + functionErrorsPerScope[i].push(diag2); + constantErrorsPerScope[i].push(diag2); + } else if (firstExposedNonVariableDeclaration) { + const diag2 = createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity); + functionErrorsPerScope[i].push(diag2); + constantErrorsPerScope[i].push(diag2); + } + } + return { + target: target, + usagesPerScope: usagesPerScope, + functionErrorsPerScope: functionErrorsPerScope, + constantErrorsPerScope: constantErrorsPerScope, + exposedVariableDeclarations: exposedVariableDeclarations + }; + function isInGenericContext(node) { + return !!findAncestor(node, (n)=>isDeclarationWithTypeParameters(n) && getEffectiveTypeParameterDeclarations(n).length !== 0); + } + function recordTypeParameterUsages(type) { + const symbolWalker = checker.getSymbolWalker(()=>(cancellationToken.throwIfCancellationRequested(), true)); + const { visitedTypes: visitedTypes } = symbolWalker.walkType(type); + for (const visitedType of visitedTypes)if (visitedType.isTypeParameter()) allTypeParameterUsages.set(visitedType.id.toString(), visitedType); + } + function collectUsages(node, valueUsage = 1 /* Read */ ) { + if (inGenericContext) { + const type = checker.getTypeAtLocation(node); + recordTypeParameterUsages(type); + } + if (isDeclaration(node) && node.symbol) visibleDeclarationsInExtractedRange.push(node); + if (isAssignmentExpression(node)) { + collectUsages(node.left, 2 /* Write */ ); + collectUsages(node.right); + } else if (isUnaryExpressionWithWrite(node)) collectUsages(node.operand, 2 /* Write */ ); + else if (isPropertyAccessExpression(node) || isElementAccessExpression(node)) forEachChild(node, collectUsages); + else if (isIdentifier(node)) { + if (!node.parent) return; + if (isQualifiedName(node.parent) && node !== node.parent.left) return; + if (isPropertyAccessExpression(node.parent) && node !== node.parent.expression) return; + recordUsage(node, valueUsage, /*isTypeNode*/ isPartOfTypeNode(node)); + } else forEachChild(node, collectUsages); + } + function recordUsage(n, usage, isTypeNode2) { + const symbolId = recordUsagebySymbol(n, usage, isTypeNode2); + if (symbolId) for(let i = 0; i < scopes.length; i++){ + const substitution = substitutionsPerScope[i].get(symbolId); + if (substitution) usagesPerScope[i].substitutions.set(getNodeId(n).toString(), substitution); + } + } + function recordUsagebySymbol(identifier, usage, isTypeName) { + const symbol = getSymbolReferencedByIdentifier(identifier); + if (!symbol) return void 0; + const symbolId = getSymbolId(symbol).toString(); + const lastUsage = seenUsages.get(symbolId); + if (lastUsage && lastUsage >= usage) return symbolId; + seenUsages.set(symbolId, usage); + if (lastUsage) { + for (const perScope of usagesPerScope){ + const prevEntry = perScope.usages.get(identifier.text); + if (prevEntry) perScope.usages.set(identifier.text, { + usage: usage, + symbol: symbol, + node: identifier }); } - getDocCommentTemplateAtPosition(fileName, position, options, formatOptions) { - return this.forwardJSONCall(`getDocCommentTemplateAtPosition('${fileName}', ${position})`, ()=>this.languageService.getDocCommentTemplateAtPosition(fileName, position, options, formatOptions)); - } - /// NAVIGATE TO - /** Return a list of symbols that are interesting to navigate to */ getNavigateToItems(searchValue, maxResultCount, fileName) { - return this.forwardJSONCall(`getNavigateToItems('${searchValue}', ${maxResultCount}, ${fileName})`, ()=>this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName)); - } - getNavigationBarItems(fileName) { - return this.forwardJSONCall(`getNavigationBarItems('${fileName}')`, ()=>this.languageService.getNavigationBarItems(fileName)); - } - getNavigationTree(fileName) { - return this.forwardJSONCall(`getNavigationTree('${fileName}')`, ()=>this.languageService.getNavigationTree(fileName)); - } - getOutliningSpans(fileName) { - return this.forwardJSONCall(`getOutliningSpans('${fileName}')`, ()=>this.languageService.getOutliningSpans(fileName)); - } - getTodoComments(fileName, descriptors) { - return this.forwardJSONCall(`getTodoComments('${fileName}')`, ()=>this.languageService.getTodoComments(fileName, JSON.parse(descriptors))); - } - /// CALL HIERARCHY - prepareCallHierarchy(fileName, position) { - return this.forwardJSONCall(`prepareCallHierarchy('${fileName}', ${position})`, ()=>this.languageService.prepareCallHierarchy(fileName, position)); - } - provideCallHierarchyIncomingCalls(fileName, position) { - return this.forwardJSONCall(`provideCallHierarchyIncomingCalls('${fileName}', ${position})`, ()=>this.languageService.provideCallHierarchyIncomingCalls(fileName, position)); - } - provideCallHierarchyOutgoingCalls(fileName, position) { - return this.forwardJSONCall(`provideCallHierarchyOutgoingCalls('${fileName}', ${position})`, ()=>this.languageService.provideCallHierarchyOutgoingCalls(fileName, position)); - } - provideInlayHints(fileName, span, preference) { - return this.forwardJSONCall(`provideInlayHints('${fileName}', '${JSON.stringify(span)}', ${JSON.stringify(preference)})`, ()=>this.languageService.provideInlayHints(fileName, span, preference)); - } - /// Emit - getEmitOutput(fileName) { - return this.forwardJSONCall(`getEmitOutput('${fileName}')`, ()=>{ - const { diagnostics: diagnostics , ...rest } = this.languageService.getEmitOutput(fileName); - return { - ...rest, - diagnostics: this.realizeDiagnostics(diagnostics) - }; + return symbolId; + } + const decls = symbol.getDeclarations(); + const declInFile = decls && find(decls, (d)=>d.getSourceFile() === sourceFile); + if (!declInFile) return void 0; + if (rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) return void 0; + if (targetRange.facts & 2 /* IsGenerator */ && usage === 2 /* Write */ ) { + const diag2 = createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators); + for (const errors of functionErrorsPerScope)errors.push(diag2); + for (const errors of constantErrorsPerScope)errors.push(diag2); + } + for(let i = 0; i < scopes.length; i++){ + const scope = scopes[i]; + const resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags, /*excludeGlobals*/ false); + if (resolvedSymbol === symbol) continue; + if (!substitutionsPerScope[i].has(symbolId)) { + const substitution = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.exportSymbol || symbol, scope, isTypeName); + if (substitution) substitutionsPerScope[i].set(symbolId, substitution); + else if (isTypeName) { + if (!(symbol.flags & 262144 /* TypeParameter */ )) { + const diag2 = createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope); + functionErrorsPerScope[i].push(diag2); + constantErrorsPerScope[i].push(diag2); + } + } else usagesPerScope[i].usages.set(identifier.text, { + usage: usage, + symbol: symbol, + node: identifier }); } - getEmitOutputObject(fileName) { - return forwardCall(this.logger, `getEmitOutput('${fileName}')`, /*returnJson*/ false, ()=>this.languageService.getEmitOutput(fileName), this.logPerformance); - } - toggleLineComment(fileName, textRange) { - return this.forwardJSONCall(`toggleLineComment('${fileName}', '${JSON.stringify(textRange)}')`, ()=>this.languageService.toggleLineComment(fileName, textRange)); - } - toggleMultilineComment(fileName, textRange) { - return this.forwardJSONCall(`toggleMultilineComment('${fileName}', '${JSON.stringify(textRange)}')`, ()=>this.languageService.toggleMultilineComment(fileName, textRange)); - } - commentSelection(fileName, textRange) { - return this.forwardJSONCall(`commentSelection('${fileName}', '${JSON.stringify(textRange)}')`, ()=>this.languageService.commentSelection(fileName, textRange)); - } - uncommentSelection(fileName, textRange) { - return this.forwardJSONCall(`uncommentSelection('${fileName}', '${JSON.stringify(textRange)}')`, ()=>this.languageService.uncommentSelection(fileName, textRange)); + } + return symbolId; + } + function checkForUsedDeclarations(node) { + if (node === targetRange.range || isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0) return; + const sym = isIdentifier(node) ? getSymbolReferencedByIdentifier(node) : checker.getSymbolAtLocation(node); + if (sym) { + const decl = find(visibleDeclarationsInExtractedRange, (d)=>d.symbol === sym); + if (decl) { + if (isVariableDeclaration(decl)) { + const idString = decl.symbol.id.toString(); + if (!exposedVariableSymbolSet.has(idString)) { + exposedVariableDeclarations.push(decl); + exposedVariableSymbolSet.set(idString, true); + } + } else firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl; } + } + forEachChild(node, checkForUsedDeclarations); + } + function getSymbolReferencedByIdentifier(identifier) { + return identifier.parent && isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier ? checker.getShorthandAssignmentValueSymbol(identifier.parent) : checker.getSymbolAtLocation(identifier); + } + function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode2) { + if (!symbol) return void 0; + const decls = symbol.getDeclarations(); + if (decls && decls.some((d)=>d.parent === scopeDecl)) return factory.createIdentifier(symbol.name); + const prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode2); + if (prefix === void 0) return void 0; + return isTypeNode2 ? factory.createQualifiedName(prefix, factory.createIdentifier(symbol.name)) : factory.createPropertyAccessExpression(prefix, symbol.name); + } + } + function getExtractableParent(node) { + return findAncestor(node, (node2)=>node2.parent && isExtractableExpression(node2) && !isBinaryExpression(node2.parent)); + } + function isExtractableExpression(node) { + const { parent: parent2 } = node; + switch(parent2.kind){ + case 306 /* EnumMember */ : + return false; + } + switch(node.kind){ + case 11 /* StringLiteral */ : + return parent2.kind !== 272 /* ImportDeclaration */ && parent2.kind !== 276 /* ImportSpecifier */ ; + case 230 /* SpreadElement */ : + case 206 /* ObjectBindingPattern */ : + case 208 /* BindingElement */ : + return false; + case 80 /* Identifier */ : + return parent2.kind !== 208 /* BindingElement */ && parent2.kind !== 276 /* ImportSpecifier */ && parent2.kind !== 281 /* ExportSpecifier */ ; + } + return true; + } + function isBlockLike(node) { + switch(node.kind){ + case 241 /* Block */ : + case 312 /* SourceFile */ : + case 268 /* ModuleBlock */ : + case 296 /* CaseClause */ : + return true; + default: + return false; + } + } + function isInJSXContent(node) { + return isStringLiteralJsxAttribute(node) || (isJsxElement(node) || isJsxSelfClosingElement(node) || isJsxFragment(node)) && (isJsxElement(node.parent) || isJsxFragment(node.parent)); + } + function isStringLiteralJsxAttribute(node) { + return isStringLiteral(node) && node.parent && isJsxAttribute(node.parent); + } + var refactorName12, extractConstantAction, extractFunctionAction, Messages, RangeFacts; + var init_extractSymbol = __esm({ + "src/services/refactors/extractSymbol.ts" () { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName12 = "Extract Symbol"; + extractConstantAction = { + name: "Extract Constant", + description: getLocaleSpecificMessage(Diagnostics.Extract_constant), + kind: "refactor.extract.constant" }; - ClassifierShimObject = class extends ShimBase { - constructor(factory2, logger){ - super(factory2); - this.logger = logger; - this.logPerformance = false; - this.classifier = createClassifier(); - } - getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent = false) { - return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", ()=>convertClassifications(this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)), this.logPerformance); - } - /// COLORIZATION - getClassificationsForLine(text, lexState, classifyKeywordsInGenerics = false) { - const classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics); - let result = ""; - for (const item of classification.entries){ - result += item.length + "\n"; - result += item.classification + "\n"; - } - result += classification.finalLexState; - return result; - } + extractFunctionAction = { + name: "Extract Function", + description: getLocaleSpecificMessage(Diagnostics.Extract_function), + kind: "refactor.extract.function" }; - CoreServicesShimObject = class extends ShimBase { - constructor(factory2, logger, host){ - super(factory2); - this.logger = logger; - this.host = host; - this.logPerformance = false; - } - forwardJSONCall(actionDescription2, action) { - return forwardJSONCall(this.logger, actionDescription2, action, this.logPerformance); - } - resolveModuleName(fileName, moduleName, compilerOptionsJson) { - return this.forwardJSONCall(`resolveModuleName('${fileName}')`, ()=>{ - const compilerOptions = JSON.parse(compilerOptionsJson); - const result = resolveModuleName(moduleName, normalizeSlashes(fileName), compilerOptions, this.host); - let resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : void 0; - if (result.resolvedModule && result.resolvedModule.extension !== ".ts" /* Ts */ && result.resolvedModule.extension !== ".tsx" /* Tsx */ && result.resolvedModule.extension !== ".d.ts" /* Dts */ ) resolvedFileName = void 0; - return { - resolvedFileName: resolvedFileName, - failedLookupLocations: result.failedLookupLocations, - affectingLocations: result.affectingLocations - }; - }); - } - resolveTypeReferenceDirective(fileName, typeReferenceDirective, compilerOptionsJson) { - return this.forwardJSONCall(`resolveTypeReferenceDirective(${fileName})`, ()=>{ - const compilerOptions = JSON.parse(compilerOptionsJson); - const result = resolveTypeReferenceDirective(typeReferenceDirective, normalizeSlashes(fileName), compilerOptions, this.host); - return { - resolvedFileName: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.resolvedFileName : void 0, - primary: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.primary : true, - failedLookupLocations: result.failedLookupLocations - }; - }); - } - getPreProcessedFileInfo(fileName, sourceTextSnapshot) { - return this.forwardJSONCall(`getPreProcessedFileInfo('${fileName}')`, ()=>{ - const result = preProcessFile(getSnapshotText(sourceTextSnapshot), /* readImportFiles */ true, /* detectJavaScriptImports */ true); - return { - referencedFiles: this.convertFileReferences(result.referencedFiles), - importedFiles: this.convertFileReferences(result.importedFiles), - ambientExternalModules: result.ambientExternalModules, - isLibFile: result.isLibFile, - typeReferenceDirectives: this.convertFileReferences(result.typeReferenceDirectives), - libReferenceDirectives: this.convertFileReferences(result.libReferenceDirectives) - }; - }); + registerRefactor(refactorName12, { + kinds: [ + extractConstantAction.kind, + extractFunctionAction.kind + ], + getEditsForAction: getRefactorEditsToExtractSymbol, + getAvailableActions: getRefactorActionsToExtractSymbol + }); + ((Messages2)=>{ + function createMessage(message) { + return { + message: message, + code: 0, + category: 3 /* Message */ , + key: message + }; } - getAutomaticTypeDirectiveNames(compilerOptionsJson) { - return this.forwardJSONCall(`getAutomaticTypeDirectiveNames('${compilerOptionsJson}')`, ()=>{ - const compilerOptions = JSON.parse(compilerOptionsJson); - return getAutomaticTypeDirectiveNames(compilerOptions, this.host); - }); - } - convertFileReferences(refs) { - if (!refs) return void 0; - const result = []; - for (const ref of refs)result.push({ - path: normalizeSlashes(ref.fileName), - position: ref.pos, - length: ref.end - ref.pos - }); - return result; - } - getTSConfigFileInfo(fileName, sourceTextSnapshot) { - return this.forwardJSONCall(`getTSConfigFileInfo('${fileName}')`, ()=>{ - const result = parseJsonText(fileName, getSnapshotText(sourceTextSnapshot)); - const normalizedFileName = normalizeSlashes(fileName); - const configFile = parseJsonSourceFileConfigFileContent(result, this.host, getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); - return { - options: configFile.options, - typeAcquisition: configFile.typeAcquisition, - files: configFile.fileNames, - raw: configFile.raw, - errors: realizeDiagnostics([ - ...result.parseDiagnostics, - ...configFile.errors - ], "\r\n") - }; - }); - } - getDefaultCompilationSettings() { - return this.forwardJSONCall("getDefaultCompilationSettings()", ()=>getDefaultCompilerOptions2()); - } - discoverTypings(discoverTypingsJson) { - const getCanonicalFileName = createGetCanonicalFileName(/*useCaseSensitivefileNames:*/ false); - return this.forwardJSONCall("discoverTypings()", ()=>{ - const info = JSON.parse(discoverTypingsJson); - if (this.safeList === void 0) this.safeList = ts_JsTyping_exports.loadSafeList(this.host, toPath(info.safeListPath, info.safeListPath, getCanonicalFileName)); - return ts_JsTyping_exports.discoverTypings(this.host, (msg)=>this.logger.log(msg), info.fileNames, toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports, info.typesRegistry, emptyOptions); - }); - } - }; - TypeScriptServicesFactory = class { - constructor(){ - this._shims = []; - } - /* - * Returns script API version. - */ getServicesVersion() { - return servicesVersion; - } - createLanguageServiceShim(host) { - try { - if (this.documentRegistry === void 0) this.documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); - const hostAdapter = new LanguageServiceShimHostAdapter(host); - const languageService = createLanguageService(hostAdapter, this.documentRegistry, /*syntaxOnly*/ false); - return new LanguageServiceShimObject(this, host, languageService); - } catch (err) { - logInternalError(host, err); - throw err; - } - } - createClassifierShim(logger) { - try { - return new ClassifierShimObject(this, logger); - } catch (err) { - logInternalError(logger, err); - throw err; - } - } - createCoreServicesShim(host) { - try { - const adapter = new CoreServicesShimHostAdapter(host); - return new CoreServicesShimObject(this, host, adapter); - } catch (err) { - logInternalError(host, err); - throw err; - } - } - close() { - clear(this._shims); - this.documentRegistry = void 0; - } - registerShim(shim) { - this._shims.push(shim); - } - unregisterShim(shim) { - for(let i = 0; i < this._shims.length; i++)if (this._shims[i] === shim) { - delete this._shims[i]; - return; - } - throw new Error("Invalid operation"); - } - }; + Messages2.cannotExtractRange = createMessage("Cannot extract range."); + Messages2.cannotExtractImport = createMessage("Cannot extract import statement."); + Messages2.cannotExtractSuper = createMessage("Cannot extract super call."); + Messages2.cannotExtractJSDoc = createMessage("Cannot extract JSDoc."); + Messages2.cannotExtractEmpty = createMessage("Cannot extract empty range."); + Messages2.expressionExpected = createMessage("expression expected."); + Messages2.uselessConstantType = createMessage("No reason to extract constant of type."); + Messages2.statementOrExpressionExpected = createMessage("Statement or expression expected."); + Messages2.cannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); + Messages2.cannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); + Messages2.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); + Messages2.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); + Messages2.typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); + Messages2.functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); + Messages2.cannotExtractIdentifier = createMessage("Select more than a single identifier."); + Messages2.cannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); + Messages2.cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression"); + Messages2.cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); + Messages2.cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); + Messages2.cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes"); + Messages2.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); + Messages2.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); + Messages2.cannotExtractFunctionsContainingThisToMethod = createMessage("Cannot extract functions containing this to method"); + })(Messages || (Messages = {})); + RangeFacts = /* @__PURE__ */ ((RangeFacts2)=>{ + RangeFacts2[RangeFacts2["None"] = 0] = "None"; + RangeFacts2[RangeFacts2["HasReturn"] = 1] = "HasReturn"; + RangeFacts2[RangeFacts2["IsGenerator"] = 2] = "IsGenerator"; + RangeFacts2[RangeFacts2["IsAsyncFunction"] = 4] = "IsAsyncFunction"; + RangeFacts2[RangeFacts2["UsesThis"] = 8] = "UsesThis"; + RangeFacts2[RangeFacts2["UsesThisInFunction"] = 16] = "UsesThisInFunction"; + RangeFacts2[RangeFacts2["InStaticRegion"] = 32] = "InStaticRegion"; + return RangeFacts2; + })(RangeFacts || {}); } }); - // src/services/breakpoints.ts - function spanInSourceFileAtLocation(sourceFile, position) { - if (sourceFile.isDeclarationFile) return void 0; - let tokenAtLocation = getTokenAtPosition(sourceFile, position); - const lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; - if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { - const preceding = findPrecedingToken(tokenAtLocation.pos, sourceFile); - if (!preceding || sourceFile.getLineAndCharacterOfPosition(preceding.getEnd()).line !== lineOfPosition) return void 0; - tokenAtLocation = preceding; - } - if (tokenAtLocation.flags & 16777216 /* Ambient */ ) return void 0; - return spanInNode(tokenAtLocation); - function textSpan(startNode2, endNode2) { - const lastDecorator = canHaveDecorators(startNode2) ? findLast(startNode2.modifiers, isDecorator) : void 0; - const start = lastDecorator ? skipTrivia(sourceFile.text, lastDecorator.end) : startNode2.getStart(sourceFile); - return createTextSpanFromBounds(start, (endNode2 || startNode2).getEnd()); - } - function textSpanEndingAtNextToken(startNode2, previousTokenToFindNextEndToken) { - return textSpan(startNode2, findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile)); - } - function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { - if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) return spanInNode(node); - return spanInNode(otherwiseOnNode); - } - function spanInNodeArray(nodeArray, node, match) { - if (nodeArray) { - const index = nodeArray.indexOf(node); - if (index >= 0) { - let start = index; - let end = index + 1; - while(start > 0 && match(nodeArray[start - 1]))start--; - while(end < nodeArray.length && match(nodeArray[end]))end++; - return createTextSpanFromBounds(skipTrivia(sourceFile.text, nodeArray[start].pos), nodeArray[end - 1].end); - } - } - return textSpan(node); - } - function spanInPreviousNode(node) { - return spanInNode(findPrecedingToken(node.pos, sourceFile)); - } - function spanInNextNode(node) { - return spanInNode(findNextToken(node, node.parent, sourceFile)); + // src/services/_namespaces/ts.refactor.extractSymbol.ts + var ts_refactor_extractSymbol_exports = {}; + __export(ts_refactor_extractSymbol_exports, { + Messages: ()=>Messages, + RangeFacts: ()=>RangeFacts, + getRangeToExtract: ()=>getRangeToExtract2, + getRefactorActionsToExtractSymbol: ()=>getRefactorActionsToExtractSymbol, + getRefactorEditsToExtractSymbol: ()=>getRefactorEditsToExtractSymbol + }); + var init_ts_refactor_extractSymbol = __esm({ + "src/services/_namespaces/ts.refactor.extractSymbol.ts" () { + "use strict"; + init_extractSymbol(); } - function spanInNode(node) { - if (node) { - const { parent: parent2 } = node; - switch(node.kind){ - case 240 /* VariableStatement */ : - return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 257 /* VariableDeclaration */ : - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : - return spanInVariableDeclaration(node); - case 166 /* Parameter */ : - return spanInParameterDeclaration(node); - case 259 /* FunctionDeclaration */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 173 /* Constructor */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - return spanInFunctionDeclaration(node); - case 238 /* Block */ : - if (isFunctionBlock(node)) return spanInFunctionBlock(node); - case 265 /* ModuleBlock */ : - return spanInBlock(node); - case 295 /* CatchClause */ : - return spanInBlock(node.block); - case 241 /* ExpressionStatement */ : - return textSpan(node.expression); - case 250 /* ReturnStatement */ : - return textSpan(node.getChildAt(0), node.expression); - case 244 /* WhileStatement */ : - return textSpanEndingAtNextToken(node, node.expression); - case 243 /* DoStatement */ : - return spanInNode(node.statement); - case 256 /* DebuggerStatement */ : - return textSpan(node.getChildAt(0)); - case 242 /* IfStatement */ : - return textSpanEndingAtNextToken(node, node.expression); - case 253 /* LabeledStatement */ : - return spanInNode(node.statement); - case 249 /* BreakStatement */ : - case 248 /* ContinueStatement */ : - return textSpan(node.getChildAt(0), node.label); - case 245 /* ForStatement */ : - return spanInForStatement(node); - case 246 /* ForInStatement */ : - return textSpanEndingAtNextToken(node, node.expression); - case 247 /* ForOfStatement */ : - return spanInInitializerOfForLike(node); - case 252 /* SwitchStatement */ : - return textSpanEndingAtNextToken(node, node.expression); - case 292 /* CaseClause */ : - case 293 /* DefaultClause */ : - return spanInNode(node.statements[0]); - case 255 /* TryStatement */ : - return spanInBlock(node.tryBlock); - case 254 /* ThrowStatement */ : - return textSpan(node, node.expression); - case 274 /* ExportAssignment */ : - return textSpan(node, node.expression); - case 268 /* ImportEqualsDeclaration */ : - return textSpan(node, node.moduleReference); - case 269 /* ImportDeclaration */ : - return textSpan(node, node.moduleSpecifier); - case 275 /* ExportDeclaration */ : - return textSpan(node, node.moduleSpecifier); - case 264 /* ModuleDeclaration */ : - if (getModuleInstanceState(node) !== 1 /* Instantiated */ ) return void 0; - case 260 /* ClassDeclaration */ : - case 263 /* EnumDeclaration */ : - case 302 /* EnumMember */ : - case 205 /* BindingElement */ : - return textSpan(node); - case 251 /* WithStatement */ : - return spanInNode(node.statement); - case 167 /* Decorator */ : - return spanInNodeArray(parent2.modifiers, node, isDecorator); - case 203 /* ObjectBindingPattern */ : - case 204 /* ArrayBindingPattern */ : - return spanInBindingPattern(node); - case 261 /* InterfaceDeclaration */ : - case 262 /* TypeAliasDeclaration */ : - return void 0; - case 26 /* SemicolonToken */ : - case 1 /* EndOfFileToken */ : - return spanInNodeIfStartsOnSameLine(findPrecedingToken(node.pos, sourceFile)); - case 27 /* CommaToken */ : - return spanInPreviousNode(node); - case 18 /* OpenBraceToken */ : - return spanInOpenBraceToken(node); - case 19 /* CloseBraceToken */ : - return spanInCloseBraceToken(node); - case 23 /* CloseBracketToken */ : - return spanInCloseBracketToken(node); - case 20 /* OpenParenToken */ : - return spanInOpenParenToken(node); - case 21 /* CloseParenToken */ : - return spanInCloseParenToken(node); - case 58 /* ColonToken */ : - return spanInColonToken(node); - case 31 /* GreaterThanToken */ : - case 29 /* LessThanToken */ : - return spanInGreaterThanOrLessThanToken(node); - case 115 /* WhileKeyword */ : - return spanInWhileKeyword(node); - case 91 /* ElseKeyword */ : - case 83 /* CatchKeyword */ : - case 96 /* FinallyKeyword */ : - return spanInNextNode(node); - case 162 /* OfKeyword */ : - return spanInOfKeyword(node); - default: - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node)) return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node); - if ((node.kind === 79 /* Identifier */ || node.kind === 227 /* SpreadElement */ || node.kind === 299 /* PropertyAssignment */ || node.kind === 300 /* ShorthandPropertyAssignment */ ) && isArrayLiteralOrObjectLiteralDestructuringPattern(parent2)) return textSpan(node); - if (node.kind === 223 /* BinaryExpression */ ) { - const { left: left , operatorToken: operatorToken } = node; - if (isArrayLiteralOrObjectLiteralDestructuringPattern(left)) return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left); - if (operatorToken.kind === 63 /* EqualsToken */ && isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) return textSpan(node); - if (operatorToken.kind === 27 /* CommaToken */ ) return spanInNode(left); - } - if (isExpressionNode(node)) switch(parent2.kind){ - case 243 /* DoStatement */ : - return spanInPreviousNode(node); - case 167 /* Decorator */ : - return spanInNode(node.parent); - case 245 /* ForStatement */ : - case 247 /* ForOfStatement */ : - return textSpan(node); - case 223 /* BinaryExpression */ : - if (node.parent.operatorToken.kind === 27 /* CommaToken */ ) return textSpan(node); - break; - case 216 /* ArrowFunction */ : - if (node.parent.body === node) return textSpan(node); - break; + }); + // src/services/refactors/generateGetAccessorAndSetAccessor.ts + var actionName, actionDescription, generateGetSetAction; + var init_generateGetAccessorAndSetAccessor = __esm({ + "src/services/refactors/generateGetAccessorAndSetAccessor.ts" () { + "use strict"; + init_ts4(); + init_ts_refactor(); + actionName = "Generate 'get' and 'set' accessors"; + actionDescription = getLocaleSpecificMessage(Diagnostics.Generate_get_and_set_accessors); + generateGetSetAction = { + name: actionName, + description: actionDescription, + kind: "refactor.rewrite.property.generateAccessors" + }; + registerRefactor(actionName, { + kinds: [ + generateGetSetAction.kind + ], + getEditsForAction: function getRefactorActionsToGenerateGetAndSetAccessors(context, actionName2) { + if (!context.endPosition) return void 0; + const info = ts_codefix_exports.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); + const edits = ts_codefix_exports.generateAccessorFromProperty(context.file, context.program, context.startPosition, context.endPosition, context, actionName2); + if (!edits) return void 0; + const renameFilename = context.file.fileName; + const nameNeedRename = info.renameAccessor ? info.accessorName : info.fieldName; + const renameLocationOffset = isIdentifier(nameNeedRename) ? 0 : -1; + const renameLocation = renameLocationOffset + getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ isParameter(info.declaration)); + return { + renameFilename: renameFilename, + renameLocation: renameLocation, + edits: edits + }; + }, + getAvailableActions (context) { + if (!context.endPosition) return emptyArray; + const info = ts_codefix_exports.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition, context.triggerReason === "invoked"); + if (!info) return emptyArray; + if (!isRefactorErrorInfo(info)) return [ + { + name: actionName, + description: actionDescription, + actions: [ + generateGetSetAction + ] } - switch(node.parent.kind){ - case 299 /* PropertyAssignment */ : - if (node.parent.name === node && !isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) return spanInNode(node.parent.initializer); - break; - case 213 /* TypeAssertionExpression */ : - if (node.parent.type === node) return spanInNextNode(node.parent.type); - break; - case 257 /* VariableDeclaration */ : - case 166 /* Parameter */ : - { - const { initializer: initializer , type: type } = node.parent; - if (initializer === node || type === node || isAssignmentOperator(node.kind)) return spanInPreviousNode(node); - break; - } - case 223 /* BinaryExpression */ : + ]; + if (context.preferences.provideRefactorNotApplicableReason) return [ + { + name: actionName, + description: actionDescription, + actions: [ { - const { left: left } = node.parent; - if (isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) return spanInPreviousNode(node); - break; + ...generateGetSetAction, + notApplicableReason: info.error } - default: - if (isFunctionLike(node.parent) && node.parent.type === node) return spanInPreviousNode(node); - } - return spanInNode(node.parent); - } - } - function textSpanFromVariableDeclaration(variableDeclaration) { - if (isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] === variableDeclaration) return textSpan(findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); - else return textSpan(variableDeclaration); - } - function spanInVariableDeclaration(variableDeclaration) { - if (variableDeclaration.parent.parent.kind === 246 /* ForInStatement */ ) return spanInNode(variableDeclaration.parent.parent); - const parent2 = variableDeclaration.parent; - if (isBindingPattern(variableDeclaration.name)) return spanInBindingPattern(variableDeclaration.name); - if (hasOnlyExpressionInitializer(variableDeclaration) && variableDeclaration.initializer || hasSyntacticModifier(variableDeclaration, 1 /* Export */ ) || parent2.parent.kind === 247 /* ForOfStatement */ ) return textSpanFromVariableDeclaration(variableDeclaration); - if (isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] !== variableDeclaration) return spanInNode(findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent)); - } - function canHaveSpanInParameterDeclaration(parameter) { - return !!parameter.initializer || parameter.dotDotDotToken !== void 0 || hasSyntacticModifier(parameter, 12 /* Private */ ); - } - function spanInParameterDeclaration(parameter) { - if (isBindingPattern(parameter.name)) return spanInBindingPattern(parameter.name); - else if (canHaveSpanInParameterDeclaration(parameter)) return textSpan(parameter); - else { - const functionDeclaration = parameter.parent; - const indexOfParameter = functionDeclaration.parameters.indexOf(parameter); - Debug.assert(indexOfParameter !== -1); - if (indexOfParameter !== 0) return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]); - else return spanInNode(functionDeclaration.body); - } - } - function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { - return hasSyntacticModifier(functionDeclaration, 1 /* Export */ ) || functionDeclaration.parent.kind === 260 /* ClassDeclaration */ && functionDeclaration.kind !== 173 /* Constructor */ ; - } - function spanInFunctionDeclaration(functionDeclaration) { - if (!functionDeclaration.body) return void 0; - if (canFunctionHaveSpanInWholeDeclaration(functionDeclaration)) return textSpan(functionDeclaration); - return spanInNode(functionDeclaration.body); - } - function spanInFunctionBlock(block) { - const nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken(); - if (canFunctionHaveSpanInWholeDeclaration(block.parent)) return spanInNodeIfStartsOnSameLine(block.parent, nodeForSpanInBlock); - return spanInNode(nodeForSpanInBlock); - } - function spanInBlock(block) { - switch(block.parent.kind){ - case 264 /* ModuleDeclaration */ : - if (getModuleInstanceState(block.parent) !== 1 /* Instantiated */ ) return void 0; - case 244 /* WhileStatement */ : - case 242 /* IfStatement */ : - case 246 /* ForInStatement */ : - return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); - case 245 /* ForStatement */ : - case 247 /* ForOfStatement */ : - return spanInNodeIfStartsOnSameLine(findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); - } - return spanInNode(block.statements[0]); - } - function spanInInitializerOfForLike(forLikeStatement) { - if (forLikeStatement.initializer.kind === 258 /* VariableDeclarationList */ ) { - const variableDeclarationList = forLikeStatement.initializer; - if (variableDeclarationList.declarations.length > 0) return spanInNode(variableDeclarationList.declarations[0]); - } else return spanInNode(forLikeStatement.initializer); - } - function spanInForStatement(forStatement) { - if (forStatement.initializer) return spanInInitializerOfForLike(forStatement); - if (forStatement.condition) return textSpan(forStatement.condition); - if (forStatement.incrementor) return textSpan(forStatement.incrementor); - } - function spanInBindingPattern(bindingPattern) { - const firstBindingElement = forEach(bindingPattern.elements, (element)=>element.kind !== 229 /* OmittedExpression */ ? element : void 0); - if (firstBindingElement) return spanInNode(firstBindingElement); - if (bindingPattern.parent.kind === 205 /* BindingElement */ ) return textSpan(bindingPattern.parent); - return textSpanFromVariableDeclaration(bindingPattern.parent); - } - function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node2) { - Debug.assert(node2.kind !== 204 /* ArrayBindingPattern */ && node2.kind !== 203 /* ObjectBindingPattern */ ); - const elements = node2.kind === 206 /* ArrayLiteralExpression */ ? node2.elements : node2.properties; - const firstBindingElement = forEach(elements, (element)=>element.kind !== 229 /* OmittedExpression */ ? element : void 0); - if (firstBindingElement) return spanInNode(firstBindingElement); - return textSpan(node2.parent.kind === 223 /* BinaryExpression */ ? node2.parent : node2); - } - function spanInOpenBraceToken(node2) { - switch(node2.parent.kind){ - case 263 /* EnumDeclaration */ : - const enumDeclaration = node2.parent; - return spanInNodeIfStartsOnSameLine(findPrecedingToken(node2.pos, sourceFile, node2.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 260 /* ClassDeclaration */ : - const classDeclaration = node2.parent; - return spanInNodeIfStartsOnSameLine(findPrecedingToken(node2.pos, sourceFile, node2.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 266 /* CaseBlock */ : - return spanInNodeIfStartsOnSameLine(node2.parent.parent, node2.parent.clauses[0]); - } - return spanInNode(node2.parent); - } - function spanInCloseBraceToken(node2) { - switch(node2.parent.kind){ - case 265 /* ModuleBlock */ : - if (getModuleInstanceState(node2.parent.parent) !== 1 /* Instantiated */ ) return void 0; - case 263 /* EnumDeclaration */ : - case 260 /* ClassDeclaration */ : - return textSpan(node2); - case 238 /* Block */ : - if (isFunctionBlock(node2.parent)) return textSpan(node2); - case 295 /* CatchClause */ : - return spanInNode(lastOrUndefined(node2.parent.statements)); - case 266 /* CaseBlock */ : - const caseBlock = node2.parent; - const lastClause = lastOrUndefined(caseBlock.clauses); - if (lastClause) return spanInNode(lastOrUndefined(lastClause.statements)); - return void 0; - case 203 /* ObjectBindingPattern */ : - const bindingPattern = node2.parent; - return spanInNode(lastOrUndefined(bindingPattern.elements) || bindingPattern); - default: - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node2.parent)) { - const objectLiteral = node2.parent; - return textSpan(lastOrUndefined(objectLiteral.properties) || objectLiteral); - } - return spanInNode(node2.parent); - } - } - function spanInCloseBracketToken(node2) { - switch(node2.parent.kind){ - case 204 /* ArrayBindingPattern */ : - const bindingPattern = node2.parent; - return textSpan(lastOrUndefined(bindingPattern.elements) || bindingPattern); - default: - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node2.parent)) { - const arrayLiteral = node2.parent; - return textSpan(lastOrUndefined(arrayLiteral.elements) || arrayLiteral); + ] } - return spanInNode(node2.parent); - } - } - function spanInOpenParenToken(node2) { - if (node2.parent.kind === 243 /* DoStatement */ || // Go to while keyword and do action instead - node2.parent.kind === 210 /* CallExpression */ || node2.parent.kind === 211 /* NewExpression */ ) return spanInPreviousNode(node2); - if (node2.parent.kind === 214 /* ParenthesizedExpression */ ) return spanInNextNode(node2); - return spanInNode(node2.parent); - } - function spanInCloseParenToken(node2) { - switch(node2.parent.kind){ - case 215 /* FunctionExpression */ : - case 259 /* FunctionDeclaration */ : - case 216 /* ArrowFunction */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 173 /* Constructor */ : - case 244 /* WhileStatement */ : - case 243 /* DoStatement */ : - case 245 /* ForStatement */ : - case 247 /* ForOfStatement */ : - case 210 /* CallExpression */ : - case 211 /* NewExpression */ : - case 214 /* ParenthesizedExpression */ : - return spanInPreviousNode(node2); - default: - return spanInNode(node2.parent); + ]; + return emptyArray; } - } - function spanInColonToken(node2) { - if (isFunctionLike(node2.parent) || node2.parent.kind === 299 /* PropertyAssignment */ || node2.parent.kind === 166 /* Parameter */ ) return spanInPreviousNode(node2); - return spanInNode(node2.parent); - } - function spanInGreaterThanOrLessThanToken(node2) { - if (node2.parent.kind === 213 /* TypeAssertionExpression */ ) return spanInNextNode(node2); - return spanInNode(node2.parent); - } - function spanInWhileKeyword(node2) { - if (node2.parent.kind === 243 /* DoStatement */ ) return textSpanEndingAtNextToken(node2, node2.parent.expression); - return spanInNode(node2.parent); - } - function spanInOfKeyword(node2) { - if (node2.parent.kind === 247 /* ForOfStatement */ ) return spanInNextNode(node2); - return spanInNode(node2.parent); - } - } - } - var init_breakpoints = __esm({ - "src/services/breakpoints.ts" () { - "use strict"; - init_ts4(); + }); } }); - // src/services/_namespaces/ts.BreakpointResolver.ts - var ts_BreakpointResolver_exports = {}; - __export(ts_BreakpointResolver_exports, { - spanInSourceFileAtLocation: ()=>spanInSourceFileAtLocation - }); - var init_ts_BreakpointResolver = __esm({ - "src/services/_namespaces/ts.BreakpointResolver.ts" () { + // src/services/_namespaces/ts.refactor.generateGetAccessorAndSetAccessor.ts + var ts_refactor_generateGetAccessorAndSetAccessor_exports = {}; + var init_ts_refactor_generateGetAccessorAndSetAccessor = __esm({ + "src/services/_namespaces/ts.refactor.generateGetAccessorAndSetAccessor.ts" () { "use strict"; - init_breakpoints(); + init_generateGetAccessorAndSetAccessor(); } }); - // src/services/callHierarchy.ts - function isNamedExpression(node) { - return (isFunctionExpression(node) || isClassExpression(node)) && isNamedDeclaration(node); - } - function isConstNamedExpression(node) { - return (isFunctionExpression(node) || isArrowFunction(node) || isClassExpression(node)) && isVariableDeclaration(node.parent) && node === node.parent.initializer && isIdentifier(node.parent.name) && !!(getCombinedNodeFlags(node.parent) & 2 /* Const */ ); - } - function isPossibleCallHierarchyDeclaration(node) { - return isSourceFile(node) || isModuleDeclaration(node) || isFunctionDeclaration(node) || isFunctionExpression(node) || isClassDeclaration(node) || isClassExpression(node) || isClassStaticBlockDeclaration(node) || isMethodDeclaration(node) || isMethodSignature(node) || isGetAccessorDeclaration(node) || isSetAccessorDeclaration(node); - } - function isValidCallHierarchyDeclaration(node) { - return isSourceFile(node) || isModuleDeclaration(node) && isIdentifier(node.name) || isFunctionDeclaration(node) || isClassDeclaration(node) || isClassStaticBlockDeclaration(node) || isMethodDeclaration(node) || isMethodSignature(node) || isGetAccessorDeclaration(node) || isSetAccessorDeclaration(node) || isNamedExpression(node) || isConstNamedExpression(node); - } - function getCallHierarchyDeclarationReferenceNode(node) { - if (isSourceFile(node)) return node; - if (isNamedDeclaration(node)) return node.name; - if (isConstNamedExpression(node)) return node.parent.name; - return Debug.checkDefined(node.modifiers && find(node.modifiers, isDefaultModifier3)); - } - function isDefaultModifier3(node) { - return node.kind === 88 /* DefaultKeyword */ ; - } - function getSymbolOfCallHierarchyDeclaration(typeChecker, node) { - const location = getCallHierarchyDeclarationReferenceNode(node); - return location && typeChecker.getSymbolAtLocation(location); - } - function getCallHierarchyItemName(program, node) { - if (isSourceFile(node)) return { - text: node.fileName, - pos: 0, - end: 0 - }; - if ((isFunctionDeclaration(node) || isClassDeclaration(node)) && !isNamedDeclaration(node)) { - const defaultModifier = node.modifiers && find(node.modifiers, isDefaultModifier3); - if (defaultModifier) return { - text: "default", - pos: defaultModifier.getStart(), - end: defaultModifier.getEnd() - }; - } - if (isClassStaticBlockDeclaration(node)) { - const sourceFile = node.getSourceFile(); - const pos = skipTrivia(sourceFile.text, moveRangePastModifiers(node).pos); - const end = pos + 6; - const typeChecker = program.getTypeChecker(); - const symbol = typeChecker.getSymbolAtLocation(node.parent); - const prefix = symbol ? `${typeChecker.symbolToString(symbol, node.parent)} ` : ""; + // src/services/refactors/inferFunctionReturnType.ts + function getRefactorEditsToInferReturnType(context) { + const info = getInfo4(context); + if (info && !isRefactorErrorInfo(info)) { + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange7(context.file, t, info.declaration, info.returnTypeNode)); return { - text: `${prefix}static {}`, - pos: pos, - end: end + renameFilename: void 0, + renameLocation: void 0, + edits: edits }; } - const declName = isConstNamedExpression(node) ? node.parent.name : Debug.checkDefined(getNameOfDeclaration(node), "Expected call hierarchy item to have a name"); - let text = isIdentifier(declName) ? idText(declName) : isStringOrNumericLiteralLike(declName) ? declName.text : isComputedPropertyName(declName) ? isStringOrNumericLiteralLike(declName.expression) ? declName.expression.text : void 0 : void 0; - if (text === void 0) { - const typeChecker = program.getTypeChecker(); - const symbol = typeChecker.getSymbolAtLocation(declName); - if (symbol) text = typeChecker.symbolToString(symbol, node); - } - if (text === void 0) { - const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon(); - text = usingSingleLineStringWriter((writer)=>printer.writeNode(4 /* Unspecified */ , node, node.getSourceFile(), writer)); - } - return { - text: text, - pos: declName.getStart(), - end: declName.getEnd() - }; - } - function getCallHierarchItemContainerName(node) { - var _a2, _b; - if (isConstNamedExpression(node)) { - if (isModuleBlock(node.parent.parent.parent.parent) && isIdentifier(node.parent.parent.parent.parent.parent.name)) return node.parent.parent.parent.parent.parent.name.getText(); - return; - } - switch(node.kind){ - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 171 /* MethodDeclaration */ : - if (node.parent.kind === 207 /* ObjectLiteralExpression */ ) return (_a2 = getAssignedName(node.parent)) == null ? void 0 : _a2.getText(); - return (_b = getNameOfDeclaration(node.parent)) == null ? void 0 : _b.getText(); - case 259 /* FunctionDeclaration */ : - case 260 /* ClassDeclaration */ : - case 264 /* ModuleDeclaration */ : - if (isModuleBlock(node.parent) && isIdentifier(node.parent.parent.name)) return node.parent.parent.name.getText(); - } - } - function findImplementation(typeChecker, node) { - if (node.body) return node; - if (isConstructorDeclaration(node)) return getFirstConstructorWithBody(node.parent); - if (isFunctionDeclaration(node) || isMethodDeclaration(node)) { - const symbol = getSymbolOfCallHierarchyDeclaration(typeChecker, node); - if (symbol && symbol.valueDeclaration && isFunctionLikeDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.body) return symbol.valueDeclaration; - return void 0; - } - return node; - } - function findAllInitialDeclarations(typeChecker, node) { - const symbol = getSymbolOfCallHierarchyDeclaration(typeChecker, node); - let declarations; - if (symbol && symbol.declarations) { - const indices = indicesOf(symbol.declarations); - const keys = map(symbol.declarations, (decl)=>({ - file: decl.getSourceFile().fileName, - pos: decl.pos - })); - indices.sort((a, b)=>compareStringsCaseSensitive(keys[a].file, keys[b].file) || keys[a].pos - keys[b].pos); - const sortedDeclarations = map(indices, (i)=>symbol.declarations[i]); - let lastDecl; - for (const decl of sortedDeclarations)if (isValidCallHierarchyDeclaration(decl)) { - if (!lastDecl || lastDecl.parent !== decl.parent || lastDecl.end !== decl.pos) declarations = append(declarations, decl); - lastDecl = decl; - } - } - return declarations; - } - function findImplementationOrAllInitialDeclarations(typeChecker, node) { - var _a2, _b, _c; - if (isClassStaticBlockDeclaration(node)) return node; - if (isFunctionLikeDeclaration(node)) return (_b = (_a2 = findImplementation(typeChecker, node)) != null ? _a2 : findAllInitialDeclarations(typeChecker, node)) != null ? _b : node; - return (_c = findAllInitialDeclarations(typeChecker, node)) != null ? _c : node; + return void 0; } - function resolveCallHierarchyDeclaration(program, location) { - const typeChecker = program.getTypeChecker(); - let followingSymbol = false; - while(true){ - if (isValidCallHierarchyDeclaration(location)) return findImplementationOrAllInitialDeclarations(typeChecker, location); - if (isPossibleCallHierarchyDeclaration(location)) { - const ancestor = findAncestor(location, isValidCallHierarchyDeclaration); - return ancestor && findImplementationOrAllInitialDeclarations(typeChecker, ancestor); - } - if (isDeclarationName(location)) { - if (isValidCallHierarchyDeclaration(location.parent)) return findImplementationOrAllInitialDeclarations(typeChecker, location.parent); - if (isPossibleCallHierarchyDeclaration(location.parent)) { - const ancestor = findAncestor(location.parent, isValidCallHierarchyDeclaration); - return ancestor && findImplementationOrAllInitialDeclarations(typeChecker, ancestor); - } - if (isVariableDeclaration(location.parent) && location.parent.initializer && isConstNamedExpression(location.parent.initializer)) return location.parent.initializer; - return void 0; - } - if (isConstructorDeclaration(location)) { - if (isValidCallHierarchyDeclaration(location.parent)) return location.parent; - return void 0; - } - if (location.kind === 124 /* StaticKeyword */ && isClassStaticBlockDeclaration(location.parent)) { - location = location.parent; - continue; + function getRefactorActionsToInferReturnType(context) { + const info = getInfo4(context); + if (!info) return emptyArray; + if (!isRefactorErrorInfo(info)) return [ + { + name: refactorName13, + description: refactorDescription7, + actions: [ + inferReturnTypeAction + ] } - if (isVariableDeclaration(location) && location.initializer && isConstNamedExpression(location.initializer)) return location.initializer; - if (!followingSymbol) { - let symbol = typeChecker.getSymbolAtLocation(location); - if (symbol) { - if (symbol.flags & 2097152 /* Alias */ ) symbol = typeChecker.getAliasedSymbol(symbol); - if (symbol.valueDeclaration) { - followingSymbol = true; - location = symbol.valueDeclaration; - continue; + ]; + if (context.preferences.provideRefactorNotApplicableReason) return [ + { + name: refactorName13, + description: refactorDescription7, + actions: [ + { + ...inferReturnTypeAction, + notApplicableReason: info.error } - } + ] } - return void 0; - } - } - function createCallHierarchyItem(program, node) { - const sourceFile = node.getSourceFile(); - const name = getCallHierarchyItemName(program, node); - const containerName = getCallHierarchItemContainerName(node); - const kind = getNodeKind(node); - const kindModifiers = getNodeModifiers(node); - const span = createTextSpanFromBounds(skipTrivia(sourceFile.text, node.getFullStart(), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true), node.getEnd()); - const selectionSpan = createTextSpanFromBounds(name.pos, name.end); - return { - file: sourceFile.fileName, - kind: kind, - kindModifiers: kindModifiers, - name: name.text, - containerName: containerName, - span: span, - selectionSpan: selectionSpan - }; - } - function isDefined(x) { - return x !== void 0; + ]; + return emptyArray; } - function convertEntryToCallSite(entry) { - if (entry.kind === ts_FindAllReferences_exports.EntryKind.Node) { - const { node: node } = entry; - if (isCallOrNewExpressionTarget(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true) || isTaggedTemplateTag(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true) || isDecoratorTarget(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true) || isJsxOpeningLikeElementTagName(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true) || isRightSideOfPropertyAccess(node) || isArgumentExpressionOfElementAccess(node)) { - const sourceFile = node.getSourceFile(); - const ancestor = findAncestor(node, isValidCallHierarchyDeclaration) || sourceFile; - return { - declaration: ancestor, - range: createTextRangeFromNode(node, sourceFile) - }; + function doChange7(sourceFile, changes, declaration, typeNode) { + const closeParen = findChildOfKind(declaration, 22 /* CloseParenToken */ , sourceFile); + const needParens = isArrowFunction(declaration) && closeParen === void 0; + const endNode2 = needParens ? first(declaration.parameters) : closeParen; + if (endNode2) { + if (needParens) { + changes.insertNodeBefore(sourceFile, endNode2, factory.createToken(21 /* OpenParenToken */ )); + changes.insertNodeAfter(sourceFile, endNode2, factory.createToken(22 /* CloseParenToken */ )); } + changes.insertNodeAt(sourceFile, endNode2.end, typeNode, { + prefix: ": " + }); } } - function getCallSiteGroupKey(entry) { - return getNodeId(entry.declaration); - } - function createCallHierarchyIncomingCall(from, fromSpans) { - return { - from: from, - fromSpans: fromSpans + function getInfo4(context) { + if (isInJSFile(context.file) || !refactorKindBeginsWith(inferReturnTypeAction.kind, context.kind)) return; + const token = getTokenAtPosition(context.file, context.startPosition); + const declaration = findAncestor(token, (n)=>isBlock(n) || n.parent && isArrowFunction(n.parent) && (n.kind === 39 /* EqualsGreaterThanToken */ || n.parent.body === n) ? "quit" : isConvertibleDeclaration(n)); + if (!declaration || !declaration.body || declaration.type) return { + error: getLocaleSpecificMessage(Diagnostics.Return_type_must_be_inferred_from_a_function) + }; + const typeChecker = context.program.getTypeChecker(); + const returnType = tryGetReturnType(typeChecker, declaration); + if (!returnType) return { + error: getLocaleSpecificMessage(Diagnostics.Could_not_determine_function_return_type) + }; + const returnTypeNode = typeChecker.typeToTypeNode(returnType, declaration, 1 /* NoTruncation */ ); + if (returnTypeNode) return { + declaration: declaration, + returnTypeNode: returnTypeNode }; } - function convertCallSiteGroupToIncomingCall(program, entries) { - return createCallHierarchyIncomingCall(createCallHierarchyItem(program, entries[0].declaration), map(entries, (entry)=>createTextSpanFromRange(entry.range))); - } - function getIncomingCalls(program, declaration, cancellationToken) { - if (isSourceFile(declaration) || isModuleDeclaration(declaration) || isClassStaticBlockDeclaration(declaration)) return []; - const location = getCallHierarchyDeclarationReferenceNode(declaration); - const calls = filter(ts_FindAllReferences_exports.findReferenceOrRenameEntries(program, cancellationToken, program.getSourceFiles(), location, /*position*/ 0, { - use: ts_FindAllReferences_exports.FindReferencesUse.References - }, convertEntryToCallSite), isDefined); - return calls ? group(calls, getCallSiteGroupKey, (entries)=>convertCallSiteGroupToIncomingCall(program, entries)) : []; - } - function createCallSiteCollector(program, callSites) { - function recordCallSite(node) { - const target = isTaggedTemplateExpression(node) ? node.tag : isJsxOpeningLikeElement(node) ? node.tagName : isAccessExpression(node) ? node : isClassStaticBlockDeclaration(node) ? node : node.expression; - const declaration = resolveCallHierarchyDeclaration(program, target); - if (declaration) { - const range = createTextRangeFromNode(target, node.getSourceFile()); - if (isArray(declaration)) for (const decl of declaration)callSites.push({ - declaration: decl, - range: range - }); - else callSites.push({ - declaration: declaration, - range: range - }); - } - } - function collect(node) { - if (!node) return; - if (node.flags & 16777216 /* Ambient */ ) return; - if (isValidCallHierarchyDeclaration(node)) { - if (isClassLike(node)) { - for (const member of node.members)if (member.name && isComputedPropertyName(member.name)) collect(member.name.expression); - } - return; - } - switch(node.kind){ - case 79 /* Identifier */ : - case 268 /* ImportEqualsDeclaration */ : - case 269 /* ImportDeclaration */ : - case 275 /* ExportDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 262 /* TypeAliasDeclaration */ : - return; - case 172 /* ClassStaticBlockDeclaration */ : - recordCallSite(node); - return; - case 213 /* TypeAssertionExpression */ : - case 231 /* AsExpression */ : - collect(node.expression); - return; - case 257 /* VariableDeclaration */ : - case 166 /* Parameter */ : - collect(node.name); - collect(node.initializer); - return; - case 210 /* CallExpression */ : - recordCallSite(node); - collect(node.expression); - forEach(node.arguments, collect); - return; - case 211 /* NewExpression */ : - recordCallSite(node); - collect(node.expression); - forEach(node.arguments, collect); - return; - case 212 /* TaggedTemplateExpression */ : - recordCallSite(node); - collect(node.tag); - collect(node.template); - return; - case 283 /* JsxOpeningElement */ : - case 282 /* JsxSelfClosingElement */ : - recordCallSite(node); - collect(node.tagName); - collect(node.attributes); - return; - case 167 /* Decorator */ : - recordCallSite(node); - collect(node.expression); - return; - case 208 /* PropertyAccessExpression */ : - case 209 /* ElementAccessExpression */ : - recordCallSite(node); - forEachChild(node, collect); - break; - case 235 /* SatisfiesExpression */ : - collect(node.expression); - return; - } - if (isPartOfTypeNode(node)) return; - forEachChild(node, collect); - } - return collect; - } - function collectCallSitesOfSourceFile(node, collect) { - forEach(node.statements, collect); - } - function collectCallSitesOfModuleDeclaration(node, collect) { - if (!hasSyntacticModifier(node, 2 /* Ambient */ ) && node.body && isModuleBlock(node.body)) forEach(node.body.statements, collect); - } - function collectCallSitesOfFunctionLikeDeclaration(typeChecker, node, collect) { - const implementation = findImplementation(typeChecker, node); - if (implementation) { - forEach(implementation.parameters, collect); - collect(implementation.body); - } - } - function collectCallSitesOfClassStaticBlockDeclaration(node, collect) { - collect(node.body); - } - function collectCallSitesOfClassLikeDeclaration(node, collect) { - forEach(node.modifiers, collect); - const heritage = getClassExtendsHeritageElement(node); - if (heritage) collect(heritage.expression); - for (const member of node.members){ - if (canHaveModifiers(member)) forEach(member.modifiers, collect); - if (isPropertyDeclaration(member)) collect(member.initializer); - else if (isConstructorDeclaration(member) && member.body) { - forEach(member.parameters, collect); - collect(member.body); - } else if (isClassStaticBlockDeclaration(member)) collect(member); - } - } - function collectCallSites(program, node) { - const callSites = []; - const collect = createCallSiteCollector(program, callSites); + function isConvertibleDeclaration(node) { switch(node.kind){ - case 308 /* SourceFile */ : - collectCallSitesOfSourceFile(node, collect); - break; - case 264 /* ModuleDeclaration */ : - collectCallSitesOfModuleDeclaration(node, collect); - break; - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - collectCallSitesOfFunctionLikeDeclaration(program.getTypeChecker(), node, collect); - break; - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : - collectCallSitesOfClassLikeDeclaration(node, collect); - break; - case 172 /* ClassStaticBlockDeclaration */ : - collectCallSitesOfClassStaticBlockDeclaration(node, collect); - break; + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + case 174 /* MethodDeclaration */ : + return true; default: - Debug.assertNever(node); + return false; } - return callSites; } - function createCallHierarchyOutgoingCall(to, fromSpans) { - return { - to: to, - fromSpans: fromSpans - }; - } - function convertCallSiteGroupToOutgoingCall(program, entries) { - return createCallHierarchyOutgoingCall(createCallHierarchyItem(program, entries[0].declaration), map(entries, (entry)=>createTextSpanFromRange(entry.range))); - } - function getOutgoingCalls(program, declaration) { - if (declaration.flags & 16777216 /* Ambient */ || isMethodSignature(declaration)) return []; - return group(collectCallSites(program, declaration), getCallSiteGroupKey, (entries)=>convertCallSiteGroupToOutgoingCall(program, entries)); + function tryGetReturnType(typeChecker, node) { + if (typeChecker.isImplementationOfOverload(node)) { + const signatures = typeChecker.getTypeAtLocation(node).getCallSignatures(); + if (signatures.length > 1) return typeChecker.getUnionType(mapDefined(signatures, (s)=>s.getReturnType())); + } + const signature = typeChecker.getSignatureFromDeclaration(node); + if (signature) return typeChecker.getReturnTypeOfSignature(signature); } - var init_callHierarchy = __esm({ - "src/services/callHierarchy.ts" () { + var refactorName13, refactorDescription7, inferReturnTypeAction; + var init_inferFunctionReturnType = __esm({ + "src/services/refactors/inferFunctionReturnType.ts" () { "use strict"; init_ts4(); + init_ts_refactor(); + refactorName13 = "Infer function return type"; + refactorDescription7 = getLocaleSpecificMessage(Diagnostics.Infer_function_return_type); + inferReturnTypeAction = { + name: refactorName13, + description: refactorDescription7, + kind: "refactor.rewrite.function.returnType" + }; + registerRefactor(refactorName13, { + kinds: [ + inferReturnTypeAction.kind + ], + getEditsForAction: getRefactorEditsToInferReturnType, + getAvailableActions: getRefactorActionsToInferReturnType + }); } }); - // src/services/_namespaces/ts.CallHierarchy.ts - var ts_CallHierarchy_exports = {}; - __export(ts_CallHierarchy_exports, { - createCallHierarchyItem: ()=>createCallHierarchyItem, - getIncomingCalls: ()=>getIncomingCalls, - getOutgoingCalls: ()=>getOutgoingCalls, - resolveCallHierarchyDeclaration: ()=>resolveCallHierarchyDeclaration + // src/services/_namespaces/ts.refactor.inferFunctionReturnType.ts + var ts_refactor_inferFunctionReturnType_exports = {}; + var init_ts_refactor_inferFunctionReturnType = __esm({ + "src/services/_namespaces/ts.refactor.inferFunctionReturnType.ts" () { + "use strict"; + init_inferFunctionReturnType(); + } }); - var init_ts_CallHierarchy = __esm({ - "src/services/_namespaces/ts.CallHierarchy.ts" () { + // src/services/_namespaces/ts.refactor.ts + var ts_refactor_exports = {}; + __export(ts_refactor_exports, { + addExportToChanges: ()=>addExportToChanges, + addExports: ()=>addExports, + addNewFileToTsconfig: ()=>addNewFileToTsconfig, + addOrRemoveBracesToArrowFunction: ()=>ts_refactor_addOrRemoveBracesToArrowFunction_exports, + convertArrowFunctionOrFunctionExpression: ()=>ts_refactor_convertArrowFunctionOrFunctionExpression_exports, + convertParamsToDestructuredObject: ()=>ts_refactor_convertParamsToDestructuredObject_exports, + convertStringOrTemplateLiteral: ()=>ts_refactor_convertStringOrTemplateLiteral_exports, + convertToOptionalChainExpression: ()=>ts_refactor_convertToOptionalChainExpression_exports, + createNewFileName: ()=>createNewFileName, + createOldFileImportsFromTargetFile: ()=>createOldFileImportsFromTargetFile, + deleteMovedStatements: ()=>deleteMovedStatements, + deleteUnusedImports: ()=>deleteUnusedImports, + deleteUnusedOldImports: ()=>deleteUnusedOldImports, + doChangeNamedToNamespaceOrDefault: ()=>doChangeNamedToNamespaceOrDefault, + extractSymbol: ()=>ts_refactor_extractSymbol_exports, + filterImport: ()=>filterImport, + forEachImportInStatement: ()=>forEachImportInStatement, + generateGetAccessorAndSetAccessor: ()=>ts_refactor_generateGetAccessorAndSetAccessor_exports, + getApplicableRefactors: ()=>getApplicableRefactors, + getEditsForRefactor: ()=>getEditsForRefactor, + getStatementsToMove: ()=>getStatementsToMove, + getTopLevelDeclarationStatement: ()=>getTopLevelDeclarationStatement, + getUsageInfo: ()=>getUsageInfo, + inferFunctionReturnType: ()=>ts_refactor_inferFunctionReturnType_exports, + isRefactorErrorInfo: ()=>isRefactorErrorInfo, + isTopLevelDeclaration: ()=>isTopLevelDeclaration, + makeImportOrRequire: ()=>makeImportOrRequire, + moduleSpecifierFromImport: ()=>moduleSpecifierFromImport, + nameOfTopLevelDeclaration: ()=>nameOfTopLevelDeclaration, + refactorKindBeginsWith: ()=>refactorKindBeginsWith, + registerRefactor: ()=>registerRefactor, + updateImportsInOtherFiles: ()=>updateImportsInOtherFiles + }); + var init_ts_refactor = __esm({ + "src/services/_namespaces/ts.refactor.ts" () { "use strict"; - init_callHierarchy(); + init_refactorProvider(); + init_convertExport(); + init_convertImport(); + init_extractType(); + init_helpers(); + init_inlineVariable(); + init_moveToNewFile(); + init_moveToFile(); + init_ts_refactor_addOrRemoveBracesToArrowFunction(); + init_ts_refactor_convertArrowFunctionOrFunctionExpression(); + init_ts_refactor_convertParamsToDestructuredObject(); + init_ts_refactor_convertStringOrTemplateLiteral(); + init_ts_refactor_convertToOptionalChainExpression(); + init_ts_refactor_extractSymbol(); + init_ts_refactor_generateGetAccessorAndSetAccessor(); + init_ts_refactor_inferFunctionReturnType(); } }); // src/services/classifier2020.ts @@ -109228,13 +112381,13 @@ ${lanes.join("\n")} let inJSXElement = false; function visit(node) { switch(node.kind){ - case 264 /* ModuleDeclaration */ : - case 260 /* ClassDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 259 /* FunctionDeclaration */ : - case 228 /* ClassExpression */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : + case 267 /* ModuleDeclaration */ : + case 263 /* ClassDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 262 /* FunctionDeclaration */ : + case 231 /* ClassExpression */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : cancellationToken.throwIfCancellationRequested(); } if (!node || !textSpanIntersectsWith(span, node.pos, node.getFullWidth()) || node.getFullWidth() === 0) return; @@ -109359,20202 +112512,19995 @@ ${lanes.join("\n")} })(TokenModifier || {}); tokenFromDeclarationMapping = /* @__PURE__ */ new Map([ [ - 257 /* VariableDeclaration */ , + 260 /* VariableDeclaration */ , 7 /* variable */ ], [ - 166 /* Parameter */ , + 169 /* Parameter */ , 6 /* parameter */ ], [ - 169 /* PropertyDeclaration */ , + 172 /* PropertyDeclaration */ , 9 /* property */ ], [ - 264 /* ModuleDeclaration */ , + 267 /* ModuleDeclaration */ , 3 /* namespace */ ], [ - 263 /* EnumDeclaration */ , + 266 /* EnumDeclaration */ , 1 /* enum */ ], [ - 302 /* EnumMember */ , + 306 /* EnumMember */ , 8 /* enumMember */ ], [ - 260 /* ClassDeclaration */ , + 263 /* ClassDeclaration */ , 0 /* class */ ], [ - 171 /* MethodDeclaration */ , + 174 /* MethodDeclaration */ , 11 /* member */ ], [ - 259 /* FunctionDeclaration */ , + 262 /* FunctionDeclaration */ , 10 /* function */ ], [ - 215 /* FunctionExpression */ , + 218 /* FunctionExpression */ , 10 /* function */ ], [ - 170 /* MethodSignature */ , + 173 /* MethodSignature */ , 11 /* member */ ], [ - 174 /* GetAccessor */ , + 177 /* GetAccessor */ , 9 /* property */ ], [ - 175 /* SetAccessor */ , + 178 /* SetAccessor */ , 9 /* property */ ], [ - 168 /* PropertySignature */ , + 171 /* PropertySignature */ , 9 /* property */ ], [ - 261 /* InterfaceDeclaration */ , + 264 /* InterfaceDeclaration */ , 2 /* interface */ ], [ - 262 /* TypeAliasDeclaration */ , + 265 /* TypeAliasDeclaration */ , 5 /* type */ ], [ - 165 /* TypeParameter */ , + 168 /* TypeParameter */ , 4 /* typeParameter */ ], [ - 299 /* PropertyAssignment */ , + 303 /* PropertyAssignment */ , 9 /* property */ ], [ - 300 /* ShorthandPropertyAssignment */ , + 304 /* ShorthandPropertyAssignment */ , 9 /* property */ ] ]); } }); - // src/services/_namespaces/ts.classifier.v2020.ts - var ts_classifier_v2020_exports = {}; - __export(ts_classifier_v2020_exports, { - TokenEncodingConsts: ()=>TokenEncodingConsts, - TokenModifier: ()=>TokenModifier, - TokenType: ()=>TokenType, - getEncodedSemanticClassifications: ()=>getEncodedSemanticClassifications2, - getSemanticClassifications: ()=>getSemanticClassifications2 - }); - var init_ts_classifier_v2020 = __esm({ - "src/services/_namespaces/ts.classifier.v2020.ts" () { - "use strict"; - init_classifier2020(); - } - }); - // src/services/_namespaces/ts.classifier.ts - var ts_classifier_exports = {}; - __export(ts_classifier_exports, { - v2020: ()=>ts_classifier_v2020_exports - }); - var init_ts_classifier = __esm({ - "src/services/_namespaces/ts.classifier.ts" () { - "use strict"; - init_ts_classifier_v2020(); - } - }); - // src/services/codeFixProvider.ts - function createCodeFixActionWithoutFixAll(fixName8, changes, description2) { - return createCodeFixActionWorker(fixName8, diagnosticToString(description2), changes, /*fixId*/ void 0, /*fixAllDescription*/ void 0); - } - function createCodeFixAction(fixName8, changes, description2, fixId51, fixAllDescription, command) { - return createCodeFixActionWorker(fixName8, diagnosticToString(description2), changes, fixId51, diagnosticToString(fixAllDescription), command); - } - function createCodeFixActionMaybeFixAll(fixName8, changes, description2, fixId51, fixAllDescription, command) { - return createCodeFixActionWorker(fixName8, diagnosticToString(description2), changes, fixId51, fixAllDescription && diagnosticToString(fixAllDescription), command); + // src/services/services.ts + function createNode(kind, pos, end, parent2) { + const node = isNodeKind(kind) ? new NodeObject(kind, pos, end) : kind === 80 /* Identifier */ ? new IdentifierObject(80 /* Identifier */ , pos, end) : kind === 81 /* PrivateIdentifier */ ? new PrivateIdentifierObject(81 /* PrivateIdentifier */ , pos, end) : new TokenObject(kind, pos, end); + node.parent = parent2; + node.flags = parent2.flags & 101441536 /* ContextFlags */ ; + return node; } - function createCodeFixActionWorker(fixName8, description2, changes, fixId51, fixAllDescription, command) { - return { - fixName: fixName8, - description: description2, - changes: changes, - fixId: fixId51, - fixAllDescription: fixAllDescription, - commands: command ? [ - command - ] : void 0 + function createChildren(node, sourceFile) { + if (!isNodeKind(node.kind)) return emptyArray; + const children = []; + if (isJSDocCommentContainingNode(node)) { + node.forEachChild((child)=>{ + children.push(child); + }); + return children; + } + scanner.setText((sourceFile || node.getSourceFile()).text); + let pos = node.pos; + const processNode = (child)=>{ + addSyntheticNodes(children, pos, child.pos, node); + children.push(child); + pos = child.end; + }; + const processNodes = (nodes)=>{ + addSyntheticNodes(children, pos, nodes.pos, node); + children.push(createSyntaxList(nodes, node)); + pos = nodes.end; }; + forEach(node.jsDoc, processNode); + pos = node.pos; + node.forEachChild(processNode, processNodes); + addSyntheticNodes(children, pos, node.end, node); + scanner.setText(void 0); + return children; } - function registerCodeFix(reg) { - for (const error of reg.errorCodes)errorCodeToFixes.add(String(error), reg); - if (reg.fixIds) for (const fixId51 of reg.fixIds){ - Debug.assert(!fixIdToRegistration.has(fixId51)); - fixIdToRegistration.set(fixId51, reg); + function addSyntheticNodes(nodes, pos, end, parent2) { + scanner.resetTokenState(pos); + while(pos < end){ + const token = scanner.scan(); + const textPos = scanner.getTokenEnd(); + if (textPos <= end) { + if (token === 80 /* Identifier */ ) { + if (hasTabstop(parent2)) continue; + Debug.fail(`Did not expect ${Debug.formatSyntaxKind(parent2.kind)} to have an Identifier in its trivia`); + } + nodes.push(createNode(token, pos, textPos, parent2)); + } + pos = textPos; + if (token === 1 /* EndOfFileToken */ ) break; } } - function getSupportedErrorCodes() { - return arrayFrom(errorCodeToFixes.keys()); - } - function removeFixIdIfFixAllUnavailable(registration, diagnostics) { - const { errorCodes: errorCodes63 } = registration; - let maybeFixableDiagnostics = 0; - for (const diag2 of diagnostics){ - if (contains(errorCodes63, diag2.code)) maybeFixableDiagnostics++; - if (maybeFixableDiagnostics > 1) break; + function createSyntaxList(nodes, parent2) { + const list = createNode(358 /* SyntaxList */ , nodes.pos, nodes.end, parent2); + list._children = []; + let pos = nodes.pos; + for (const node of nodes){ + addSyntheticNodes(list._children, pos, node.pos, parent2); + list._children.push(node); + pos = node.end; } - const fixAllUnavailable = maybeFixableDiagnostics < 2; - return ({ fixId: fixId51 , fixAllDescription: fixAllDescription , ...action })=>{ - return fixAllUnavailable ? action : { - ...action, - fixId: fixId51, - fixAllDescription: fixAllDescription - }; - }; - } - function getFixes(context) { - const diagnostics = getDiagnostics(context); - const registrations = errorCodeToFixes.get(String(context.errorCode)); - return flatMap(registrations, (f)=>map(f.getCodeActions(context), removeFixIdIfFixAllUnavailable(f, diagnostics))); - } - function getAllFixes(context) { - return fixIdToRegistration.get(cast(context.fixId, isString)).getAllCodeActions(context); - } - function createCombinedCodeActions(changes, commands) { - return { - changes: changes, - commands: commands - }; - } - function createFileTextChanges(fileName, textChanges2) { - return { - fileName: fileName, - textChanges: textChanges2 - }; + addSyntheticNodes(list._children, pos, nodes.end, parent2); + return list; } - function codeFixAll(context, errorCodes63, use) { - const commands = []; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>eachDiagnostic(context, errorCodes63, (diag2)=>use(t, diag2, commands))); - return createCombinedCodeActions(changes, commands.length === 0 ? void 0 : commands); + function hasJSDocInheritDocTag(node) { + return getJSDocTags(node).some((tag)=>tag.tagName.text === "inheritDoc" || tag.tagName.text === "inheritdoc"); } - function eachDiagnostic(context, errorCodes63, cb) { - for (const diag2 of getDiagnostics(context))if (contains(errorCodes63, diag2.code)) cb(diag2); + function getJsDocTagsOfDeclarations(declarations, checker) { + if (!declarations) return emptyArray; + let tags = ts_JsDoc_exports.getJsDocTagsFromDeclarations(declarations, checker); + if (checker && (tags.length === 0 || declarations.some(hasJSDocInheritDocTag))) { + const seenSymbols = /* @__PURE__ */ new Set(); + for (const declaration of declarations){ + const inheritedTags = findBaseOfDeclaration(checker, declaration, (symbol)=>{ + var _a; + if (!seenSymbols.has(symbol)) { + seenSymbols.add(symbol); + if (declaration.kind === 177 /* GetAccessor */ || declaration.kind === 178 /* SetAccessor */ ) return symbol.getContextualJsDocTags(declaration, checker); + return ((_a = symbol.declarations) == null ? void 0 : _a.length) === 1 ? symbol.getJsDocTags() : void 0; + } + }); + if (inheritedTags) tags = [ + ...inheritedTags, + ...tags + ]; + } + } + return tags; } - function getDiagnostics({ program: program , sourceFile: sourceFile , cancellationToken: cancellationToken }) { - return [ - ...program.getSemanticDiagnostics(sourceFile, cancellationToken), - ...program.getSyntacticDiagnostics(sourceFile, cancellationToken), - ...computeSuggestionDiagnostics(sourceFile, program, cancellationToken) - ]; - } - var errorCodeToFixes, fixIdToRegistration; - var init_codeFixProvider = __esm({ - "src/services/codeFixProvider.ts" () { - "use strict"; - init_ts4(); - errorCodeToFixes = createMultiMap(); - fixIdToRegistration = /* @__PURE__ */ new Map(); + function getDocumentationComment(declarations, checker) { + if (!declarations) return emptyArray; + let doc = ts_JsDoc_exports.getJsDocCommentsFromDeclarations(declarations, checker); + if (checker && (doc.length === 0 || declarations.some(hasJSDocInheritDocTag))) { + const seenSymbols = /* @__PURE__ */ new Set(); + for (const declaration of declarations){ + const inheritedDocs = findBaseOfDeclaration(checker, declaration, (symbol)=>{ + if (!seenSymbols.has(symbol)) { + seenSymbols.add(symbol); + if (declaration.kind === 177 /* GetAccessor */ || declaration.kind === 178 /* SetAccessor */ ) return symbol.getContextualDocumentationComment(declaration, checker); + return symbol.getDocumentationComment(checker); + } + }); + if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(lineBreakPart(), doc); + } } - }); - // src/services/codefixes/addConvertToUnknownForNonOverlappingTypes.ts - function makeChange(changeTracker, sourceFile, assertion) { - const replacement = isAsExpression(assertion) ? factory.createAsExpression(assertion.expression, factory.createKeywordTypeNode(157 /* UnknownKeyword */ )) : factory.createTypeAssertion(factory.createKeywordTypeNode(157 /* UnknownKeyword */ ), assertion.expression); - changeTracker.replaceNode(sourceFile, assertion.expression, replacement); + return doc; } - function getAssertion(sourceFile, pos) { - if (isInJSFile(sourceFile)) return void 0; - return findAncestor(getTokenAtPosition(sourceFile, pos), (n)=>isAsExpression(n) || isTypeAssertionExpression(n)); + function findBaseOfDeclaration(checker, declaration, cb) { + var _a; + const classOrInterfaceDeclaration = ((_a = declaration.parent) == null ? void 0 : _a.kind) === 176 /* Constructor */ ? declaration.parent.parent : declaration.parent; + if (!classOrInterfaceDeclaration) return; + const isStaticMember = hasStaticModifier(declaration); + return firstDefined(getAllSuperTypeNodes(classOrInterfaceDeclaration), (superTypeNode)=>{ + const baseType = checker.getTypeAtLocation(superTypeNode); + const type = isStaticMember && baseType.symbol ? checker.getTypeOfSymbol(baseType.symbol) : baseType; + const symbol = checker.getPropertyOfType(type, declaration.symbol.name); + return symbol ? cb(symbol) : void 0; + }); } - var fixId, errorCodes; - var init_addConvertToUnknownForNonOverlappingTypes = __esm({ - "src/services/codefixes/addConvertToUnknownForNonOverlappingTypes.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId = "addConvertToUnknownForNonOverlappingTypes"; - errorCodes = [ - Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first.code - ]; - registerCodeFix({ - errorCodes: errorCodes, - getCodeActions: function getCodeActionsToAddConvertToUnknownForNonOverlappingTypes(context) { - const assertion = getAssertion(context.sourceFile, context.span.start); - if (assertion === void 0) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>makeChange(t, context.sourceFile, assertion)); - return [ - createCodeFixAction(fixId, changes, Diagnostics.Add_unknown_conversion_for_non_overlapping_types, fixId, Diagnostics.Add_unknown_to_all_conversions_of_non_overlapping_types) - ]; - }, - fixIds: [ - fixId - ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes, (changes, diag2)=>{ - const assertion = getAssertion(diag2.file, diag2.start); - if (assertion) makeChange(changes, diag2.file, assertion); - }) - }); - } - }); - // src/services/codefixes/addEmptyExportDeclaration.ts - var init_addEmptyExportDeclaration = __esm({ - "src/services/codefixes/addEmptyExportDeclaration.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - registerCodeFix({ - errorCodes: [ - Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, - Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code - ], - getCodeActions: function getCodeActionsToAddEmptyExportDeclaration(context) { - const { sourceFile: sourceFile } = context; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2)=>{ - const exportDeclaration = factory.createExportDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ void 0); - changes2.insertNodeAtEndOfScope(sourceFile, sourceFile, exportDeclaration); - }); - return [ - createCodeFixActionWithoutFixAll("addEmptyExportDeclaration", changes, Diagnostics.Add_export_to_make_this_file_into_a_module) - ]; - } - }); - } - }); - // src/services/codefixes/addMissingAsync.ts - function getFix(context, decl, trackChanges, fixedDeclarations) { - const changes = trackChanges((t)=>makeChange2(t, context.sourceFile, decl, fixedDeclarations)); - return createCodeFixAction(fixId2, changes, Diagnostics.Add_async_modifier_to_containing_function, fixId2, Diagnostics.Add_all_missing_async_modifiers); + function getServicesObjectAllocator() { + return { + getNodeConstructor: ()=>NodeObject, + getTokenConstructor: ()=>TokenObject, + getIdentifierConstructor: ()=>IdentifierObject, + getPrivateIdentifierConstructor: ()=>PrivateIdentifierObject, + getSourceFileConstructor: ()=>SourceFileObject, + getSymbolConstructor: ()=>SymbolObject, + getTypeConstructor: ()=>TypeObject, + getSignatureConstructor: ()=>SignatureObject, + getSourceMapSourceConstructor: ()=>SourceMapSourceObject + }; } - function makeChange2(changeTracker, sourceFile, insertionSite, fixedDeclarations) { - if (fixedDeclarations) { - if (fixedDeclarations.has(getNodeId(insertionSite))) return; + function toEditorSettings(optionsAsMap) { + let allPropertiesAreCamelCased = true; + for(const key in optionsAsMap)if (hasProperty(optionsAsMap, key) && !isCamelCase(key)) { + allPropertiesAreCamelCased = false; + break; } - fixedDeclarations == null || fixedDeclarations.add(getNodeId(insertionSite)); - const cloneWithModifier = factory.updateModifiers(getSynthesizedDeepClone(insertionSite, /*includeTrivia*/ true), factory.createNodeArray(factory.createModifiersFromModifierFlags(getSyntacticModifierFlags(insertionSite) | 512 /* Async */ ))); - changeTracker.replaceNode(sourceFile, insertionSite, cloneWithModifier); + if (allPropertiesAreCamelCased) return optionsAsMap; + const settings = {}; + for(const key in optionsAsMap)if (hasProperty(optionsAsMap, key)) { + const newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1); + settings[newKey] = optionsAsMap[key]; + } + return settings; } - function getFixableErrorSpanDeclaration(sourceFile, span) { - if (!span) return void 0; - const token = getTokenAtPosition(sourceFile, span.start); - const decl = findAncestor(token, (node)=>{ - if (node.getStart(sourceFile) < span.start || node.getEnd() > textSpanEnd(span)) return "quit"; - return (isArrowFunction(node) || isMethodDeclaration(node) || isFunctionExpression(node) || isFunctionDeclaration(node)) && textSpansEqual(span, createTextSpanFromNode(node, sourceFile)); - }); - return decl; + function isCamelCase(s) { + return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); } - function getIsMatchingAsyncError(span, errorCode) { - return ({ start: start , length: length2 , relatedInformation: relatedInformation , code: code })=>isNumber(start) && isNumber(length2) && textSpansEqual({ - start: start, - length: length2 - }, span) && code === errorCode && !!relatedInformation && some(relatedInformation, (related)=>related.code === Diagnostics.Did_you_mean_to_mark_this_function_as_async.code); + function displayPartsToString(displayParts) { + if (displayParts) return map(displayParts, (displayPart2)=>displayPart2.text).join(""); + return ""; } - var fixId2, errorCodes2; - var init_addMissingAsync = __esm({ - "src/services/codefixes/addMissingAsync.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId2 = "addMissingAsync"; - errorCodes2 = [ - Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, - Diagnostics.Type_0_is_not_assignable_to_type_1.code, - Diagnostics.Type_0_is_not_comparable_to_type_1.code - ]; - registerCodeFix({ - fixIds: [ - fixId2 - ], - errorCodes: errorCodes2, - getCodeActions: function getCodeActionsToAddMissingAsync(context) { - const { sourceFile: sourceFile , errorCode: errorCode , cancellationToken: cancellationToken , program: program , span: span } = context; - const diagnostic = find(program.getTypeChecker().getDiagnostics(sourceFile, cancellationToken), getIsMatchingAsyncError(span, errorCode)); - const directSpan = diagnostic && diagnostic.relatedInformation && find(diagnostic.relatedInformation, (r)=>r.code === Diagnostics.Did_you_mean_to_mark_this_function_as_async.code); - const decl = getFixableErrorSpanDeclaration(sourceFile, directSpan); - if (!decl) return; - const trackChanges = (cb)=>ts_textChanges_exports.ChangeTracker.with(context, cb); - return [ - getFix(context, decl, trackChanges) - ]; - }, - getAllCodeActions: (context)=>{ - const { sourceFile: sourceFile } = context; - const fixedDeclarations = /* @__PURE__ */ new Set(); - return codeFixAll(context, errorCodes2, (t, diagnostic)=>{ - const span = diagnostic.relatedInformation && find(diagnostic.relatedInformation, (r)=>r.code === Diagnostics.Did_you_mean_to_mark_this_function_as_async.code); - const decl = getFixableErrorSpanDeclaration(sourceFile, span); - if (!decl) return; - const trackChanges = (cb)=>(cb(t), []); - return getFix(context, decl, trackChanges, fixedDeclarations); - }); - } - }); - } - }); - // src/services/codefixes/addMissingAwait.ts - function getAwaitErrorSpanExpression(sourceFile, errorCode, span, cancellationToken, program) { - const expression = getFixableErrorSpanExpression(sourceFile, span); - return expression && isMissingAwaitError(sourceFile, errorCode, span, cancellationToken, program) && isInsideAwaitableBody(expression) ? expression : void 0; + function getDefaultCompilerOptions2() { + return { + target: 1 /* ES5 */ , + jsx: 1 /* Preserve */ + }; } - function getDeclarationSiteFix(context, expression, errorCode, checker, trackChanges, fixedDeclarations) { - const { sourceFile: sourceFile , program: program , cancellationToken: cancellationToken } = context; - const awaitableInitializers = findAwaitableInitializers(expression, sourceFile, cancellationToken, program, checker); - if (awaitableInitializers) { - const initializerChanges = trackChanges((t)=>{ - forEach(awaitableInitializers.initializers, ({ expression: expression2 })=>makeChange3(t, errorCode, sourceFile, checker, expression2, fixedDeclarations)); - if (fixedDeclarations && awaitableInitializers.needsSecondPassForFixAll) makeChange3(t, errorCode, sourceFile, checker, expression, fixedDeclarations); - }); - return createCodeFixActionWithoutFixAll("addMissingAwaitToInitializer", initializerChanges, awaitableInitializers.initializers.length === 1 ? [ - Diagnostics.Add_await_to_initializer_for_0, - awaitableInitializers.initializers[0].declarationSymbol.name - ] : Diagnostics.Add_await_to_initializers); - } + function getSupportedCodeFixes() { + return ts_codefix_exports.getSupportedErrorCodes(); } - function getUseSiteFix(context, expression, errorCode, checker, trackChanges, fixedDeclarations) { - const changes = trackChanges((t)=>makeChange3(t, errorCode, context.sourceFile, checker, expression, fixedDeclarations)); - return createCodeFixAction(fixId3, changes, Diagnostics.Add_await, fixId3, Diagnostics.Fix_all_expressions_possibly_missing_await); + function setSourceFileFields(sourceFile, scriptSnapshot, version2) { + sourceFile.version = version2; + sourceFile.scriptSnapshot = scriptSnapshot; } - function isMissingAwaitError(sourceFile, errorCode, span, cancellationToken, program) { - const checker = program.getTypeChecker(); - const diagnostics = checker.getDiagnostics(sourceFile, cancellationToken); - return some(diagnostics, ({ start: start , length: length2 , relatedInformation: relatedInformation , code: code })=>isNumber(start) && isNumber(length2) && textSpansEqual({ - start: start, - length: length2 - }, span) && code === errorCode && !!relatedInformation && some(relatedInformation, (related)=>related.code === Diagnostics.Did_you_forget_to_use_await.code)); + function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTargetOrOptions, version2, setNodeParents, scriptKind) { + const sourceFile = createSourceFile(fileName, getSnapshotText(scriptSnapshot), scriptTargetOrOptions, setNodeParents, scriptKind); + setSourceFileFields(sourceFile, scriptSnapshot, version2); + return sourceFile; } - function findAwaitableInitializers(expression, sourceFile, cancellationToken, program, checker) { - const identifiers = getIdentifiersFromErrorSpanExpression(expression, checker); - if (!identifiers) return; - let isCompleteFix = identifiers.isCompleteFix; - let initializers; - for (const identifier of identifiers.identifiers){ - const symbol = checker.getSymbolAtLocation(identifier); - if (!symbol) continue; - const declaration = tryCast(symbol.valueDeclaration, isVariableDeclaration); - const variableName = declaration && tryCast(declaration.name, isIdentifier); - const variableStatement = getAncestor(declaration, 240 /* VariableStatement */ ); - if (!declaration || !variableStatement || declaration.type || !declaration.initializer || variableStatement.getSourceFile() !== sourceFile || hasSyntacticModifier(variableStatement, 1 /* Export */ ) || !variableName || !isInsideAwaitableBody(declaration.initializer)) { - isCompleteFix = false; - continue; - } - const diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken); - const isUsedElsewhere = ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(variableName, checker, sourceFile, (reference)=>{ - return identifier !== reference && !symbolReferenceIsAlsoMissingAwait(reference, diagnostics, sourceFile, checker); - }); - if (isUsedElsewhere) { - isCompleteFix = false; - continue; + function updateLanguageServiceSourceFile(sourceFile, scriptSnapshot, version2, textChangeRange, aggressiveChecks) { + if (textChangeRange) { + if (version2 !== sourceFile.version) { + let newText; + const prefix = textChangeRange.span.start !== 0 ? sourceFile.text.substr(0, textChangeRange.span.start) : ""; + const suffix = textSpanEnd(textChangeRange.span) !== sourceFile.text.length ? sourceFile.text.substr(textSpanEnd(textChangeRange.span)) : ""; + if (textChangeRange.newLength === 0) newText = prefix && suffix ? prefix + suffix : prefix || suffix; + else { + const changedText = scriptSnapshot.getText(textChangeRange.span.start, textChangeRange.span.start + textChangeRange.newLength); + newText = prefix && suffix ? prefix + changedText + suffix : prefix ? prefix + changedText : changedText + suffix; + } + const newSourceFile = updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); + setSourceFileFields(newSourceFile, scriptSnapshot, version2); + newSourceFile.nameTable = void 0; + if (sourceFile !== newSourceFile && sourceFile.scriptSnapshot) { + if (sourceFile.scriptSnapshot.dispose) sourceFile.scriptSnapshot.dispose(); + sourceFile.scriptSnapshot = void 0; + } + return newSourceFile; } - (initializers || (initializers = [])).push({ - expression: declaration.initializer, - declarationSymbol: symbol - }); } - return initializers && { - initializers: initializers, - needsSecondPassForFixAll: !isCompleteFix + const options = { + languageVersion: sourceFile.languageVersion, + impliedNodeFormat: sourceFile.impliedNodeFormat, + setExternalModuleIndicator: sourceFile.setExternalModuleIndicator }; + return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, options, version2, /*setNodeParents*/ true, sourceFile.scriptKind); } - function getIdentifiersFromErrorSpanExpression(expression, checker) { - if (isPropertyAccessExpression(expression.parent) && isIdentifier(expression.parent.expression)) return { - identifiers: [ - expression.parent.expression - ], - isCompleteFix: true - }; - if (isIdentifier(expression)) return { - identifiers: [ - expression - ], - isCompleteFix: true - }; - if (isBinaryExpression(expression)) { - let sides; - let isCompleteFix = true; - for (const side of [ - expression.left, - expression.right - ]){ - const type = checker.getTypeAtLocation(side); - if (checker.getPromisedTypeOfPromise(type)) { - if (!isIdentifier(side)) { - isCompleteFix = false; - continue; - } - (sides || (sides = [])).push(side); + function createLanguageService(host, documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()), syntaxOnlyOrLanguageServiceMode) { + var _a; + let languageServiceMode; + if (syntaxOnlyOrLanguageServiceMode === void 0) languageServiceMode = 0 /* Semantic */ ; + else if (typeof syntaxOnlyOrLanguageServiceMode === "boolean") languageServiceMode = syntaxOnlyOrLanguageServiceMode ? 2 /* Syntactic */ : 0 /* Semantic */ ; + else languageServiceMode = syntaxOnlyOrLanguageServiceMode; + const syntaxTreeCache = new SyntaxTreeCache(host); + let program; + let lastProjectVersion; + let lastTypesRootVersion = 0; + const cancellationToken = host.getCancellationToken ? new CancellationTokenObject(host.getCancellationToken()) : NoopCancellationToken; + const currentDirectory = host.getCurrentDirectory(); + maybeSetLocalizedDiagnosticMessages((_a = host.getLocalizedDiagnosticMessages) == null ? void 0 : _a.bind(host)); + function log(message) { + if (host.log) host.log(message); + } + const useCaseSensitiveFileNames2 = hostUsesCaseSensitiveFileNames(host); + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); + const sourceMapper = getSourceMapper({ + useCaseSensitiveFileNames: ()=>useCaseSensitiveFileNames2, + getCurrentDirectory: ()=>currentDirectory, + getProgram: getProgram, + fileExists: maybeBind(host, host.fileExists), + readFile: maybeBind(host, host.readFile), + getDocumentPositionMapper: maybeBind(host, host.getDocumentPositionMapper), + getSourceFileLike: maybeBind(host, host.getSourceFileLike), + log: log + }); + function getValidSourceFile(fileName) { + const sourceFile = program.getSourceFile(fileName); + if (!sourceFile) { + const error2 = new Error(`Could not find source file: '${fileName}'.`); + error2.ProgramFiles = program.getSourceFiles().map((f)=>f.fileName); + throw error2; + } + return sourceFile; + } + function synchronizeHostData() { + var _a2, _b, _c; + Debug.assert(languageServiceMode !== 2 /* Syntactic */ ); + if (host.getProjectVersion) { + const hostProjectVersion = host.getProjectVersion(); + if (hostProjectVersion) { + if (lastProjectVersion === hostProjectVersion && !((_a2 = host.hasChangedAutomaticTypeDirectiveNames) == null ? void 0 : _a2.call(host))) return; + lastProjectVersion = hostProjectVersion; } } - return sides && { - identifiers: sides, - isCompleteFix: isCompleteFix + const typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; + if (lastTypesRootVersion !== typeRootsVersion) { + log("TypeRoots version has changed; provide new program"); + program = void 0; + lastTypesRootVersion = typeRootsVersion; + } + const rootFileNames = host.getScriptFileNames().slice(); + const newSettings = host.getCompilationSettings() || getDefaultCompilerOptions2(); + const hasInvalidatedResolutions = host.hasInvalidatedResolutions || returnFalse; + const hasInvalidatedLibResolutions = maybeBind(host, host.hasInvalidatedLibResolutions) || returnFalse; + const hasChangedAutomaticTypeDirectiveNames = maybeBind(host, host.hasChangedAutomaticTypeDirectiveNames); + const projectReferences = (_b = host.getProjectReferences) == null ? void 0 : _b.call(host); + let parsedCommandLines; + let compilerHost = { + getSourceFile: getOrCreateSourceFile, + getSourceFileByPath: getOrCreateSourceFileByPath, + getCancellationToken: ()=>cancellationToken, + getCanonicalFileName: getCanonicalFileName, + useCaseSensitiveFileNames: ()=>useCaseSensitiveFileNames2, + getNewLine: ()=>getNewLineCharacter(newSettings), + getDefaultLibFileName: (options2)=>host.getDefaultLibFileName(options2), + writeFile: noop, + getCurrentDirectory: ()=>currentDirectory, + fileExists: (fileName)=>host.fileExists(fileName), + readFile: (fileName)=>host.readFile && host.readFile(fileName), + getSymlinkCache: maybeBind(host, host.getSymlinkCache), + realpath: maybeBind(host, host.realpath), + directoryExists: (directoryName)=>{ + return directoryProbablyExists(directoryName, host); + }, + getDirectories: (path)=>{ + return host.getDirectories ? host.getDirectories(path) : []; + }, + readDirectory: (path, extensions, exclude, include, depth)=>{ + Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, + onReleaseOldSourceFile: onReleaseOldSourceFile, + onReleaseParsedCommandLine: onReleaseParsedCommandLine, + hasInvalidatedResolutions: hasInvalidatedResolutions, + hasInvalidatedLibResolutions: hasInvalidatedLibResolutions, + hasChangedAutomaticTypeDirectiveNames: hasChangedAutomaticTypeDirectiveNames, + trace: maybeBind(host, host.trace), + resolveModuleNames: maybeBind(host, host.resolveModuleNames), + getModuleResolutionCache: maybeBind(host, host.getModuleResolutionCache), + createHash: maybeBind(host, host.createHash), + resolveTypeReferenceDirectives: maybeBind(host, host.resolveTypeReferenceDirectives), + resolveModuleNameLiterals: maybeBind(host, host.resolveModuleNameLiterals), + resolveTypeReferenceDirectiveReferences: maybeBind(host, host.resolveTypeReferenceDirectiveReferences), + resolveLibrary: maybeBind(host, host.resolveLibrary), + useSourceOfProjectReferenceRedirect: maybeBind(host, host.useSourceOfProjectReferenceRedirect), + getParsedCommandLine: getParsedCommandLine }; - } - } - function symbolReferenceIsAlsoMissingAwait(reference, diagnostics, sourceFile, checker) { - const errorNode = isPropertyAccessExpression(reference.parent) ? reference.parent.name : isBinaryExpression(reference.parent) ? reference.parent : reference; - const diagnostic = find(diagnostics, (diagnostic2)=>diagnostic2.start === errorNode.getStart(sourceFile) && diagnostic2.start + diagnostic2.length === errorNode.getEnd()); - return diagnostic && contains(errorCodes3, diagnostic.code) || // A Promise is usually not correct in a binary expression (it’s not valid - // in an arithmetic expression and an equality comparison seems unusual), - // but if the other side of the binary expression has an error, the side - // is typed `any` which will squash the error that would identify this - // Promise as an invalid operand. So if the whole binary expression is - // typed `any` as a result, there is a strong likelihood that this Promise - // is accidentally missing `await`. - checker.getTypeAtLocation(errorNode).flags & 1 /* Any */ ; - } - function isInsideAwaitableBody(node) { - return node.kind & 32768 /* AwaitContext */ || !!findAncestor(node, (ancestor)=>ancestor.parent && isArrowFunction(ancestor.parent) && ancestor.parent.body === ancestor || isBlock(ancestor) && (ancestor.parent.kind === 259 /* FunctionDeclaration */ || ancestor.parent.kind === 215 /* FunctionExpression */ || ancestor.parent.kind === 216 /* ArrowFunction */ || ancestor.parent.kind === 171 /* MethodDeclaration */ )); - } - function makeChange3(changeTracker, errorCode, sourceFile, checker, insertionSite, fixedDeclarations) { - if (isForOfStatement(insertionSite.parent) && !insertionSite.parent.awaitModifier) { - const exprType = checker.getTypeAtLocation(insertionSite); - const asyncIter = checker.getAsyncIterableType(); - if (asyncIter && checker.isTypeAssignableTo(exprType, asyncIter)) { - const forOf = insertionSite.parent; - changeTracker.replaceNode(sourceFile, forOf, factory.updateForOfStatement(forOf, factory.createToken(133 /* AwaitKeyword */ ), forOf.initializer, forOf.expression, forOf.statement)); + const originalGetSourceFile = compilerHost.getSourceFile; + const { getSourceFileWithCache: getSourceFileWithCache } = changeCompilerHostLikeToUseCache(compilerHost, (fileName)=>toPath(fileName, currentDirectory, getCanonicalFileName), (...args)=>originalGetSourceFile.call(compilerHost, ...args)); + compilerHost.getSourceFile = getSourceFileWithCache; + (_c = host.setCompilerHost) == null || _c.call(host, compilerHost); + const parseConfigHost = { + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, + fileExists: (fileName)=>compilerHost.fileExists(fileName), + readFile: (fileName)=>compilerHost.readFile(fileName), + directoryExists: (f)=>compilerHost.directoryExists(f), + getDirectories: (f)=>compilerHost.getDirectories(f), + realpath: compilerHost.realpath, + readDirectory: (...args)=>compilerHost.readDirectory(...args), + trace: compilerHost.trace, + getCurrentDirectory: compilerHost.getCurrentDirectory, + onUnRecoverableConfigFileDiagnostic: noop + }; + const documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); + let releasedScriptKinds = /* @__PURE__ */ new Set(); + if (isProgramUptoDate(program, rootFileNames, newSettings, (_path, fileName)=>host.getScriptVersion(fileName), (fileName)=>compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { + compilerHost = void 0; + parsedCommandLines = void 0; + releasedScriptKinds = void 0; return; } - } - if (isBinaryExpression(insertionSite)) for (const side of [ - insertionSite.left, - insertionSite.right - ]){ - if (fixedDeclarations && isIdentifier(side)) { - const symbol = checker.getSymbolAtLocation(side); - if (symbol && fixedDeclarations.has(getSymbolId(symbol))) continue; + const options = { + rootNames: rootFileNames, + options: newSettings, + host: compilerHost, + oldProgram: program, + projectReferences: projectReferences + }; + program = createProgram(options); + compilerHost = void 0; + parsedCommandLines = void 0; + releasedScriptKinds = void 0; + sourceMapper.clearCache(); + program.getTypeChecker(); + return; + function getParsedCommandLine(fileName) { + const path = toPath(fileName, currentDirectory, getCanonicalFileName); + const existing = parsedCommandLines == null ? void 0 : parsedCommandLines.get(path); + if (existing !== void 0) return existing || void 0; + const result = host.getParsedCommandLine ? host.getParsedCommandLine(fileName) : getParsedCommandLineOfConfigFileUsingSourceFile(fileName); + (parsedCommandLines || (parsedCommandLines = /* @__PURE__ */ new Map())).set(path, result || false); + return result; } - const type = checker.getTypeAtLocation(side); - const newNode = checker.getPromisedTypeOfPromise(type) ? factory.createAwaitExpression(side) : side; - changeTracker.replaceNode(sourceFile, side, newNode); - } - else if (errorCode === propertyAccessCode && isPropertyAccessExpression(insertionSite.parent)) { - if (fixedDeclarations && isIdentifier(insertionSite.parent.expression)) { - const symbol = checker.getSymbolAtLocation(insertionSite.parent.expression); - if (symbol && fixedDeclarations.has(getSymbolId(symbol))) return; + function getParsedCommandLineOfConfigFileUsingSourceFile(configFileName) { + const result = getOrCreateSourceFile(configFileName, 100 /* JSON */ ); + if (!result) return void 0; + result.path = toPath(configFileName, currentDirectory, getCanonicalFileName); + result.resolvedPath = result.path; + result.originalFileName = result.fileName; + return parseJsonSourceFileConfigFileContent(result, parseConfigHost, getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), /*existingOptions*/ void 0, getNormalizedAbsolutePath(configFileName, currentDirectory)); } - changeTracker.replaceNode(sourceFile, insertionSite.parent.expression, factory.createParenthesizedExpression(factory.createAwaitExpression(insertionSite.parent.expression))); - insertLeadingSemicolonIfNeeded(changeTracker, insertionSite.parent.expression, sourceFile); - } else if (contains(callableConstructableErrorCodes, errorCode) && isCallOrNewExpression(insertionSite.parent)) { - if (fixedDeclarations && isIdentifier(insertionSite)) { - const symbol = checker.getSymbolAtLocation(insertionSite); - if (symbol && fixedDeclarations.has(getSymbolId(symbol))) return; + function onReleaseParsedCommandLine(configFileName, oldResolvedRef, oldOptions) { + var _a3; + if (host.getParsedCommandLine) (_a3 = host.onReleaseParsedCommandLine) == null || _a3.call(host, configFileName, oldResolvedRef, oldOptions); + else if (oldResolvedRef) onReleaseOldSourceFile(oldResolvedRef.sourceFile, oldOptions); } - changeTracker.replaceNode(sourceFile, insertionSite, factory.createParenthesizedExpression(factory.createAwaitExpression(insertionSite))); - insertLeadingSemicolonIfNeeded(changeTracker, insertionSite, sourceFile); - } else { - if (fixedDeclarations && isVariableDeclaration(insertionSite.parent) && isIdentifier(insertionSite.parent.name)) { - const symbol = checker.getSymbolAtLocation(insertionSite.parent.name); - if (symbol && !tryAddToSet(fixedDeclarations, getSymbolId(symbol))) return; + function onReleaseOldSourceFile(oldSourceFile, oldOptions) { + const oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind, oldSourceFile.impliedNodeFormat); + } + function getOrCreateSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile) { + return getOrCreateSourceFileByPath(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), languageVersionOrOptions, onError, shouldCreateNewSourceFile); + } + function getOrCreateSourceFileByPath(fileName, path, languageVersionOrOptions, _onError, shouldCreateNewSourceFile) { + Debug.assert(compilerHost, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host."); + const scriptSnapshot = host.getScriptSnapshot(fileName); + if (!scriptSnapshot) return void 0; + const scriptKind = getScriptKind(fileName, host); + const scriptVersion = host.getScriptVersion(fileName); + if (!shouldCreateNewSourceFile) { + const oldSourceFile = program && program.getSourceFileByPath(path); + if (oldSourceFile) { + if (scriptKind === oldSourceFile.scriptKind || releasedScriptKinds.has(oldSourceFile.resolvedPath)) return documentRegistry.updateDocumentWithKey(fileName, path, host, documentRegistryBucketKey, scriptSnapshot, scriptVersion, scriptKind, languageVersionOrOptions); + else { + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()), oldSourceFile.scriptKind, oldSourceFile.impliedNodeFormat); + releasedScriptKinds.add(oldSourceFile.resolvedPath); + } + } + } + return documentRegistry.acquireDocumentWithKey(fileName, path, host, documentRegistryBucketKey, scriptSnapshot, scriptVersion, scriptKind, languageVersionOrOptions); } - changeTracker.replaceNode(sourceFile, insertionSite, factory.createAwaitExpression(insertionSite)); } - } - function insertLeadingSemicolonIfNeeded(changeTracker, beforeNode, sourceFile) { - const precedingToken = findPrecedingToken(beforeNode.pos, sourceFile); - if (precedingToken && positionIsASICandidate(precedingToken.end, precedingToken.parent, sourceFile)) changeTracker.insertText(sourceFile, beforeNode.getStart(sourceFile), ";"); - } - var fixId3, propertyAccessCode, callableConstructableErrorCodes, errorCodes3; - var init_addMissingAwait = __esm({ - "src/services/codefixes/addMissingAwait.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId3 = "addMissingAwait"; - propertyAccessCode = Diagnostics.Property_0_does_not_exist_on_type_1.code; - callableConstructableErrorCodes = [ - Diagnostics.This_expression_is_not_callable.code, - Diagnostics.This_expression_is_not_constructable.code - ]; - errorCodes3 = [ - Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type.code, - Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type.code, - Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type.code, - Diagnostics.Operator_0_cannot_be_applied_to_type_1.code, - Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2.code, - Diagnostics.This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap.code, - Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined.code, - Diagnostics.Type_0_is_not_an_array_type.code, - Diagnostics.Type_0_is_not_an_array_type_or_a_string_type.code, - Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher.code, - Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator.code, - Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator.code, - Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator.code, - Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator.code, - Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, - propertyAccessCode, - ...callableConstructableErrorCodes - ]; - registerCodeFix({ - fixIds: [ - fixId3 - ], - errorCodes: errorCodes3, - getCodeActions: function getCodeActionsToAddMissingAwait(context) { - const { sourceFile: sourceFile , errorCode: errorCode , span: span , cancellationToken: cancellationToken , program: program } = context; - const expression = getAwaitErrorSpanExpression(sourceFile, errorCode, span, cancellationToken, program); - if (!expression) return; - const checker = context.program.getTypeChecker(); - const trackChanges = (cb)=>ts_textChanges_exports.ChangeTracker.with(context, cb); - return compact([ - getDeclarationSiteFix(context, expression, errorCode, checker, trackChanges), - getUseSiteFix(context, expression, errorCode, checker, trackChanges) - ]); - }, - getAllCodeActions: (context)=>{ - const { sourceFile: sourceFile , program: program , cancellationToken: cancellationToken } = context; - const checker = context.program.getTypeChecker(); - const fixedDeclarations = /* @__PURE__ */ new Set(); - return codeFixAll(context, errorCodes3, (t, diagnostic)=>{ - const expression = getAwaitErrorSpanExpression(sourceFile, diagnostic.code, diagnostic, cancellationToken, program); - if (!expression) return; - const trackChanges = (cb)=>(cb(t), []); - return getDeclarationSiteFix(context, expression, diagnostic.code, checker, trackChanges, fixedDeclarations) || getUseSiteFix(context, expression, diagnostic.code, checker, trackChanges, fixedDeclarations); - }); - } - }); + function getProgram() { + if (languageServiceMode === 2 /* Syntactic */ ) { + Debug.assert(program === void 0); + return void 0; + } + synchronizeHostData(); + return program; } - }); - // src/services/codefixes/addMissingConst.ts - function makeChange4(changeTracker, sourceFile, pos, program, fixedNodes) { - const token = getTokenAtPosition(sourceFile, pos); - const forInitializer = findAncestor(token, (node)=>isForInOrOfStatement(node.parent) ? node.parent.initializer === node : isPossiblyPartOfDestructuring(node) ? false : "quit"); - if (forInitializer) return applyChange(changeTracker, forInitializer, sourceFile, fixedNodes); - const parent2 = token.parent; - if (isBinaryExpression(parent2) && parent2.operatorToken.kind === 63 /* EqualsToken */ && isExpressionStatement(parent2.parent)) return applyChange(changeTracker, token, sourceFile, fixedNodes); - if (isArrayLiteralExpression(parent2)) { - const checker = program.getTypeChecker(); - if (!every(parent2.elements, (element)=>arrayElementCouldBeVariableDeclaration(element, checker))) return; - return applyChange(changeTracker, parent2, sourceFile, fixedNodes); + function getAutoImportProvider() { + var _a2; + return (_a2 = host.getPackageJsonAutoImportProvider) == null ? void 0 : _a2.call(host); } - const commaExpression = findAncestor(token, (node)=>isExpressionStatement(node.parent) ? true : isPossiblyPartOfCommaSeperatedInitializer(node) ? false : "quit"); - if (commaExpression) { + function updateIsDefinitionOfReferencedSymbols(referencedSymbols, knownSymbolSpans) { const checker = program.getTypeChecker(); - if (!expressionCouldBeVariableDeclaration(commaExpression, checker)) return; - return applyChange(changeTracker, commaExpression, sourceFile, fixedNodes); + const symbol = getSymbolForProgram(); + if (!symbol) return false; + for (const referencedSymbol of referencedSymbols)for (const ref of referencedSymbol.references){ + const refNode = getNodeForSpan(ref); + Debug.assertIsDefined(refNode); + if (knownSymbolSpans.has(ref) || ts_FindAllReferences_exports.isDeclarationOfSymbol(refNode, symbol)) { + knownSymbolSpans.add(ref); + ref.isDefinition = true; + const mappedSpan = getMappedDocumentSpan(ref, sourceMapper, maybeBind(host, host.fileExists)); + if (mappedSpan) knownSymbolSpans.add(mappedSpan); + } else ref.isDefinition = false; + } + return true; + function getSymbolForProgram() { + for (const referencedSymbol of referencedSymbols)for (const ref of referencedSymbol.references){ + if (knownSymbolSpans.has(ref)) { + const refNode = getNodeForSpan(ref); + Debug.assertIsDefined(refNode); + return checker.getSymbolAtLocation(refNode); + } + const mappedSpan = getMappedDocumentSpan(ref, sourceMapper, maybeBind(host, host.fileExists)); + if (mappedSpan && knownSymbolSpans.has(mappedSpan)) { + const refNode = getNodeForSpan(mappedSpan); + if (refNode) return checker.getSymbolAtLocation(refNode); + } + } + return void 0; + } + function getNodeForSpan(docSpan) { + const sourceFile = program.getSourceFile(docSpan.fileName); + if (!sourceFile) return void 0; + const rawNode = getTouchingPropertyName(sourceFile, docSpan.textSpan.start); + const adjustedNode = ts_FindAllReferences_exports.Core.getAdjustedNode(rawNode, { + use: ts_FindAllReferences_exports.FindReferencesUse.References + }); + return adjustedNode; + } } - } - function applyChange(changeTracker, initializer, sourceFile, fixedNodes) { - if (!fixedNodes || tryAddToSet(fixedNodes, initializer)) changeTracker.insertModifierBefore(sourceFile, 85 /* ConstKeyword */ , initializer); - } - function isPossiblyPartOfDestructuring(node) { - switch(node.kind){ - case 79 /* Identifier */ : - case 206 /* ArrayLiteralExpression */ : - case 207 /* ObjectLiteralExpression */ : - case 299 /* PropertyAssignment */ : - case 300 /* ShorthandPropertyAssignment */ : - return true; - default: - return false; + function cleanupSemanticCache() { + if (program) { + const key = documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()); + forEach(program.getSourceFiles(), (f)=>documentRegistry.releaseDocumentWithKey(f.resolvedPath, key, f.scriptKind, f.impliedNodeFormat)); + program = void 0; + } } - } - function arrayElementCouldBeVariableDeclaration(expression, checker) { - const identifier = isIdentifier(expression) ? expression : isAssignmentExpression(expression, /*excludeCompoundAssignment*/ true) && isIdentifier(expression.left) ? expression.left : void 0; - return !!identifier && !checker.getSymbolAtLocation(identifier); - } - function isPossiblyPartOfCommaSeperatedInitializer(node) { - switch(node.kind){ - case 79 /* Identifier */ : - case 223 /* BinaryExpression */ : - case 27 /* CommaToken */ : - return true; - default: - return false; + function dispose() { + cleanupSemanticCache(); + host = void 0; } - } - function expressionCouldBeVariableDeclaration(expression, checker) { - if (!isBinaryExpression(expression)) return false; - if (expression.operatorToken.kind === 27 /* CommaToken */ ) return every([ - expression.left, - expression.right - ], (expression2)=>expressionCouldBeVariableDeclaration(expression2, checker)); - return expression.operatorToken.kind === 63 /* EqualsToken */ && isIdentifier(expression.left) && !checker.getSymbolAtLocation(expression.left); - } - var fixId4, errorCodes4; - var init_addMissingConst = __esm({ - "src/services/codefixes/addMissingConst.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId4 = "addMissingConst"; - errorCodes4 = [ - Diagnostics.Cannot_find_name_0.code, - Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer.code - ]; - registerCodeFix({ - errorCodes: errorCodes4, - getCodeActions: function getCodeActionsToAddMissingConst(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>makeChange4(t, context.sourceFile, context.span.start, context.program)); - if (changes.length > 0) return [ - createCodeFixAction(fixId4, changes, Diagnostics.Add_const_to_unresolved_variable, fixId4, Diagnostics.Add_const_to_all_unresolved_variables) - ]; - }, - fixIds: [ - fixId4 - ], - getAllCodeActions: (context)=>{ - const fixedNodes = /* @__PURE__ */ new Set(); - return codeFixAll(context, errorCodes4, (changes, diag2)=>makeChange4(changes, diag2.file, diag2.start, context.program, fixedNodes)); - } - }); + function getSyntacticDiagnostics(fileName) { + synchronizeHostData(); + return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken).slice(); } - }); - // src/services/codefixes/addMissingDeclareProperty.ts - function makeChange5(changeTracker, sourceFile, pos, fixedNodes) { - const token = getTokenAtPosition(sourceFile, pos); - if (!isIdentifier(token)) return; - const declaration = token.parent; - if (declaration.kind === 169 /* PropertyDeclaration */ && (!fixedNodes || tryAddToSet(fixedNodes, declaration))) changeTracker.insertModifierBefore(sourceFile, 136 /* DeclareKeyword */ , declaration); - } - var fixId5, errorCodes5; - var init_addMissingDeclareProperty = __esm({ - "src/services/codefixes/addMissingDeclareProperty.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId5 = "addMissingDeclareProperty"; - errorCodes5 = [ - Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration.code + function getSemanticDiagnostics(fileName) { + synchronizeHostData(); + const targetSourceFile = getValidSourceFile(fileName); + const semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); + if (!getEmitDeclarations(program.getCompilerOptions())) return semanticDiagnostics.slice(); + const declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); + return [ + ...semanticDiagnostics, + ...declarationDiagnostics ]; - registerCodeFix({ - errorCodes: errorCodes5, - getCodeActions: function getCodeActionsToAddMissingDeclareOnProperty(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>makeChange5(t, context.sourceFile, context.span.start)); - if (changes.length > 0) return [ - createCodeFixAction(fixId5, changes, Diagnostics.Prefix_with_declare, fixId5, Diagnostics.Prefix_all_incorrect_property_declarations_with_declare) - ]; - }, - fixIds: [ - fixId5 - ], - getAllCodeActions: (context)=>{ - const fixedNodes = /* @__PURE__ */ new Set(); - return codeFixAll(context, errorCodes5, (changes, diag2)=>makeChange5(changes, diag2.file, diag2.start, fixedNodes)); - } - }); } - }); - // src/services/codefixes/addMissingInvocationForDecorator.ts - function makeChange6(changeTracker, sourceFile, pos) { - const token = getTokenAtPosition(sourceFile, pos); - const decorator = findAncestor(token, isDecorator); - Debug.assert(!!decorator, "Expected position to be owned by a decorator."); - const replacement = factory.createCallExpression(decorator.expression, /*typeArguments*/ void 0, /*argumentsArray*/ void 0); - changeTracker.replaceNode(sourceFile, decorator.expression, replacement); - } - var fixId6, errorCodes6; - var init_addMissingInvocationForDecorator = __esm({ - "src/services/codefixes/addMissingInvocationForDecorator.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId6 = "addMissingInvocationForDecorator"; - errorCodes6 = [ - Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code - ]; - registerCodeFix({ - errorCodes: errorCodes6, - getCodeActions: function getCodeActionsToAddMissingInvocationForDecorator(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>makeChange6(t, context.sourceFile, context.span.start)); - return [ - createCodeFixAction(fixId6, changes, Diagnostics.Call_decorator_expression, fixId6, Diagnostics.Add_to_all_uncalled_decorators) - ]; - }, - fixIds: [ - fixId6 - ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes6, (changes, diag2)=>makeChange6(changes, diag2.file, diag2.start)) - }); + function getSuggestionDiagnostics(fileName) { + synchronizeHostData(); + return computeSuggestionDiagnostics(getValidSourceFile(fileName), program, cancellationToken); } - }); - // src/services/codefixes/addNameToNamelessParameter.ts - function makeChange7(changeTracker, sourceFile, pos) { - const token = getTokenAtPosition(sourceFile, pos); - const param = token.parent; - if (!isParameter(param)) return Debug.fail("Tried to add a parameter name to a non-parameter: " + Debug.formatSyntaxKind(token.kind)); - const i = param.parent.parameters.indexOf(param); - Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one."); - Debug.assert(i > -1, "Parameter not found in parent parameter list."); - const typeNode = factory.createTypeReferenceNode(param.name, /*typeArguments*/ void 0); - const replacement = factory.createParameterDeclaration(param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, param.dotDotDotToken ? factory.createArrayTypeNode(typeNode) : typeNode, param.initializer); - changeTracker.replaceNode(sourceFile, param, replacement); - } - var fixId7, errorCodes7; - var init_addNameToNamelessParameter = __esm({ - "src/services/codefixes/addNameToNamelessParameter.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId7 = "addNameToNamelessParameter"; - errorCodes7 = [ - Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1.code + function getCompilerOptionsDiagnostics() { + synchronizeHostData(); + return [ + ...program.getOptionsDiagnostics(cancellationToken), + ...program.getGlobalDiagnostics(cancellationToken) ]; - registerCodeFix({ - errorCodes: errorCodes7, - getCodeActions: function getCodeActionsToAddNameToNamelessParameter(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>makeChange7(t, context.sourceFile, context.span.start)); - return [ - createCodeFixAction(fixId7, changes, Diagnostics.Add_parameter_name, fixId7, Diagnostics.Add_names_to_all_parameters_without_names) - ]; - }, - fixIds: [ - fixId7 - ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes7, (changes, diag2)=>makeChange7(changes, diag2.file, diag2.start)) - }); } - }); - // src/services/codefixes/addOptionalPropertyUndefined.ts - function getPropertiesToAdd(file, span, checker) { - var _a2, _b; - const sourceTarget = getSourceTarget(getFixableErrorSpanExpression(file, span), checker); - if (!sourceTarget) return emptyArray; - const { source: sourceNode , target: targetNode } = sourceTarget; - const target = shouldUseParentTypeOfProperty(sourceNode, targetNode, checker) ? checker.getTypeAtLocation(targetNode.expression) : checker.getTypeAtLocation(targetNode); - if ((_b = (_a2 = target.symbol) == null ? void 0 : _a2.declarations) == null ? void 0 : _b.some((d)=>getSourceFileOfNode(d).fileName.match(/\.d\.ts$/))) return emptyArray; - return checker.getExactOptionalProperties(target); - } - function shouldUseParentTypeOfProperty(sourceNode, targetNode, checker) { - return isPropertyAccessExpression(targetNode) && !!checker.getExactOptionalProperties(checker.getTypeAtLocation(targetNode.expression)).length && checker.getTypeAtLocation(sourceNode) === checker.getUndefinedType(); - } - function getSourceTarget(errorNode, checker) { - var _a2; - if (!errorNode) return void 0; - else if (isBinaryExpression(errorNode.parent) && errorNode.parent.operatorToken.kind === 63 /* EqualsToken */ ) return { - source: errorNode.parent.right, - target: errorNode.parent.left - }; - else if (isVariableDeclaration(errorNode.parent) && errorNode.parent.initializer) return { - source: errorNode.parent.initializer, - target: errorNode.parent.name - }; - else if (isCallExpression(errorNode.parent)) { - const n = checker.getSymbolAtLocation(errorNode.parent.expression); - if (!(n == null ? void 0 : n.valueDeclaration) || !isFunctionLikeKind(n.valueDeclaration.kind)) return void 0; - if (!isExpression(errorNode)) return void 0; - const i = errorNode.parent.arguments.indexOf(errorNode); - if (i === -1) return void 0; - const name = n.valueDeclaration.parameters[i].name; - if (isIdentifier(name)) return { - source: errorNode, - target: name + function getCompletionsAtPosition2(fileName, position, options = emptyOptions, formattingSettings) { + const fullPreferences = { + ...identity(options), + // avoid excess property check + includeCompletionsForModuleExports: options.includeCompletionsForModuleExports || options.includeExternalModuleExports, + includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions }; - } else if (isPropertyAssignment(errorNode.parent) && isIdentifier(errorNode.parent.name) || isShorthandPropertyAssignment(errorNode.parent)) { - const parentTarget = getSourceTarget(errorNode.parent.parent, checker); - if (!parentTarget) return void 0; - const prop = checker.getPropertyOfType(checker.getTypeAtLocation(parentTarget.target), errorNode.parent.name.text); - const declaration = (_a2 = prop == null ? void 0 : prop.declarations) == null ? void 0 : _a2[0]; - if (!declaration) return void 0; + synchronizeHostData(); + return ts_Completions_exports.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter, options.triggerKind, cancellationToken, formattingSettings && ts_formatting_exports.getFormatContext(formattingSettings, host), options.includeSymbol); + } + function getCompletionEntryDetails2(fileName, position, name, formattingOptions, source, preferences = emptyOptions, data) { + synchronizeHostData(); + return ts_Completions_exports.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { + name: name, + source: source, + data: data + }, host, formattingOptions && ts_formatting_exports.getFormatContext(formattingOptions, host), // TODO: GH#18217 + preferences, cancellationToken); + } + function getCompletionEntrySymbol2(fileName, position, name, source, preferences = emptyOptions) { + synchronizeHostData(); + return ts_Completions_exports.getCompletionEntrySymbol(program, log, getValidSourceFile(fileName), position, { + name: name, + source: source + }, host, preferences); + } + function getQuickInfoAtPosition(fileName, position) { + synchronizeHostData(); + const sourceFile = getValidSourceFile(fileName); + const node = getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) return void 0; + const typeChecker = program.getTypeChecker(); + const nodeForQuickInfo = getNodeForQuickInfo(node); + const symbol = getSymbolAtLocationForQuickInfo(nodeForQuickInfo, typeChecker); + if (!symbol || typeChecker.isUnknownSymbol(symbol)) { + const type = shouldGetType(sourceFile, nodeForQuickInfo, position) ? typeChecker.getTypeAtLocation(nodeForQuickInfo) : void 0; + return type && { + kind: "" /* unknown */ , + kindModifiers: "" /* none */ , + textSpan: createTextSpanFromNode(nodeForQuickInfo, sourceFile), + displayParts: typeChecker.runWithCancellationToken(cancellationToken, (typeChecker2)=>typeToDisplayParts(typeChecker2, type, getContainerNode(nodeForQuickInfo))), + documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : void 0, + tags: type.symbol ? type.symbol.getJsDocTags(typeChecker) : void 0 + }; + } + const { symbolKind: symbolKind, displayParts: displayParts, documentation: documentation, tags: tags } = typeChecker.runWithCancellationToken(cancellationToken, (typeChecker2)=>ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker2, symbol, sourceFile, getContainerNode(nodeForQuickInfo), nodeForQuickInfo)); return { - source: isPropertyAssignment(errorNode.parent) ? errorNode.parent.initializer : errorNode.parent.name, - target: declaration + kind: symbolKind, + kindModifiers: ts_SymbolDisplay_exports.getSymbolModifiers(typeChecker, symbol), + textSpan: createTextSpanFromNode(nodeForQuickInfo, sourceFile), + displayParts: displayParts, + documentation: documentation, + tags: tags }; } - return void 0; - } - function addUndefinedToOptionalProperty(changes, toAdd) { - for (const add of toAdd){ - const d = add.valueDeclaration; - if (d && (isPropertySignature(d) || isPropertyDeclaration(d)) && d.type) { - const t = factory.createUnionTypeNode([ - ...d.type.kind === 189 /* UnionType */ ? d.type.types : [ - d.type - ], - factory.createTypeReferenceNode("undefined") - ]); - changes.replaceNode(d.getSourceFile(), d.type, t); + function getNodeForQuickInfo(node) { + if (isNewExpression(node.parent) && node.pos === node.parent.pos) return node.parent.expression; + if (isNamedTupleMember(node.parent) && node.pos === node.parent.pos) return node.parent; + if (isImportMeta(node.parent) && node.parent.name === node) return node.parent; + if (isJsxNamespacedName(node.parent)) return node.parent; + return node; + } + function shouldGetType(sourceFile, node, position) { + switch(node.kind){ + case 80 /* Identifier */ : + return !isLabelName(node) && !isTagName(node) && !isConstTypeReference(node.parent); + case 211 /* PropertyAccessExpression */ : + case 166 /* QualifiedName */ : + return !isInComment(sourceFile, position); + case 110 /* ThisKeyword */ : + case 197 /* ThisType */ : + case 108 /* SuperKeyword */ : + case 202 /* NamedTupleMember */ : + return true; + case 236 /* MetaProperty */ : + return isImportMeta(node); + default: + return false; } } - } - var addOptionalPropertyUndefined, errorCodes8; - var init_addOptionalPropertyUndefined = __esm({ - "src/services/codefixes/addOptionalPropertyUndefined.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - addOptionalPropertyUndefined = "addOptionalPropertyUndefined"; - errorCodes8 = [ - Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_type_of_the_target.code, - Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, - Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code - ]; - registerCodeFix({ - errorCodes: errorCodes8, - getCodeActions (context) { - const typeChecker = context.program.getTypeChecker(); - const toAdd = getPropertiesToAdd(context.sourceFile, context.span, typeChecker); - if (!toAdd.length) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addUndefinedToOptionalProperty(t, toAdd)); - return [ - createCodeFixActionWithoutFixAll(addOptionalPropertyUndefined, changes, Diagnostics.Add_undefined_to_optional_property_type) - ]; - }, - fixIds: [ - addOptionalPropertyUndefined - ] - }); + function getDefinitionAtPosition2(fileName, position, searchOtherFilesOnly, stopAtAlias) { + synchronizeHostData(); + return ts_GoToDefinition_exports.getDefinitionAtPosition(program, getValidSourceFile(fileName), position, searchOtherFilesOnly, stopAtAlias); } - }); - // src/services/codefixes/annotateWithTypeFromJSDoc.ts - function getDeclaration(file, pos) { - const name = getTokenAtPosition(file, pos); - return tryCast(isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc); - } - function parameterShouldGetTypeFromJSDoc(node) { - return isDeclarationWithType(node) && hasUsableJSDoc(node); - } - function hasUsableJSDoc(decl) { - return isFunctionLikeDeclaration(decl) ? decl.parameters.some(hasUsableJSDoc) || !decl.type && !!getJSDocReturnType(decl) : !decl.type && !!getJSDocType(decl); - } - function doChange(changes, sourceFile, decl) { - if (isFunctionLikeDeclaration(decl) && (getJSDocReturnType(decl) || decl.parameters.some((p)=>!!getJSDocType(p)))) { - if (!decl.typeParameters) { - const typeParameters = getJSDocTypeParameterDeclarations(decl); - if (typeParameters.length) changes.insertTypeParameters(sourceFile, decl, typeParameters); - } - const needParens = isArrowFunction(decl) && !findChildOfKind(decl, 20 /* OpenParenToken */ , sourceFile); - if (needParens) changes.insertNodeBefore(sourceFile, first(decl.parameters), factory.createToken(20 /* OpenParenToken */ )); - for (const param of decl.parameters)if (!param.type) { - const paramType = getJSDocType(param); - if (paramType) changes.tryInsertTypeAnnotation(sourceFile, param, visitNode(paramType, transformJSDocType, isTypeNode)); - } - if (needParens) changes.insertNodeAfter(sourceFile, last(decl.parameters), factory.createToken(21 /* CloseParenToken */ )); - if (!decl.type) { - const returnType = getJSDocReturnType(decl); - if (returnType) changes.tryInsertTypeAnnotation(sourceFile, decl, visitNode(returnType, transformJSDocType, isTypeNode)); - } - } else { - const jsdocType = Debug.checkDefined(getJSDocType(decl), "A JSDocType for this declaration should exist"); - Debug.assert(!decl.type, "The JSDocType decl should have a type"); - changes.tryInsertTypeAnnotation(sourceFile, decl, visitNode(jsdocType, transformJSDocType, isTypeNode)); + function getDefinitionAndBoundSpan2(fileName, position) { + synchronizeHostData(); + return ts_GoToDefinition_exports.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); } - } - function isDeclarationWithType(node) { - return isFunctionLikeDeclaration(node) || node.kind === 257 /* VariableDeclaration */ || node.kind === 168 /* PropertySignature */ || node.kind === 169 /* PropertyDeclaration */ ; - } - function transformJSDocType(node) { - switch(node.kind){ - case 315 /* JSDocAllType */ : - case 316 /* JSDocUnknownType */ : - return factory.createTypeReferenceNode("any", emptyArray); - case 319 /* JSDocOptionalType */ : - return transformJSDocOptionalType(node); - case 318 /* JSDocNonNullableType */ : - return transformJSDocType(node.type); - case 317 /* JSDocNullableType */ : - return transformJSDocNullableType(node); - case 321 /* JSDocVariadicType */ : - return transformJSDocVariadicType(node); - case 320 /* JSDocFunctionType */ : - return transformJSDocFunctionType(node); - case 180 /* TypeReference */ : - return transformJSDocTypeReference(node); - case 325 /* JSDocTypeLiteral */ : - return transformJSDocTypeLiteral(node); - default: - const visited = visitEachChild(node, transformJSDocType, nullTransformationContext); - setEmitFlags(visited, 1 /* SingleLine */ ); - return visited; + function getTypeDefinitionAtPosition2(fileName, position) { + synchronizeHostData(); + return ts_GoToDefinition_exports.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); } - } - function transformJSDocTypeLiteral(node) { - const typeNode = factory.createTypeLiteralNode(map(node.jsDocPropertyTags, (tag)=>factory.createPropertySignature(/*modifiers*/ void 0, isIdentifier(tag.name) ? tag.name : tag.name.right, isOptionalJSDocPropertyLikeTag(tag) ? factory.createToken(57 /* QuestionToken */ ) : void 0, tag.typeExpression && visitNode(tag.typeExpression.type, transformJSDocType, isTypeNode) || factory.createKeywordTypeNode(131 /* AnyKeyword */ )))); - setEmitFlags(typeNode, 1 /* SingleLine */ ); - return typeNode; - } - function transformJSDocOptionalType(node) { - return factory.createUnionTypeNode([ - visitNode(node.type, transformJSDocType, isTypeNode), - factory.createTypeReferenceNode("undefined", emptyArray) - ]); - } - function transformJSDocNullableType(node) { - return factory.createUnionTypeNode([ - visitNode(node.type, transformJSDocType, isTypeNode), - factory.createTypeReferenceNode("null", emptyArray) - ]); - } - function transformJSDocVariadicType(node) { - return factory.createArrayTypeNode(visitNode(node.type, transformJSDocType, isTypeNode)); - } - function transformJSDocFunctionType(node) { - var _a2; - return factory.createFunctionTypeNode(emptyArray, node.parameters.map(transformJSDocParameter), (_a2 = node.type) != null ? _a2 : factory.createKeywordTypeNode(131 /* AnyKeyword */ )); - } - function transformJSDocParameter(node) { - const index = node.parent.parameters.indexOf(node); - const isRest = node.type.kind === 321 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; - const name = node.name || (isRest ? "rest" : "arg" + index); - const dotdotdot = isRest ? factory.createToken(25 /* DotDotDotToken */ ) : node.dotDotDotToken; - return factory.createParameterDeclaration(node.modifiers, dotdotdot, name, node.questionToken, visitNode(node.type, transformJSDocType, isTypeNode), node.initializer); - } - function transformJSDocTypeReference(node) { - let name = node.typeName; - let args = node.typeArguments; - if (isIdentifier(node.typeName)) { - if (isJSDocIndexSignature(node)) return transformJSDocIndexSignature(node); - let text = node.typeName.text; - switch(node.typeName.text){ - case "String": - case "Boolean": - case "Object": - case "Number": - text = text.toLowerCase(); - break; - case "array": - case "date": - case "promise": - text = text[0].toUpperCase() + text.slice(1); - break; - } - name = factory.createIdentifier(text); - if ((text === "Array" || text === "Promise") && !node.typeArguments) args = factory.createNodeArray([ - factory.createTypeReferenceNode("any", emptyArray) - ]); - else args = visitNodes2(node.typeArguments, transformJSDocType, isTypeNode); - } - return factory.createTypeReferenceNode(name, args); - } - function transformJSDocIndexSignature(node) { - const index = factory.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, node.typeArguments[0].kind === 148 /* NumberKeyword */ ? "n" : "s", /*questionToken*/ void 0, factory.createTypeReferenceNode(node.typeArguments[0].kind === 148 /* NumberKeyword */ ? "number" : "string", []), /*initializer*/ void 0); - const indexSignature = factory.createTypeLiteralNode([ - factory.createIndexSignature(/*modifiers*/ void 0, [ - index - ], node.typeArguments[1]) - ]); - setEmitFlags(indexSignature, 1 /* SingleLine */ ); - return indexSignature; - } - var fixId8, errorCodes9; - var init_annotateWithTypeFromJSDoc = __esm({ - "src/services/codefixes/annotateWithTypeFromJSDoc.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId8 = "annotateWithTypeFromJSDoc"; - errorCodes9 = [ - Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code - ]; - registerCodeFix({ - errorCodes: errorCodes9, - getCodeActions (context) { - const decl = getDeclaration(context.sourceFile, context.span.start); - if (!decl) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange(t, context.sourceFile, decl)); - return [ - createCodeFixAction(fixId8, changes, Diagnostics.Annotate_with_type_from_JSDoc, fixId8, Diagnostics.Annotate_everything_with_types_from_JSDoc) - ]; - }, - fixIds: [ - fixId8 - ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes9, (changes, diag2)=>{ - const decl = getDeclaration(diag2.file, diag2.start); - if (decl) doChange(changes, diag2.file, decl); - }) - }); + function getImplementationAtPosition(fileName, position) { + synchronizeHostData(); + return ts_FindAllReferences_exports.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } - }); - // src/services/codefixes/convertFunctionToEs6Class.ts - function doChange2(changes, sourceFile, position, checker, preferences, compilerOptions) { - const ctorSymbol = checker.getSymbolAtLocation(getTokenAtPosition(sourceFile, position)); - if (!ctorSymbol || !ctorSymbol.valueDeclaration || !(ctorSymbol.flags & 19 /* Variable */ )) return void 0; - const ctorDeclaration = ctorSymbol.valueDeclaration; - if (isFunctionDeclaration(ctorDeclaration) || isFunctionExpression(ctorDeclaration)) changes.replaceNode(sourceFile, ctorDeclaration, createClassFromFunction(ctorDeclaration)); - else if (isVariableDeclaration(ctorDeclaration)) { - const classDeclaration = createClassFromVariableDeclaration(ctorDeclaration); - if (!classDeclaration) return void 0; - const ancestor = ctorDeclaration.parent.parent; - if (isVariableDeclarationList(ctorDeclaration.parent) && ctorDeclaration.parent.declarations.length > 1) { - changes.delete(sourceFile, ctorDeclaration); - changes.insertNodeAfter(sourceFile, ancestor, classDeclaration); - } else changes.replaceNode(sourceFile, ancestor, classDeclaration); + function getDocumentHighlights(fileName, position, filesToSearch) { + const normalizedFileName = normalizePath(fileName); + Debug.assert(filesToSearch.some((f)=>normalizePath(f) === normalizedFileName)); + synchronizeHostData(); + const sourceFilesToSearch = mapDefined(filesToSearch, (fileName2)=>program.getSourceFile(fileName2)); + const sourceFile = getValidSourceFile(fileName); + return DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } - function createClassElementsFromSymbol(symbol) { - const memberElements = []; - if (symbol.exports) symbol.exports.forEach((member)=>{ - if (member.name === "prototype" && member.declarations) { - const firstDeclaration = member.declarations[0]; - if (member.declarations.length === 1 && isPropertyAccessExpression(firstDeclaration) && isBinaryExpression(firstDeclaration.parent) && firstDeclaration.parent.operatorToken.kind === 63 /* EqualsToken */ && isObjectLiteralExpression(firstDeclaration.parent.right)) { - const prototypes = firstDeclaration.parent.right; - createClassElement(prototypes.symbol, /** modifiers */ void 0, memberElements); - } - } else createClassElement(member, [ - factory.createToken(124 /* StaticKeyword */ ) - ], memberElements); - }); - if (symbol.members) symbol.members.forEach((member, key)=>{ - var _a2, _b, _c, _d; - if (key === "constructor" && member.valueDeclaration) { - const prototypeAssignment = (_d = (_c = (_b = (_a2 = symbol.exports) == null ? void 0 : _a2.get("prototype")) == null ? void 0 : _b.declarations) == null ? void 0 : _c[0]) == null ? void 0 : _d.parent; - if (prototypeAssignment && isBinaryExpression(prototypeAssignment) && isObjectLiteralExpression(prototypeAssignment.right) && some(prototypeAssignment.right.properties, isConstructorAssignment)) ; - else changes.delete(sourceFile, member.valueDeclaration.parent); - return; - } - createClassElement(member, /*modifiers*/ void 0, memberElements); - }); - return memberElements; - function shouldConvertDeclaration(_target, source) { - if (isAccessExpression(_target)) { - if (isPropertyAccessExpression(_target) && isConstructorAssignment(_target)) return true; - return isFunctionLike(source); - } else return every(_target.properties, (property)=>{ - if (isMethodDeclaration(property) || isGetOrSetAccessorDeclaration(property)) return true; - if (isPropertyAssignment(property) && isFunctionExpression(property.initializer) && !!property.name) return true; - if (isConstructorAssignment(property)) return true; - return false; + function findRenameLocations(fileName, position, findInStrings, findInComments, preferences) { + synchronizeHostData(); + const sourceFile = getValidSourceFile(fileName); + const node = getAdjustedRenameLocation(getTouchingPropertyName(sourceFile, position)); + if (!ts_Rename_exports.nodeIsEligibleForRename(node)) return void 0; + if (isIdentifier(node) && (isJsxOpeningElement(node.parent) || isJsxClosingElement(node.parent)) && isIntrinsicJsxName(node.escapedText)) { + const { openingElement: openingElement, closingElement: closingElement } = node.parent.parent; + return [ + openingElement, + closingElement + ].map((node2)=>{ + const textSpan = createTextSpanFromNode(node2.tagName, sourceFile); + return { + fileName: sourceFile.fileName, + textSpan: textSpan, + ...ts_FindAllReferences_exports.toContextSpan(textSpan, sourceFile, node2.parent) + }; }); - } - function createClassElement(symbol2, modifiers, members) { - if (!(symbol2.flags & 8192 /* Method */ ) && !(symbol2.flags & 4096 /* ObjectLiteral */ )) return; - const memberDeclaration = symbol2.valueDeclaration; - const assignmentBinaryExpression = memberDeclaration.parent; - const assignmentExpr = assignmentBinaryExpression.right; - if (!shouldConvertDeclaration(memberDeclaration, assignmentExpr)) return; - if (some(members, (m)=>{ - const name = getNameOfDeclaration(m); - if (name && isIdentifier(name) && idText(name) === symbolName(symbol2)) return true; - return false; - })) return; - const nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 241 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression; - changes.delete(sourceFile, nodeToDelete); - if (!assignmentExpr) { - members.push(factory.createPropertyDeclaration(modifiers, symbol2.name, /*questionToken*/ void 0, /*type*/ void 0, /*initializer*/ void 0)); - return; - } - if (isAccessExpression(memberDeclaration) && (isFunctionExpression(assignmentExpr) || isArrowFunction(assignmentExpr))) { - const quotePreference = getQuotePreference(sourceFile, preferences); - const name = tryGetPropertyName(memberDeclaration, compilerOptions, quotePreference); - if (name) createFunctionLikeExpressionMember(members, assignmentExpr, name); - return; - } else if (isObjectLiteralExpression(assignmentExpr)) { - forEach(assignmentExpr.properties, (property)=>{ - if (isMethodDeclaration(property) || isGetOrSetAccessorDeclaration(property)) members.push(property); - if (isPropertyAssignment(property) && isFunctionExpression(property.initializer)) createFunctionLikeExpressionMember(members, property.initializer, property.name); - if (isConstructorAssignment(property)) return; - return; - }); - return; - } else { - if (isSourceFileJS(sourceFile)) return; - if (!isPropertyAccessExpression(memberDeclaration)) return; - const prop = factory.createPropertyDeclaration(modifiers, memberDeclaration.name, /*questionToken*/ void 0, /*type*/ void 0, assignmentExpr); - copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile); - members.push(prop); - return; - } - function createFunctionLikeExpressionMember(members2, expression, name) { - if (isFunctionExpression(expression)) return createFunctionExpressionMember(members2, expression, name); - else return createArrowFunctionExpressionMember(members2, expression, name); - } - function createFunctionExpressionMember(members2, functionExpression, name) { - const fullModifiers = concatenate(modifiers, getModifierKindFromSource(functionExpression, 132 /* AsyncKeyword */ )); - const method = factory.createMethodDeclaration(fullModifiers, /*asteriskToken*/ void 0, name, /*questionToken*/ void 0, /*typeParameters*/ void 0, functionExpression.parameters, /*type*/ void 0, functionExpression.body); - copyLeadingComments(assignmentBinaryExpression, method, sourceFile); - members2.push(method); - return; - } - function createArrowFunctionExpressionMember(members2, arrowFunction, name) { - const arrowFunctionBody = arrowFunction.body; - let bodyBlock; - if (arrowFunctionBody.kind === 238 /* Block */ ) bodyBlock = arrowFunctionBody; - else bodyBlock = factory.createBlock([ - factory.createReturnStatement(arrowFunctionBody) - ]); - const fullModifiers = concatenate(modifiers, getModifierKindFromSource(arrowFunction, 132 /* AsyncKeyword */ )); - const method = factory.createMethodDeclaration(fullModifiers, /*asteriskToken*/ void 0, name, /*questionToken*/ void 0, /*typeParameters*/ void 0, arrowFunction.parameters, /*type*/ void 0, bodyBlock); - copyLeadingComments(assignmentBinaryExpression, method, sourceFile); - members2.push(method); - } + } else { + const quotePreference = getQuotePreference(sourceFile, preferences ?? emptyOptions); + const providePrefixAndSuffixTextForRename = typeof preferences === "boolean" ? preferences : preferences == null ? void 0 : preferences.providePrefixAndSuffixTextForRename; + return getReferencesWorker(node, position, { + findInStrings: findInStrings, + findInComments: findInComments, + providePrefixAndSuffixTextForRename: providePrefixAndSuffixTextForRename, + use: ts_FindAllReferences_exports.FindReferencesUse.Rename + }, (entry, originalNode, checker)=>ts_FindAllReferences_exports.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false, quotePreference)); } } - function createClassFromVariableDeclaration(node) { - const initializer = node.initializer; - if (!initializer || !isFunctionExpression(initializer) || !isIdentifier(node.name)) return void 0; - const memberElements = createClassElementsFromSymbol(node.symbol); - if (initializer.body) memberElements.unshift(factory.createConstructorDeclaration(/*modifiers*/ void 0, initializer.parameters, initializer.body)); - const modifiers = getModifierKindFromSource(node.parent.parent, 93 /* ExportKeyword */ ); - const cls = factory.createClassDeclaration(modifiers, node.name, /*typeParameters*/ void 0, /*heritageClauses*/ void 0, memberElements); - return cls; + function getReferencesAtPosition(fileName, position) { + synchronizeHostData(); + return getReferencesWorker(getTouchingPropertyName(getValidSourceFile(fileName), position), position, { + use: ts_FindAllReferences_exports.FindReferencesUse.References + }, ts_FindAllReferences_exports.toReferenceEntry); } - function createClassFromFunction(node) { - const memberElements = createClassElementsFromSymbol(ctorSymbol); - if (node.body) memberElements.unshift(factory.createConstructorDeclaration(/*modifiers*/ void 0, node.parameters, node.body)); - const modifiers = getModifierKindFromSource(node, 93 /* ExportKeyword */ ); - const cls = factory.createClassDeclaration(modifiers, node.name, /*typeParameters*/ void 0, /*heritageClauses*/ void 0, memberElements); - return cls; + function getReferencesWorker(node, position, options, cb) { + synchronizeHostData(); + const sourceFiles = options && options.use === ts_FindAllReferences_exports.FindReferencesUse.Rename ? program.getSourceFiles().filter((sourceFile)=>!program.isSourceFileDefaultLibrary(sourceFile)) : program.getSourceFiles(); + return ts_FindAllReferences_exports.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); } - } - function getModifierKindFromSource(source, kind) { - return canHaveModifiers(source) ? filter(source.modifiers, (modifier)=>modifier.kind === kind) : void 0; - } - function isConstructorAssignment(x) { - if (!x.name) return false; - if (isIdentifier(x.name) && x.name.text === "constructor") return true; - return false; - } - function tryGetPropertyName(node, compilerOptions, quotePreference) { - if (isPropertyAccessExpression(node)) return node.name; - const propName = node.argumentExpression; - if (isNumericLiteral(propName)) return propName; - if (isStringLiteralLike(propName)) return isIdentifierText(propName.text, getEmitScriptTarget(compilerOptions)) ? factory.createIdentifier(propName.text) : isNoSubstitutionTemplateLiteral(propName) ? factory.createStringLiteral(propName.text, quotePreference === 0 /* Single */ ) : propName; - return void 0; - } - var fixId9, errorCodes10; - var init_convertFunctionToEs6Class = __esm({ - "src/services/codefixes/convertFunctionToEs6Class.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId9 = "convertFunctionToEs6Class"; - errorCodes10 = [ - Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code - ]; - registerCodeFix({ - errorCodes: errorCodes10, - getCodeActions (context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange2(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())); - return [ - createCodeFixAction(fixId9, changes, Diagnostics.Convert_function_to_an_ES2015_class, fixId9, Diagnostics.Convert_all_constructor_functions_to_classes) - ]; - }, - fixIds: [ - fixId9 - ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes10, (changes, err)=>doChange2(changes, err.file, err.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())) - }); + function findReferences(fileName, position) { + synchronizeHostData(); + return ts_FindAllReferences_exports.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } - }); - // src/services/codefixes/convertToAsyncFunction.ts - function convertToAsyncFunction(changes, sourceFile, position, checker) { - const tokenAtPosition = getTokenAtPosition(sourceFile, position); - let functionToConvert; - if (isIdentifier(tokenAtPosition) && isVariableDeclaration(tokenAtPosition.parent) && tokenAtPosition.parent.initializer && isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) functionToConvert = tokenAtPosition.parent.initializer; - else functionToConvert = tryCast(getContainingFunction(getTokenAtPosition(sourceFile, position)), canBeConvertedToAsync); - if (!functionToConvert) return; - const synthNamesMap = /* @__PURE__ */ new Map(); - const isInJavascript = isInJSFile(functionToConvert); - const setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); - const functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap); - if (!returnsPromise(functionToConvertRenamed, checker)) return; - const returnStatements = functionToConvertRenamed.body && isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body, checker) : emptyArray; - const transformer = { - checker: checker, - synthNamesMap: synthNamesMap, - setOfExpressionsToReturn: setOfExpressionsToReturn, - isInJSFile: isInJavascript - }; - if (!returnStatements.length) return; - const pos = skipTrivia(sourceFile.text, moveRangePastModifiers(functionToConvert).pos); - changes.insertModifierAt(sourceFile, pos, 132 /* AsyncKeyword */ , { - suffix: " " - }); - for (const returnStatement of returnStatements){ - forEachChild(returnStatement, function visit(node) { - if (isCallExpression(node)) { - const newNodes = transformExpression(node, node, transformer, /*hasContinuation*/ false); - if (hasFailed()) return true; - changes.replaceNodeWithNodes(sourceFile, returnStatement, newNodes); - } else if (!isFunctionLike(node)) { - forEachChild(node, visit); - if (hasFailed()) return true; - } - }); - if (hasFailed()) return; + function getFileReferences(fileName) { + synchronizeHostData(); + return ts_FindAllReferences_exports.Core.getReferencesForFileName(fileName, program, program.getSourceFiles()).map(ts_FindAllReferences_exports.toReferenceEntry); } - } - function getReturnStatementsWithPromiseHandlers(body, checker) { - const res = []; - forEachReturnStatement(body, (ret)=>{ - if (isReturnStatementWithFixablePromiseHandler(ret, checker)) res.push(ret); - }); - return res; - } - function getAllPromiseExpressionsToReturn(func, checker) { - if (!func.body) return /* @__PURE__ */ new Set(); - const setOfExpressionsToReturn = /* @__PURE__ */ new Set(); - forEachChild(func.body, function visit(node) { - if (isPromiseReturningCallExpression(node, checker, "then")) { - setOfExpressionsToReturn.add(getNodeId(node)); - forEach(node.arguments, visit); - } else if (isPromiseReturningCallExpression(node, checker, "catch") || isPromiseReturningCallExpression(node, checker, "finally")) { - setOfExpressionsToReturn.add(getNodeId(node)); - forEachChild(node, visit); - } else if (isPromiseTypedExpression(node, checker)) setOfExpressionsToReturn.add(getNodeId(node)); - else forEachChild(node, visit); - }); - return setOfExpressionsToReturn; - } - function isPromiseReturningCallExpression(node, checker, name) { - if (!isCallExpression(node)) return false; - const isExpressionOfName = hasPropertyAccessExpressionWithName(node, name); - const nodeType = isExpressionOfName && checker.getTypeAtLocation(node); - return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); - } - function isReferenceToType(type, target) { - return (getObjectFlags(type) & 4 /* Reference */ ) !== 0 && type.target === target; - } - function getExplicitPromisedTypeOfPromiseReturningCallExpression(node, callback, checker) { - if (node.expression.name.escapedText === "finally") return void 0; - const promiseType = checker.getTypeAtLocation(node.expression.expression); - if (isReferenceToType(promiseType, checker.getPromiseType()) || isReferenceToType(promiseType, checker.getPromiseLikeType())) { - if (node.expression.name.escapedText === "then") { - if (callback === elementAt(node.arguments, 0)) return elementAt(node.typeArguments, 0); - else if (callback === elementAt(node.arguments, 1)) return elementAt(node.typeArguments, 1); - } else return elementAt(node.typeArguments, 0); + function getNavigateToItems2(searchValue, maxResultCount, fileName, excludeDtsFiles = false) { + synchronizeHostData(); + const sourceFiles = fileName ? [ + getValidSourceFile(fileName) + ] : program.getSourceFiles(); + return getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - } - function isPromiseTypedExpression(node, checker) { - if (!isExpression(node)) return false; - return !!checker.getPromisedTypeOfPromise(checker.getTypeAtLocation(node)); - } - function renameCollidingVarNames(nodeToRename, checker, synthNamesMap) { - const identsToRenameMap = /* @__PURE__ */ new Map(); - const collidingSymbolMap = createMultiMap(); - forEachChild(nodeToRename, function visit(node) { - if (!isIdentifier(node)) { - forEachChild(node, visit); - return; - } - const symbol = checker.getSymbolAtLocation(node); - if (symbol) { - const type = checker.getTypeAtLocation(node); - const lastCallSignature = getLastCallSignature(type, checker); - const symbolIdString = getSymbolId(symbol).toString(); - if (lastCallSignature && !isParameter(node.parent) && !isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { - const firstParameter = firstOrUndefined(lastCallSignature.parameters); - const ident = (firstParameter == null ? void 0 : firstParameter.valueDeclaration) && isParameter(firstParameter.valueDeclaration) && tryCast(firstParameter.valueDeclaration.name, isIdentifier) || factory.createUniqueName("result", 16 /* Optimistic */ ); - const synthName = getNewNameIfConflict(ident, collidingSymbolMap); - synthNamesMap.set(symbolIdString, synthName); - collidingSymbolMap.add(ident.text, symbol); - } else if (node.parent && (isParameter(node.parent) || isVariableDeclaration(node.parent) || isBindingElement(node.parent))) { - const originalName = node.text; - const collidingSymbols = collidingSymbolMap.get(originalName); - if (collidingSymbols && collidingSymbols.some((prevSymbol)=>prevSymbol !== symbol)) { - const newName = getNewNameIfConflict(node, collidingSymbolMap); - identsToRenameMap.set(symbolIdString, newName.identifier); - synthNamesMap.set(symbolIdString, newName); - collidingSymbolMap.add(originalName, symbol); - } else { - const identifier = getSynthesizedDeepClone(node); - synthNamesMap.set(symbolIdString, createSynthIdentifier(identifier)); - collidingSymbolMap.add(originalName, symbol); - } - } + function getEmitOutput(fileName, emitOnlyDtsFiles, forceDtsEmit) { + synchronizeHostData(); + const sourceFile = getValidSourceFile(fileName); + const customTransformers = host.getCustomTransformers && host.getCustomTransformers(); + return getFileEmitOutput(program, sourceFile, !!emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit); + } + function getSignatureHelpItems2(fileName, position, { triggerReason: triggerReason } = emptyOptions) { + synchronizeHostData(); + const sourceFile = getValidSourceFile(fileName); + return ts_SignatureHelp_exports.getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken); + } + function getNonBoundSourceFile(fileName) { + return syntaxTreeCache.getCurrentSourceFile(fileName); + } + function getNameOrDottedNameSpan(fileName, startPos, _endPos) { + const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + const node = getTouchingPropertyName(sourceFile, startPos); + if (node === sourceFile) return void 0; + switch(node.kind){ + case 211 /* PropertyAccessExpression */ : + case 166 /* QualifiedName */ : + case 11 /* StringLiteral */ : + case 97 /* FalseKeyword */ : + case 112 /* TrueKeyword */ : + case 106 /* NullKeyword */ : + case 108 /* SuperKeyword */ : + case 110 /* ThisKeyword */ : + case 197 /* ThisType */ : + case 80 /* Identifier */ : + break; + default: + return void 0; } - }); - return getSynthesizedDeepCloneWithReplacements(nodeToRename, /*includeTrivia*/ true, (original)=>{ - if (isBindingElement(original) && isIdentifier(original.name) && isObjectBindingPattern(original.parent)) { - const symbol = checker.getSymbolAtLocation(original.name); - const renameInfo = symbol && identsToRenameMap.get(String(getSymbolId(symbol))); - if (renameInfo && renameInfo.text !== (original.name || original.propertyName).getText()) return factory.createBindingElement(original.dotDotDotToken, original.propertyName || original.name, renameInfo, original.initializer); - } else if (isIdentifier(original)) { - const symbol = checker.getSymbolAtLocation(original); - const renameInfo = symbol && identsToRenameMap.get(String(getSymbolId(symbol))); - if (renameInfo) return factory.createIdentifier(renameInfo.text); + let nodeForStartPos = node; + while(true){ + if (isRightSideOfPropertyAccess(nodeForStartPos) || isRightSideOfQualifiedName(nodeForStartPos)) nodeForStartPos = nodeForStartPos.parent; + else if (isNameOfModuleDeclaration(nodeForStartPos)) { + if (nodeForStartPos.parent.parent.kind === 267 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) nodeForStartPos = nodeForStartPos.parent.parent.name; + else break; + } else break; } - }); - } - function getNewNameIfConflict(name, originalNames) { - const numVarsSameName = (originalNames.get(name.text) || emptyArray).length; - const identifier = numVarsSameName === 0 ? name : factory.createIdentifier(name.text + "_" + numVarsSameName); - return createSynthIdentifier(identifier); - } - function hasFailed() { - return !codeActionSucceeded; - } - function silentFail() { - codeActionSucceeded = false; - return emptyArray; - } - function transformExpression(returnContextNode, node, transformer, hasContinuation, continuationArgName) { - if (isPromiseReturningCallExpression(node, transformer.checker, "then")) return transformThen(node, elementAt(node.arguments, 0), elementAt(node.arguments, 1), transformer, hasContinuation, continuationArgName); - if (isPromiseReturningCallExpression(node, transformer.checker, "catch")) return transformCatch(node, elementAt(node.arguments, 0), transformer, hasContinuation, continuationArgName); - if (isPromiseReturningCallExpression(node, transformer.checker, "finally")) return transformFinally(node, elementAt(node.arguments, 0), transformer, hasContinuation, continuationArgName); - if (isPropertyAccessExpression(node)) return transformExpression(returnContextNode, node.expression, transformer, hasContinuation, continuationArgName); - const nodeType = transformer.checker.getTypeAtLocation(node); - if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { - Debug.assertNode(getOriginalNode(node).parent, isPropertyAccessExpression); - return transformPromiseExpressionOfPropertyAccess(returnContextNode, node, transformer, hasContinuation, continuationArgName); + return createTextSpanFromBounds(nodeForStartPos.getStart(), node.getEnd()); } - return silentFail(); - } - function isNullOrUndefined2({ checker: checker }, node) { - if (node.kind === 104 /* NullKeyword */ ) return true; - if (isIdentifier(node) && !isGeneratedIdentifier(node) && idText(node) === "undefined") { - const symbol = checker.getSymbolAtLocation(node); - return !symbol || checker.isUndefinedSymbol(symbol); + function getBreakpointStatementAtPosition(fileName, position) { + const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + return ts_BreakpointResolver_exports.spanInSourceFileAtLocation(sourceFile, position); } - return false; - } - function createUniqueSynthName(prevArgName) { - const renamedPrevArg = factory.createUniqueName(prevArgName.identifier.text, 16 /* Optimistic */ ); - return createSynthIdentifier(renamedPrevArg); - } - function getPossibleNameForVarDecl(node, transformer, continuationArgName) { - let possibleNameForVarDecl; - if (continuationArgName && !shouldReturn(node, transformer)) { - if (isSynthIdentifier(continuationArgName)) { - possibleNameForVarDecl = continuationArgName; - transformer.synthNamesMap.forEach((val, key)=>{ - if (val.identifier.text === continuationArgName.identifier.text) { - const newSynthName = createUniqueSynthName(continuationArgName); - transformer.synthNamesMap.set(key, newSynthName); - } - }); - } else possibleNameForVarDecl = createSynthIdentifier(factory.createUniqueName("result", 16 /* Optimistic */ ), continuationArgName.types); - declareSynthIdentifier(possibleNameForVarDecl); + function getNavigationBarItems2(fileName) { + return getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken); } - return possibleNameForVarDecl; - } - function finishCatchOrFinallyTransform(node, transformer, tryStatement, possibleNameForVarDecl, continuationArgName) { - const statements = []; - let varDeclIdentifier; - if (possibleNameForVarDecl && !shouldReturn(node, transformer)) { - varDeclIdentifier = getSynthesizedDeepClone(declareSynthIdentifier(possibleNameForVarDecl)); - const typeArray = possibleNameForVarDecl.types; - const unionType = transformer.checker.getUnionType(typeArray, 2 /* Subtype */ ); - const unionTypeNode = transformer.isInJSFile ? void 0 : transformer.checker.typeToTypeNode(unionType, /*enclosingDeclaration*/ void 0, /*flags*/ void 0); - const varDecl = [ - factory.createVariableDeclaration(varDeclIdentifier, /*exclamationToken*/ void 0, unionTypeNode) - ]; - const varDeclList = factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList(varDecl, 1 /* Let */ )); - statements.push(varDeclList); + function getNavigationTree2(fileName) { + return getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken); } - statements.push(tryStatement); - if (continuationArgName && varDeclIdentifier && isSynthBindingPattern(continuationArgName)) statements.push(factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ - factory.createVariableDeclaration(getSynthesizedDeepClone(declareSynthBindingPattern(continuationArgName)), /*exclamationToken*/ void 0, /*type*/ void 0, varDeclIdentifier) - ], 2 /* Const */ ))); - return statements; - } - function transformFinally(node, onFinally, transformer, hasContinuation, continuationArgName) { - if (!onFinally || isNullOrUndefined2(transformer, onFinally)) return transformExpression(/* returnContextNode */ node, node.expression.expression, transformer, hasContinuation, continuationArgName); - const possibleNameForVarDecl = getPossibleNameForVarDecl(node, transformer, continuationArgName); - const inlinedLeftHandSide = transformExpression(/*returnContextNode*/ node, node.expression.expression, transformer, /*hasContinuation*/ true, possibleNameForVarDecl); - if (hasFailed()) return silentFail(); - const inlinedCallback = transformCallbackArgument(onFinally, hasContinuation, /*continuationArgName*/ void 0, /*argName*/ void 0, node, transformer); - if (hasFailed()) return silentFail(); - const tryBlock = factory.createBlock(inlinedLeftHandSide); - const finallyBlock = factory.createBlock(inlinedCallback); - const tryStatement = factory.createTryStatement(tryBlock, /*catchClause*/ void 0, finallyBlock); - return finishCatchOrFinallyTransform(node, transformer, tryStatement, possibleNameForVarDecl, continuationArgName); - } - function transformCatch(node, onRejected, transformer, hasContinuation, continuationArgName) { - if (!onRejected || isNullOrUndefined2(transformer, onRejected)) return transformExpression(/* returnContextNode */ node, node.expression.expression, transformer, hasContinuation, continuationArgName); - const inputArgName = getArgBindingName(onRejected, transformer); - const possibleNameForVarDecl = getPossibleNameForVarDecl(node, transformer, continuationArgName); - const inlinedLeftHandSide = transformExpression(/*returnContextNode*/ node, node.expression.expression, transformer, /*hasContinuation*/ true, possibleNameForVarDecl); - if (hasFailed()) return silentFail(); - const inlinedCallback = transformCallbackArgument(onRejected, hasContinuation, possibleNameForVarDecl, inputArgName, node, transformer); - if (hasFailed()) return silentFail(); - const tryBlock = factory.createBlock(inlinedLeftHandSide); - const catchClause = factory.createCatchClause(inputArgName && getSynthesizedDeepClone(declareSynthBindingName(inputArgName)), factory.createBlock(inlinedCallback)); - const tryStatement = factory.createTryStatement(tryBlock, catchClause, /*finallyBlock*/ void 0); - return finishCatchOrFinallyTransform(node, transformer, tryStatement, possibleNameForVarDecl, continuationArgName); - } - function transformThen(node, onFulfilled, onRejected, transformer, hasContinuation, continuationArgName) { - if (!onFulfilled || isNullOrUndefined2(transformer, onFulfilled)) return transformCatch(node, onRejected, transformer, hasContinuation, continuationArgName); - if (onRejected && !isNullOrUndefined2(transformer, onRejected)) return silentFail(); - const inputArgName = getArgBindingName(onFulfilled, transformer); - const inlinedLeftHandSide = transformExpression(node.expression.expression, node.expression.expression, transformer, /*hasContinuation*/ true, inputArgName); - if (hasFailed()) return silentFail(); - const inlinedCallback = transformCallbackArgument(onFulfilled, hasContinuation, continuationArgName, inputArgName, node, transformer); - if (hasFailed()) return silentFail(); - return concatenate(inlinedLeftHandSide, inlinedCallback); - } - function transformPromiseExpressionOfPropertyAccess(returnContextNode, node, transformer, hasContinuation, continuationArgName) { - if (shouldReturn(returnContextNode, transformer)) { - let returnValue = getSynthesizedDeepClone(node); - if (hasContinuation) returnValue = factory.createAwaitExpression(returnValue); - return [ - factory.createReturnStatement(returnValue) - ]; + function getSemanticClassifications3(fileName, span, format) { + synchronizeHostData(); + const responseFormat = format || "original" /* Original */ ; + if (responseFormat === "2020" /* TwentyTwenty */ ) return getSemanticClassifications2(program, cancellationToken, getValidSourceFile(fileName), span); + else return getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } - return createVariableOrAssignmentOrExpressionStatement(continuationArgName, factory.createAwaitExpression(node), /*typeAnnotation*/ void 0); - } - function createVariableOrAssignmentOrExpressionStatement(variableName, rightHandSide, typeAnnotation) { - if (!variableName || isEmptyBindingName(variableName)) return [ - factory.createExpressionStatement(rightHandSide) - ]; - if (isSynthIdentifier(variableName) && variableName.hasBeenDeclared) return [ - factory.createExpressionStatement(factory.createAssignment(getSynthesizedDeepClone(referenceSynthIdentifier(variableName)), rightHandSide)) - ]; - return [ - factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ - factory.createVariableDeclaration(getSynthesizedDeepClone(declareSynthBindingName(variableName)), /*exclamationToken*/ void 0, typeAnnotation, rightHandSide) - ], 2 /* Const */ )) - ]; - } - function maybeAnnotateAndReturn(expressionToReturn, typeAnnotation) { - if (typeAnnotation && expressionToReturn) { - const name = factory.createUniqueName("result", 16 /* Optimistic */ ); - return [ - ...createVariableOrAssignmentOrExpressionStatement(createSynthIdentifier(name), expressionToReturn, typeAnnotation), - factory.createReturnStatement(name) - ]; + function getEncodedSemanticClassifications3(fileName, span, format) { + synchronizeHostData(); + const responseFormat = format || "original" /* Original */ ; + if (responseFormat === "original" /* Original */ ) return getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); + else return getEncodedSemanticClassifications2(program, cancellationToken, getValidSourceFile(fileName), span); } - return [ - factory.createReturnStatement(expressionToReturn) - ]; - } - function transformCallbackArgument(func, hasContinuation, continuationArgName, inputArgName, parent2, transformer) { - var _a2; - switch(func.kind){ - case 104 /* NullKeyword */ : - break; - case 208 /* PropertyAccessExpression */ : - case 79 /* Identifier */ : - if (!inputArgName) break; - const synthCall = factory.createCallExpression(getSynthesizedDeepClone(func), /*typeArguments*/ void 0, isSynthIdentifier(inputArgName) ? [ - referenceSynthIdentifier(inputArgName) - ] : []); - if (shouldReturn(parent2, transformer)) return maybeAnnotateAndReturn(synthCall, getExplicitPromisedTypeOfPromiseReturningCallExpression(parent2, func, transformer.checker)); - const type = transformer.checker.getTypeAtLocation(func); - const callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */ ); - if (!callSignatures.length) return silentFail(); - const returnType = callSignatures[0].getReturnType(); - const varDeclOrAssignment = createVariableOrAssignmentOrExpressionStatement(continuationArgName, factory.createAwaitExpression(synthCall), getExplicitPromisedTypeOfPromiseReturningCallExpression(parent2, func, transformer.checker)); - if (continuationArgName) continuationArgName.types.push(transformer.checker.getAwaitedType(returnType) || returnType); - return varDeclOrAssignment; - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - { - const funcBody = func.body; - const returnType2 = (_a2 = getLastCallSignature(transformer.checker.getTypeAtLocation(func), transformer.checker)) == null ? void 0 : _a2.getReturnType(); - if (isBlock(funcBody)) { - let refactoredStmts = []; - let seenReturnStatement = false; - for (const statement of funcBody.statements){ - if (isReturnStatement(statement)) { - seenReturnStatement = true; - if (isReturnStatementWithFixablePromiseHandler(statement, transformer.checker)) refactoredStmts = refactoredStmts.concat(transformReturnStatementWithFixablePromiseHandler(transformer, statement, hasContinuation, continuationArgName)); - else { - const possiblyAwaitedRightHandSide = returnType2 && statement.expression ? getPossiblyAwaitedRightHandSide(transformer.checker, returnType2, statement.expression) : statement.expression; - refactoredStmts.push(...maybeAnnotateAndReturn(possiblyAwaitedRightHandSide, getExplicitPromisedTypeOfPromiseReturningCallExpression(parent2, func, transformer.checker))); - } - } else if (hasContinuation && forEachReturnStatement(statement, returnTrue)) return silentFail(); - else refactoredStmts.push(statement); - } - return shouldReturn(parent2, transformer) ? refactoredStmts.map((s)=>getSynthesizedDeepClone(s)) : removeReturns(refactoredStmts, continuationArgName, transformer, seenReturnStatement); - } else { - const inlinedStatements = isFixablePromiseHandler(funcBody, transformer.checker) ? transformReturnStatementWithFixablePromiseHandler(transformer, factory.createReturnStatement(funcBody), hasContinuation, continuationArgName) : emptyArray; - if (inlinedStatements.length > 0) return inlinedStatements; - if (returnType2) { - const possiblyAwaitedRightHandSide = getPossiblyAwaitedRightHandSide(transformer.checker, returnType2, funcBody); - if (!shouldReturn(parent2, transformer)) { - const transformedStatement = createVariableOrAssignmentOrExpressionStatement(continuationArgName, possiblyAwaitedRightHandSide, /*typeAnnotation*/ void 0); - if (continuationArgName) continuationArgName.types.push(transformer.checker.getAwaitedType(returnType2) || returnType2); - return transformedStatement; - } else return maybeAnnotateAndReturn(possiblyAwaitedRightHandSide, getExplicitPromisedTypeOfPromiseReturningCallExpression(parent2, func, transformer.checker)); - } else return silentFail(); - } - } - default: - return silentFail(); + function getSyntacticClassifications2(fileName, span) { + return getSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span); } - return emptyArray; - } - function getPossiblyAwaitedRightHandSide(checker, type, expr) { - const rightHandSide = getSynthesizedDeepClone(expr); - return !!checker.getPromisedTypeOfPromise(type) ? factory.createAwaitExpression(rightHandSide) : rightHandSide; - } - function getLastCallSignature(type, checker) { - const callSignatures = checker.getSignaturesOfType(type, 0 /* Call */ ); - return lastOrUndefined(callSignatures); - } - function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) { - const ret = []; - for (const stmt of stmts){ - if (isReturnStatement(stmt)) { - if (stmt.expression) { - const possiblyAwaitedExpression = isPromiseTypedExpression(stmt.expression, transformer.checker) ? factory.createAwaitExpression(stmt.expression) : stmt.expression; - if (prevArgName === void 0) ret.push(factory.createExpressionStatement(possiblyAwaitedExpression)); - else if (isSynthIdentifier(prevArgName) && prevArgName.hasBeenDeclared) ret.push(factory.createExpressionStatement(factory.createAssignment(referenceSynthIdentifier(prevArgName), possiblyAwaitedExpression))); - else ret.push(factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ - factory.createVariableDeclaration(declareSynthBindingName(prevArgName), /*exclamationToken*/ void 0, /*type*/ void 0, possiblyAwaitedExpression) - ], 2 /* Const */ ))); - } - } else ret.push(getSynthesizedDeepClone(stmt)); + function getEncodedSyntacticClassifications2(fileName, span) { + return getEncodedSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span); } - if (!seenReturnStatement && prevArgName !== void 0) ret.push(factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ - factory.createVariableDeclaration(declareSynthBindingName(prevArgName), /*exclamationToken*/ void 0, /*type*/ void 0, factory.createIdentifier("undefined")) - ], 2 /* Const */ ))); - return ret; - } - function transformReturnStatementWithFixablePromiseHandler(transformer, innerRetStmt, hasContinuation, continuationArgName) { - let innerCbBody = []; - forEachChild(innerRetStmt, function visit(node) { - if (isCallExpression(node)) { - const temp = transformExpression(node, node, transformer, hasContinuation, continuationArgName); - innerCbBody = innerCbBody.concat(temp); - if (innerCbBody.length > 0) return; - } else if (!isFunctionLike(node)) forEachChild(node, visit); - }); - return innerCbBody; - } - function getArgBindingName(funcNode, transformer) { - const types = []; - let name; - if (isFunctionLikeDeclaration(funcNode)) { - if (funcNode.parameters.length > 0) { - const param = funcNode.parameters[0].name; - name = getMappedBindingNameOrDefault(param); - } - } else if (isIdentifier(funcNode)) name = getMapEntryOrDefault(funcNode); - else if (isPropertyAccessExpression(funcNode) && isIdentifier(funcNode.name)) name = getMapEntryOrDefault(funcNode.name); - if (!name || "identifier" in name && name.identifier.text === "undefined") return void 0; - return name; - function getMappedBindingNameOrDefault(bindingName) { - if (isIdentifier(bindingName)) return getMapEntryOrDefault(bindingName); - const elements = flatMap(bindingName.elements, (element)=>{ - if (isOmittedExpression(element)) return []; - return [ - getMappedBindingNameOrDefault(element.name) - ]; - }); - return createSynthBindingPattern(bindingName, elements); + function getOutliningSpans(fileName) { + const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + return ts_OutliningElementsCollector_exports.collectElements(sourceFile, cancellationToken); } - function getMapEntryOrDefault(identifier) { - const originalNode = getOriginalNode2(identifier); - const symbol = getSymbol2(originalNode); - if (!symbol) return createSynthIdentifier(identifier, types); - const mapEntry = transformer.synthNamesMap.get(getSymbolId(symbol).toString()); - return mapEntry || createSynthIdentifier(identifier, types); + const braceMatching = new Map(Object.entries({ + [19 /* OpenBraceToken */ ]: 20 /* CloseBraceToken */ , + [21 /* OpenParenToken */ ]: 22 /* CloseParenToken */ , + [23 /* OpenBracketToken */ ]: 24 /* CloseBracketToken */ , + [32 /* GreaterThanToken */ ]: 30 /* LessThanToken */ + })); + braceMatching.forEach((value1, key)=>braceMatching.set(value1.toString(), Number(key))); + function getBraceMatchingAtPosition(fileName, position) { + const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + const token = getTouchingToken(sourceFile, position); + const matchKind = token.getStart(sourceFile) === position ? braceMatching.get(token.kind.toString()) : void 0; + const match = matchKind && findChildOfKind(token.parent, matchKind, sourceFile); + return match ? [ + createTextSpanFromNode(token, sourceFile), + createTextSpanFromNode(match, sourceFile) + ].sort((a, b)=>a.start - b.start) : emptyArray; } - function getSymbol2(node) { - var _a2, _b; - return (_b = (_a2 = tryCast(node, canHaveSymbol)) == null ? void 0 : _a2.symbol) != null ? _b : transformer.checker.getSymbolAtLocation(node); + function getIndentationAtPosition(fileName, position, editorOptions) { + let start = timestamp(); + const settings = toEditorSettings(editorOptions); + const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + log("getIndentationAtPosition: getCurrentSourceFile: " + (timestamp() - start)); + start = timestamp(); + const result = ts_formatting_exports.SmartIndenter.getIndentation(position, sourceFile, settings); + log("getIndentationAtPosition: computeIndentation : " + (timestamp() - start)); + return result; } - function getOriginalNode2(node) { - return node.original ? node.original : node; + function getFormattingEditsForRange(fileName, start, end, options) { + const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + return ts_formatting_exports.formatSelection(start, end, sourceFile, ts_formatting_exports.getFormatContext(toEditorSettings(options), host)); } - } - function isEmptyBindingName(bindingName) { - if (!bindingName) return true; - if (isSynthIdentifier(bindingName)) return !bindingName.identifier.text; - return every(bindingName.elements, isEmptyBindingName); - } - function createSynthIdentifier(identifier, types = []) { - return { - kind: 0 /* Identifier */ , - identifier: identifier, - types: types, - hasBeenDeclared: false, - hasBeenReferenced: false - }; - } - function createSynthBindingPattern(bindingPattern, elements = emptyArray, types = []) { - return { - kind: 1 /* BindingPattern */ , - bindingPattern: bindingPattern, - elements: elements, - types: types - }; - } - function referenceSynthIdentifier(synthId) { - synthId.hasBeenReferenced = true; - return synthId.identifier; - } - function declareSynthBindingName(synthName) { - return isSynthIdentifier(synthName) ? declareSynthIdentifier(synthName) : declareSynthBindingPattern(synthName); - } - function declareSynthBindingPattern(synthPattern) { - for (const element of synthPattern.elements)declareSynthBindingName(element); - return synthPattern.bindingPattern; - } - function declareSynthIdentifier(synthId) { - synthId.hasBeenDeclared = true; - return synthId.identifier; - } - function isSynthIdentifier(bindingName) { - return bindingName.kind === 0 /* Identifier */ ; - } - function isSynthBindingPattern(bindingName) { - return bindingName.kind === 1 /* BindingPattern */ ; - } - function shouldReturn(expression, transformer) { - return !!expression.original && transformer.setOfExpressionsToReturn.has(getNodeId(expression.original)); - } - var fixId10, errorCodes11, codeActionSucceeded; - var init_convertToAsyncFunction = __esm({ - "src/services/codefixes/convertToAsyncFunction.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId10 = "convertToAsyncFunction"; - errorCodes11 = [ - Diagnostics.This_may_be_converted_to_an_async_function.code - ]; - codeActionSucceeded = true; - registerCodeFix({ - errorCodes: errorCodes11, - getCodeActions (context) { - codeActionSucceeded = true; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker())); - return codeActionSucceeded ? [ - createCodeFixAction(fixId10, changes, Diagnostics.Convert_to_async_function, fixId10, Diagnostics.Convert_all_to_async_functions) - ] : []; - }, - fixIds: [ - fixId10 - ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes11, (changes, err)=>convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker())) - }); + function getFormattingEditsForDocument(fileName, options) { + return ts_formatting_exports.formatDocument(syntaxTreeCache.getCurrentSourceFile(fileName), ts_formatting_exports.getFormatContext(toEditorSettings(options), host)); } - }); - // src/services/codefixes/convertToEsModule.ts - function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) { - for (const moduleSpecifier of importingFile.imports){ - const imported = getResolvedModule(importingFile, moduleSpecifier.text, getModeForUsageLocation(importingFile, moduleSpecifier)); - if (!imported || imported.resolvedFileName !== exportingFile.fileName) continue; - const importNode = importFromModuleSpecifier(moduleSpecifier); - switch(importNode.kind){ - case 268 /* ImportEqualsDeclaration */ : - changes.replaceNode(importingFile, importNode, makeImport(importNode.name, /*namedImports*/ void 0, moduleSpecifier, quotePreference)); - break; - case 210 /* CallExpression */ : - if (isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) changes.replaceNode(importingFile, importNode, factory.createPropertyAccessExpression(getSynthesizedDeepClone(importNode), "default")); - break; + function getFormattingEditsAfterKeystroke(fileName, position, key, options) { + const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + const formatContext = ts_formatting_exports.getFormatContext(toEditorSettings(options), host); + if (!isInComment(sourceFile, position)) switch(key){ + case "{": + return ts_formatting_exports.formatOnOpeningCurly(position, sourceFile, formatContext); + case "}": + return ts_formatting_exports.formatOnClosingCurly(position, sourceFile, formatContext); + case ";": + return ts_formatting_exports.formatOnSemicolon(position, sourceFile, formatContext); + case "\n": + return ts_formatting_exports.formatOnEnter(position, sourceFile, formatContext); } + return []; } - } - function convertFileToEsModule(sourceFile, checker, changes, target, quotePreference) { - const identifiers = { - original: collectFreeIdentifiers(sourceFile), - additional: /* @__PURE__ */ new Set() - }; - const exports = collectExportRenames(sourceFile, checker, identifiers); - convertExportsAccesses(sourceFile, exports, changes); - let moduleExportsChangedToDefault = false; - let useSitesToUnqualify; - for (const statement of filter(sourceFile.statements, isVariableStatement)){ - const newUseSites = convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); - if (newUseSites) copyEntries(newUseSites, useSitesToUnqualify != null ? useSitesToUnqualify : useSitesToUnqualify = /* @__PURE__ */ new Map()); + function getCodeFixesAtPosition(fileName, start, end, errorCodes64, formatOptions, preferences = emptyOptions) { + synchronizeHostData(); + const sourceFile = getValidSourceFile(fileName); + const span = createTextSpanFromBounds(start, end); + const formatContext = ts_formatting_exports.getFormatContext(formatOptions, host); + return flatMap(deduplicate(errorCodes64, equateValues, compareValues), (errorCode)=>{ + cancellationToken.throwIfCancellationRequested(); + return ts_codefix_exports.getFixes({ + errorCode: errorCode, + sourceFile: sourceFile, + span: span, + program: program, + host: host, + cancellationToken: cancellationToken, + formatContext: formatContext, + preferences: preferences + }); + }); } - for (const statement of filter(sourceFile.statements, (s)=>!isVariableStatement(s))){ - const moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, useSitesToUnqualify, quotePreference); - moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; + function getCombinedCodeFix(scope, fixId52, formatOptions, preferences = emptyOptions) { + synchronizeHostData(); + Debug.assert(scope.type === "file"); + const sourceFile = getValidSourceFile(scope.fileName); + const formatContext = ts_formatting_exports.getFormatContext(formatOptions, host); + return ts_codefix_exports.getAllFixes({ + fixId: fixId52, + sourceFile: sourceFile, + program: program, + host: host, + cancellationToken: cancellationToken, + formatContext: formatContext, + preferences: preferences + }); } - useSitesToUnqualify == null || useSitesToUnqualify.forEach((replacement, original)=>{ - changes.replaceNode(sourceFile, original, replacement); - }); - return moduleExportsChangedToDefault; - } - function collectExportRenames(sourceFile, checker, identifiers) { - const res = /* @__PURE__ */ new Map(); - forEachExportReference(sourceFile, (node)=>{ - const { text: text } = node.name; - if (!res.has(text) && (isIdentifierANonContextualKeyword(node.name) || checker.resolveName(text, node, 111551 /* Value */ , /*excludeGlobals*/ true))) res.set(text, makeUniqueName(`_${text}`, identifiers)); - }); - return res; - } - function convertExportsAccesses(sourceFile, exports, changes) { - forEachExportReference(sourceFile, (node, isAssignmentLhs)=>{ - if (isAssignmentLhs) return; - const { text: text } = node.name; - changes.replaceNode(sourceFile, node, factory.createIdentifier(exports.get(text) || text)); - }); - } - function forEachExportReference(sourceFile, cb) { - sourceFile.forEachChild(function recur(node) { - if (isPropertyAccessExpression(node) && isExportsOrModuleExportsOrAlias(sourceFile, node.expression) && isIdentifier(node.name)) { - const { parent: parent2 } = node; - cb(node, isBinaryExpression(parent2) && parent2.left === node && parent2.operatorToken.kind === 63 /* EqualsToken */ ); - } - node.forEachChild(recur); - }); - } - function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, useSitesToUnqualify, quotePreference) { - switch(statement.kind){ - case 240 /* VariableStatement */ : - convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); - return false; - case 241 /* ExpressionStatement */ : - { - const { expression: expression } = statement; - switch(expression.kind){ - case 210 /* CallExpression */ : - if (isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) changes.replaceNode(sourceFile, statement, makeImport(/*name*/ void 0, /*namedImports*/ void 0, expression.arguments[0], quotePreference)); - return false; - case 223 /* BinaryExpression */ : - { - const { operatorToken: operatorToken } = expression; - return operatorToken.kind === 63 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports, useSitesToUnqualify); - } - } - } - default: - return false; + function organizeImports2(args, formatOptions, preferences = emptyOptions) { + synchronizeHostData(); + Debug.assert(args.type === "file"); + const sourceFile = getValidSourceFile(args.fileName); + const formatContext = ts_formatting_exports.getFormatContext(formatOptions, host); + const mode = args.mode ?? (args.skipDestructiveCodeActions ? "SortAndCombine" /* SortAndCombine */ : "All" /* All */ ); + return ts_OrganizeImports_exports.organizeImports(sourceFile, formatContext, host, program, preferences, mode); } - } - function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference) { - const { declarationList: declarationList } = statement; - let foundImport = false; - const converted = map(declarationList.declarations, (decl)=>{ - const { name: name , initializer: initializer } = decl; - if (initializer) { - if (isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { - foundImport = true; - return convertedImports([]); - } else if (isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) { - foundImport = true; - return convertSingleImport(name, initializer.arguments[0], checker, identifiers, target, quotePreference); - } else if (isPropertyAccessExpression(initializer) && isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) { - foundImport = true; - return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, quotePreference); - } - } - return convertedImports([ - factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ - decl - ], declarationList.flags)) - ]); - }); - if (foundImport) { - changes.replaceNodeWithNodes(sourceFile, statement, flatMap(converted, (c)=>c.newImports)); - let combinedUseSites; - forEach(converted, (c)=>{ - if (c.useSitesToUnqualify) copyEntries(c.useSitesToUnqualify, combinedUseSites != null ? combinedUseSites : combinedUseSites = /* @__PURE__ */ new Map()); - }); - return combinedUseSites; + function getEditsForFileRename2(oldFilePath, newFilePath, formatOptions, preferences = emptyOptions) { + return getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts_formatting_exports.getFormatContext(formatOptions, host), preferences, sourceMapper); } - } - function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { - switch(name.kind){ - case 203 /* ObjectBindingPattern */ : - case 204 /* ArrayBindingPattern */ : - { - const tmp = makeUniqueName(propertyName, identifiers); - return convertedImports([ - makeSingleImport(tmp, propertyName, moduleSpecifier, quotePreference), - makeConst(/*modifiers*/ void 0, name, factory.createIdentifier(tmp)) - ]); - } - case 79 /* Identifier */ : - return convertedImports([ - makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference) - ]); - default: - return Debug.assertNever(name, `Convert to ES module got invalid syntax form ${name.kind}`); + function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { + const action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; + return isArray(action) ? Promise.all(action.map((a)=>applySingleCodeActionCommand(a))) : applySingleCodeActionCommand(action); } - } - function convertAssignment(sourceFile, checker, assignment, changes, exports, useSitesToUnqualify) { - const { left: left , right: right } = assignment; - if (!isPropertyAccessExpression(left)) return false; - if (isExportsOrModuleExportsOrAlias(sourceFile, left)) { - if (isExportsOrModuleExportsOrAlias(sourceFile, right)) changes.delete(sourceFile, assignment.parent); - else { - const replacement = isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right, useSitesToUnqualify) : isRequireCall(right, /*checkArgumentIsStringLiteralLike*/ true) ? convertReExportAll(right.arguments[0], checker) : void 0; - if (replacement) { - changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]); - return replacement[1]; - } else { - changes.replaceRangeWithText(sourceFile, createRange(left.getStart(sourceFile), right.pos), "export default"); - return true; - } + function applySingleCodeActionCommand(action) { + const getPath = (path)=>toPath(path, currentDirectory, getCanonicalFileName); + Debug.assertEqual(action.type, "install package"); + return host.installPackage ? host.installPackage({ + fileName: getPath(action.file), + packageName: action.packageName + }) : Promise.reject("Host does not implement `installPackage`"); + } + function getDocCommentTemplateAtPosition2(fileName, position, options, formatOptions) { + const formatSettings = formatOptions ? ts_formatting_exports.getFormatContext(formatOptions, host).options : void 0; + return ts_JsDoc_exports.getDocCommentTemplateAtPosition(getNewLineOrDefaultFromHost(host, formatSettings), syntaxTreeCache.getCurrentSourceFile(fileName), position, options); + } + function isValidBraceCompletionAtPosition(fileName, position, openingBrace) { + if (openingBrace === 60 /* lessThan */ ) return false; + const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + if (isInString(sourceFile, position)) return false; + if (isInsideJsxElementOrAttribute(sourceFile, position)) return openingBrace === 123 /* openBrace */ ; + if (isInTemplateString(sourceFile, position)) return false; + switch(openingBrace){ + case 39 /* singleQuote */ : + case 34 /* doubleQuote */ : + case 96 /* backtick */ : + return !isInComment(sourceFile, position); } - } else if (isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) convertNamedExport(sourceFile, assignment, changes, exports); - return false; - } - function tryChangeModuleExportsObject(object, useSitesToUnqualify) { - const statements = mapAllOrFail(object.properties, (prop)=>{ - switch(prop.kind){ - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 300 /* ShorthandPropertyAssignment */ : - case 301 /* SpreadAssignment */ : - return void 0; - case 299 /* PropertyAssignment */ : - return !isIdentifier(prop.name) ? void 0 : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer, useSitesToUnqualify); - case 171 /* MethodDeclaration */ : - return !isIdentifier(prop.name) ? void 0 : functionExpressionToDeclaration(prop.name.text, [ - factory.createToken(93 /* ExportKeyword */ ) - ], prop, useSitesToUnqualify); - default: - Debug.assertNever(prop, `Convert to ES6 got invalid prop kind ${prop.kind}`); + return true; + } + function getJsxClosingTagAtPosition(fileName, position) { + const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + const token = findPrecedingToken(position, sourceFile); + if (!token) return void 0; + const element = token.kind === 32 /* GreaterThanToken */ && isJsxOpeningElement(token.parent) ? token.parent.parent : isJsxText(token) && isJsxElement(token.parent) ? token.parent : void 0; + if (element && isUnclosedTag(element)) return { + newText: `` + }; + const fragment = token.kind === 32 /* GreaterThanToken */ && isJsxOpeningFragment(token.parent) ? token.parent.parent : isJsxText(token) && isJsxFragment(token.parent) ? token.parent : void 0; + if (fragment && isUnclosedFragment(fragment)) return { + newText: "" + }; + } + function getLinkedEditingRangeAtPosition(fileName, position) { + const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + const token = findPrecedingToken(position, sourceFile); + if (!token || token.parent.kind === 312 /* SourceFile */ ) return void 0; + const jsxTagWordPattern = "[a-zA-Z0-9:\\-\\._$]*"; + if (isJsxFragment(token.parent.parent)) { + const openFragment = token.parent.parent.openingFragment; + const closeFragment = token.parent.parent.closingFragment; + if (containsParseError(openFragment) || containsParseError(closeFragment)) return void 0; + const openPos = openFragment.getStart(sourceFile) + 1; + const closePos = closeFragment.getStart(sourceFile) + 2; + if (position !== openPos && position !== closePos) return void 0; + return { + ranges: [ + { + start: openPos, + length: 0 + }, + { + start: closePos, + length: 0 + } + ], + wordPattern: jsxTagWordPattern + }; + } else { + const tag = findAncestor(token.parent, (n)=>{ + if (isJsxOpeningElement(n) || isJsxClosingElement(n)) return true; + return false; + }); + if (!tag) return void 0; + Debug.assert(isJsxOpeningElement(tag) || isJsxClosingElement(tag), "tag should be opening or closing element"); + const openTag = tag.parent.openingElement; + const closeTag = tag.parent.closingElement; + const openTagStart = openTag.tagName.getStart(sourceFile); + const openTagEnd = openTag.tagName.end; + const closeTagStart = closeTag.tagName.getStart(sourceFile); + const closeTagEnd = closeTag.tagName.end; + if (!(openTagStart <= position && position <= openTagEnd || closeTagStart <= position && position <= closeTagEnd)) return void 0; + const openingTagText = openTag.tagName.getText(sourceFile); + if (openingTagText !== closeTag.tagName.getText(sourceFile)) return void 0; + return { + ranges: [ + { + start: openTagStart, + length: openTagEnd - openTagStart + }, + { + start: closeTagStart, + length: closeTagEnd - closeTagStart + } + ], + wordPattern: jsxTagWordPattern + }; } - }); - return statements && [ - statements, - false - ]; - } - function convertNamedExport(sourceFile, assignment, changes, exports) { - const { text: text } = assignment.left.name; - const rename = exports.get(text); - if (rename !== void 0) { - const newNodes = [ - makeConst(/*modifiers*/ void 0, rename, assignment.right), - makeExportDeclaration([ - factory.createExportSpecifier(/*isTypeOnly*/ false, rename, text) - ]) - ]; - changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes); - } else convertExportsPropertyAssignment(assignment, sourceFile, changes); - } - function convertReExportAll(reExported, checker) { - const moduleSpecifier = reExported.text; - const moduleSymbol = checker.getSymbolAtLocation(reExported); - const exports = moduleSymbol ? moduleSymbol.exports : emptyMap; - return exports.has("export=" /* ExportEquals */ ) ? [ - [ - reExportDefault(moduleSpecifier) - ], - true - ] : !exports.has("default" /* Default */ ) ? [ - [ - reExportStar(moduleSpecifier) - ], - false - ] : // If there's some non-default export, must include both `export *` and `export default`. - exports.size > 1 ? [ - [ - reExportStar(moduleSpecifier), - reExportDefault(moduleSpecifier) - ], - true - ] : [ - [ - reExportDefault(moduleSpecifier) - ], - true - ]; - } - function reExportStar(moduleSpecifier) { - return makeExportDeclaration(/*exportClause*/ void 0, moduleSpecifier); - } - function reExportDefault(moduleSpecifier) { - return makeExportDeclaration([ - factory.createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ void 0, "default") - ], moduleSpecifier); - } - function convertExportsPropertyAssignment({ left: left , right: right , parent: parent2 }, sourceFile, changes) { - const name = left.name.text; - if ((isFunctionExpression(right) || isArrowFunction(right) || isClassExpression(right)) && (!right.name || right.name.text === name)) { - changes.replaceRange(sourceFile, { - pos: left.getStart(sourceFile), - end: right.getStart(sourceFile) - }, factory.createToken(93 /* ExportKeyword */ ), { - suffix: " " - }); - if (!right.name) changes.insertName(sourceFile, right, name); - const semi = findChildOfKind(parent2, 26 /* SemicolonToken */ , sourceFile); - if (semi) changes.delete(sourceFile, semi); - } else changes.replaceNodeRangeWithNodes(sourceFile, left.expression, findChildOfKind(left, 24 /* DotToken */ , sourceFile), [ - factory.createToken(93 /* ExportKeyword */ ), - factory.createToken(85 /* ConstKeyword */ ) - ], { - joiner: " ", - suffix: " " - }); - } - function convertExportsDotXEquals_replaceNode(name, exported, useSitesToUnqualify) { - const modifiers = [ - factory.createToken(93 /* ExportKeyword */ ) - ]; - switch(exported.kind){ - case 215 /* FunctionExpression */ : - { - const { name: expressionName } = exported; - if (expressionName && expressionName.text !== name) return exportConst(); - } - case 216 /* ArrowFunction */ : - return functionExpressionToDeclaration(name, modifiers, exported, useSitesToUnqualify); - case 228 /* ClassExpression */ : - return classExpressionToDeclaration(name, modifiers, exported, useSitesToUnqualify); - default: - return exportConst(); - } - function exportConst() { - return makeConst(modifiers, factory.createIdentifier(name), replaceImportUseSites(exported, useSitesToUnqualify)); } - } - function replaceImportUseSites(nodeOrNodes, useSitesToUnqualify) { - if (!useSitesToUnqualify || !some(arrayFrom(useSitesToUnqualify.keys()), (original)=>rangeContainsRange(nodeOrNodes, original))) return nodeOrNodes; - return isArray(nodeOrNodes) ? getSynthesizedDeepClonesWithReplacements(nodeOrNodes, /*includeTrivia*/ true, replaceNode) : getSynthesizedDeepCloneWithReplacements(nodeOrNodes, /*includeTrivia*/ true, replaceNode); - function replaceNode(original) { - if (original.kind === 208 /* PropertyAccessExpression */ ) { - const replacement = useSitesToUnqualify.get(original); - useSitesToUnqualify.delete(original); - return replacement; - } + function getLinesForRange(sourceFile, textRange) { + return { + lineStarts: sourceFile.getLineStarts(), + firstLine: sourceFile.getLineAndCharacterOfPosition(textRange.pos).line, + lastLine: sourceFile.getLineAndCharacterOfPosition(textRange.end).line + }; } - } - function convertSingleImport(name, moduleSpecifier, checker, identifiers, target, quotePreference) { - switch(name.kind){ - case 203 /* ObjectBindingPattern */ : - { - const importSpecifiers = mapAllOrFail(name.elements, (e)=>e.dotDotDotToken || e.initializer || e.propertyName && !isIdentifier(e.propertyName) || !isIdentifier(e.name) ? void 0 : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text)); - if (importSpecifiers) return convertedImports([ - makeImport(/*name*/ void 0, importSpecifiers, moduleSpecifier, quotePreference) - ]); + function toggleLineComment(fileName, textRange, insertComment) { + const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + const textChanges2 = []; + const { lineStarts: lineStarts, firstLine: firstLine, lastLine: lastLine } = getLinesForRange(sourceFile, textRange); + let isCommenting = insertComment || false; + let leftMostPosition = Number.MAX_VALUE; + const lineTextStarts = /* @__PURE__ */ new Map(); + const firstNonWhitespaceCharacterRegex = new RegExp(/\S/); + const isJsx = isInsideJsxElement(sourceFile, lineStarts[firstLine]); + const openComment = isJsx ? "{/*" : "//"; + for(let i = firstLine; i <= lastLine; i++){ + const lineText = sourceFile.text.substring(lineStarts[i], sourceFile.getLineEndOfPosition(lineStarts[i])); + const regExec = firstNonWhitespaceCharacterRegex.exec(lineText); + if (regExec) { + leftMostPosition = Math.min(leftMostPosition, regExec.index); + lineTextStarts.set(i.toString(), regExec.index); + if (lineText.substr(regExec.index, openComment.length) !== openComment) isCommenting = insertComment === void 0 || insertComment; } - case 204 /* ArrayBindingPattern */ : - { - const tmp = makeUniqueName(moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); - return convertedImports([ - makeImport(factory.createIdentifier(tmp), /*namedImports*/ void 0, moduleSpecifier, quotePreference), - makeConst(/*modifiers*/ void 0, getSynthesizedDeepClone(name), factory.createIdentifier(tmp)) - ]); + } + for(let i = firstLine; i <= lastLine; i++){ + if (firstLine !== lastLine && lineStarts[i] === textRange.end) continue; + const lineTextStart = lineTextStarts.get(i.toString()); + if (lineTextStart !== void 0) { + if (isJsx) textChanges2.push.apply(textChanges2, toggleMultilineComment(fileName, { + pos: lineStarts[i] + leftMostPosition, + end: sourceFile.getLineEndOfPosition(lineStarts[i]) + }, isCommenting, isJsx)); + else if (isCommenting) textChanges2.push({ + newText: openComment, + span: { + length: 0, + start: lineStarts[i] + leftMostPosition + } + }); + else if (sourceFile.text.substr(lineStarts[i] + lineTextStart, openComment.length) === openComment) textChanges2.push({ + newText: "", + span: { + length: openComment.length, + start: lineStarts[i] + lineTextStart + } + }); } - case 79 /* Identifier */ : - return convertSingleIdentifierImport(name, moduleSpecifier, checker, identifiers, quotePreference); - default: - return Debug.assertNever(name, `Convert to ES module got invalid name kind ${name.kind}`); + } + return textChanges2; } - } - function convertSingleIdentifierImport(name, moduleSpecifier, checker, identifiers, quotePreference) { - const nameSymbol = checker.getSymbolAtLocation(name); - const namedBindingsNames = /* @__PURE__ */ new Map(); - let needDefaultImport = false; - let useSitesToUnqualify; - for (const use of identifiers.original.get(name.text)){ - if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) continue; - const { parent: parent2 } = use; - if (isPropertyAccessExpression(parent2)) { - const { name: { text: propertyName } } = parent2; - if (propertyName === "default") { - needDefaultImport = true; - const importDefaultName = use.getText(); - (useSitesToUnqualify != null ? useSitesToUnqualify : useSitesToUnqualify = /* @__PURE__ */ new Map()).set(parent2, factory.createIdentifier(importDefaultName)); + function toggleMultilineComment(fileName, textRange, insertComment, isInsideJsx) { + var _a2; + const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + const textChanges2 = []; + const { text: text } = sourceFile; + let hasComment = false; + let isCommenting = insertComment || false; + const positions = []; + let { pos: pos } = textRange; + const isJsx = isInsideJsx !== void 0 ? isInsideJsx : isInsideJsxElement(sourceFile, pos); + const openMultiline = isJsx ? "{/*" : "/*"; + const closeMultiline = isJsx ? "*/}" : "*/"; + const openMultilineRegex = isJsx ? "\\{\\/\\*" : "\\/\\*"; + const closeMultilineRegex = isJsx ? "\\*\\/\\}" : "\\*\\/"; + while(pos <= textRange.end){ + const offset = text.substr(pos, openMultiline.length) === openMultiline ? openMultiline.length : 0; + const commentRange = isInComment(sourceFile, pos + offset); + if (commentRange) { + if (isJsx) { + commentRange.pos--; + commentRange.end++; + } + positions.push(commentRange.pos); + if (commentRange.kind === 3 /* MultiLineCommentTrivia */ ) positions.push(commentRange.end); + hasComment = true; + pos = commentRange.end + 1; } else { - Debug.assert(parent2.expression === use, "Didn't expect expression === use"); - let idName = namedBindingsNames.get(propertyName); - if (idName === void 0) { - idName = makeUniqueName(propertyName, identifiers); - namedBindingsNames.set(propertyName, idName); + const newPos = text.substring(pos, textRange.end).search(`(${openMultilineRegex})|(${closeMultilineRegex})`); + isCommenting = insertComment !== void 0 ? insertComment : isCommenting || !isTextWhiteSpaceLike(text, pos, newPos === -1 ? textRange.end : pos + newPos); + pos = newPos === -1 ? textRange.end + 1 : pos + newPos + closeMultiline.length; + } + } + if (isCommenting || !hasComment) { + if (((_a2 = isInComment(sourceFile, textRange.pos)) == null ? void 0 : _a2.kind) !== 2 /* SingleLineCommentTrivia */ ) insertSorted(positions, textRange.pos, compareValues); + insertSorted(positions, textRange.end, compareValues); + const firstPos = positions[0]; + if (text.substr(firstPos, openMultiline.length) !== openMultiline) textChanges2.push({ + newText: openMultiline, + span: { + length: 0, + start: firstPos } - (useSitesToUnqualify != null ? useSitesToUnqualify : useSitesToUnqualify = /* @__PURE__ */ new Map()).set(parent2, factory.createIdentifier(idName)); + }); + for(let i = 1; i < positions.length - 1; i++){ + if (text.substr(positions[i] - closeMultiline.length, closeMultiline.length) !== closeMultiline) textChanges2.push({ + newText: closeMultiline, + span: { + length: 0, + start: positions[i] + } + }); + if (text.substr(positions[i], openMultiline.length) !== openMultiline) textChanges2.push({ + newText: openMultiline, + span: { + length: 0, + start: positions[i] + } + }); } - } else needDefaultImport = true; + if (textChanges2.length % 2 !== 0) textChanges2.push({ + newText: closeMultiline, + span: { + length: 0, + start: positions[positions.length - 1] + } + }); + } else for (const pos2 of positions){ + const from = pos2 - closeMultiline.length > 0 ? pos2 - closeMultiline.length : 0; + const offset = text.substr(from, closeMultiline.length) === closeMultiline ? closeMultiline.length : 0; + textChanges2.push({ + newText: "", + span: { + length: openMultiline.length, + start: pos2 - offset + } + }); + } + return textChanges2; } - const namedBindings = namedBindingsNames.size === 0 ? void 0 : arrayFrom(mapIterator(namedBindingsNames.entries(), ([propertyName, idName])=>factory.createImportSpecifier(/*isTypeOnly*/ false, propertyName === idName ? void 0 : factory.createIdentifier(propertyName), factory.createIdentifier(idName)))); - if (!namedBindings) needDefaultImport = true; - return convertedImports([ - makeImport(needDefaultImport ? getSynthesizedDeepClone(name) : void 0, namedBindings, moduleSpecifier, quotePreference) - ], useSitesToUnqualify); - } - function makeUniqueName(name, identifiers) { - while(identifiers.original.has(name) || identifiers.additional.has(name))name = `_${name}`; - identifiers.additional.add(name); - return name; - } - function collectFreeIdentifiers(file) { - const map2 = createMultiMap(); - forEachFreeIdentifier(file, (id)=>map2.add(id.text, id)); - return map2; - } - function forEachFreeIdentifier(node, cb) { - if (isIdentifier(node) && isFreeIdentifier(node)) cb(node); - node.forEachChild((child)=>forEachFreeIdentifier(child, cb)); - } - function isFreeIdentifier(node) { - const { parent: parent2 } = node; - switch(parent2.kind){ - case 208 /* PropertyAccessExpression */ : - return parent2.name !== node; - case 205 /* BindingElement */ : - return parent2.propertyName !== node; - case 273 /* ImportSpecifier */ : - return parent2.propertyName !== node; - default: - return true; + function commentSelection(fileName, textRange) { + const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + const { firstLine: firstLine, lastLine: lastLine } = getLinesForRange(sourceFile, textRange); + return firstLine === lastLine && textRange.pos !== textRange.end ? toggleMultilineComment(fileName, textRange, /*insertComment*/ true) : toggleLineComment(fileName, textRange, /*insertComment*/ true); } - } - function functionExpressionToDeclaration(name, additionalModifiers, fn, useSitesToUnqualify) { - return factory.createFunctionDeclaration(concatenate(additionalModifiers, getSynthesizedDeepClones(fn.modifiers)), getSynthesizedDeepClone(fn.asteriskToken), name, getSynthesizedDeepClones(fn.typeParameters), getSynthesizedDeepClones(fn.parameters), getSynthesizedDeepClone(fn.type), factory.converters.convertToFunctionBlock(replaceImportUseSites(fn.body, useSitesToUnqualify))); - } - function classExpressionToDeclaration(name, additionalModifiers, cls, useSitesToUnqualify) { - return factory.createClassDeclaration(concatenate(additionalModifiers, getSynthesizedDeepClones(cls.modifiers)), name, getSynthesizedDeepClones(cls.typeParameters), getSynthesizedDeepClones(cls.heritageClauses), replaceImportUseSites(cls.members, useSitesToUnqualify)); - } - function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) { - return propertyName === "default" ? makeImport(factory.createIdentifier(localName), /*namedImports*/ void 0, moduleSpecifier, quotePreference) : makeImport(/*name*/ void 0, [ - makeImportSpecifier(propertyName, localName) - ], moduleSpecifier, quotePreference); - } - function makeImportSpecifier(propertyName, name) { - return factory.createImportSpecifier(/*isTypeOnly*/ false, propertyName !== void 0 && propertyName !== name ? factory.createIdentifier(propertyName) : void 0, factory.createIdentifier(name)); - } - function makeConst(modifiers, name, init) { - return factory.createVariableStatement(modifiers, factory.createVariableDeclarationList([ - factory.createVariableDeclaration(name, /*exclamationToken*/ void 0, /*type*/ void 0, init) - ], 2 /* Const */ )); - } - function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { - return factory.createExportDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, exportSpecifiers && factory.createNamedExports(exportSpecifiers), moduleSpecifier === void 0 ? void 0 : factory.createStringLiteral(moduleSpecifier)); - } - function convertedImports(newImports, useSitesToUnqualify) { - return { - newImports: newImports, - useSitesToUnqualify: useSitesToUnqualify - }; - } - var init_convertToEsModule = __esm({ - "src/services/codefixes/convertToEsModule.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - registerCodeFix({ - errorCodes: [ - Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module.code - ], - getCodeActions (context) { - const { sourceFile: sourceFile , program: program , preferences: preferences } = context; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2)=>{ - const moduleExportsChangedToDefault = convertFileToEsModule(sourceFile, program.getTypeChecker(), changes2, getEmitScriptTarget(program.getCompilerOptions()), getQuotePreference(sourceFile, preferences)); - if (moduleExportsChangedToDefault) for (const importingFile of program.getSourceFiles())fixImportOfModuleExports(importingFile, sourceFile, changes2, getQuotePreference(importingFile, preferences)); - }); - return [ - createCodeFixActionWithoutFixAll("convertToEsModule", changes, Diagnostics.Convert_to_ES_module) - ]; + function uncommentSelection(fileName, textRange) { + const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + const textChanges2 = []; + const { pos: pos } = textRange; + let { end: end } = textRange; + if (pos === end) end += isInsideJsxElement(sourceFile, pos) ? 2 : 1; + for(let i = pos; i <= end; i++){ + const commentRange = isInComment(sourceFile, i); + if (commentRange) { + switch(commentRange.kind){ + case 2 /* SingleLineCommentTrivia */ : + textChanges2.push.apply(textChanges2, toggleLineComment(fileName, { + end: commentRange.end, + pos: commentRange.pos + 1 + }, /*insertComment*/ false)); + break; + case 3 /* MultiLineCommentTrivia */ : + textChanges2.push.apply(textChanges2, toggleMultilineComment(fileName, { + end: commentRange.end, + pos: commentRange.pos + 1 + }, /*insertComment*/ false)); + } + i = commentRange.end + 1; } - }); + } + return textChanges2; } - }); - // src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts - function getQualifiedName(sourceFile, pos) { - const qualifiedName = findAncestor(getTokenAtPosition(sourceFile, pos), isQualifiedName); - Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); - return isIdentifier(qualifiedName.left) ? qualifiedName : void 0; - } - function doChange3(changeTracker, sourceFile, qualifiedName) { - const rightText = qualifiedName.right.text; - const replacement = factory.createIndexedAccessTypeNode(factory.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ void 0), factory.createLiteralTypeNode(factory.createStringLiteral(rightText))); - changeTracker.replaceNode(sourceFile, qualifiedName, replacement); - } - var fixId11, errorCodes12; - var init_correctQualifiedNameToIndexedAccessType = __esm({ - "src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId11 = "correctQualifiedNameToIndexedAccessType"; - errorCodes12 = [ - Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code - ]; - registerCodeFix({ - errorCodes: errorCodes12, - getCodeActions (context) { - const qualifiedName = getQualifiedName(context.sourceFile, context.span.start); - if (!qualifiedName) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange3(t, context.sourceFile, qualifiedName)); - const newText = `${qualifiedName.left.text}["${qualifiedName.right.text}"]`; - return [ - createCodeFixAction(fixId11, changes, [ - Diagnostics.Rewrite_as_the_indexed_access_type_0, - newText - ], fixId11, Diagnostics.Rewrite_all_as_indexed_access_types) - ]; - }, - fixIds: [ - fixId11 - ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes12, (changes, diag2)=>{ - const q = getQualifiedName(diag2.file, diag2.start); - if (q) doChange3(changes, diag2.file, q); - }) - }); + function isUnclosedTag({ openingElement: openingElement, closingElement: closingElement, parent: parent2 }) { + return !tagNamesAreEquivalent(openingElement.tagName, closingElement.tagName) || isJsxElement(parent2) && tagNamesAreEquivalent(openingElement.tagName, parent2.openingElement.tagName) && isUnclosedTag(parent2); } - }); - // src/services/codefixes/convertToTypeOnlyExport.ts - function getExportSpecifierForDiagnosticSpan(span, sourceFile) { - return tryCast(getTokenAtPosition(sourceFile, span.start).parent, isExportSpecifier); - } - function fixSingleExportDeclaration(changes, exportSpecifier, context) { - if (!exportSpecifier) return; - const exportClause = exportSpecifier.parent; - const exportDeclaration = exportClause.parent; - const typeExportSpecifiers = getTypeExportSpecifiers(exportSpecifier, context); - if (typeExportSpecifiers.length === exportClause.elements.length) changes.insertModifierBefore(context.sourceFile, 154 /* TypeKeyword */ , exportClause); - else { - const valueExportDeclaration = factory.updateExportDeclaration(exportDeclaration, exportDeclaration.modifiers, /*isTypeOnly*/ false, factory.updateNamedExports(exportClause, filter(exportClause.elements, (e)=>!contains(typeExportSpecifiers, e))), exportDeclaration.moduleSpecifier, /*assertClause*/ void 0); - const typeExportDeclaration = factory.createExportDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ true, factory.createNamedExports(typeExportSpecifiers), exportDeclaration.moduleSpecifier, /*assertClause*/ void 0); - changes.replaceNode(context.sourceFile, exportDeclaration, valueExportDeclaration, { - leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, - trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Exclude - }); - changes.insertNodeAfter(context.sourceFile, exportDeclaration, typeExportDeclaration); + function isUnclosedFragment({ closingFragment: closingFragment, parent: parent2 }) { + return !!(closingFragment.flags & 262144 /* ThisNodeHasError */ ) || isJsxFragment(parent2) && isUnclosedFragment(parent2); } - } - function getTypeExportSpecifiers(originExportSpecifier, context) { - const exportClause = originExportSpecifier.parent; - if (exportClause.elements.length === 1) return exportClause.elements; - const diagnostics = getDiagnosticsWithinSpan(createTextSpanFromNode(exportClause), context.program.getSemanticDiagnostics(context.sourceFile, context.cancellationToken)); - return filter(exportClause.elements, (element)=>{ - var _a2; - return element === originExportSpecifier || ((_a2 = findDiagnosticForNode(element, diagnostics)) == null ? void 0 : _a2.code) === errorCodes13[0]; - }); - } - var errorCodes13, fixId12; - var init_convertToTypeOnlyExport = __esm({ - "src/services/codefixes/convertToTypeOnlyExport.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - errorCodes13 = [ - Diagnostics.Re_exporting_a_type_when_0_is_enabled_requires_using_export_type.code - ]; - fixId12 = "convertToTypeOnlyExport"; - registerCodeFix({ - errorCodes: errorCodes13, - getCodeActions: function getCodeActionsToConvertToTypeOnlyExport(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>fixSingleExportDeclaration(t, getExportSpecifierForDiagnosticSpan(context.span, context.sourceFile), context)); - if (changes.length) return [ - createCodeFixAction(fixId12, changes, Diagnostics.Convert_to_type_only_export, fixId12, Diagnostics.Convert_all_re_exported_types_to_type_only_exports) - ]; - }, - fixIds: [ - fixId12 - ], - getAllCodeActions: function getAllCodeActionsToConvertToTypeOnlyExport(context) { - const fixedExportDeclarations = /* @__PURE__ */ new Map(); - return codeFixAll(context, errorCodes13, (changes, diag2)=>{ - const exportSpecifier = getExportSpecifierForDiagnosticSpan(diag2, context.sourceFile); - if (exportSpecifier && addToSeen(fixedExportDeclarations, getNodeId(exportSpecifier.parent.parent))) fixSingleExportDeclaration(changes, exportSpecifier, context); + function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) { + const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + const range = ts_formatting_exports.getRangeOfEnclosingComment(sourceFile, position); + return range && (!onlyMultiLine || range.kind === 3 /* MultiLineCommentTrivia */ ) ? createTextSpanFromRange(range) : void 0; + } + function getTodoComments(fileName, descriptors) { + synchronizeHostData(); + const sourceFile = getValidSourceFile(fileName); + cancellationToken.throwIfCancellationRequested(); + const fileContents = sourceFile.text; + const result = []; + if (descriptors.length > 0 && !isNodeModulesFile(sourceFile.fileName)) { + const regExp = getTodoCommentsRegExp(); + let matchArray; + while(matchArray = regExp.exec(fileContents)){ + cancellationToken.throwIfCancellationRequested(); + const firstDescriptorCaptureIndex = 3; + Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex); + const preamble = matchArray[1]; + const matchPosition = matchArray.index + preamble.length; + if (!isInComment(sourceFile, matchPosition)) continue; + let descriptor; + for(let i = 0; i < descriptors.length; i++)if (matchArray[i + firstDescriptorCaptureIndex]) descriptor = descriptors[i]; + if (descriptor === void 0) return Debug.fail(); + if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) continue; + const message = matchArray[2]; + result.push({ + descriptor: descriptor, + message: message, + position: matchPosition }); } - }); - } - }); - // src/services/codefixes/convertToTypeOnlyImport.ts - function getDeclaration2(sourceFile, pos) { - const { parent: parent2 } = getTokenAtPosition(sourceFile, pos); - return isImportSpecifier(parent2) || isImportDeclaration(parent2) && parent2.importClause ? parent2 : void 0; - } - function doChange4(changes, sourceFile, declaration) { - if (isImportSpecifier(declaration)) changes.replaceNode(sourceFile, declaration, factory.updateImportSpecifier(declaration, /*isTypeOnly*/ true, declaration.propertyName, declaration.name)); - else { - const importClause = declaration.importClause; - if (importClause.name && importClause.namedBindings) changes.replaceNodeWithNodes(sourceFile, declaration, [ - factory.createImportDeclaration(getSynthesizedDeepClones(declaration.modifiers, /*includeTrivia*/ true), factory.createImportClause(/*isTypeOnly*/ true, getSynthesizedDeepClone(importClause.name, /*includeTrivia*/ true), /*namedBindings*/ void 0), getSynthesizedDeepClone(declaration.moduleSpecifier, /*includeTrivia*/ true), getSynthesizedDeepClone(declaration.assertClause, /*includeTrivia*/ true)), - factory.createImportDeclaration(getSynthesizedDeepClones(declaration.modifiers, /*includeTrivia*/ true), factory.createImportClause(/*isTypeOnly*/ true, /*name*/ void 0, getSynthesizedDeepClone(importClause.namedBindings, /*includeTrivia*/ true)), getSynthesizedDeepClone(declaration.moduleSpecifier, /*includeTrivia*/ true), getSynthesizedDeepClone(declaration.assertClause, /*includeTrivia*/ true)) - ]); - else { - const importDeclaration = factory.updateImportDeclaration(declaration, declaration.modifiers, factory.updateImportClause(importClause, /*isTypeOnly*/ true, importClause.name, importClause.namedBindings), declaration.moduleSpecifier, declaration.assertClause); - changes.replaceNode(sourceFile, declaration, importDeclaration); + } + return result; + function escapeRegExp(str) { + return str.replace(/[-[\]/{}()*+?.\\^$|]/g, "\\$&"); + } + function getTodoCommentsRegExp() { + const singleLineCommentStart = /(?:\/\/+\s*)/.source; + const multiLineCommentStart = /(?:\/\*+\s*)/.source; + const anyNumberOfSpacesAndAsterisksAtStartOfLine = /(?:^(?:\s|\*)*)/.source; + const preamble = "(" + anyNumberOfSpacesAndAsterisksAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")"; + const literals = "(?:" + map(descriptors, (d)=>"(" + escapeRegExp(d.text) + ")").join("|") + ")"; + const endOfLineOrEndOfComment = /(?:$|\*\/)/.source; + const messageRemainder = /(?:.*?)/.source; + const messagePortion = "(" + literals + messageRemainder + ")"; + const regExpString = preamble + messagePortion + endOfLineOrEndOfComment; + return new RegExp(regExpString, "gim"); + } + function isLetterOrDigit(char) { + return char >= 97 /* a */ && char <= 122 /* z */ || char >= 65 /* A */ && char <= 90 /* Z */ || char >= 48 /* _0 */ && char <= 57 /* _9 */ ; + } + function isNodeModulesFile(path) { + return stringContains(path, "/node_modules/"); } } - } - var errorCodes14, fixId13; - var init_convertToTypeOnlyImport = __esm({ - "src/services/codefixes/convertToTypeOnlyImport.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - errorCodes14 = [ - Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set_to_error.code, - Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled.code - ]; - fixId13 = "convertToTypeOnlyImport"; - registerCodeFix({ - errorCodes: errorCodes14, - getCodeActions: function getCodeActionsToConvertToTypeOnlyImport(context) { - const declaration = getDeclaration2(context.sourceFile, context.span.start); - if (declaration) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange4(t, context.sourceFile, declaration)); - return [ - createCodeFixAction(fixId13, changes, Diagnostics.Convert_to_type_only_import, fixId13, Diagnostics.Convert_all_imports_not_used_as_a_value_to_type_only_imports) - ]; - } - return void 0; - }, - fixIds: [ - fixId13 - ], - getAllCodeActions: function getAllCodeActionsToConvertToTypeOnlyImport(context) { - return codeFixAll(context, errorCodes14, (changes, diag2)=>{ - const declaration = getDeclaration2(diag2.file, diag2.start); - if (declaration) doChange4(changes, diag2.file, declaration); - }); - } - }); + function getRenameInfo2(fileName, position, preferences) { + synchronizeHostData(); + return ts_Rename_exports.getRenameInfo(program, getValidSourceFile(fileName), position, preferences || {}); } - }); - // src/services/codefixes/convertLiteralTypeToMappedType.ts - function getInfo2(sourceFile, pos) { - const token = getTokenAtPosition(sourceFile, pos); - if (isIdentifier(token)) { - const propertySignature = cast(token.parent.parent, isPropertySignature); - const propertyName = token.getText(sourceFile); + function getRefactorContext(file, positionOrRange, preferences, formatOptions, triggerReason, kind) { + const [startPosition, endPosition] = typeof positionOrRange === "number" ? [ + positionOrRange, + void 0 + ] : [ + positionOrRange.pos, + positionOrRange.end + ]; return { - container: cast(propertySignature.parent, isTypeLiteralNode), - typeNode: propertySignature.type, - constraint: propertyName, - name: propertyName === "K" ? "P" : "K" + file: file, + startPosition: startPosition, + endPosition: endPosition, + program: getProgram(), + host: host, + formatContext: ts_formatting_exports.getFormatContext(formatOptions, host), + cancellationToken: // TODO: GH#18217 + cancellationToken, + preferences: preferences, + triggerReason: triggerReason, + kind: kind }; } - return void 0; - } - function doChange5(changes, sourceFile, { container: container , typeNode: typeNode , constraint: constraint , name: name }) { - changes.replaceNode(sourceFile, container, factory.createMappedTypeNode(/*readonlyToken*/ void 0, factory.createTypeParameterDeclaration(/*modifiers*/ void 0, name, factory.createTypeReferenceNode(constraint)), /*nameType*/ void 0, /*questionToken*/ void 0, typeNode, /*members*/ void 0)); - } - var fixId14, errorCodes15; - var init_convertLiteralTypeToMappedType = __esm({ - "src/services/codefixes/convertLiteralTypeToMappedType.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId14 = "convertLiteralTypeToMappedType"; - errorCodes15 = [ - Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0.code - ]; - registerCodeFix({ - errorCodes: errorCodes15, - getCodeActions: function getCodeActionsToConvertLiteralTypeToMappedType(context) { - const { sourceFile: sourceFile , span: span } = context; - const info = getInfo2(sourceFile, span.start); - if (!info) return void 0; - const { name: name , constraint: constraint } = info; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange5(t, sourceFile, info)); - return [ - createCodeFixAction(fixId14, changes, [ - Diagnostics.Convert_0_to_1_in_0, - constraint, - name - ], fixId14, Diagnostics.Convert_all_type_literals_to_mapped_type) - ]; - }, - fixIds: [ - fixId14 - ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes15, (changes, diag2)=>{ - const info = getInfo2(diag2.file, diag2.start); - if (info) doChange5(changes, diag2.file, info); - }) - }); + function getInlayHintsContext(file, span, preferences) { + return { + file: file, + program: getProgram(), + host: host, + span: span, + preferences: preferences, + cancellationToken: cancellationToken + }; } - }); - // src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts - function getClass(sourceFile, pos) { - return Debug.checkDefined(getContainingClass(getTokenAtPosition(sourceFile, pos)), "There should be a containing class"); - } - function symbolPointsToNonPrivateMember(symbol) { - return !symbol.valueDeclaration || !(getEffectiveModifierFlags(symbol.valueDeclaration) & 8 /* Private */ ); - } - function addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) { - const checker = context.program.getTypeChecker(); - const maybeHeritageClauseSymbol = getHeritageClauseSymbolTable(classDeclaration, checker); - const implementedType = checker.getTypeAtLocation(implementedTypeNode); - const implementedTypeSymbols = checker.getPropertiesOfType(implementedType); - const nonPrivateAndNotExistedInHeritageClauseMembers = implementedTypeSymbols.filter(and(symbolPointsToNonPrivateMember, (symbol)=>!maybeHeritageClauseSymbol.has(symbol.escapedName))); - const classType = checker.getTypeAtLocation(classDeclaration); - const constructor = find(classDeclaration.members, (m)=>isConstructorDeclaration(m)); - if (!classType.getNumberIndexType()) createMissingIndexSignatureDeclaration(implementedType, 1 /* Number */ ); - if (!classType.getStringIndexType()) createMissingIndexSignatureDeclaration(implementedType, 0 /* String */ ); - const importAdder = createImportAdder(sourceFile, context.program, preferences, context.host); - createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, sourceFile, context, preferences, importAdder, (member)=>insertInterfaceMemberNode(sourceFile, classDeclaration, member)); - importAdder.writeFixes(changeTracker); - function createMissingIndexSignatureDeclaration(type, kind) { - const indexInfoOfKind = checker.getIndexInfoOfType(type, kind); - if (indexInfoOfKind) insertInterfaceMemberNode(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, classDeclaration, /*flags*/ void 0, getNoopSymbolTrackerWithResolver(context))); + function getSmartSelectionRange2(fileName, position) { + return ts_SmartSelectionRange_exports.getSmartSelectionRange(position, syntaxTreeCache.getCurrentSourceFile(fileName)); } - function insertInterfaceMemberNode(sourceFile2, cls, newElement) { - if (constructor) changeTracker.insertNodeAfter(sourceFile2, constructor, newElement); - else changeTracker.insertMemberAtStart(sourceFile2, cls, newElement); + function getApplicableRefactors2(fileName, positionOrRange, preferences = emptyOptions, triggerReason, kind, includeInteractiveActions) { + synchronizeHostData(); + const file = getValidSourceFile(fileName); + return ts_refactor_exports.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences, emptyOptions, triggerReason, kind), includeInteractiveActions); } - } - function getHeritageClauseSymbolTable(classDeclaration, checker) { - const heritageClauseNode = getEffectiveBaseTypeNode(classDeclaration); - if (!heritageClauseNode) return createSymbolTable(); - const heritageClauseType = checker.getTypeAtLocation(heritageClauseNode); - const heritageClauseTypeSymbols = checker.getPropertiesOfType(heritageClauseType); - return createSymbolTable(heritageClauseTypeSymbols.filter(symbolPointsToNonPrivateMember)); - } - var errorCodes16, fixId15; - var init_fixClassIncorrectlyImplementsInterface = __esm({ - "src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - errorCodes16 = [ - Diagnostics.Class_0_incorrectly_implements_interface_1.code, - Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code - ]; - fixId15 = "fixClassIncorrectlyImplementsInterface"; - registerCodeFix({ - errorCodes: errorCodes16, - getCodeActions (context) { - const { sourceFile: sourceFile , span: span } = context; - const classDeclaration = getClass(sourceFile, span.start); - return mapDefined(getEffectiveImplementsTypeNodes(classDeclaration), (implementedTypeNode)=>{ - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences)); - return changes.length === 0 ? void 0 : createCodeFixAction(fixId15, changes, [ - Diagnostics.Implement_interface_0, - implementedTypeNode.getText(sourceFile) - ], fixId15, Diagnostics.Implement_all_unimplemented_interfaces); - }); - }, - fixIds: [ - fixId15 - ], - getAllCodeActions (context) { - const seenClassDeclarations = /* @__PURE__ */ new Map(); - return codeFixAll(context, errorCodes16, (changes, diag2)=>{ - const classDeclaration = getClass(diag2.file, diag2.start); - if (addToSeen(seenClassDeclarations, getNodeId(classDeclaration))) for (const implementedTypeNode of getEffectiveImplementsTypeNodes(classDeclaration))addMissingDeclarations(context, implementedTypeNode, diag2.file, classDeclaration, changes, context.preferences); - }); - } - }); + function getMoveToRefactoringFileSuggestions(fileName, positionOrRange, preferences = emptyOptions) { + synchronizeHostData(); + const sourceFile = getValidSourceFile(fileName); + const allFiles = Debug.checkDefined(program.getSourceFiles()); + const extension = extensionFromPath(fileName); + const files = mapDefined(allFiles, (file)=>!(program == null ? void 0 : program.isSourceFileFromExternalLibrary(sourceFile)) && !(sourceFile === getValidSourceFile(file.fileName) || extension === ".ts" /* Ts */ && extensionFromPath(file.fileName) === ".d.ts" /* Dts */ || extension === ".d.ts" /* Dts */ && startsWith(getBaseFileName(file.fileName), "lib.") && extensionFromPath(file.fileName) === ".d.ts" /* Dts */ ) && extension === extensionFromPath(file.fileName) ? file.fileName : void 0); + const newFileName = createNewFileName(sourceFile, program, getRefactorContext(sourceFile, positionOrRange, preferences, emptyOptions), host); + return { + newFileName: newFileName, + files: files + }; } - }); - // src/services/codefixes/importFixes.ts - function createImportAdder(sourceFile, program, preferences, host, cancellationToken) { - return createImportAdderWorker(sourceFile, program, /*useAutoImportProvider*/ false, preferences, host, cancellationToken); - } - function createImportAdderWorker(sourceFile, program, useAutoImportProvider, preferences, host, cancellationToken) { - const compilerOptions = program.getCompilerOptions(); - const addToNamespace = []; - const importType = []; - const addToExisting = /* @__PURE__ */ new Map(); - const newImports = /* @__PURE__ */ new Map(); - return { - addImportFromDiagnostic: addImportFromDiagnostic, - addImportFromExportedSymbol: addImportFromExportedSymbol, - writeFixes: writeFixes, - hasFixes: hasFixes - }; - function addImportFromDiagnostic(diagnostic, context) { - const info = getFixInfos(context, diagnostic.code, diagnostic.start, useAutoImportProvider); - if (!info || !info.length) return; - addImport(first(info)); + function getEditsForRefactor2(fileName, formatOptions, positionOrRange, refactorName14, actionName2, preferences = emptyOptions, interactiveRefactorArguments) { + synchronizeHostData(); + const file = getValidSourceFile(fileName); + return ts_refactor_exports.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName14, actionName2, interactiveRefactorArguments); } - function addImportFromExportedSymbol(exportedSymbol, isValidTypeOnlyUseSite) { - const moduleSymbol = Debug.checkDefined(exportedSymbol.parent); - const symbolName2 = getNameForExportedSymbol(exportedSymbol, getEmitScriptTarget(compilerOptions)); - const checker = program.getTypeChecker(); - const symbol = checker.getMergedSymbol(skipAlias(exportedSymbol, checker)); - const exportInfo = getAllExportInfoForSymbol(sourceFile, symbol, symbolName2, moduleSymbol, /*isJsxTagName*/ false, program, host, preferences, cancellationToken); - const useRequire = shouldUseRequire(sourceFile, program); - const fix = getImportFixForSymbol(sourceFile, Debug.checkDefined(exportInfo), program, /*position*/ void 0, !!isValidTypeOnlyUseSite, useRequire, host, preferences); - if (fix) addImport({ - fix: fix, - symbolName: symbolName2, - errorIdentifierText: void 0 - }); + function toLineColumnOffset(fileName, position) { + if (position === 0) return { + line: 0, + character: 0 + }; + return sourceMapper.toLineColumnOffset(fileName, position); } - function addImport(info) { - var _a2, _b; - const { fix: fix , symbolName: symbolName2 } = info; - switch(fix.kind){ - case 0 /* UseNamespace */ : - addToNamespace.push(fix); - break; - case 1 /* JsdocTypeImport */ : - importType.push(fix); - break; - case 2 /* AddToExisting */ : - { - const { importClauseOrBindingPattern: importClauseOrBindingPattern , importKind: importKind , addAsTypeOnly: addAsTypeOnly } = fix; - const key = String(getNodeId(importClauseOrBindingPattern)); - let entry = addToExisting.get(key); - if (!entry) addToExisting.set(key, entry = { - importClauseOrBindingPattern: importClauseOrBindingPattern, - defaultImport: void 0, - namedImports: /* @__PURE__ */ new Map() - }); - if (importKind === 0 /* Named */ ) { - const prevValue = entry == null ? void 0 : entry.namedImports.get(symbolName2); - entry.namedImports.set(symbolName2, reduceAddAsTypeOnlyValues(prevValue, addAsTypeOnly)); - } else { - Debug.assert(entry.defaultImport === void 0 || entry.defaultImport.name === symbolName2, "(Add to Existing) Default import should be missing or match symbolName"); - entry.defaultImport = { - name: symbolName2, - addAsTypeOnly: reduceAddAsTypeOnlyValues((_a2 = entry.defaultImport) == null ? void 0 : _a2.addAsTypeOnly, addAsTypeOnly) - }; - } - break; - } - case 3 /* AddNew */ : - { - const { moduleSpecifier: moduleSpecifier , importKind: importKind , useRequire: useRequire , addAsTypeOnly: addAsTypeOnly } = fix; - const entry = getNewImportEntry(moduleSpecifier, importKind, useRequire, addAsTypeOnly); - Debug.assert(entry.useRequire === useRequire, "(Add new) Tried to add an `import` and a `require` for the same module"); - switch(importKind){ - case 1 /* Default */ : - Debug.assert(entry.defaultImport === void 0 || entry.defaultImport.name === symbolName2, "(Add new) Default import should be missing or match symbolName"); - entry.defaultImport = { - name: symbolName2, - addAsTypeOnly: reduceAddAsTypeOnlyValues((_b = entry.defaultImport) == null ? void 0 : _b.addAsTypeOnly, addAsTypeOnly) - }; - break; - case 0 /* Named */ : - const prevValue = (entry.namedImports || (entry.namedImports = /* @__PURE__ */ new Map())).get(symbolName2); - entry.namedImports.set(symbolName2, reduceAddAsTypeOnlyValues(prevValue, addAsTypeOnly)); - break; - case 3 /* CommonJS */ : - case 2 /* Namespace */ : - Debug.assert(entry.namespaceLikeImport === void 0 || entry.namespaceLikeImport.name === symbolName2, "Namespacelike import shoudl be missing or match symbolName"); - entry.namespaceLikeImport = { - importKind: importKind, - name: symbolName2, - addAsTypeOnly: addAsTypeOnly - }; - break; - } - break; - } - case 4 /* PromoteTypeOnly */ : - break; - default: - Debug.assertNever(fix, `fix wasn't never - got kind ${fix.kind}`); - } - function reduceAddAsTypeOnlyValues(prevValue, newValue) { - return Math.max(prevValue != null ? prevValue : 0, newValue); - } - function getNewImportEntry(moduleSpecifier, importKind, useRequire, addAsTypeOnly) { - const typeOnlyKey = newImportsKey(moduleSpecifier, /*topLevelTypeOnly*/ true); - const nonTypeOnlyKey = newImportsKey(moduleSpecifier, /*topLevelTypeOnly*/ false); - const typeOnlyEntry = newImports.get(typeOnlyKey); - const nonTypeOnlyEntry = newImports.get(nonTypeOnlyKey); - const newEntry = { - defaultImport: void 0, - namedImports: void 0, - namespaceLikeImport: void 0, - useRequire: useRequire - }; - if (importKind === 1 /* Default */ && addAsTypeOnly === 2 /* Required */ ) { - if (typeOnlyEntry) return typeOnlyEntry; - newImports.set(typeOnlyKey, newEntry); - return newEntry; - } - if (addAsTypeOnly === 1 /* Allowed */ && (typeOnlyEntry || nonTypeOnlyEntry)) return typeOnlyEntry || nonTypeOnlyEntry; - if (nonTypeOnlyEntry) return nonTypeOnlyEntry; - newImports.set(nonTypeOnlyKey, newEntry); - return newEntry; - } - function newImportsKey(moduleSpecifier, topLevelTypeOnly) { - return `${topLevelTypeOnly ? 1 : 0}|${moduleSpecifier}`; - } + function prepareCallHierarchy(fileName, position) { + synchronizeHostData(); + const declarations = ts_CallHierarchy_exports.resolveCallHierarchyDeclaration(program, getTouchingPropertyName(getValidSourceFile(fileName), position)); + return declarations && mapOneOrMany(declarations, (declaration)=>ts_CallHierarchy_exports.createCallHierarchyItem(program, declaration)); } - function writeFixes(changeTracker) { - const quotePreference = getQuotePreference(sourceFile, preferences); - for (const fix of addToNamespace)addNamespaceQualifier(changeTracker, sourceFile, fix); - for (const fix of importType)addImportType(changeTracker, sourceFile, fix, quotePreference); - addToExisting.forEach(({ importClauseOrBindingPattern: importClauseOrBindingPattern , defaultImport: defaultImport , namedImports: namedImports })=>{ - doAddExistingFix(changeTracker, sourceFile, importClauseOrBindingPattern, defaultImport, arrayFrom(namedImports.entries(), ([name, addAsTypeOnly])=>({ - addAsTypeOnly: addAsTypeOnly, - name: name - })), compilerOptions, preferences); - }); - let newDeclarations; - newImports.forEach(({ useRequire: useRequire , defaultImport: defaultImport , namedImports: namedImports , namespaceLikeImport: namespaceLikeImport }, key)=>{ - const moduleSpecifier = key.slice(2); - const getDeclarations = useRequire ? getNewRequires : getNewImports; - const declarations = getDeclarations(moduleSpecifier, quotePreference, defaultImport, namedImports && arrayFrom(namedImports.entries(), ([name, addAsTypeOnly])=>({ - addAsTypeOnly: addAsTypeOnly, - name: name - })), namespaceLikeImport, compilerOptions); - newDeclarations = combine(newDeclarations, declarations); - }); - if (newDeclarations) insertImports(changeTracker, sourceFile, newDeclarations, /*blankLineBetween*/ true, preferences); + function provideCallHierarchyIncomingCalls(fileName, position) { + synchronizeHostData(); + const sourceFile = getValidSourceFile(fileName); + const declaration = firstOrOnly(ts_CallHierarchy_exports.resolveCallHierarchyDeclaration(program, position === 0 ? sourceFile : getTouchingPropertyName(sourceFile, position))); + return declaration ? ts_CallHierarchy_exports.getIncomingCalls(program, declaration, cancellationToken) : []; } - function hasFixes() { - return addToNamespace.length > 0 || importType.length > 0 || addToExisting.size > 0 || newImports.size > 0; + function provideCallHierarchyOutgoingCalls(fileName, position) { + synchronizeHostData(); + const sourceFile = getValidSourceFile(fileName); + const declaration = firstOrOnly(ts_CallHierarchy_exports.resolveCallHierarchyDeclaration(program, position === 0 ? sourceFile : getTouchingPropertyName(sourceFile, position))); + return declaration ? ts_CallHierarchy_exports.getOutgoingCalls(program, declaration) : []; } - } - function createImportSpecifierResolver(importingFile, program, host, preferences) { - const packageJsonImportFilter = createPackageJsonImportFilter(importingFile, preferences, host); - const importMap = createExistingImportMap(program.getTypeChecker(), importingFile, program.getCompilerOptions()); - return { - getModuleSpecifierForBestExportInfo: getModuleSpecifierForBestExportInfo + function provideInlayHints2(fileName, span, preferences = emptyOptions) { + synchronizeHostData(); + const sourceFile = getValidSourceFile(fileName); + return ts_InlayHints_exports.provideInlayHints(getInlayHintsContext(sourceFile, span, preferences)); + } + const ls = { + dispose: dispose, + cleanupSemanticCache: cleanupSemanticCache, + getSyntacticDiagnostics: getSyntacticDiagnostics, + getSemanticDiagnostics: getSemanticDiagnostics, + getSuggestionDiagnostics: getSuggestionDiagnostics, + getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, + getSyntacticClassifications: getSyntacticClassifications2, + getSemanticClassifications: getSemanticClassifications3, + getEncodedSyntacticClassifications: getEncodedSyntacticClassifications2, + getEncodedSemanticClassifications: getEncodedSemanticClassifications3, + getCompletionsAtPosition: getCompletionsAtPosition2, + getCompletionEntryDetails: getCompletionEntryDetails2, + getCompletionEntrySymbol: getCompletionEntrySymbol2, + getSignatureHelpItems: getSignatureHelpItems2, + getQuickInfoAtPosition: getQuickInfoAtPosition, + getDefinitionAtPosition: getDefinitionAtPosition2, + getDefinitionAndBoundSpan: getDefinitionAndBoundSpan2, + getImplementationAtPosition: getImplementationAtPosition, + getTypeDefinitionAtPosition: getTypeDefinitionAtPosition2, + getReferencesAtPosition: getReferencesAtPosition, + findReferences: findReferences, + getFileReferences: getFileReferences, + getDocumentHighlights: getDocumentHighlights, + getNameOrDottedNameSpan: getNameOrDottedNameSpan, + getBreakpointStatementAtPosition: getBreakpointStatementAtPosition, + getNavigateToItems: getNavigateToItems2, + getRenameInfo: getRenameInfo2, + getSmartSelectionRange: getSmartSelectionRange2, + findRenameLocations: findRenameLocations, + getNavigationBarItems: getNavigationBarItems2, + getNavigationTree: getNavigationTree2, + getOutliningSpans: getOutliningSpans, + getTodoComments: getTodoComments, + getBraceMatchingAtPosition: getBraceMatchingAtPosition, + getIndentationAtPosition: getIndentationAtPosition, + getFormattingEditsForRange: getFormattingEditsForRange, + getFormattingEditsForDocument: getFormattingEditsForDocument, + getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, + getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition2, + isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getJsxClosingTagAtPosition: getJsxClosingTagAtPosition, + getLinkedEditingRangeAtPosition: getLinkedEditingRangeAtPosition, + getSpanOfEnclosingComment: getSpanOfEnclosingComment, + getCodeFixesAtPosition: getCodeFixesAtPosition, + getCombinedCodeFix: getCombinedCodeFix, + applyCodeActionCommand: applyCodeActionCommand, + organizeImports: organizeImports2, + getEditsForFileRename: getEditsForFileRename2, + getEmitOutput: getEmitOutput, + getNonBoundSourceFile: getNonBoundSourceFile, + getProgram: getProgram, + getCurrentProgram: ()=>program, + getAutoImportProvider: getAutoImportProvider, + updateIsDefinitionOfReferencedSymbols: updateIsDefinitionOfReferencedSymbols, + getApplicableRefactors: getApplicableRefactors2, + getEditsForRefactor: getEditsForRefactor2, + getMoveToRefactoringFileSuggestions: getMoveToRefactoringFileSuggestions, + toLineColumnOffset: toLineColumnOffset, + getSourceMapper: ()=>sourceMapper, + clearSourceMapperCache: ()=>sourceMapper.clearCache(), + prepareCallHierarchy: prepareCallHierarchy, + provideCallHierarchyIncomingCalls: provideCallHierarchyIncomingCalls, + provideCallHierarchyOutgoingCalls: provideCallHierarchyOutgoingCalls, + toggleLineComment: toggleLineComment, + toggleMultilineComment: toggleMultilineComment, + commentSelection: commentSelection, + uncommentSelection: uncommentSelection, + provideInlayHints: provideInlayHints2, + getSupportedCodeFixes: getSupportedCodeFixes }; - function getModuleSpecifierForBestExportInfo(exportInfo, position, isValidTypeOnlyUseSite, fromCacheOnly) { - const { fixes: fixes , computedWithoutCacheCount: computedWithoutCacheCount } = getImportFixes(exportInfo, position, isValidTypeOnlyUseSite, /*useRequire*/ false, program, importingFile, host, preferences, importMap, fromCacheOnly); - const result = getBestFix(fixes, importingFile, program, packageJsonImportFilter, host); - return result && { - ...result, - computedWithoutCacheCount: computedWithoutCacheCount - }; + switch(languageServiceMode){ + case 0 /* Semantic */ : + break; + case 1 /* PartialSemantic */ : + invalidOperationsInPartialSemanticMode.forEach((key)=>ls[key] = ()=>{ + throw new Error(`LanguageService Operation: ${key} not allowed in LanguageServiceMode.PartialSemantic`); + }); + break; + case 2 /* Syntactic */ : + invalidOperationsInSyntacticMode.forEach((key)=>ls[key] = ()=>{ + throw new Error(`LanguageService Operation: ${key} not allowed in LanguageServiceMode.Syntactic`); + }); + break; + default: + Debug.assertNever(languageServiceMode); } + return ls; } - function getImportCompletionAction(targetSymbol, moduleSymbol, exportMapKey, sourceFile, symbolName2, isJsxTagName, host, program, formatContext, position, preferences, cancellationToken) { - const compilerOptions = program.getCompilerOptions(); - let exportInfos; - if (exportMapKey) { - exportInfos = getExportInfoMap(sourceFile, host, program, preferences, cancellationToken).get(sourceFile.path, exportMapKey); - Debug.assertIsDefined(exportInfos, "Some exportInfo should match the specified exportMapKey"); - } else { - exportInfos = pathIsBareSpecifier(stripQuotes(moduleSymbol.name)) ? [ - getSingleExportInfoForSymbol(targetSymbol, symbolName2, moduleSymbol, program, host) - ] : getAllExportInfoForSymbol(sourceFile, targetSymbol, symbolName2, moduleSymbol, isJsxTagName, program, host, preferences, cancellationToken); - Debug.assertIsDefined(exportInfos, "Some exportInfo should match the specified symbol / moduleSymbol"); - } - const useRequire = shouldUseRequire(sourceFile, program); - const isValidTypeOnlyUseSite = isValidTypeOnlyAliasUseSite(getTokenAtPosition(sourceFile, position)); - const fix = Debug.checkDefined(getImportFixForSymbol(sourceFile, exportInfos, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences)); - return { - moduleSpecifier: fix.moduleSpecifier, - codeAction: codeFixActionToCodeAction(codeActionForFix({ - host: host, - formatContext: formatContext, - preferences: preferences - }, sourceFile, symbolName2, fix, /*includeSymbolNameInDescription*/ false, compilerOptions, preferences)) - }; + function getNameTable(sourceFile) { + if (!sourceFile.nameTable) initializeNameTable(sourceFile); + return sourceFile.nameTable; } - function getPromoteTypeOnlyCompletionAction(sourceFile, symbolToken, program, host, formatContext, preferences) { - const compilerOptions = program.getCompilerOptions(); - const symbolName2 = single(getSymbolNamesToImport(sourceFile, program.getTypeChecker(), symbolToken, compilerOptions)); - const fix = getTypeOnlyPromotionFix(sourceFile, symbolToken, symbolName2, program); - const includeSymbolNameInDescription = symbolName2 !== symbolToken.text; - return fix && codeFixActionToCodeAction(codeActionForFix({ - host: host, - formatContext: formatContext, - preferences: preferences - }, sourceFile, symbolName2, fix, includeSymbolNameInDescription, compilerOptions, preferences)); + function initializeNameTable(sourceFile) { + const nameTable = sourceFile.nameTable = /* @__PURE__ */ new Map(); + sourceFile.forEachChild(function walk(node) { + if (isIdentifier(node) && !isTagName(node) && node.escapedText || isStringOrNumericLiteralLike(node) && literalIsName(node)) { + const text = getEscapedTextOfIdentifierOrLiteral(node); + nameTable.set(text, nameTable.get(text) === void 0 ? node.pos : -1); + } else if (isPrivateIdentifier(node)) { + const text = node.escapedText; + nameTable.set(text, nameTable.get(text) === void 0 ? node.pos : -1); + } + forEachChild(node, walk); + if (hasJSDocNodes(node)) for (const jsDoc of node.jsDoc)forEachChild(jsDoc, walk); + }); } - function getImportFixForSymbol(sourceFile, exportInfos, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences) { - const packageJsonImportFilter = createPackageJsonImportFilter(sourceFile, preferences, host); - return getBestFix(getImportFixes(exportInfos, position, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences).fixes, sourceFile, program, packageJsonImportFilter, host); + function literalIsName(node) { + return isDeclarationName(node) || node.parent.kind === 283 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node) || isLiteralComputedPropertyDeclarationName(node); } - function codeFixActionToCodeAction({ description: description2 , changes: changes , commands: commands }) { - return { - description: description2, - changes: changes, - commands: commands - }; + function getContainingObjectLiteralElement(node) { + const element = getContainingObjectLiteralElementWorker(node); + return element && (isObjectLiteralExpression(element.parent) || isJsxAttributes(element.parent)) ? element : void 0; } - function getAllExportInfoForSymbol(importingFile, symbol, symbolName2, moduleSymbol, preferCapitalized, program, host, preferences, cancellationToken) { - const getChecker = createGetChecker(program, host); - return getExportInfoMap(importingFile, host, program, preferences, cancellationToken).search(importingFile.path, preferCapitalized, (name)=>name === symbolName2, (info)=>{ - if (skipAlias(info[0].symbol, getChecker(info[0].isFromPackageJson)) === symbol && info.some((i)=>i.moduleSymbol === moduleSymbol || i.symbol.parent === moduleSymbol)) return info; - }); + function getContainingObjectLiteralElementWorker(node) { + switch(node.kind){ + case 11 /* StringLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + case 9 /* NumericLiteral */ : + if (node.parent.kind === 167 /* ComputedPropertyName */ ) return isObjectLiteralElement(node.parent.parent) ? node.parent.parent : void 0; + case 80 /* Identifier */ : + return isObjectLiteralElement(node.parent) && (node.parent.parent.kind === 210 /* ObjectLiteralExpression */ || node.parent.parent.kind === 292 /* JsxAttributes */ ) && node.parent.name === node ? node.parent : void 0; + } + return void 0; } - function getSingleExportInfoForSymbol(symbol, symbolName2, moduleSymbol, program, host) { - var _a2, _b; - const compilerOptions = program.getCompilerOptions(); - const mainProgramInfo = getInfoWithChecker(program.getTypeChecker(), /*isFromPackageJson*/ false); - if (mainProgramInfo) return mainProgramInfo; - const autoImportProvider = (_b = (_a2 = host.getPackageJsonAutoImportProvider) == null ? void 0 : _a2.call(host)) == null ? void 0 : _b.getTypeChecker(); - return Debug.checkDefined(autoImportProvider && getInfoWithChecker(autoImportProvider, /*isFromPackageJson*/ true), `Could not find symbol in specified module for code actions`); - function getInfoWithChecker(checker, isFromPackageJson) { - const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); - if (defaultInfo && skipAlias(defaultInfo.symbol, checker) === symbol) return { - symbol: defaultInfo.symbol, - moduleSymbol: moduleSymbol, - moduleFileName: void 0, - exportKind: defaultInfo.exportKind, - targetFlags: skipAlias(symbol, checker).flags, - isFromPackageJson: isFromPackageJson - }; - const named = checker.tryGetMemberInModuleExportsAndProperties(symbolName2, moduleSymbol); - if (named && skipAlias(named, checker) === symbol) return { - symbol: named, - moduleSymbol: moduleSymbol, - moduleFileName: void 0, - exportKind: 0 /* Named */ , - targetFlags: skipAlias(symbol, checker).flags, - isFromPackageJson: isFromPackageJson - }; + function getSymbolAtLocationForQuickInfo(node, checker) { + const object = getContainingObjectLiteralElement(node); + if (object) { + const contextualType = checker.getContextualType(object.parent); + const properties = contextualType && getPropertySymbolsFromContextualType(object, checker, contextualType, /*unionSymbolOk*/ false); + if (properties && properties.length === 1) return first(properties); } + return checker.getSymbolAtLocation(node); } - function getImportFixes(exportInfos, usagePosition, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences, importMap = createExistingImportMap(program.getTypeChecker(), sourceFile, program.getCompilerOptions()), fromCacheOnly) { - const checker = program.getTypeChecker(); - const existingImports = flatMap(exportInfos, importMap.getImportsForExportInfo); - const useNamespace = usagePosition !== void 0 && tryUseExistingNamespaceImport(existingImports, usagePosition); - const addToExisting = tryAddToExistingImport(existingImports, isValidTypeOnlyUseSite, checker, program.getCompilerOptions()); - if (addToExisting) return { - computedWithoutCacheCount: 0, - fixes: [ - ...useNamespace ? [ - useNamespace - ] : emptyArray, - addToExisting - ] - }; - const { fixes: fixes , computedWithoutCacheCount: computedWithoutCacheCount = 0 } = getFixesForAddImport(exportInfos, existingImports, program, sourceFile, usagePosition, isValidTypeOnlyUseSite, useRequire, host, preferences, fromCacheOnly); - return { - computedWithoutCacheCount: computedWithoutCacheCount, - fixes: [ - ...useNamespace ? [ - useNamespace - ] : emptyArray, - ...fixes - ] - }; - } - function tryUseExistingNamespaceImport(existingImports, position) { - return firstDefined(existingImports, ({ declaration: declaration , importKind: importKind })=>{ - var _a2; - if (importKind !== 0 /* Named */ ) return void 0; - const namespacePrefix = getNamespaceLikeImportText(declaration); - const moduleSpecifier = namespacePrefix && ((_a2 = tryGetModuleSpecifierFromDeclaration(declaration)) == null ? void 0 : _a2.text); - if (moduleSpecifier) return { - kind: 0 /* UseNamespace */ , - namespacePrefix: namespacePrefix, - usagePosition: position, - moduleSpecifier: moduleSpecifier - }; - }); - } - function getNamespaceLikeImportText(declaration) { - var _a2, _b, _c; - switch(declaration.kind){ - case 257 /* VariableDeclaration */ : - return (_a2 = tryCast(declaration.name, isIdentifier)) == null ? void 0 : _a2.text; - case 268 /* ImportEqualsDeclaration */ : - return declaration.name.text; - case 269 /* ImportDeclaration */ : - return (_c = tryCast((_b = declaration.importClause) == null ? void 0 : _b.namedBindings, isNamespaceImport)) == null ? void 0 : _c.name.text; - default: - return Debug.assertNever(declaration); + function getPropertySymbolsFromContextualType(node, checker, contextualType, unionSymbolOk) { + const name = getNameFromPropertyName(node.name); + if (!name) return emptyArray; + if (!contextualType.isUnion()) { + const symbol = contextualType.getProperty(name); + return symbol ? [ + symbol + ] : emptyArray; } - } - function getAddAsTypeOnly(isValidTypeOnlyUseSite, isForNewImportDeclaration, symbol, targetFlags, checker, compilerOptions) { - if (!isValidTypeOnlyUseSite) return 4 /* NotAllowed */ ; - if (isForNewImportDeclaration && compilerOptions.importsNotUsedAsValues === 2 /* Error */ ) return 2 /* Required */ ; - if (importNameElisionDisabled(compilerOptions) && (!(targetFlags & 111551 /* Value */ ) || !!checker.getTypeOnlyAliasDeclaration(symbol))) return 2 /* Required */ ; - return 1 /* Allowed */ ; - } - function tryAddToExistingImport(existingImports, isValidTypeOnlyUseSite, checker, compilerOptions) { - return firstDefined(existingImports, ({ declaration: declaration , importKind: importKind , symbol: symbol , targetFlags: targetFlags })=>{ - if (importKind === 3 /* CommonJS */ || importKind === 2 /* Namespace */ || declaration.kind === 268 /* ImportEqualsDeclaration */ ) return void 0; - if (declaration.kind === 257 /* VariableDeclaration */ ) return (importKind === 0 /* Named */ || importKind === 1 /* Default */ ) && declaration.name.kind === 203 /* ObjectBindingPattern */ ? { - kind: 2 /* AddToExisting */ , - importClauseOrBindingPattern: declaration.name, - importKind: importKind, - moduleSpecifier: declaration.initializer.arguments[0].text, - addAsTypeOnly: 4 /* NotAllowed */ - } : void 0; - const { importClause: importClause } = declaration; - if (!importClause || !isStringLiteralLike(declaration.moduleSpecifier)) return void 0; - const { name: name , namedBindings: namedBindings } = importClause; - if (importClause.isTypeOnly && !(importKind === 0 /* Named */ && namedBindings)) return void 0; - const addAsTypeOnly = getAddAsTypeOnly(isValidTypeOnlyUseSite, /*isForNewImportDeclaration*/ false, symbol, targetFlags, checker, compilerOptions); - if (importKind === 1 /* Default */ && (name || // Cannot add a default import to a declaration that already has one - addAsTypeOnly === 2 /* Required */ && namedBindings)) return void 0; - if (importKind === 0 /* Named */ && (namedBindings == null ? void 0 : namedBindings.kind) === 271 /* NamespaceImport */ ) return void 0; - return { - kind: 2 /* AddToExisting */ , - importClauseOrBindingPattern: importClause, - importKind: importKind, - moduleSpecifier: declaration.moduleSpecifier.text, - addAsTypeOnly: addAsTypeOnly - }; - }); - } - function createExistingImportMap(checker, importingFile, compilerOptions) { - let importMap; - for (const moduleSpecifier of importingFile.imports){ - const i = importFromModuleSpecifier(moduleSpecifier); - if (isVariableDeclarationInitializedToRequire(i.parent)) { - const moduleSymbol = checker.resolveExternalModuleName(moduleSpecifier); - if (moduleSymbol) (importMap || (importMap = createMultiMap())).add(getSymbolId(moduleSymbol), i.parent); - } else if (i.kind === 269 /* ImportDeclaration */ || i.kind === 268 /* ImportEqualsDeclaration */ ) { - const moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); - if (moduleSymbol) (importMap || (importMap = createMultiMap())).add(getSymbolId(moduleSymbol), i); - } + const discriminatedPropertySymbols = mapDefined(contextualType.types, (t)=>(isObjectLiteralExpression(node.parent) || isJsxAttributes(node.parent)) && checker.isTypeInvalidDueToUnionDiscriminant(t, node.parent) ? void 0 : t.getProperty(name)); + if (unionSymbolOk && (discriminatedPropertySymbols.length === 0 || discriminatedPropertySymbols.length === contextualType.types.length)) { + const symbol = contextualType.getProperty(name); + if (symbol) return [ + symbol + ]; } - return { - getImportsForExportInfo: ({ moduleSymbol: moduleSymbol , exportKind: exportKind , targetFlags: targetFlags , symbol: symbol })=>{ - if (!(targetFlags & 111551 /* Value */ ) && isSourceFileJS(importingFile)) return emptyArray; - const matchingDeclarations = importMap == null ? void 0 : importMap.get(getSymbolId(moduleSymbol)); - if (!matchingDeclarations) return emptyArray; - const importKind = getImportKind(importingFile, exportKind, compilerOptions); - return matchingDeclarations.map((declaration)=>({ - declaration: declaration, - importKind: importKind, - symbol: symbol, - targetFlags: targetFlags - })); - } - }; + if (discriminatedPropertySymbols.length === 0) return mapDefined(contextualType.types, (t)=>t.getProperty(name)); + return discriminatedPropertySymbols; } - function shouldUseRequire(sourceFile, program) { - if (!isSourceFileJS(sourceFile)) return false; - if (sourceFile.commonJsModuleIndicator && !sourceFile.externalModuleIndicator) return true; - if (sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) return false; - const compilerOptions = program.getCompilerOptions(); - if (compilerOptions.configFile) return getEmitModuleKind(compilerOptions) < 5 /* ES2015 */ ; - for (const otherFile of program.getSourceFiles()){ - if (otherFile === sourceFile || !isSourceFileJS(otherFile) || program.isSourceFileFromExternalLibrary(otherFile)) continue; - if (otherFile.commonJsModuleIndicator && !otherFile.externalModuleIndicator) return true; - if (otherFile.externalModuleIndicator && !otherFile.commonJsModuleIndicator) return false; - } - return true; + function isArgumentOfElementAccessExpression(node) { + return node && node.parent && node.parent.kind === 212 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } - function createGetChecker(program, host) { - return memoizeOne((isFromPackageJson)=>isFromPackageJson ? host.getPackageJsonAutoImportProvider().getTypeChecker() : program.getTypeChecker()); + function getDefaultLibFilePath(options) { + if (sys) return combinePaths(getDirectoryPath(normalizePath(sys.getExecutingFilePath())), getDefaultLibFileName(options)); + throw new Error("getDefaultLibFilePath is only supported when consumed as a node module. "); } - function getNewImportFixes(program, sourceFile, usagePosition, isValidTypeOnlyUseSite, useRequire, exportInfo, host, preferences, fromCacheOnly) { - const isJs = isSourceFileJS(sourceFile); - const compilerOptions = program.getCompilerOptions(); - const moduleSpecifierResolutionHost = createModuleSpecifierResolutionHost(program, host); - const getChecker = createGetChecker(program, host); - const moduleResolution = getEmitModuleResolutionKind(compilerOptions); - const rejectNodeModulesRelativePaths = moduleResolutionUsesNodeModules(moduleResolution); - const getModuleSpecifiers2 = fromCacheOnly ? (moduleSymbol)=>({ - moduleSpecifiers: ts_moduleSpecifiers_exports.tryGetModuleSpecifiersFromCache(moduleSymbol, sourceFile, moduleSpecifierResolutionHost, preferences), - computedWithoutCache: false - }) : (moduleSymbol, checker)=>ts_moduleSpecifiers_exports.getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, sourceFile, moduleSpecifierResolutionHost, preferences); - let computedWithoutCacheCount = 0; - const fixes = flatMap(exportInfo, (exportInfo2, i)=>{ - const checker = getChecker(exportInfo2.isFromPackageJson); - const { computedWithoutCache: computedWithoutCache , moduleSpecifiers: moduleSpecifiers } = getModuleSpecifiers2(exportInfo2.moduleSymbol, checker); - const importedSymbolHasValueMeaning = !!(exportInfo2.targetFlags & 111551 /* Value */ ); - const addAsTypeOnly = getAddAsTypeOnly(isValidTypeOnlyUseSite, /*isForNewImportDeclaration*/ true, exportInfo2.symbol, exportInfo2.targetFlags, checker, compilerOptions); - computedWithoutCacheCount += computedWithoutCache ? 1 : 0; - return mapDefined(moduleSpecifiers, (moduleSpecifier)=>{ - var _a2; - if (rejectNodeModulesRelativePaths && pathContainsNodeModules(moduleSpecifier)) return void 0; - if (!importedSymbolHasValueMeaning && isJs && usagePosition !== void 0) return { - kind: 1 /* JsdocTypeImport */ , - moduleSpecifier: moduleSpecifier, - usagePosition: usagePosition, - exportInfo: exportInfo2, - isReExport: i > 0 - }; - const importKind = getImportKind(sourceFile, exportInfo2.exportKind, compilerOptions); - let qualification; - if (usagePosition !== void 0 && importKind === 3 /* CommonJS */ && exportInfo2.exportKind === 0 /* Named */ ) { - const exportEquals = checker.resolveExternalModuleSymbol(exportInfo2.moduleSymbol); - let namespacePrefix; - if (exportEquals !== exportInfo2.moduleSymbol) namespacePrefix = (_a2 = getDefaultExportInfoWorker(exportEquals, checker, compilerOptions)) == null ? void 0 : _a2.name; - namespacePrefix || (namespacePrefix = moduleSymbolToValidIdentifier(exportInfo2.moduleSymbol, getEmitScriptTarget(compilerOptions), /*forceCapitalize*/ false)); - qualification = { - namespacePrefix: namespacePrefix, - usagePosition: usagePosition - }; + var servicesVersion, NodeObject, TokenOrIdentifierObject, SymbolObject, TokenObject, IdentifierObject, PrivateIdentifierObject, TypeObject, SignatureObject, SourceFileObject, SourceMapSourceObject, SyntaxTreeCache, NoopCancellationToken, CancellationTokenObject, ThrottledCancellationToken, invalidOperationsInPartialSemanticMode, invalidOperationsInSyntacticMode; + var init_services = __esm({ + "src/services/services.ts" () { + "use strict"; + init_ts4(); + init_ts_NavigateTo(); + init_ts_NavigationBar(); + init_ts_refactor(); + init_classifier(); + init_classifier2020(); + servicesVersion = "0.8"; + NodeObject = class { + constructor(kind, pos, end){ + this.pos = pos; + this.end = end; + this.flags = 0 /* None */ ; + this.modifierFlagsCache = 0 /* None */ ; + this.transformFlags = 0 /* None */ ; + this.parent = void 0; + this.kind = kind; + } + assertHasRealPosition(message) { + Debug.assert(!positionIsSynthesized(this.pos) && !positionIsSynthesized(this.end), message || "Node must have a real position for this operation"); + } + getSourceFile() { + return getSourceFileOfNode(this); + } + getStart(sourceFile, includeJsDocComment) { + this.assertHasRealPosition(); + return getTokenPosOfNode(this, sourceFile, includeJsDocComment); + } + getFullStart() { + this.assertHasRealPosition(); + return this.pos; + } + getEnd() { + this.assertHasRealPosition(); + return this.end; + } + getWidth(sourceFile) { + this.assertHasRealPosition(); + return this.getEnd() - this.getStart(sourceFile); + } + getFullWidth() { + this.assertHasRealPosition(); + return this.end - this.pos; + } + getLeadingTriviaWidth(sourceFile) { + this.assertHasRealPosition(); + return this.getStart(sourceFile) - this.pos; + } + getFullText(sourceFile) { + this.assertHasRealPosition(); + return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); + } + getText(sourceFile) { + this.assertHasRealPosition(); + if (!sourceFile) sourceFile = this.getSourceFile(); + return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); + } + getChildCount(sourceFile) { + return this.getChildren(sourceFile).length; + } + getChildAt(index, sourceFile) { + return this.getChildren(sourceFile)[index]; + } + getChildren(sourceFile) { + this.assertHasRealPosition("Node without a real position cannot be scanned and thus has no token nodes - use forEachChild and collect the result if that's fine"); + return this._children || (this._children = createChildren(this, sourceFile)); + } + getFirstToken(sourceFile) { + this.assertHasRealPosition(); + const children = this.getChildren(sourceFile); + if (!children.length) return void 0; + const child = find(children, (kid)=>kid.kind < 316 /* FirstJSDocNode */ || kid.kind > 357 /* LastJSDocNode */ ); + return child.kind < 166 /* FirstNode */ ? child : child.getFirstToken(sourceFile); + } + getLastToken(sourceFile) { + this.assertHasRealPosition(); + const children = this.getChildren(sourceFile); + const child = lastOrUndefined(children); + if (!child) return void 0; + return child.kind < 166 /* FirstNode */ ? child : child.getLastToken(sourceFile); + } + forEachChild(cbNode, cbNodeArray) { + return forEachChild(this, cbNode, cbNodeArray); } - return { - kind: 3 /* AddNew */ , - moduleSpecifier: moduleSpecifier, - importKind: importKind, - useRequire: useRequire, - addAsTypeOnly: addAsTypeOnly, - exportInfo: exportInfo2, - isReExport: i > 0, - qualification: qualification - }; - }); - }); - return { - computedWithoutCacheCount: computedWithoutCacheCount, - fixes: fixes - }; - } - function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, usagePosition, isValidTypeOnlyUseSite, useRequire, host, preferences, fromCacheOnly) { - const existingDeclaration = firstDefined(existingImports, (info)=>newImportInfoFromExistingSpecifier(info, isValidTypeOnlyUseSite, useRequire, program.getTypeChecker(), program.getCompilerOptions())); - return existingDeclaration ? { - fixes: [ - existingDeclaration - ] - } : getNewImportFixes(program, sourceFile, usagePosition, isValidTypeOnlyUseSite, useRequire, exportInfos, host, preferences, fromCacheOnly); - } - function newImportInfoFromExistingSpecifier({ declaration: declaration , importKind: importKind , symbol: symbol , targetFlags: targetFlags }, isValidTypeOnlyUseSite, useRequire, checker, compilerOptions) { - var _a2; - const moduleSpecifier = (_a2 = tryGetModuleSpecifierFromDeclaration(declaration)) == null ? void 0 : _a2.text; - if (moduleSpecifier) { - const addAsTypeOnly = useRequire ? 4 /* NotAllowed */ : getAddAsTypeOnly(isValidTypeOnlyUseSite, /*isForNewImportDeclaration*/ true, symbol, targetFlags, checker, compilerOptions); - return { - kind: 3 /* AddNew */ , - moduleSpecifier: moduleSpecifier, - importKind: importKind, - addAsTypeOnly: addAsTypeOnly, - useRequire: useRequire }; - } - } - function getFixInfos(context, errorCode, pos, useAutoImportProvider) { - const symbolToken = getTokenAtPosition(context.sourceFile, pos); - let info; - if (errorCode === Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) info = getFixesInfoForUMDImport(context, symbolToken); - else if (!isIdentifier(symbolToken)) return void 0; - else if (errorCode === Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type.code) { - const symbolName2 = single(getSymbolNamesToImport(context.sourceFile, context.program.getTypeChecker(), symbolToken, context.program.getCompilerOptions())); - const fix = getTypeOnlyPromotionFix(context.sourceFile, symbolToken, symbolName2, context.program); - return fix && [ - { - fix: fix, - symbolName: symbolName2, - errorIdentifierText: symbolToken.text + TokenOrIdentifierObject = class { + constructor(pos, end){ + this.pos = pos; + this.end = end; + this.flags = 0 /* None */ ; + this.modifierFlagsCache = 0 /* None */ ; + this.transformFlags = 0 /* None */ ; + this.parent = void 0; + } + getSourceFile() { + return getSourceFileOfNode(this); + } + getStart(sourceFile, includeJsDocComment) { + return getTokenPosOfNode(this, sourceFile, includeJsDocComment); + } + getFullStart() { + return this.pos; + } + getEnd() { + return this.end; + } + getWidth(sourceFile) { + return this.getEnd() - this.getStart(sourceFile); + } + getFullWidth() { + return this.end - this.pos; + } + getLeadingTriviaWidth(sourceFile) { + return this.getStart(sourceFile) - this.pos; + } + getFullText(sourceFile) { + return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); + } + getText(sourceFile) { + if (!sourceFile) sourceFile = this.getSourceFile(); + return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); + } + getChildCount() { + return this.getChildren().length; + } + getChildAt(index) { + return this.getChildren()[index]; + } + getChildren() { + return this.kind === 1 /* EndOfFileToken */ ? this.jsDoc || emptyArray : emptyArray; + } + getFirstToken() { + return void 0; + } + getLastToken() { + return void 0; + } + forEachChild() { + return void 0; } - ]; - } else info = getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider); - const packageJsonImportFilter = createPackageJsonImportFilter(context.sourceFile, context.preferences, context.host); - return info && sortFixInfo(info, context.sourceFile, context.program, packageJsonImportFilter, context.host); - } - function sortFixInfo(fixes, sourceFile, program, packageJsonImportFilter, host) { - const _toPath = (fileName)=>toPath(fileName, host.getCurrentDirectory(), hostGetCanonicalFileName(host)); - return sort(fixes, (a, b)=>compareBooleans(!!a.isJsxNamespaceFix, !!b.isJsxNamespaceFix) || compareValues(a.fix.kind, b.fix.kind) || compareModuleSpecifiers(a.fix, b.fix, sourceFile, program, packageJsonImportFilter.allowsImportingSpecifier, _toPath)); - } - function getBestFix(fixes, sourceFile, program, packageJsonImportFilter, host) { - if (!some(fixes)) return; - if (fixes[0].kind === 0 /* UseNamespace */ || fixes[0].kind === 2 /* AddToExisting */ ) return fixes[0]; - return fixes.reduce((best, fix)=>// Takes true branch of conditional if `fix` is better than `best` - compareModuleSpecifiers(fix, best, sourceFile, program, packageJsonImportFilter.allowsImportingSpecifier, (fileName)=>toPath(fileName, host.getCurrentDirectory(), hostGetCanonicalFileName(host))) === -1 /* LessThan */ ? fix : best); - } - function compareModuleSpecifiers(a, b, importingFile, program, allowsImportingSpecifier, toPath3) { - if (a.kind !== 0 /* UseNamespace */ && b.kind !== 0 /* UseNamespace */ ) return compareBooleans(allowsImportingSpecifier(b.moduleSpecifier), allowsImportingSpecifier(a.moduleSpecifier)) || compareNodeCoreModuleSpecifiers(a.moduleSpecifier, b.moduleSpecifier, importingFile, program) || compareBooleans(isFixPossiblyReExportingImportingFile(a, importingFile, program.getCompilerOptions(), toPath3), isFixPossiblyReExportingImportingFile(b, importingFile, program.getCompilerOptions(), toPath3)) || compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier); - return 0 /* EqualTo */ ; - } - function isFixPossiblyReExportingImportingFile(fix, importingFile, compilerOptions, toPath3) { - var _a2; - if (fix.isReExport && ((_a2 = fix.exportInfo) == null ? void 0 : _a2.moduleFileName) && getEmitModuleResolutionKind(compilerOptions) === 2 /* Node10 */ && isIndexFileName(fix.exportInfo.moduleFileName)) { - const reExportDir = toPath3(getDirectoryPath(fix.exportInfo.moduleFileName)); - return startsWith(importingFile.path, reExportDir); - } - return false; - } - function isIndexFileName(fileName) { - return getBaseFileName(fileName, [ - ".js", - ".jsx", - ".d.ts", - ".ts", - ".tsx" - ], /*ignoreCase*/ true) === "index"; - } - function compareNodeCoreModuleSpecifiers(a, b, importingFile, program) { - if (startsWith(a, "node:") && !startsWith(b, "node:")) return shouldUseUriStyleNodeCoreModules(importingFile, program) ? -1 /* LessThan */ : 1 /* GreaterThan */ ; - if (startsWith(b, "node:") && !startsWith(a, "node:")) return shouldUseUriStyleNodeCoreModules(importingFile, program) ? 1 /* GreaterThan */ : -1 /* LessThan */ ; - return 0 /* EqualTo */ ; - } - function getFixesInfoForUMDImport({ sourceFile: sourceFile , program: program , host: host , preferences: preferences }, token) { - const checker = program.getTypeChecker(); - const umdSymbol = getUmdSymbol(token, checker); - if (!umdSymbol) return void 0; - const symbol = checker.getAliasedSymbol(umdSymbol); - const symbolName2 = umdSymbol.name; - const exportInfo = [ - { - symbol: umdSymbol, - moduleSymbol: symbol, - moduleFileName: void 0, - exportKind: 3 /* UMD */ , - targetFlags: symbol.flags, - isFromPackageJson: false - } - ]; - const useRequire = shouldUseRequire(sourceFile, program); - const fixes = getImportFixes(exportInfo, /*usagePosition*/ void 0, /*isValidTypeOnlyUseSite*/ false, useRequire, program, sourceFile, host, preferences).fixes; - return fixes.map((fix)=>{ - var _a2; - return { - fix: fix, - symbolName: symbolName2, - errorIdentifierText: (_a2 = tryCast(token, isIdentifier)) == null ? void 0 : _a2.text }; - }); - } - function getUmdSymbol(token, checker) { - const umdSymbol = isIdentifier(token) ? checker.getSymbolAtLocation(token) : void 0; - if (isUMDExportSymbol(umdSymbol)) return umdSymbol; - const { parent: parent2 } = token; - if (isJsxOpeningLikeElement(parent2) && parent2.tagName === token || isJsxOpeningFragment(parent2)) { - const parentSymbol = checker.resolveName(checker.getJsxNamespace(parent2), isJsxOpeningLikeElement(parent2) ? token : parent2, 111551 /* Value */ , /*excludeGlobals*/ false); - if (isUMDExportSymbol(parentSymbol)) return parentSymbol; - } - return void 0; - } - function getImportKind(importingFile, exportKind, compilerOptions, forceImportKeyword) { - if (compilerOptions.verbatimModuleSyntax && (getEmitModuleKind(compilerOptions) === 1 /* CommonJS */ || importingFile.impliedNodeFormat === 1 /* CommonJS */ )) return 3 /* CommonJS */ ; - switch(exportKind){ - case 0 /* Named */ : - return 0 /* Named */ ; - case 1 /* Default */ : - return 1 /* Default */ ; - case 2 /* ExportEquals */ : - return getExportEqualsImportKind(importingFile, compilerOptions, !!forceImportKeyword); - case 3 /* UMD */ : - return getUmdImportKind(importingFile, compilerOptions, !!forceImportKeyword); - default: - return Debug.assertNever(exportKind); - } - } - function getUmdImportKind(importingFile, compilerOptions, forceImportKeyword) { - if (getAllowSyntheticDefaultImports(compilerOptions)) return 1 /* Default */ ; - const moduleKind = getEmitModuleKind(compilerOptions); - switch(moduleKind){ - case 2 /* AMD */ : - case 1 /* CommonJS */ : - case 3 /* UMD */ : - if (isInJSFile(importingFile)) return isExternalModule(importingFile) || forceImportKeyword ? 2 /* Namespace */ : 3 /* CommonJS */ ; - return 3 /* CommonJS */ ; - case 4 /* System */ : - case 5 /* ES2015 */ : - case 6 /* ES2020 */ : - case 7 /* ES2022 */ : - case 99 /* ESNext */ : - case 0 /* None */ : - return 2 /* Namespace */ ; - case 100 /* Node16 */ : - case 199 /* NodeNext */ : - return importingFile.impliedNodeFormat === 99 /* ESNext */ ? 2 /* Namespace */ : 3 /* CommonJS */ ; - default: - return Debug.assertNever(moduleKind, `Unexpected moduleKind ${moduleKind}`); - } - } - function getFixesInfoForNonUMDImport({ sourceFile: sourceFile , program: program , cancellationToken: cancellationToken , host: host , preferences: preferences }, symbolToken, useAutoImportProvider) { - const checker = program.getTypeChecker(); - const compilerOptions = program.getCompilerOptions(); - return flatMap(getSymbolNamesToImport(sourceFile, checker, symbolToken, compilerOptions), (symbolName2)=>{ - if (symbolName2 === "default" /* Default */ ) return void 0; - const isValidTypeOnlyUseSite = isValidTypeOnlyAliasUseSite(symbolToken); - const useRequire = shouldUseRequire(sourceFile, program); - const exportInfo = getExportInfos(symbolName2, isJSXTagName(symbolToken), getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, program, useAutoImportProvider, host, preferences); - return arrayFrom(flatMapIterator(exportInfo.values(), (exportInfos)=>getImportFixes(exportInfos, symbolToken.getStart(sourceFile), isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences).fixes), (fix)=>({ - fix: fix, - symbolName: symbolName2, - errorIdentifierText: symbolToken.text, - isJsxNamespaceFix: symbolName2 !== symbolToken.text - })); - }); - } - function getTypeOnlyPromotionFix(sourceFile, symbolToken, symbolName2, program) { - const checker = program.getTypeChecker(); - const symbol = checker.resolveName(symbolName2, symbolToken, 111551 /* Value */ , /*excludeGlobals*/ true); - if (!symbol) return void 0; - const typeOnlyAliasDeclaration = checker.getTypeOnlyAliasDeclaration(symbol); - if (!typeOnlyAliasDeclaration || getSourceFileOfNode(typeOnlyAliasDeclaration) !== sourceFile) return void 0; - return { - kind: 4 /* PromoteTypeOnly */ , - typeOnlyAliasDeclaration: typeOnlyAliasDeclaration - }; - } - function getSymbolNamesToImport(sourceFile, checker, symbolToken, compilerOptions) { - const parent2 = symbolToken.parent; - if ((isJsxOpeningLikeElement(parent2) || isJsxClosingElement(parent2)) && parent2.tagName === symbolToken && jsxModeNeedsExplicitImport(compilerOptions.jsx)) { - const jsxNamespace = checker.getJsxNamespace(sourceFile); - if (needsJsxNamespaceFix(jsxNamespace, symbolToken, checker)) { - const needsComponentNameFix = !isIntrinsicJsxName(symbolToken.text) && !checker.resolveName(symbolToken.text, symbolToken, 111551 /* Value */ , /*excludeGlobals*/ false); - return needsComponentNameFix ? [ - symbolToken.text, - jsxNamespace - ] : [ - jsxNamespace - ]; - } - } - return [ - symbolToken.text - ]; - } - function needsJsxNamespaceFix(jsxNamespace, symbolToken, checker) { - if (isIntrinsicJsxName(symbolToken.text)) return true; - const namespaceSymbol = checker.resolveName(jsxNamespace, symbolToken, 111551 /* Value */ , /*excludeGlobals*/ true); - return !namespaceSymbol || some(namespaceSymbol.declarations, isTypeOnlyImportOrExportDeclaration) && !(namespaceSymbol.flags & 111551 /* Value */ ); - } - function getExportInfos(symbolName2, isJsxTagName, currentTokenMeaning, cancellationToken, fromFile, program, useAutoImportProvider, host, preferences) { - var _a2; - const originalSymbolToExportInfos = createMultiMap(); - const packageJsonFilter = createPackageJsonImportFilter(fromFile, preferences, host); - const moduleSpecifierCache = (_a2 = host.getModuleSpecifierCache) == null ? void 0 : _a2.call(host); - const getModuleSpecifierResolutionHost = memoizeOne((isFromPackageJson)=>{ - return createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); - }); - function addSymbol(moduleSymbol, toFile, exportedSymbol, exportKind, program2, isFromPackageJson) { - const moduleSpecifierResolutionHost = getModuleSpecifierResolutionHost(isFromPackageJson); - if (toFile && isImportableFile(program2, fromFile, toFile, preferences, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) || !toFile && packageJsonFilter.allowsImportingAmbientModule(moduleSymbol, moduleSpecifierResolutionHost)) { - const checker = program2.getTypeChecker(); - originalSymbolToExportInfos.add(getUniqueSymbolId(exportedSymbol, checker).toString(), { - symbol: exportedSymbol, - moduleSymbol: moduleSymbol, - moduleFileName: toFile == null ? void 0 : toFile.fileName, - exportKind: exportKind, - targetFlags: skipAlias(exportedSymbol, checker).flags, - isFromPackageJson: isFromPackageJson - }); - } - } - forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, (moduleSymbol, sourceFile, program2, isFromPackageJson)=>{ - const checker = program2.getTypeChecker(); - cancellationToken.throwIfCancellationRequested(); - const compilerOptions = program2.getCompilerOptions(); - const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); - if (defaultInfo && (defaultInfo.name === symbolName2 || moduleSymbolToValidIdentifier(moduleSymbol, getEmitScriptTarget(compilerOptions), isJsxTagName) === symbolName2) && symbolHasMeaning(defaultInfo.resolvedSymbol, currentTokenMeaning)) addSymbol(moduleSymbol, sourceFile, defaultInfo.symbol, defaultInfo.exportKind, program2, isFromPackageJson); - const exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName2, moduleSymbol); - if (exportSymbolWithIdenticalName && symbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) addSymbol(moduleSymbol, sourceFile, exportSymbolWithIdenticalName, 0 /* Named */ , program2, isFromPackageJson); - }); - return originalSymbolToExportInfos; - } - function getExportEqualsImportKind(importingFile, compilerOptions, forceImportKeyword) { - const allowSyntheticDefaults = getAllowSyntheticDefaultImports(compilerOptions); - const isJS = isInJSFile(importingFile); - if (!isJS && getEmitModuleKind(compilerOptions) >= 5 /* ES2015 */ ) return allowSyntheticDefaults ? 1 /* Default */ : 2 /* Namespace */ ; - if (isJS) return isExternalModule(importingFile) || forceImportKeyword ? allowSyntheticDefaults ? 1 /* Default */ : 2 /* Namespace */ : 3 /* CommonJS */ ; - for (const statement of importingFile.statements){ - if (isImportEqualsDeclaration(statement) && !nodeIsMissing(statement.moduleReference)) return 3 /* CommonJS */ ; - } - return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */ ; - } - function codeActionForFix(context, sourceFile, symbolName2, fix, includeSymbolNameInDescription, compilerOptions, preferences) { - let diag2; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (tracker)=>{ - diag2 = codeActionForFixWorker(tracker, sourceFile, symbolName2, fix, includeSymbolNameInDescription, compilerOptions, preferences); - }); - return createCodeFixAction(importFixName, changes, diag2, importFixId, Diagnostics.Add_all_missing_imports); - } - function codeActionForFixWorker(changes, sourceFile, symbolName2, fix, includeSymbolNameInDescription, compilerOptions, preferences) { - const quotePreference = getQuotePreference(sourceFile, preferences); - switch(fix.kind){ - case 0 /* UseNamespace */ : - addNamespaceQualifier(changes, sourceFile, fix); - return [ - Diagnostics.Change_0_to_1, - symbolName2, - `${fix.namespacePrefix}.${symbolName2}` - ]; - case 1 /* JsdocTypeImport */ : - addImportType(changes, sourceFile, fix, quotePreference); - return [ - Diagnostics.Change_0_to_1, - symbolName2, - getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName2 - ]; - case 2 /* AddToExisting */ : - { - const { importClauseOrBindingPattern: importClauseOrBindingPattern , importKind: importKind , addAsTypeOnly: addAsTypeOnly , moduleSpecifier: moduleSpecifier } = fix; - doAddExistingFix(changes, sourceFile, importClauseOrBindingPattern, importKind === 1 /* Default */ ? { - name: symbolName2, - addAsTypeOnly: addAsTypeOnly - } : void 0, importKind === 0 /* Named */ ? [ - { - name: symbolName2, - addAsTypeOnly: addAsTypeOnly + SymbolObject = class { + constructor(flags, name){ + this.id = 0; + this.mergeId = 0; + this.flags = flags; + this.escapedName = name; + } + getFlags() { + return this.flags; + } + get name() { + return symbolName(this); + } + getEscapedName() { + return this.escapedName; + } + getName() { + return this.name; + } + getDeclarations() { + return this.declarations; + } + getDocumentationComment(checker) { + if (!this.documentationComment) { + this.documentationComment = emptyArray; + if (!this.declarations && isTransientSymbol(this) && this.links.target && isTransientSymbol(this.links.target) && this.links.target.links.tupleLabelDeclaration) { + const labelDecl = this.links.target.links.tupleLabelDeclaration; + this.documentationComment = getDocumentationComment([ + labelDecl + ], checker); + } else this.documentationComment = getDocumentationComment(this.declarations, checker); + } + return this.documentationComment; + } + getContextualDocumentationComment(context, checker) { + if (context) { + if (isGetAccessor(context)) { + if (!this.contextualGetAccessorDocumentationComment) this.contextualGetAccessorDocumentationComment = getDocumentationComment(filter(this.declarations, isGetAccessor), checker); + if (length(this.contextualGetAccessorDocumentationComment)) return this.contextualGetAccessorDocumentationComment; } - ] : emptyArray, compilerOptions, preferences); - const moduleSpecifierWithoutQuotes = stripQuotes(moduleSpecifier); - return includeSymbolNameInDescription ? [ - Diagnostics.Import_0_from_1, - symbolName2, - moduleSpecifierWithoutQuotes - ] : [ - Diagnostics.Update_import_from_0, - moduleSpecifierWithoutQuotes - ]; + if (isSetAccessor(context)) { + if (!this.contextualSetAccessorDocumentationComment) this.contextualSetAccessorDocumentationComment = getDocumentationComment(filter(this.declarations, isSetAccessor), checker); + if (length(this.contextualSetAccessorDocumentationComment)) return this.contextualSetAccessorDocumentationComment; + } + } + return this.getDocumentationComment(checker); } - case 3 /* AddNew */ : - { - const { importKind: importKind , moduleSpecifier: moduleSpecifier , addAsTypeOnly: addAsTypeOnly , useRequire: useRequire , qualification: qualification } = fix; - const getDeclarations = useRequire ? getNewRequires : getNewImports; - const defaultImport = importKind === 1 /* Default */ ? { - name: symbolName2, - addAsTypeOnly: addAsTypeOnly - } : void 0; - const namedImports = importKind === 0 /* Named */ ? [ - { - name: symbolName2, - addAsTypeOnly: addAsTypeOnly + getJsDocTags(checker) { + if (this.tags === void 0) this.tags = getJsDocTagsOfDeclarations(this.declarations, checker); + return this.tags; + } + getContextualJsDocTags(context, checker) { + if (context) { + if (isGetAccessor(context)) { + if (!this.contextualGetAccessorTags) this.contextualGetAccessorTags = getJsDocTagsOfDeclarations(filter(this.declarations, isGetAccessor), checker); + if (length(this.contextualGetAccessorTags)) return this.contextualGetAccessorTags; } - ] : void 0; - const namespaceLikeImport = importKind === 2 /* Namespace */ || importKind === 3 /* CommonJS */ ? { - importKind: importKind, - name: (qualification == null ? void 0 : qualification.namespacePrefix) || symbolName2, - addAsTypeOnly: addAsTypeOnly - } : void 0; - insertImports(changes, sourceFile, getDeclarations(moduleSpecifier, quotePreference, defaultImport, namedImports, namespaceLikeImport, compilerOptions), /*blankLineBetween*/ true, preferences); - if (qualification) addNamespaceQualifier(changes, sourceFile, qualification); - return includeSymbolNameInDescription ? [ - Diagnostics.Import_0_from_1, - symbolName2, - moduleSpecifier - ] : [ - Diagnostics.Add_import_from_0, - moduleSpecifier - ]; + if (isSetAccessor(context)) { + if (!this.contextualSetAccessorTags) this.contextualSetAccessorTags = getJsDocTagsOfDeclarations(filter(this.declarations, isSetAccessor), checker); + if (length(this.contextualSetAccessorTags)) return this.contextualSetAccessorTags; + } + } + return this.getJsDocTags(checker); } - case 4 /* PromoteTypeOnly */ : - { - const { typeOnlyAliasDeclaration: typeOnlyAliasDeclaration } = fix; - const promotedDeclaration = promoteFromTypeOnly(changes, typeOnlyAliasDeclaration, compilerOptions, sourceFile, preferences); - return promotedDeclaration.kind === 273 /* ImportSpecifier */ ? [ - Diagnostics.Remove_type_from_import_of_0_from_1, - symbolName2, - getModuleSpecifierText(promotedDeclaration.parent.parent) - ] : [ - Diagnostics.Remove_type_from_import_declaration_from_0, - getModuleSpecifierText(promotedDeclaration) - ]; + }; + TokenObject = class extends TokenOrIdentifierObject { + constructor(kind, pos, end){ + super(pos, end); + this.kind = kind; } - default: - return Debug.assertNever(fix, `Unexpected fix kind ${fix.kind}`); - } - } - function getModuleSpecifierText(promotedDeclaration) { - var _a2, _b; - return promotedDeclaration.kind === 268 /* ImportEqualsDeclaration */ ? ((_b = tryCast((_a2 = tryCast(promotedDeclaration.moduleReference, isExternalModuleReference)) == null ? void 0 : _a2.expression, isStringLiteralLike)) == null ? void 0 : _b.text) || promotedDeclaration.moduleReference.getText() : cast(promotedDeclaration.parent.moduleSpecifier, isStringLiteral).text; - } - function promoteFromTypeOnly(changes, aliasDeclaration, compilerOptions, sourceFile, preferences) { - const convertExistingToTypeOnly = importNameElisionDisabled(compilerOptions); - switch(aliasDeclaration.kind){ - case 273 /* ImportSpecifier */ : - if (aliasDeclaration.isTypeOnly) { - const sortKind = ts_OrganizeImports_exports.detectImportSpecifierSorting(aliasDeclaration.parent.elements, preferences); - if (aliasDeclaration.parent.elements.length > 1 && sortKind) { - changes.delete(sourceFile, aliasDeclaration); - const newSpecifier = factory.updateImportSpecifier(aliasDeclaration, /*isTypeOnly*/ false, aliasDeclaration.propertyName, aliasDeclaration.name); - const comparer = ts_OrganizeImports_exports.getOrganizeImportsComparer(preferences, sortKind === 2 /* CaseInsensitive */ ); - const insertionIndex = ts_OrganizeImports_exports.getImportSpecifierInsertionIndex(aliasDeclaration.parent.elements, newSpecifier, comparer); - changes.insertImportSpecifierAtIndex(sourceFile, newSpecifier, aliasDeclaration.parent, insertionIndex); - } else changes.deleteRange(sourceFile, aliasDeclaration.getFirstToken()); - return aliasDeclaration; - } else { - Debug.assert(aliasDeclaration.parent.parent.isTypeOnly); - promoteImportClause(aliasDeclaration.parent.parent); - return aliasDeclaration.parent.parent; + }; + IdentifierObject = class extends TokenOrIdentifierObject { + constructor(_kind, pos, end){ + super(pos, end); + this.kind = 80 /* Identifier */ ; } - case 270 /* ImportClause */ : - promoteImportClause(aliasDeclaration); - return aliasDeclaration; - case 271 /* NamespaceImport */ : - promoteImportClause(aliasDeclaration.parent); - return aliasDeclaration.parent; - case 268 /* ImportEqualsDeclaration */ : - changes.deleteRange(sourceFile, aliasDeclaration.getChildAt(1)); - return aliasDeclaration; - default: - Debug.failBadSyntaxKind(aliasDeclaration); - } - function promoteImportClause(importClause) { - changes.delete(sourceFile, getTypeKeywordOfTypeOnlyImport(importClause, sourceFile)); - if (convertExistingToTypeOnly) { - const namedImports = tryCast(importClause.namedBindings, isNamedImports); - if (namedImports && namedImports.elements.length > 1) { - if (ts_OrganizeImports_exports.detectImportSpecifierSorting(namedImports.elements, preferences) && aliasDeclaration.kind === 273 /* ImportSpecifier */ && namedImports.elements.indexOf(aliasDeclaration) !== 0) { - changes.delete(sourceFile, aliasDeclaration); - changes.insertImportSpecifierAtIndex(sourceFile, aliasDeclaration, namedImports, 0); - } - for (const element of namedImports.elements)if (element !== aliasDeclaration && !element.isTypeOnly) changes.insertModifierBefore(sourceFile, 154 /* TypeKeyword */ , element); + get text() { + return idText(this); } - } - } - } - function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports, compilerOptions, preferences) { - var _a2; - if (clause.kind === 203 /* ObjectBindingPattern */ ) { - if (defaultImport) addElementToBindingPattern(clause, defaultImport.name, "default"); - for (const specifier of namedImports)addElementToBindingPattern(clause, specifier.name, /*propertyName*/ void 0); - return; - } - const promoteFromTypeOnly2 = clause.isTypeOnly && some([ - defaultImport, - ...namedImports - ], (i)=>(i == null ? void 0 : i.addAsTypeOnly) === 4 /* NotAllowed */ ); - const existingSpecifiers = clause.namedBindings && ((_a2 = tryCast(clause.namedBindings, isNamedImports)) == null ? void 0 : _a2.elements); - const convertExistingToTypeOnly = promoteFromTypeOnly2 && importNameElisionDisabled(compilerOptions); - if (defaultImport) { - Debug.assert(!clause.name, "Cannot add a default import to an import clause that already has one"); - changes.insertNodeAt(sourceFile, clause.getStart(sourceFile), factory.createIdentifier(defaultImport.name), { - suffix: ", " - }); - } - if (namedImports.length) { - let ignoreCaseForSorting; - if (typeof preferences.organizeImportsIgnoreCase === "boolean") ignoreCaseForSorting = preferences.organizeImportsIgnoreCase; - else if (existingSpecifiers) { - const targetImportSorting = ts_OrganizeImports_exports.detectImportSpecifierSorting(existingSpecifiers, preferences); - if (targetImportSorting !== 3 /* Both */ ) ignoreCaseForSorting = targetImportSorting === 2 /* CaseInsensitive */ ; - } - if (ignoreCaseForSorting === void 0) ignoreCaseForSorting = ts_OrganizeImports_exports.detectSorting(sourceFile, preferences) === 2 /* CaseInsensitive */ ; - const comparer = ts_OrganizeImports_exports.getOrganizeImportsComparer(preferences, ignoreCaseForSorting); - const newSpecifiers = stableSort(namedImports.map((namedImport)=>factory.createImportSpecifier((!clause.isTypeOnly || promoteFromTypeOnly2) && needsTypeOnly(namedImport), /*propertyName*/ void 0, factory.createIdentifier(namedImport.name))), (s1, s2)=>ts_OrganizeImports_exports.compareImportOrExportSpecifiers(s1, s2, comparer)); - const specifierSort = (existingSpecifiers == null ? void 0 : existingSpecifiers.length) && ts_OrganizeImports_exports.detectImportSpecifierSorting(existingSpecifiers, preferences); - if (specifierSort && !(ignoreCaseForSorting && specifierSort === 1 /* CaseSensitive */ )) for (const spec of newSpecifiers){ - const insertionIndex = convertExistingToTypeOnly && !spec.isTypeOnly ? 0 : ts_OrganizeImports_exports.getImportSpecifierInsertionIndex(existingSpecifiers, spec, comparer); - changes.insertImportSpecifierAtIndex(sourceFile, spec, clause.namedBindings, insertionIndex); - } - else if (existingSpecifiers == null ? void 0 : existingSpecifiers.length) for (const spec of newSpecifiers)changes.insertNodeInListAfter(sourceFile, last(existingSpecifiers), spec, existingSpecifiers); - else if (newSpecifiers.length) { - const namedImports2 = factory.createNamedImports(newSpecifiers); - if (clause.namedBindings) changes.replaceNode(sourceFile, clause.namedBindings, namedImports2); - else changes.insertNodeAfter(sourceFile, Debug.checkDefined(clause.name, "Import clause must have either named imports or a default import"), namedImports2); - } - } - if (promoteFromTypeOnly2) { - changes.delete(sourceFile, getTypeKeywordOfTypeOnlyImport(clause, sourceFile)); - if (convertExistingToTypeOnly && existingSpecifiers) for (const specifier of existingSpecifiers)changes.insertModifierBefore(sourceFile, 154 /* TypeKeyword */ , specifier); - } - function addElementToBindingPattern(bindingPattern, name, propertyName) { - const element = factory.createBindingElement(/*dotDotDotToken*/ void 0, propertyName, name); - if (bindingPattern.elements.length) changes.insertNodeInListAfter(sourceFile, last(bindingPattern.elements), element); - else changes.replaceNode(sourceFile, bindingPattern, factory.createObjectBindingPattern([ - element - ])); - } - } - function addNamespaceQualifier(changes, sourceFile, { namespacePrefix: namespacePrefix , usagePosition: usagePosition }) { - changes.insertText(sourceFile, usagePosition, namespacePrefix + "."); - } - function addImportType(changes, sourceFile, { moduleSpecifier: moduleSpecifier , usagePosition: position }, quotePreference) { - changes.insertText(sourceFile, position, getImportTypePrefix(moduleSpecifier, quotePreference)); - } - function getImportTypePrefix(moduleSpecifier, quotePreference) { - const quote2 = getQuoteFromPreference(quotePreference); - return `import(${quote2}${moduleSpecifier}${quote2}).`; - } - function needsTypeOnly({ addAsTypeOnly: addAsTypeOnly }) { - return addAsTypeOnly === 2 /* Required */ ; - } - function getNewImports(moduleSpecifier, quotePreference, defaultImport, namedImports, namespaceLikeImport, compilerOptions) { - const quotedModuleSpecifier = makeStringLiteral(moduleSpecifier, quotePreference); - let statements; - if (defaultImport !== void 0 || (namedImports == null ? void 0 : namedImports.length)) { - const topLevelTypeOnly = (!defaultImport || needsTypeOnly(defaultImport)) && every(namedImports, needsTypeOnly) || compilerOptions.verbatimModuleSyntax && (defaultImport == null ? void 0 : defaultImport.addAsTypeOnly) !== 4 /* NotAllowed */ && !some(namedImports, (i)=>i.addAsTypeOnly === 4 /* NotAllowed */ ); - statements = combine(statements, makeImport(defaultImport && factory.createIdentifier(defaultImport.name), namedImports == null ? void 0 : namedImports.map(({ addAsTypeOnly: addAsTypeOnly , name: name })=>factory.createImportSpecifier(!topLevelTypeOnly && addAsTypeOnly === 2 /* Required */ , /*propertyName*/ void 0, factory.createIdentifier(name))), moduleSpecifier, quotePreference, topLevelTypeOnly)); - } - if (namespaceLikeImport) { - const declaration = namespaceLikeImport.importKind === 3 /* CommonJS */ ? factory.createImportEqualsDeclaration(/*modifiers*/ void 0, needsTypeOnly(namespaceLikeImport), factory.createIdentifier(namespaceLikeImport.name), factory.createExternalModuleReference(quotedModuleSpecifier)) : factory.createImportDeclaration(/*modifiers*/ void 0, factory.createImportClause(needsTypeOnly(namespaceLikeImport), /*name*/ void 0, factory.createNamespaceImport(factory.createIdentifier(namespaceLikeImport.name))), quotedModuleSpecifier, /*assertClause*/ void 0); - statements = combine(statements, declaration); - } - return Debug.checkDefined(statements); - } - function getNewRequires(moduleSpecifier, quotePreference, defaultImport, namedImports, namespaceLikeImport) { - const quotedModuleSpecifier = makeStringLiteral(moduleSpecifier, quotePreference); - let statements; - if (defaultImport || (namedImports == null ? void 0 : namedImports.length)) { - const bindingElements = (namedImports == null ? void 0 : namedImports.map(({ name: name })=>factory.createBindingElement(/*dotDotDotToken*/ void 0, /*propertyName*/ void 0, name))) || []; - if (defaultImport) bindingElements.unshift(factory.createBindingElement(/*dotDotDotToken*/ void 0, "default", defaultImport.name)); - const declaration = createConstEqualsRequireDeclaration(factory.createObjectBindingPattern(bindingElements), quotedModuleSpecifier); - statements = combine(statements, declaration); - } - if (namespaceLikeImport) { - const declaration = createConstEqualsRequireDeclaration(namespaceLikeImport.name, quotedModuleSpecifier); - statements = combine(statements, declaration); - } - return Debug.checkDefined(statements); - } - function createConstEqualsRequireDeclaration(name, quotedModuleSpecifier) { - return factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ - factory.createVariableDeclaration(typeof name === "string" ? factory.createIdentifier(name) : name, /*exclamationToken*/ void 0, /*type*/ void 0, factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ void 0, [ - quotedModuleSpecifier - ])) - ], 2 /* Const */ )); - } - function symbolHasMeaning({ declarations: declarations }, meaning) { - return some(declarations, (decl)=>!!(getMeaningFromDeclaration(decl) & meaning)); - } - function moduleSymbolToValidIdentifier(moduleSymbol, target, forceCapitalize) { - return moduleSpecifierToValidIdentifier(removeFileExtension(stripQuotes(moduleSymbol.name)), target, forceCapitalize); - } - function moduleSpecifierToValidIdentifier(moduleSpecifier, target, forceCapitalize) { - const baseName = getBaseFileName(removeSuffix(moduleSpecifier, "/index")); - let res = ""; - let lastCharWasValid = true; - const firstCharCode = baseName.charCodeAt(0); - if (isIdentifierStart(firstCharCode, target)) { - res += String.fromCharCode(firstCharCode); - if (forceCapitalize) res = res.toUpperCase(); - } else lastCharWasValid = false; - for(let i = 1; i < baseName.length; i++){ - const ch = baseName.charCodeAt(i); - const isValid = isIdentifierPart(ch, target); - if (isValid) { - let char = String.fromCharCode(ch); - if (!lastCharWasValid) char = char.toUpperCase(); - res += char; - } - lastCharWasValid = isValid; - } - return !isStringANonContextualKeyword(res) ? res || "_" : `_${res}`; - } - var importFixName, importFixId, errorCodes17; - var init_importFixes = __esm({ - "src/services/codefixes/importFixes.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - importFixName = "import"; - importFixId = "fixMissingImport"; - errorCodes17 = [ - Diagnostics.Cannot_find_name_0.code, - Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, - Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, - Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, - Diagnostics.Cannot_find_namespace_0.code, - Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code, - Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code, - Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer.code, - Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type.code - ]; - registerCodeFix({ - errorCodes: errorCodes17, - getCodeActions (context) { - const { errorCode: errorCode , preferences: preferences , sourceFile: sourceFile , span: span , program: program } = context; - const info = getFixInfos(context, errorCode, span.start, /*useAutoImportProvider*/ true); - if (!info) return void 0; - return info.map(({ fix: fix , symbolName: symbolName2 , errorIdentifierText: errorIdentifierText })=>codeActionForFix(context, sourceFile, symbolName2, fix, /*includeSymbolNameInDescription*/ symbolName2 !== errorIdentifierText, program.getCompilerOptions(), preferences)); - }, - fixIds: [ - importFixId - ], - getAllCodeActions: (context)=>{ - const { sourceFile: sourceFile , program: program , preferences: preferences , host: host , cancellationToken: cancellationToken } = context; - const importAdder = createImportAdderWorker(sourceFile, program, /*useAutoImportProvider*/ true, preferences, host, cancellationToken); - eachDiagnostic(context, errorCodes17, (diag2)=>importAdder.addImportFromDiagnostic(diag2, context)); - return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, importAdder.writeFixes)); + }; + IdentifierObject.prototype.kind = 80 /* Identifier */ ; + PrivateIdentifierObject = class extends TokenOrIdentifierObject { + constructor(_kind, pos, end){ + super(pos, end); + this.kind = 81 /* PrivateIdentifier */ ; + } + get text() { + return idText(this); } - }); - } - }); - // src/services/codefixes/fixAddMissingConstraint.ts - function getInfo3(program, sourceFile, span) { - const diag2 = find(program.getSemanticDiagnostics(sourceFile), (diag3)=>diag3.start === span.start && diag3.length === span.length); - if (diag2 === void 0 || diag2.relatedInformation === void 0) return; - const related = find(diag2.relatedInformation, (related2)=>related2.code === Diagnostics.This_type_parameter_might_need_an_extends_0_constraint.code); - if (related === void 0 || related.file === void 0 || related.start === void 0 || related.length === void 0) return; - let declaration = findAncestorMatchingSpan(related.file, createTextSpan(related.start, related.length)); - if (declaration === void 0) return; - if (isIdentifier(declaration) && isTypeParameterDeclaration(declaration.parent)) declaration = declaration.parent; - if (isTypeParameterDeclaration(declaration)) { - if (isMappedTypeNode(declaration.parent)) return; - const token = getTokenAtPosition(sourceFile, span.start); - const checker = program.getTypeChecker(); - const constraint = tryGetConstraintType(checker, token) || tryGetConstraintFromDiagnosticMessage(related.messageText); - return { - constraint: constraint, - declaration: declaration, - token: token }; - } - return void 0; - } - function addMissingConstraint(changes, program, preferences, host, sourceFile, info) { - const { declaration: declaration , constraint: constraint } = info; - const checker = program.getTypeChecker(); - if (isString(constraint)) changes.insertText(sourceFile, declaration.name.end, ` extends ${constraint}`); - else { - const scriptTarget = getEmitScriptTarget(program.getCompilerOptions()); - const tracker = getNoopSymbolTrackerWithResolver({ - program: program, - host: host - }); - const importAdder = createImportAdder(sourceFile, program, preferences, host); - const typeNode = typeToAutoImportableTypeNode(checker, importAdder, constraint, /*contextNode*/ void 0, scriptTarget, /*flags*/ void 0, tracker); - if (typeNode) { - changes.replaceNode(sourceFile, declaration, factory.updateTypeParameterDeclaration(declaration, /*modifiers*/ void 0, declaration.name, typeNode, declaration.default)); - importAdder.writeFixes(changes); - } - } - } - function tryGetConstraintFromDiagnosticMessage(messageText) { - const [_, constraint] = flattenDiagnosticMessageText(messageText, "\n", 0).match(/`extends (.*)`/) || []; - return constraint; - } - function tryGetConstraintType(checker, node) { - if (isTypeNode(node.parent)) return checker.getTypeArgumentConstraint(node.parent); - const contextualType = isExpression(node) ? checker.getContextualType(node) : void 0; - return contextualType || checker.getTypeAtLocation(node); - } - var fixId16, errorCodes18; - var init_fixAddMissingConstraint = __esm({ - "src/services/codefixes/fixAddMissingConstraint.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId16 = "addMissingConstraint"; - errorCodes18 = [ - // We want errors this could be attached to: - // Diagnostics.This_type_parameter_probably_needs_an_extends_0_constraint - Diagnostics.Type_0_is_not_comparable_to_type_1.code, - Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code, - Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, - Diagnostics.Type_0_is_not_assignable_to_type_1.code, - Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, - Diagnostics.Property_0_is_incompatible_with_index_signature.code, - Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code, - Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code - ]; - registerCodeFix({ - errorCodes: errorCodes18, - getCodeActions (context) { - const { sourceFile: sourceFile , span: span , program: program , preferences: preferences , host: host } = context; - const info = getInfo3(program, sourceFile, span); - if (info === void 0) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addMissingConstraint(t, program, preferences, host, sourceFile, info)); - return [ - createCodeFixAction(fixId16, changes, Diagnostics.Add_extends_constraint, fixId16, Diagnostics.Add_extends_constraint_to_all_type_parameters) - ]; - }, - fixIds: [ - fixId16 - ], - getAllCodeActions: (context)=>{ - const { program: program , preferences: preferences , host: host } = context; - const seen = /* @__PURE__ */ new Map(); - return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes)=>{ - eachDiagnostic(context, errorCodes18, (diag2)=>{ - const info = getInfo3(program, diag2.file, createTextSpan(diag2.start, diag2.length)); - if (info) { - if (addToSeen(seen, getNodeId(info.declaration))) return addMissingConstraint(changes, program, preferences, host, diag2.file, info); - } - return void 0; - }); - })); + PrivateIdentifierObject.prototype.kind = 81 /* PrivateIdentifier */ ; + TypeObject = class { + constructor(checker, flags){ + this.checker = checker; + this.flags = flags; } - }); - } - }); - // src/services/codefixes/fixOverrideModifier.ts - function dispatchChanges(changeTracker, context, errorCode, pos) { - switch(errorCode){ - case Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code: - case Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code: - case Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code: - case Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code: - case Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code: - return doAddOverrideModifierChange(changeTracker, context.sourceFile, pos); - case Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code: - case Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code: - case Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code: - case Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code: - return doRemoveOverrideModifierChange(changeTracker, context.sourceFile, pos); - default: - Debug.fail("Unexpected error code: " + errorCode); - } - } - function doAddOverrideModifierChange(changeTracker, sourceFile, pos) { - const classElement = findContainerClassElementLike(sourceFile, pos); - if (isSourceFileJS(sourceFile)) { - changeTracker.addJSDocTags(sourceFile, classElement, [ - factory.createJSDocOverrideTag(factory.createIdentifier("override")) - ]); - return; - } - const modifiers = classElement.modifiers || emptyArray; - const staticModifier = find(modifiers, isStaticModifier); - const abstractModifier = find(modifiers, isAbstractModifier); - const accessibilityModifier = find(modifiers, (m)=>isAccessibilityModifier(m.kind)); - const lastDecorator = findLast(modifiers, isDecorator); - const modifierPos = abstractModifier ? abstractModifier.end : staticModifier ? staticModifier.end : accessibilityModifier ? accessibilityModifier.end : lastDecorator ? skipTrivia(sourceFile.text, lastDecorator.end) : classElement.getStart(sourceFile); - const options = accessibilityModifier || staticModifier || abstractModifier ? { - prefix: " " - } : { - suffix: " " - }; - changeTracker.insertModifierAt(sourceFile, modifierPos, 161 /* OverrideKeyword */ , options); + getFlags() { + return this.flags; + } + getSymbol() { + return this.symbol; + } + getProperties() { + return this.checker.getPropertiesOfType(this); + } + getProperty(propertyName) { + return this.checker.getPropertyOfType(this, propertyName); + } + getApparentProperties() { + return this.checker.getAugmentedPropertiesOfType(this); + } + getCallSignatures() { + return this.checker.getSignaturesOfType(this, 0 /* Call */ ); + } + getConstructSignatures() { + return this.checker.getSignaturesOfType(this, 1 /* Construct */ ); + } + getStringIndexType() { + return this.checker.getIndexTypeOfType(this, 0 /* String */ ); + } + getNumberIndexType() { + return this.checker.getIndexTypeOfType(this, 1 /* Number */ ); + } + getBaseTypes() { + return this.isClassOrInterface() ? this.checker.getBaseTypes(this) : void 0; + } + isNullableType() { + return this.checker.isNullableType(this); + } + getNonNullableType() { + return this.checker.getNonNullableType(this); + } + getNonOptionalType() { + return this.checker.getNonOptionalType(this); + } + getConstraint() { + return this.checker.getBaseConstraintOfType(this); + } + getDefault() { + return this.checker.getDefaultFromTypeParameter(this); + } + isUnion() { + return !!(this.flags & 1048576 /* Union */ ); + } + isIntersection() { + return !!(this.flags & 2097152 /* Intersection */ ); + } + isUnionOrIntersection() { + return !!(this.flags & 3145728 /* UnionOrIntersection */ ); + } + isLiteral() { + return !!(this.flags & 2432 /* BigIntLiteral */ ); + } + isStringLiteral() { + return !!(this.flags & 128 /* StringLiteral */ ); + } + isNumberLiteral() { + return !!(this.flags & 256 /* NumberLiteral */ ); + } + isTypeParameter() { + return !!(this.flags & 262144 /* TypeParameter */ ); + } + isClassOrInterface() { + return !!(getObjectFlags(this) & 3 /* ClassOrInterface */ ); + } + isClass() { + return !!(getObjectFlags(this) & 1 /* Class */ ); + } + isIndexType() { + return !!(this.flags & 4194304 /* Index */ ); + } + /** + * This polyfills `referenceType.typeArguments` for API consumers + */ get typeArguments() { + if (getObjectFlags(this) & 4 /* Reference */ ) return this.checker.getTypeArguments(this); + return void 0; + } + }; + SignatureObject = class { + // same + constructor(checker, flags){ + this.checker = checker; + this.flags = flags; + } + getDeclaration() { + return this.declaration; + } + getTypeParameters() { + return this.typeParameters; + } + getParameters() { + return this.parameters; + } + getReturnType() { + return this.checker.getReturnTypeOfSignature(this); + } + getTypeParameterAtPosition(pos) { + const type = this.checker.getParameterType(this, pos); + if (type.isIndexType() && isThisTypeParameter(type.type)) { + const constraint = type.type.getConstraint(); + if (constraint) return this.checker.getIndexType(constraint); + } + return type; + } + getDocumentationComment() { + return this.documentationComment || (this.documentationComment = getDocumentationComment(singleElementArray(this.declaration), this.checker)); + } + getJsDocTags() { + return this.jsDocTags || (this.jsDocTags = getJsDocTagsOfDeclarations(singleElementArray(this.declaration), this.checker)); + } + }; + SourceFileObject = class extends NodeObject { + constructor(kind, pos, end){ + super(kind, pos, end); + this.kind = 312 /* SourceFile */ ; + } + update(newText, textChangeRange) { + return updateSourceFile(this, newText, textChangeRange); + } + getLineAndCharacterOfPosition(position) { + return getLineAndCharacterOfPosition(this, position); + } + getLineStarts() { + return getLineStarts(this); + } + getPositionOfLineAndCharacter(line, character, allowEdits) { + return computePositionOfLineAndCharacter(getLineStarts(this), line, character, this.text, allowEdits); + } + getLineEndOfPosition(pos) { + const { line: line } = this.getLineAndCharacterOfPosition(pos); + const lineStarts = this.getLineStarts(); + let lastCharPos; + if (line + 1 >= lineStarts.length) lastCharPos = this.getEnd(); + if (!lastCharPos) lastCharPos = lineStarts[line + 1] - 1; + const fullText = this.getFullText(); + return fullText[lastCharPos] === "\n" && fullText[lastCharPos - 1] === "\r" ? lastCharPos - 1 : lastCharPos; + } + getNamedDeclarations() { + if (!this.namedDeclarations) this.namedDeclarations = this.computeNamedDeclarations(); + return this.namedDeclarations; + } + computeNamedDeclarations() { + const result = createMultiMap(); + this.forEachChild(visit); + return result; + function addDeclaration(declaration) { + const name = getDeclarationName(declaration); + if (name) result.add(name, declaration); + } + function getDeclarations(name) { + let declarations = result.get(name); + if (!declarations) result.set(name, declarations = []); + return declarations; + } + function getDeclarationName(declaration) { + const name = getNonAssignedNameOfDeclaration(declaration); + return name && (isComputedPropertyName(name) && isPropertyAccessExpression(name.expression) ? name.expression.name.text : isPropertyName(name) ? getNameFromPropertyName(name) : void 0); + } + function visit(node) { + switch(node.kind){ + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + const functionDeclaration = node; + const declarationName = getDeclarationName(functionDeclaration); + if (declarationName) { + const declarations = getDeclarations(declarationName); + const lastDeclaration = lastOrUndefined(declarations); + if (lastDeclaration && functionDeclaration.parent === lastDeclaration.parent && functionDeclaration.symbol === lastDeclaration.symbol) { + if (functionDeclaration.body && !lastDeclaration.body) declarations[declarations.length - 1] = functionDeclaration; + } else declarations.push(functionDeclaration); + } + forEachChild(node, visit); + break; + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 264 /* InterfaceDeclaration */ : + case 265 /* TypeAliasDeclaration */ : + case 266 /* EnumDeclaration */ : + case 267 /* ModuleDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : + case 281 /* ExportSpecifier */ : + case 276 /* ImportSpecifier */ : + case 273 /* ImportClause */ : + case 274 /* NamespaceImport */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 187 /* TypeLiteral */ : + addDeclaration(node); + forEachChild(node, visit); + break; + case 169 /* Parameter */ : + if (!hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */ )) break; + case 260 /* VariableDeclaration */ : + case 208 /* BindingElement */ : + { + const decl = node; + if (isBindingPattern(decl.name)) { + forEachChild(decl.name, visit); + break; + } + if (decl.initializer) visit(decl.initializer); + } + case 306 /* EnumMember */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : + addDeclaration(node); + break; + case 278 /* ExportDeclaration */ : + const exportDeclaration = node; + if (exportDeclaration.exportClause) { + if (isNamedExports(exportDeclaration.exportClause)) forEach(exportDeclaration.exportClause.elements, visit); + else visit(exportDeclaration.exportClause.name); + } + break; + case 272 /* ImportDeclaration */ : + const importClause = node.importClause; + if (importClause) { + if (importClause.name) addDeclaration(importClause.name); + if (importClause.namedBindings) { + if (importClause.namedBindings.kind === 274 /* NamespaceImport */ ) addDeclaration(importClause.namedBindings); + else forEach(importClause.namedBindings.elements, visit); + } + } + break; + case 226 /* BinaryExpression */ : + if (getAssignmentDeclarationKind(node) !== 0 /* None */ ) addDeclaration(node); + default: + forEachChild(node, visit); + } + } + } + }; + SourceMapSourceObject = class { + constructor(fileName, text, skipTrivia2){ + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia2; + } + getLineAndCharacterOfPosition(pos) { + return getLineAndCharacterOfPosition(this, pos); + } + }; + SyntaxTreeCache = class { + constructor(host){ + this.host = host; + } + getCurrentSourceFile(fileName) { + var _a, _b, _c, _d, _e, _f, _g, _h; + const scriptSnapshot = this.host.getScriptSnapshot(fileName); + if (!scriptSnapshot) throw new Error("Could not find file: '" + fileName + "'."); + const scriptKind = getScriptKind(fileName, this.host); + const version2 = this.host.getScriptVersion(fileName); + let sourceFile; + if (this.currentFileName !== fileName) { + const options = { + languageVersion: 99 /* Latest */ , + impliedNodeFormat: getImpliedNodeFormatForFile(toPath(fileName, this.host.getCurrentDirectory(), ((_c = (_b = (_a = this.host).getCompilerHost) == null ? void 0 : _b.call(_a)) == null ? void 0 : _c.getCanonicalFileName) || hostGetCanonicalFileName(this.host)), (_h = (_g = (_f = (_e = (_d = this.host).getCompilerHost) == null ? void 0 : _e.call(_d)) == null ? void 0 : _f.getModuleResolutionCache) == null ? void 0 : _g.call(_f)) == null ? void 0 : _h.getPackageJsonInfoCache(), this.host, this.host.getCompilationSettings()), + setExternalModuleIndicator: getSetExternalModuleIndicator(this.host.getCompilationSettings()) + }; + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, options, version2, /*setNodeParents*/ true, scriptKind); + } else if (this.currentFileVersion !== version2) { + const editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot); + sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version2, editRange); + } + if (sourceFile) { + this.currentFileVersion = version2; + this.currentFileName = fileName; + this.currentFileScriptSnapshot = scriptSnapshot; + this.currentSourceFile = sourceFile; + } + return this.currentSourceFile; + } + }; + NoopCancellationToken = { + isCancellationRequested: returnFalse, + throwIfCancellationRequested: noop + }; + CancellationTokenObject = class { + constructor(cancellationToken){ + this.cancellationToken = cancellationToken; + } + isCancellationRequested() { + return this.cancellationToken.isCancellationRequested(); + } + throwIfCancellationRequested() { + var _a; + if (this.isCancellationRequested()) { + (_a = tracing) == null || _a.instant(tracing.Phase.Session, "cancellationThrown", { + kind: "CancellationTokenObject" + }); + throw new OperationCanceledException(); + } + } + }; + ThrottledCancellationToken = class { + constructor(hostCancellationToken, throttleWaitMilliseconds = 20){ + this.hostCancellationToken = hostCancellationToken; + this.throttleWaitMilliseconds = throttleWaitMilliseconds; + // Store when we last tried to cancel. Checking cancellation can be expensive (as we have + // to marshall over to the host layer). So we only bother actually checking once enough + // time has passed. + this.lastCancellationCheckTime = 0; + } + isCancellationRequested() { + const time = timestamp(); + const duration = Math.abs(time - this.lastCancellationCheckTime); + if (duration >= this.throttleWaitMilliseconds) { + this.lastCancellationCheckTime = time; + return this.hostCancellationToken.isCancellationRequested(); + } + return false; + } + throwIfCancellationRequested() { + var _a; + if (this.isCancellationRequested()) { + (_a = tracing) == null || _a.instant(tracing.Phase.Session, "cancellationThrown", { + kind: "ThrottledCancellationToken" + }); + throw new OperationCanceledException(); + } + } + }; + invalidOperationsInPartialSemanticMode = [ + "getSemanticDiagnostics", + "getSuggestionDiagnostics", + "getCompilerOptionsDiagnostics", + "getSemanticClassifications", + "getEncodedSemanticClassifications", + "getCodeFixesAtPosition", + "getCombinedCodeFix", + "applyCodeActionCommand", + "organizeImports", + "getEditsForFileRename", + "getEmitOutput", + "getApplicableRefactors", + "getEditsForRefactor", + "prepareCallHierarchy", + "provideCallHierarchyIncomingCalls", + "provideCallHierarchyOutgoingCalls", + "provideInlayHints", + "getSupportedCodeFixes" + ]; + invalidOperationsInSyntacticMode = [ + ...invalidOperationsInPartialSemanticMode, + "getCompletionsAtPosition", + "getCompletionEntryDetails", + "getCompletionEntrySymbol", + "getSignatureHelpItems", + "getQuickInfoAtPosition", + "getDefinitionAtPosition", + "getDefinitionAndBoundSpan", + "getImplementationAtPosition", + "getTypeDefinitionAtPosition", + "getReferencesAtPosition", + "findReferences", + "getDocumentHighlights", + "getNavigateToItems", + "getRenameInfo", + "findRenameLocations", + "getApplicableRefactors" + ]; + setObjectAllocator(getServicesObjectAllocator()); + } + }); + // src/services/transform.ts + function transform(source, transformers, compilerOptions) { + const diagnostics = []; + compilerOptions = fixupCompilerOptions(compilerOptions, diagnostics); + const nodes = isArray(source) ? source : [ + source + ]; + const result = transformNodes(/*resolver*/ void 0, /*host*/ void 0, factory, compilerOptions, nodes, transformers, /*allowDtsFiles*/ true); + result.diagnostics = concatenate(result.diagnostics, diagnostics); + return result; } - function doRemoveOverrideModifierChange(changeTracker, sourceFile, pos) { - const classElement = findContainerClassElementLike(sourceFile, pos); - if (isSourceFileJS(sourceFile)) { - changeTracker.filterJSDocTags(sourceFile, classElement, not(isJSDocOverrideTag)); - return; + var init_transform = __esm({ + "src/services/transform.ts" () { + "use strict"; + init_ts4(); } - const overrideModifier = find(classElement.modifiers, isOverrideModifier); - Debug.assertIsDefined(overrideModifier); - changeTracker.deleteModifier(sourceFile, overrideModifier); + }); + // src/services/shims.ts + function logInternalError(logger, err) { + if (logger) logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message); } - function isClassElementLikeHasJSDoc(node) { - switch(node.kind){ - case 173 /* Constructor */ : - case 169 /* PropertyDeclaration */ : - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - return true; - case 166 /* Parameter */ : - return isParameterPropertyDeclaration(node, node.parent); - default: - return false; + function simpleForwardCall(logger, actionDescription2, action, logPerformance) { + let start; + if (logPerformance) { + logger.log(actionDescription2); + start = timestamp(); + } + const result = action(); + if (logPerformance) { + const end = timestamp(); + logger.log(`${actionDescription2} completed in ${end - start} msec`); + if (isString(result)) { + let str = result; + if (str.length > 128) str = str.substring(0, 128) + "..."; + logger.log(` result.length=${str.length}, result='${JSON.stringify(str)}'`); + } } + return result; } - function findContainerClassElementLike(sourceFile, pos) { - const token = getTokenAtPosition(sourceFile, pos); - const classElement = findAncestor(token, (node)=>{ - if (isClassLike(node)) return "quit"; - return isClassElementLikeHasJSDoc(node); - }); - Debug.assert(classElement && isClassElementLikeHasJSDoc(classElement)); - return classElement; + function forwardJSONCall(logger, actionDescription2, action, logPerformance) { + return forwardCall(logger, actionDescription2, /*returnJson*/ true, action, logPerformance); } - var fixName, fixAddOverrideId, fixRemoveOverrideId, errorCodes19, errorCodeFixIdMap; - var init_fixOverrideModifier = __esm({ - "src/services/codefixes/fixOverrideModifier.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixName = "fixOverrideModifier"; - fixAddOverrideId = "fixAddOverrideModifier"; - fixRemoveOverrideId = "fixRemoveOverrideModifier"; - errorCodes19 = [ - Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code, - Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code, - Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code, - Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code, - Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code, - Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code, - Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code, - Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code, - Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code - ]; - errorCodeFixIdMap = { - // case #1: - [Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code]: { - descriptions: Diagnostics.Add_override_modifier, - fixId: fixAddOverrideId, - fixAllDescriptions: Diagnostics.Add_all_missing_override_modifiers - }, - [Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code]: { - descriptions: Diagnostics.Add_override_modifier, - fixId: fixAddOverrideId, - fixAllDescriptions: Diagnostics.Add_all_missing_override_modifiers - }, - // case #2: - [Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code]: { - descriptions: Diagnostics.Remove_override_modifier, - fixId: fixRemoveOverrideId, - fixAllDescriptions: Diagnostics.Remove_all_unnecessary_override_modifiers - }, - [Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code]: { - descriptions: Diagnostics.Remove_override_modifier, - fixId: fixRemoveOverrideId, - fixAllDescriptions: Diagnostics.Remove_override_modifier - }, - // case #3: - [Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code]: { - descriptions: Diagnostics.Add_override_modifier, - fixId: fixAddOverrideId, - fixAllDescriptions: Diagnostics.Add_all_missing_override_modifiers - }, - [Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code]: { - descriptions: Diagnostics.Add_override_modifier, - fixId: fixAddOverrideId, - fixAllDescriptions: Diagnostics.Add_all_missing_override_modifiers - }, - // case #4: - [Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code]: { - descriptions: Diagnostics.Add_override_modifier, - fixId: fixAddOverrideId, - fixAllDescriptions: Diagnostics.Remove_all_unnecessary_override_modifiers - }, - // case #5: - [Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code]: { - descriptions: Diagnostics.Remove_override_modifier, - fixId: fixRemoveOverrideId, - fixAllDescriptions: Diagnostics.Remove_all_unnecessary_override_modifiers - }, - [Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code]: { - descriptions: Diagnostics.Remove_override_modifier, - fixId: fixRemoveOverrideId, - fixAllDescriptions: Diagnostics.Remove_all_unnecessary_override_modifiers - } - }; - registerCodeFix({ - errorCodes: errorCodes19, - getCodeActions: function getCodeActionsToFixOverrideModifierIssues(context) { - const { errorCode: errorCode , span: span } = context; - const info = errorCodeFixIdMap[errorCode]; - if (!info) return emptyArray; - const { descriptions: descriptions , fixId: fixId51 , fixAllDescriptions: fixAllDescriptions } = info; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2)=>dispatchChanges(changes2, context, errorCode, span.start)); - return [ - createCodeFixActionMaybeFixAll(fixName, changes, descriptions, fixId51, fixAllDescriptions) - ]; - }, - fixIds: [ - fixName, - fixAddOverrideId, - fixRemoveOverrideId - ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes19, (changes, diag2)=>{ - const { code: code , start: start } = diag2; - const info = errorCodeFixIdMap[code]; - if (!info || info.fixId !== context.fixId) return; - dispatchChanges(changes, context, code, start); - }) + function forwardCall(logger, actionDescription2, returnJson, action, logPerformance) { + try { + const result = simpleForwardCall(logger, actionDescription2, action, logPerformance); + return returnJson ? JSON.stringify({ + result: result + }) : result; + } catch (err) { + if (err instanceof OperationCanceledException) return JSON.stringify({ + canceled: true + }); + logInternalError(logger, err); + err.description = actionDescription2; + return JSON.stringify({ + error: err }); } - }); - // src/services/codefixes/fixNoPropertyAccessFromIndexSignature.ts - function doChange6(changes, sourceFile, node, preferences) { - const quotePreference = getQuotePreference(sourceFile, preferences); - const argumentsExpression = factory.createStringLiteral(node.name.text, quotePreference === 0 /* Single */ ); - changes.replaceNode(sourceFile, node, isPropertyAccessChain(node) ? factory.createElementAccessChain(node.expression, node.questionDotToken, argumentsExpression) : factory.createElementAccessExpression(node.expression, argumentsExpression)); } - function getPropertyAccessExpression(sourceFile, pos) { - return cast(getTokenAtPosition(sourceFile, pos).parent, isPropertyAccessExpression); + function realizeDiagnostics(diagnostics, newLine) { + return diagnostics.map((d)=>realizeDiagnostic(d, newLine)); } - var fixId17, errorCodes20; - var init_fixNoPropertyAccessFromIndexSignature = __esm({ - "src/services/codefixes/fixNoPropertyAccessFromIndexSignature.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId17 = "fixNoPropertyAccessFromIndexSignature"; - errorCodes20 = [ - Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0.code - ]; - registerCodeFix({ - errorCodes: errorCodes20, - fixIds: [ - fixId17 - ], - getCodeActions (context) { - const { sourceFile: sourceFile , span: span , preferences: preferences } = context; - const property = getPropertyAccessExpression(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange6(t, context.sourceFile, property, preferences)); - return [ - createCodeFixAction(fixId17, changes, [ - Diagnostics.Use_element_access_for_0, - property.name.text - ], fixId17, Diagnostics.Use_element_access_for_all_undeclared_properties) - ]; - }, - getAllCodeActions: (context)=>codeFixAll(context, errorCodes20, (changes, diag2)=>doChange6(changes, diag2.file, getPropertyAccessExpression(diag2.file, diag2.start), context.preferences)) - }); - } - }); - // src/services/codefixes/fixImplicitThis.ts - function doChange7(changes, sourceFile, pos, checker) { - const token = getTokenAtPosition(sourceFile, pos); - if (!isThis(token)) return void 0; - const fn = getThisContainer(token, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false); - if (!isFunctionDeclaration(fn) && !isFunctionExpression(fn)) return void 0; - if (!isSourceFile(getThisContainer(fn, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false))) { - const fnKeyword = Debug.checkDefined(findChildOfKind(fn, 98 /* FunctionKeyword */ , sourceFile)); - const { name: name } = fn; - const body = Debug.checkDefined(fn.body); - if (isFunctionExpression(fn)) { - if (name && ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(name, checker, sourceFile, body)) return void 0; - changes.delete(sourceFile, fnKeyword); - if (name) changes.delete(sourceFile, name); - changes.insertText(sourceFile, body.pos, " =>"); - return [ - Diagnostics.Convert_function_expression_0_to_arrow_function, - name ? name.text : ANONYMOUS - ]; - } else { - changes.replaceNode(sourceFile, fnKeyword, factory.createToken(85 /* ConstKeyword */ )); - changes.insertText(sourceFile, name.end, " = "); - changes.insertText(sourceFile, body.pos, " =>"); - return [ - Diagnostics.Convert_function_declaration_0_to_arrow_function, - name.text - ]; - } - } - } - var fixId18, errorCodes21; - var init_fixImplicitThis = __esm({ - "src/services/codefixes/fixImplicitThis.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId18 = "fixImplicitThis"; - errorCodes21 = [ - Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code - ]; - registerCodeFix({ - errorCodes: errorCodes21, - getCodeActions: function getCodeActionsToFixImplicitThis(context) { - const { sourceFile: sourceFile , program: program , span: span } = context; - let diagnostic; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>{ - diagnostic = doChange7(t, sourceFile, span.start, program.getTypeChecker()); - }); - return diagnostic ? [ - createCodeFixAction(fixId18, changes, diagnostic, fixId18, Diagnostics.Fix_all_implicit_this_errors) - ] : emptyArray; - }, - fixIds: [ - fixId18 - ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes21, (changes, diag2)=>{ - doChange7(changes, diag2.file, diag2.start, context.program.getTypeChecker()); - }) - }); - } - }); - // src/services/codefixes/fixImportNonExportedMember.ts - function getInfo4(sourceFile, pos, program) { - var _a2; - const token = getTokenAtPosition(sourceFile, pos); - if (isIdentifier(token)) { - const importDeclaration = findAncestor(token, isImportDeclaration); - if (importDeclaration === void 0) return void 0; - const moduleSpecifier = isStringLiteral(importDeclaration.moduleSpecifier) ? importDeclaration.moduleSpecifier.text : void 0; - if (moduleSpecifier === void 0) return void 0; - const resolvedModule = getResolvedModule(sourceFile, moduleSpecifier, /*mode*/ void 0); - if (resolvedModule === void 0) return void 0; - const moduleSourceFile = program.getSourceFile(resolvedModule.resolvedFileName); - if (moduleSourceFile === void 0 || isSourceFileFromLibrary(program, moduleSourceFile)) return void 0; - const moduleSymbol = moduleSourceFile.symbol; - const locals = (_a2 = tryCast(moduleSymbol.valueDeclaration, canHaveLocals)) == null ? void 0 : _a2.locals; - if (locals === void 0) return void 0; - const localSymbol = locals.get(token.escapedText); - if (localSymbol === void 0) return void 0; - const node = getNodeOfSymbol(localSymbol); - if (node === void 0) return void 0; - const exportName = { - node: token, - isTypeOnly: isTypeDeclaration(node) - }; - return { - exportName: exportName, - node: node, - moduleSourceFile: moduleSourceFile, - moduleSpecifier: moduleSpecifier - }; - } - return void 0; - } - function doChange8(changes, program, { exportName: exportName , node: node , moduleSourceFile: moduleSourceFile }) { - const exportDeclaration = tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly); - if (exportDeclaration) updateExport(changes, program, moduleSourceFile, exportDeclaration, [ - exportName - ]); - else if (canHaveExportModifier(node)) changes.insertExportModifier(moduleSourceFile, node); - else createExport(changes, program, moduleSourceFile, [ - exportName - ]); - } - function doChanges(changes, program, sourceFile, moduleExports, node) { - if (length(moduleExports)) { - if (node) updateExport(changes, program, sourceFile, node, moduleExports); - else createExport(changes, program, sourceFile, moduleExports); - } - } - function tryGetExportDeclaration(sourceFile, isTypeOnly) { - const predicate = (node)=>isExportDeclaration(node) && (isTypeOnly && node.isTypeOnly || !node.isTypeOnly); - return findLast(sourceFile.statements, predicate); - } - function updateExport(changes, program, sourceFile, node, names) { - const namedExports = node.exportClause && isNamedExports(node.exportClause) ? node.exportClause.elements : factory.createNodeArray([]); - const allowTypeModifier = !node.isTypeOnly && !!(getIsolatedModules(program.getCompilerOptions()) || find(namedExports, (e)=>e.isTypeOnly)); - changes.replaceNode(sourceFile, node, factory.updateExportDeclaration(node, node.modifiers, node.isTypeOnly, factory.createNamedExports(factory.createNodeArray([ - ...namedExports, - ...createExportSpecifiers(names, allowTypeModifier) - ], /*hasTrailingComma*/ namedExports.hasTrailingComma)), node.moduleSpecifier, node.assertClause)); - } - function createExport(changes, program, sourceFile, names) { - changes.insertNodeAtEndOfScope(sourceFile, sourceFile, factory.createExportDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, factory.createNamedExports(createExportSpecifiers(names, /*allowTypeModifier*/ getIsolatedModules(program.getCompilerOptions()))), /*moduleSpecifier*/ void 0, /*assertClause*/ void 0)); - } - function createExportSpecifiers(names, allowTypeModifier) { - return factory.createNodeArray(map(names, (n)=>factory.createExportSpecifier(allowTypeModifier && n.isTypeOnly, /*propertyName*/ void 0, n.node))); + function realizeDiagnostic(diagnostic, newLine) { + return { + message: flattenDiagnosticMessageText(diagnostic.messageText, newLine), + start: diagnostic.start, + // TODO: GH#18217 + length: diagnostic.length, + // TODO: GH#18217 + category: diagnosticCategoryName(diagnostic), + code: diagnostic.code, + reportsUnnecessary: diagnostic.reportsUnnecessary, + reportsDeprecated: diagnostic.reportsDeprecated + }; } - function getNodeOfSymbol(symbol) { - if (symbol.valueDeclaration === void 0) return firstOrUndefined(symbol.declarations); - const declaration = symbol.valueDeclaration; - const variableStatement = isVariableDeclaration(declaration) ? tryCast(declaration.parent.parent, isVariableStatement) : void 0; - return variableStatement && length(variableStatement.declarationList.declarations) === 1 ? variableStatement : declaration; + function convertClassifications(classifications) { + return { + spans: classifications.spans.join(","), + endOfLineState: classifications.endOfLineState + }; } - var fixId19, errorCodes22; - var init_fixImportNonExportedMember = __esm({ - "src/services/codefixes/fixImportNonExportedMember.ts" () { + var debugObjectHost, ScriptSnapshotShimAdapter, LanguageServiceShimHostAdapter, CoreServicesShimHostAdapter, ShimBase, LanguageServiceShimObject, ClassifierShimObject, CoreServicesShimObject, TypeScriptServicesFactory; + var init_shims = __esm({ + "src/services/shims.ts" () { "use strict"; init_ts4(); - init_ts_codefix(); - fixId19 = "fixImportNonExportedMember"; - errorCodes22 = [ - Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported.code - ]; - registerCodeFix({ - errorCodes: errorCodes22, - fixIds: [ - fixId19 - ], - getCodeActions (context) { - const { sourceFile: sourceFile , span: span , program: program } = context; - const info = getInfo4(sourceFile, span.start, program); - if (info === void 0) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange8(t, program, info)); - return [ - createCodeFixAction(fixId19, changes, [ - Diagnostics.Export_0_from_module_1, - info.exportName.node.text, - info.moduleSpecifier - ], fixId19, Diagnostics.Export_all_referenced_locals) - ]; - }, - getAllCodeActions (context) { - const { program: program } = context; - return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes)=>{ - const exports = /* @__PURE__ */ new Map(); - eachDiagnostic(context, errorCodes22, (diag2)=>{ - const info = getInfo4(diag2.file, diag2.start, program); - if (info === void 0) return void 0; - const { exportName: exportName , node: node , moduleSourceFile: moduleSourceFile } = info; - if (tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly) === void 0 && canHaveExportModifier(node)) changes.insertExportModifier(moduleSourceFile, node); - else { - const moduleExports = exports.get(moduleSourceFile) || { - typeOnlyExports: [], - exports: [] - }; - if (exportName.isTypeOnly) moduleExports.typeOnlyExports.push(exportName); - else moduleExports.exports.push(exportName); - exports.set(moduleSourceFile, moduleExports); - } - }); - exports.forEach((moduleExports, moduleSourceFile)=>{ - const exportDeclaration = tryGetExportDeclaration(moduleSourceFile, /*isTypeOnly*/ true); - if (exportDeclaration && exportDeclaration.isTypeOnly) { - doChanges(changes, program, moduleSourceFile, moduleExports.typeOnlyExports, exportDeclaration); - doChanges(changes, program, moduleSourceFile, moduleExports.exports, tryGetExportDeclaration(moduleSourceFile, /*isTypeOnly*/ false)); - } else doChanges(changes, program, moduleSourceFile, [ - ...moduleExports.exports, - ...moduleExports.typeOnlyExports - ], exportDeclaration); + debugObjectHost = function() { + return this; + }(); + ScriptSnapshotShimAdapter = class { + constructor(scriptSnapshotShim){ + this.scriptSnapshotShim = scriptSnapshotShim; + } + getText(start, end) { + return this.scriptSnapshotShim.getText(start, end); + } + getLength() { + return this.scriptSnapshotShim.getLength(); + } + getChangeRange(oldSnapshot) { + const oldSnapshotShim = oldSnapshot; + const encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim); + if (encoded === null) return null; + const decoded = JSON.parse(encoded); + return createTextChangeRange(createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength); + } + dispose() { + if ("dispose" in this.scriptSnapshotShim) this.scriptSnapshotShim.dispose(); + } + }; + LanguageServiceShimHostAdapter = class { + constructor(shimHost){ + this.shimHost = shimHost; + this.loggingEnabled = false; + this.tracingEnabled = false; + if ("getModuleResolutionsForFile" in this.shimHost) this.resolveModuleNames = (moduleNames, containingFile)=>{ + const resolutionsInFile = JSON.parse(this.shimHost.getModuleResolutionsForFile(containingFile)); + return map(moduleNames, (name)=>{ + const result = getProperty(resolutionsInFile, name); + return result ? { + resolvedFileName: result, + extension: extensionFromPath(result), + isExternalLibraryImport: false + } : void 0; }); - })); + }; + if ("directoryExists" in this.shimHost) this.directoryExists = (directoryName)=>this.shimHost.directoryExists(directoryName); + if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) this.resolveTypeReferenceDirectives = (typeDirectiveNames, containingFile)=>{ + const typeDirectivesForFile = JSON.parse(this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); + return map(typeDirectiveNames, (name)=>getProperty(typeDirectivesForFile, isString(name) ? name : toFileNameLowerCase(name.fileName))); + }; + } + log(s) { + if (this.loggingEnabled) this.shimHost.log(s); + } + trace(s) { + if (this.tracingEnabled) this.shimHost.trace(s); + } + error(s) { + this.shimHost.error(s); + } + getProjectVersion() { + if (!this.shimHost.getProjectVersion) return void 0; + return this.shimHost.getProjectVersion(); + } + getTypeRootsVersion() { + if (!this.shimHost.getTypeRootsVersion) return 0; + return this.shimHost.getTypeRootsVersion(); + } + useCaseSensitiveFileNames() { + return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; + } + getCompilationSettings() { + const settingsJson = this.shimHost.getCompilationSettings(); + if (settingsJson === null || settingsJson === "") throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings"); + const compilerOptions = JSON.parse(settingsJson); + compilerOptions.allowNonTsExtensions = true; + return compilerOptions; + } + getScriptFileNames() { + const encoded = this.shimHost.getScriptFileNames(); + return JSON.parse(encoded); + } + getScriptSnapshot(fileName) { + const scriptSnapshot = this.shimHost.getScriptSnapshot(fileName); + return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot); + } + getScriptKind(fileName) { + if ("getScriptKind" in this.shimHost) return this.shimHost.getScriptKind(fileName); + else return 0 /* Unknown */ ; + } + getScriptVersion(fileName) { + return this.shimHost.getScriptVersion(fileName); + } + getLocalizedDiagnosticMessages() { + const diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages(); + if (diagnosticMessagesJson === null || diagnosticMessagesJson === "") return null; + try { + return JSON.parse(diagnosticMessagesJson); + } catch (e) { + this.log(e.description || "diagnosticMessages.generated.json has invalid JSON format"); + return null; + } + } + getCancellationToken() { + const hostCancellationToken = this.shimHost.getCancellationToken(); + return new ThrottledCancellationToken(hostCancellationToken); + } + getCurrentDirectory() { + return this.shimHost.getCurrentDirectory(); + } + getDirectories(path) { + return JSON.parse(this.shimHost.getDirectories(path)); + } + getDefaultLibFileName(options) { + return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); + } + readDirectory(path, extensions, exclude, include, depth) { + const pattern = getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); + } + readFile(path, encoding) { + return this.shimHost.readFile(path, encoding); + } + fileExists(path) { + return this.shimHost.fileExists(path); } - }); - } - }); - // src/services/codefixes/fixIncorrectNamedTupleSyntax.ts - function getNamedTupleMember(sourceFile, pos) { - const token = getTokenAtPosition(sourceFile, pos); - return findAncestor(token, (t)=>t.kind === 199 /* NamedTupleMember */ ); - } - function doChange9(changes, sourceFile, namedTupleMember) { - if (!namedTupleMember) return; - let unwrappedType = namedTupleMember.type; - let sawOptional = false; - let sawRest = false; - while(unwrappedType.kind === 187 /* OptionalType */ || unwrappedType.kind === 188 /* RestType */ || unwrappedType.kind === 193 /* ParenthesizedType */ ){ - if (unwrappedType.kind === 187 /* OptionalType */ ) sawOptional = true; - else if (unwrappedType.kind === 188 /* RestType */ ) sawRest = true; - unwrappedType = unwrappedType.type; - } - const updated = factory.updateNamedTupleMember(namedTupleMember, namedTupleMember.dotDotDotToken || (sawRest ? factory.createToken(25 /* DotDotDotToken */ ) : void 0), namedTupleMember.name, namedTupleMember.questionToken || (sawOptional ? factory.createToken(57 /* QuestionToken */ ) : void 0), unwrappedType); - if (updated === namedTupleMember) return; - changes.replaceNode(sourceFile, namedTupleMember, updated); - } - var fixId20, errorCodes23; - var init_fixIncorrectNamedTupleSyntax = __esm({ - "src/services/codefixes/fixIncorrectNamedTupleSyntax.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId20 = "fixIncorrectNamedTupleSyntax"; - errorCodes23 = [ - Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type.code, - Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type.code - ]; - registerCodeFix({ - errorCodes: errorCodes23, - getCodeActions: function getCodeActionsToFixIncorrectNamedTupleSyntax(context) { - const { sourceFile: sourceFile , span: span } = context; - const namedTupleMember = getNamedTupleMember(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange9(t, sourceFile, namedTupleMember)); - return [ - createCodeFixAction(fixId20, changes, Diagnostics.Move_labeled_tuple_element_modifiers_to_labels, fixId20, Diagnostics.Move_labeled_tuple_element_modifiers_to_labels) - ]; - }, - fixIds: [ - fixId20 - ] - }); - } - }); - // src/services/codefixes/fixSpelling.ts - function getInfo5(sourceFile, pos, context, errorCode) { - const node = getTokenAtPosition(sourceFile, pos); - const parent2 = node.parent; - if ((errorCode === Diagnostics.No_overload_matches_this_call.code || errorCode === Diagnostics.Type_0_is_not_assignable_to_type_1.code) && !isJsxAttribute(parent2)) return void 0; - const checker = context.program.getTypeChecker(); - let suggestedSymbol; - if (isPropertyAccessExpression(parent2) && parent2.name === node) { - Debug.assert(isMemberName(node), "Expected an identifier for spelling (property access)"); - let containingType = checker.getTypeAtLocation(parent2.expression); - if (parent2.flags & 32 /* OptionalChain */ ) containingType = checker.getNonNullableType(containingType); - suggestedSymbol = checker.getSuggestedSymbolForNonexistentProperty(node, containingType); - } else if (isBinaryExpression(parent2) && parent2.operatorToken.kind === 101 /* InKeyword */ && parent2.left === node && isPrivateIdentifier(node)) { - const receiverType = checker.getTypeAtLocation(parent2.right); - suggestedSymbol = checker.getSuggestedSymbolForNonexistentProperty(node, receiverType); - } else if (isQualifiedName(parent2) && parent2.right === node) { - const symbol = checker.getSymbolAtLocation(parent2.left); - if (symbol && symbol.flags & 1536 /* Module */ ) suggestedSymbol = checker.getSuggestedSymbolForNonexistentModule(parent2.right, symbol); - } else if (isImportSpecifier(parent2) && parent2.name === node) { - Debug.assertNode(node, isIdentifier, "Expected an identifier for spelling (import)"); - const importDeclaration = findAncestor(node, isImportDeclaration); - const resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration); - if (resolvedSourceFile && resolvedSourceFile.symbol) suggestedSymbol = checker.getSuggestedSymbolForNonexistentModule(node, resolvedSourceFile.symbol); - } else if (isJsxAttribute(parent2) && parent2.name === node) { - Debug.assertNode(node, isIdentifier, "Expected an identifier for JSX attribute"); - const tag = findAncestor(node, isJsxOpeningLikeElement); - const props = checker.getContextualTypeForArgumentAtIndex(tag, 0); - suggestedSymbol = checker.getSuggestedSymbolForNonexistentJSXAttribute(node, props); - } else if (hasSyntacticModifier(parent2, 16384 /* Override */ ) && isClassElement(parent2) && parent2.name === node) { - const baseDeclaration = findAncestor(node, isClassLike); - const baseTypeNode = baseDeclaration ? getEffectiveBaseTypeNode(baseDeclaration) : void 0; - const baseType = baseTypeNode ? checker.getTypeAtLocation(baseTypeNode) : void 0; - if (baseType) suggestedSymbol = checker.getSuggestedSymbolForNonexistentClassMember(getTextOfNode(node), baseType); - } else { - const meaning = getMeaningFromLocation(node); - const name = getTextOfNode(node); - Debug.assert(name !== void 0, "name should be defined"); - suggestedSymbol = checker.getSuggestedSymbolForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); - } - return suggestedSymbol === void 0 ? void 0 : { - node: node, - suggestedSymbol: suggestedSymbol - }; - } - function doChange10(changes, sourceFile, node, suggestedSymbol, target) { - const suggestion = symbolName(suggestedSymbol); - if (!isIdentifierText(suggestion, target) && isPropertyAccessExpression(node.parent)) { - const valDecl = suggestedSymbol.valueDeclaration; - if (valDecl && isNamedDeclaration(valDecl) && isPrivateIdentifier(valDecl.name)) changes.replaceNode(sourceFile, node, factory.createIdentifier(suggestion)); - else changes.replaceNode(sourceFile, node.parent, factory.createElementAccessExpression(node.parent.expression, factory.createStringLiteral(suggestion))); - } else changes.replaceNode(sourceFile, node, factory.createIdentifier(suggestion)); - } - function convertSemanticMeaningToSymbolFlags(meaning) { - let flags = 0; - if (meaning & 4 /* Namespace */ ) flags |= 1920 /* Namespace */ ; - if (meaning & 2 /* Type */ ) flags |= 788968 /* Type */ ; - if (meaning & 1 /* Value */ ) flags |= 111551 /* Value */ ; - return flags; - } - function getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration) { - if (!importDeclaration || !isStringLiteralLike(importDeclaration.moduleSpecifier)) return void 0; - const resolvedModule = getResolvedModule(sourceFile, importDeclaration.moduleSpecifier.text, getModeForUsageLocation(sourceFile, importDeclaration.moduleSpecifier)); - if (!resolvedModule) return void 0; - return context.program.getSourceFile(resolvedModule.resolvedFileName); - } - var fixId21, errorCodes24; - var init_fixSpelling = __esm({ - "src/services/codefixes/fixSpelling.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId21 = "fixSpelling"; - errorCodes24 = [ - Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, - Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code, - Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, - Diagnostics.Could_not_find_name_0_Did_you_mean_1.code, - Diagnostics.Cannot_find_namespace_0_Did_you_mean_1.code, - Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, - Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, - Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2.code, - Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1.code, - Diagnostics.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.code, - // for JSX class components - Diagnostics.No_overload_matches_this_call.code, - // for JSX FC - Diagnostics.Type_0_is_not_assignable_to_type_1.code - ]; - registerCodeFix({ - errorCodes: errorCodes24, - getCodeActions (context) { - const { sourceFile: sourceFile , errorCode: errorCode } = context; - const info = getInfo5(sourceFile, context.span.start, context, errorCode); - if (!info) return void 0; - const { node: node , suggestedSymbol: suggestedSymbol } = info; - const target = getEmitScriptTarget(context.host.getCompilationSettings()); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange10(t, sourceFile, node, suggestedSymbol, target)); - return [ - createCodeFixAction("spelling", changes, [ - Diagnostics.Change_spelling_to_0, - symbolName(suggestedSymbol) - ], fixId21, Diagnostics.Fix_all_detected_spelling_errors) - ]; - }, - fixIds: [ - fixId21 - ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes24, (changes, diag2)=>{ - const info = getInfo5(diag2.file, diag2.start, context, diag2.code); - const target = getEmitScriptTarget(context.host.getCompilationSettings()); - if (info) doChange10(changes, context.sourceFile, info.node, info.suggestedSymbol, target); - }) - }); - } - }); - // src/services/codefixes/returnValueCorrect.ts - function createObjectTypeFromLabeledExpression(checker, label, expression) { - const member = checker.createSymbol(4 /* Property */ , label.escapedText); - member.links.type = checker.getTypeAtLocation(expression); - const members = createSymbolTable([ - member - ]); - return checker.createAnonymousType(/*symbol*/ void 0, members, [], [], []); - } - function getFixInfo(checker, declaration, expectType, isFunctionType) { - if (!declaration.body || !isBlock(declaration.body) || length(declaration.body.statements) !== 1) return void 0; - const firstStatement = first(declaration.body.statements); - if (isExpressionStatement(firstStatement) && checkFixedAssignableTo(checker, declaration, checker.getTypeAtLocation(firstStatement.expression), expectType, isFunctionType)) return { - declaration: declaration, - kind: 0 /* MissingReturnStatement */ , - expression: firstStatement.expression, - statement: firstStatement, - commentSource: firstStatement.expression - }; - else if (isLabeledStatement(firstStatement) && isExpressionStatement(firstStatement.statement)) { - const node = factory.createObjectLiteralExpression([ - factory.createPropertyAssignment(firstStatement.label, firstStatement.statement.expression) - ]); - const nodeType = createObjectTypeFromLabeledExpression(checker, firstStatement.label, firstStatement.statement.expression); - if (checkFixedAssignableTo(checker, declaration, nodeType, expectType, isFunctionType)) return isArrowFunction(declaration) ? { - declaration: declaration, - kind: 1 /* MissingParentheses */ , - expression: node, - statement: firstStatement, - commentSource: firstStatement.statement.expression - } : { - declaration: declaration, - kind: 0 /* MissingReturnStatement */ , - expression: node, - statement: firstStatement, - commentSource: firstStatement.statement.expression }; - } else if (isBlock(firstStatement) && length(firstStatement.statements) === 1) { - const firstBlockStatement = first(firstStatement.statements); - if (isLabeledStatement(firstBlockStatement) && isExpressionStatement(firstBlockStatement.statement)) { - const node = factory.createObjectLiteralExpression([ - factory.createPropertyAssignment(firstBlockStatement.label, firstBlockStatement.statement.expression) - ]); - const nodeType = createObjectTypeFromLabeledExpression(checker, firstBlockStatement.label, firstBlockStatement.statement.expression); - if (checkFixedAssignableTo(checker, declaration, nodeType, expectType, isFunctionType)) return { - declaration: declaration, - kind: 0 /* MissingReturnStatement */ , - expression: node, - statement: firstStatement, - commentSource: firstBlockStatement - }; - } - } - return void 0; - } - function checkFixedAssignableTo(checker, declaration, exprType, type, isFunctionType) { - if (isFunctionType) { - const sig = checker.getSignatureFromDeclaration(declaration); - if (sig) { - if (hasSyntacticModifier(declaration, 512 /* Async */ )) exprType = checker.createPromiseType(exprType); - const newSig = checker.createSignature(declaration, sig.typeParameters, sig.thisParameter, sig.parameters, exprType, /*typePredicate*/ void 0, sig.minArgumentCount, sig.flags); - exprType = checker.createAnonymousType(/*symbol*/ void 0, createSymbolTable(), [ - newSig - ], [], []); - } else exprType = checker.getAnyType(); - } - return checker.isTypeAssignableTo(exprType, type); - } - function getInfo6(checker, sourceFile, position, errorCode) { - const node = getTokenAtPosition(sourceFile, position); - if (!node.parent) return void 0; - const declaration = findAncestor(node.parent, isFunctionLikeDeclaration); - switch(errorCode){ - case Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value.code: - if (!declaration || !declaration.body || !declaration.type || !rangeContainsRange(declaration.type, node)) return void 0; - return getFixInfo(checker, declaration, checker.getTypeFromTypeNode(declaration.type), /* isFunctionType */ false); - case Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code: - if (!declaration || !isCallExpression(declaration.parent) || !declaration.body) return void 0; - const pos = declaration.parent.arguments.indexOf(declaration); - const type = checker.getContextualTypeForArgumentAtIndex(declaration.parent, pos); - if (!type) return void 0; - return getFixInfo(checker, declaration, type, /* isFunctionType */ true); - case Diagnostics.Type_0_is_not_assignable_to_type_1.code: - if (!isDeclarationName(node) || !isVariableLike(node.parent) && !isJsxAttribute(node.parent)) return void 0; - const initializer = getVariableLikeInitializer(node.parent); - if (!initializer || !isFunctionLikeDeclaration(initializer) || !initializer.body) return void 0; - return getFixInfo(checker, initializer, checker.getTypeAtLocation(node.parent), /* isFunctionType */ true); - } - return void 0; - } - function getVariableLikeInitializer(declaration) { - switch(declaration.kind){ - case 257 /* VariableDeclaration */ : - case 166 /* Parameter */ : - case 205 /* BindingElement */ : - case 169 /* PropertyDeclaration */ : - case 299 /* PropertyAssignment */ : - return declaration.initializer; - case 288 /* JsxAttribute */ : - return declaration.initializer && (isJsxExpression(declaration.initializer) ? declaration.initializer.expression : void 0); - case 300 /* ShorthandPropertyAssignment */ : - case 168 /* PropertySignature */ : - case 302 /* EnumMember */ : - case 351 /* JSDocPropertyTag */ : - case 344 /* JSDocParameterTag */ : - return void 0; - } - } - function addReturnStatement(changes, sourceFile, expression, statement) { - suppressLeadingAndTrailingTrivia(expression); - const probablyNeedSemi = probablyUsesSemicolons(sourceFile); - changes.replaceNode(sourceFile, statement, factory.createReturnStatement(expression), { - leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, - trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Exclude, - suffix: probablyNeedSemi ? ";" : void 0 - }); - } - function removeBlockBodyBrace(changes, sourceFile, declaration, expression, commentSource, withParen) { - const newBody = withParen || needsParentheses(expression) ? factory.createParenthesizedExpression(expression) : expression; - suppressLeadingAndTrailingTrivia(commentSource); - copyComments(commentSource, newBody); - changes.replaceNode(sourceFile, declaration.body, newBody); - } - function wrapBlockWithParen(changes, sourceFile, declaration, expression) { - changes.replaceNode(sourceFile, declaration.body, factory.createParenthesizedExpression(expression)); - } - function getActionForfixAddReturnStatement(context, expression, statement) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addReturnStatement(t, context.sourceFile, expression, statement)); - return createCodeFixAction(fixId22, changes, Diagnostics.Add_a_return_statement, fixIdAddReturnStatement, Diagnostics.Add_all_missing_return_statement); - } - function getActionForFixRemoveBracesFromArrowFunctionBody(context, declaration, expression, commentSource) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>removeBlockBodyBrace(t, context.sourceFile, declaration, expression, commentSource, /* withParen */ false)); - return createCodeFixAction(fixId22, changes, Diagnostics.Remove_braces_from_arrow_function_body, fixRemoveBracesFromArrowFunctionBody, Diagnostics.Remove_braces_from_all_arrow_function_bodies_with_relevant_issues); - } - function getActionForfixWrapTheBlockWithParen(context, declaration, expression) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>wrapBlockWithParen(t, context.sourceFile, declaration, expression)); - return createCodeFixAction(fixId22, changes, Diagnostics.Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal, fixIdWrapTheBlockWithParen, Diagnostics.Wrap_all_object_literal_with_parentheses); - } - var fixId22, fixIdAddReturnStatement, fixRemoveBracesFromArrowFunctionBody, fixIdWrapTheBlockWithParen, errorCodes25; - var init_returnValueCorrect = __esm({ - "src/services/codefixes/returnValueCorrect.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId22 = "returnValueCorrect"; - fixIdAddReturnStatement = "fixAddReturnStatement"; - fixRemoveBracesFromArrowFunctionBody = "fixRemoveBracesFromArrowFunctionBody"; - fixIdWrapTheBlockWithParen = "fixWrapTheBlockWithParen"; - errorCodes25 = [ - Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value.code, - Diagnostics.Type_0_is_not_assignable_to_type_1.code, - Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code - ]; - registerCodeFix({ - errorCodes: errorCodes25, - fixIds: [ - fixIdAddReturnStatement, - fixRemoveBracesFromArrowFunctionBody, - fixIdWrapTheBlockWithParen - ], - getCodeActions: function getCodeActionsToCorrectReturnValue(context) { - const { program: program , sourceFile: sourceFile , span: { start: start } , errorCode: errorCode } = context; - const info = getInfo6(program.getTypeChecker(), sourceFile, start, errorCode); - if (!info) return void 0; - if (info.kind === 0 /* MissingReturnStatement */ ) return append([ - getActionForfixAddReturnStatement(context, info.expression, info.statement) - ], isArrowFunction(info.declaration) ? getActionForFixRemoveBracesFromArrowFunctionBody(context, info.declaration, info.expression, info.commentSource) : void 0); - else return [ - getActionForfixWrapTheBlockWithParen(context, info.declaration, info.expression) - ]; - }, - getAllCodeActions: (context)=>codeFixAll(context, errorCodes25, (changes, diag2)=>{ - const info = getInfo6(context.program.getTypeChecker(), diag2.file, diag2.start, diag2.code); - if (!info) return void 0; - switch(context.fixId){ - case fixIdAddReturnStatement: - addReturnStatement(changes, diag2.file, info.expression, info.statement); - break; - case fixRemoveBracesFromArrowFunctionBody: - if (!isArrowFunction(info.declaration)) return void 0; - removeBlockBodyBrace(changes, diag2.file, info.declaration, info.expression, info.commentSource, /* withParen */ false); - break; - case fixIdWrapTheBlockWithParen: - if (!isArrowFunction(info.declaration)) return void 0; - wrapBlockWithParen(changes, diag2.file, info.declaration, info.expression); - break; - default: - Debug.fail(JSON.stringify(context.fixId)); - } - }) - }); - } - }); - // src/services/codefixes/fixAddMissingMember.ts - function getInfo7(sourceFile, tokenPos, errorCode, checker, program) { - var _a2; - const token = getTokenAtPosition(sourceFile, tokenPos); - const parent2 = token.parent; - if (errorCode === Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code) { - if (!(token.kind === 18 /* OpenBraceToken */ && isObjectLiteralExpression(parent2) && isCallExpression(parent2.parent))) return void 0; - const argIndex = findIndex(parent2.parent.arguments, (arg)=>arg === parent2); - if (argIndex < 0) return void 0; - const signature = checker.getResolvedSignature(parent2.parent); - if (!(signature && signature.declaration && signature.parameters[argIndex])) return void 0; - const param = signature.parameters[argIndex].valueDeclaration; - if (!(param && isParameter(param) && isIdentifier(param.name))) return void 0; - const properties = arrayFrom(checker.getUnmatchedProperties(checker.getTypeAtLocation(parent2), checker.getParameterType(signature, argIndex), /* requireOptionalProperties */ false, /* matchDiscriminantProperties */ false)); - if (!length(properties)) return void 0; - return { - kind: 3 /* ObjectLiteral */ , - token: param.name, - properties: properties, - parentDeclaration: parent2 - }; - } - if (!isMemberName(token)) return void 0; - if (isIdentifier(token) && hasInitializer(parent2) && parent2.initializer && isObjectLiteralExpression(parent2.initializer)) { - const properties = arrayFrom(checker.getUnmatchedProperties(checker.getTypeAtLocation(parent2.initializer), checker.getTypeAtLocation(token), /* requireOptionalProperties */ false, /* matchDiscriminantProperties */ false)); - if (!length(properties)) return void 0; - return { - kind: 3 /* ObjectLiteral */ , - token: token, - properties: properties, - parentDeclaration: parent2.initializer - }; - } - if (isIdentifier(token) && isJsxOpeningLikeElement(token.parent)) { - const target = getEmitScriptTarget(program.getCompilerOptions()); - const attributes = getUnmatchedAttributes(checker, target, token.parent); - if (!length(attributes)) return void 0; - return { - kind: 4 /* JsxAttributes */ , - token: token, - attributes: attributes, - parentDeclaration: token.parent + CoreServicesShimHostAdapter = class { + constructor(shimHost){ + this.shimHost = shimHost; + this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; + if ("directoryExists" in this.shimHost) this.directoryExists = (directoryName)=>this.shimHost.directoryExists(directoryName); + else this.directoryExists = void 0; + if ("realpath" in this.shimHost) this.realpath = (path)=>this.shimHost.realpath(path); + else this.realpath = void 0; + } + readDirectory(rootDir, extensions, exclude, include, depth) { + const pattern = getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); + } + fileExists(fileName) { + return this.shimHost.fileExists(fileName); + } + readFile(fileName) { + return this.shimHost.readFile(fileName); + } + getDirectories(path) { + return JSON.parse(this.shimHost.getDirectories(path)); + } }; - } - if (isIdentifier(token)) { - const type = (_a2 = checker.getContextualType(token)) == null ? void 0 : _a2.getNonNullableType(); - if (type && getObjectFlags(type) & 16 /* Anonymous */ ) { - const signature = firstOrUndefined(checker.getSignaturesOfType(type, 0 /* Call */ )); - if (signature === void 0) return void 0; - return { - kind: 5 /* Signature */ , - token: token, - signature: signature, - sourceFile: sourceFile, - parentDeclaration: findScope(token) - }; - } - if (isCallExpression(parent2) && parent2.expression === token) return { - kind: 2 /* Function */ , - token: token, - call: parent2, - sourceFile: sourceFile, - modifierFlags: 0 /* None */ , - parentDeclaration: findScope(token) + ShimBase = class { + constructor(factory2){ + this.factory = factory2; + factory2.registerShim(this); + } + dispose(_dummy) { + this.factory.unregisterShim(this); + } }; - } - if (!isPropertyAccessExpression(parent2)) return void 0; - const leftExpressionType = skipConstraint(checker.getTypeAtLocation(parent2.expression)); - const symbol = leftExpressionType.symbol; - if (!symbol || !symbol.declarations) return void 0; - if (isIdentifier(token) && isCallExpression(parent2.parent)) { - const moduleDeclaration = find(symbol.declarations, isModuleDeclaration); - const moduleDeclarationSourceFile = moduleDeclaration == null ? void 0 : moduleDeclaration.getSourceFile(); - if (moduleDeclaration && moduleDeclarationSourceFile && !isSourceFileFromLibrary(program, moduleDeclarationSourceFile)) return { - kind: 2 /* Function */ , - token: token, - call: parent2.parent, - sourceFile: sourceFile, - modifierFlags: 1 /* Export */ , - parentDeclaration: moduleDeclaration + LanguageServiceShimObject = class extends ShimBase { + constructor(factory2, host, languageService){ + super(factory2); + this.host = host; + this.languageService = languageService; + this.logPerformance = false; + this.logger = this.host; + } + forwardJSONCall(actionDescription2, action) { + return forwardJSONCall(this.logger, actionDescription2, action, this.logPerformance); + } + /// DISPOSE + /** + * Ensure (almost) deterministic release of internal Javascript resources when + * some external native objects holds onto us (e.g. Com/Interop). + */ dispose(dummy) { + this.logger.log("dispose()"); + this.languageService.dispose(); + this.languageService = null; + if (debugObjectHost && debugObjectHost.CollectGarbage) { + debugObjectHost.CollectGarbage(); + this.logger.log("CollectGarbage()"); + } + this.logger = null; + super.dispose(dummy); + } + /// REFRESH + /** + * Update the list of scripts known to the compiler + */ refresh(throwOnError) { + this.forwardJSONCall(`refresh(${throwOnError})`, ()=>null); + } + cleanupSemanticCache() { + this.forwardJSONCall("cleanupSemanticCache()", ()=>{ + this.languageService.cleanupSemanticCache(); + return null; + }); + } + realizeDiagnostics(diagnostics) { + const newLine = getNewLineOrDefaultFromHost(this.host, /*formatSettings*/ void 0); + return realizeDiagnostics(diagnostics, newLine); + } + getSyntacticClassifications(fileName, start, length2) { + return this.forwardJSONCall(`getSyntacticClassifications('${fileName}', ${start}, ${length2})`, ()=>this.languageService.getSyntacticClassifications(fileName, createTextSpan(start, length2))); + } + getSemanticClassifications(fileName, start, length2) { + return this.forwardJSONCall(`getSemanticClassifications('${fileName}', ${start}, ${length2})`, ()=>this.languageService.getSemanticClassifications(fileName, createTextSpan(start, length2))); + } + getEncodedSyntacticClassifications(fileName, start, length2) { + return this.forwardJSONCall(`getEncodedSyntacticClassifications('${fileName}', ${start}, ${length2})`, // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + ()=>convertClassifications(this.languageService.getEncodedSyntacticClassifications(fileName, createTextSpan(start, length2)))); + } + getEncodedSemanticClassifications(fileName, start, length2) { + return this.forwardJSONCall(`getEncodedSemanticClassifications('${fileName}', ${start}, ${length2})`, // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + ()=>convertClassifications(this.languageService.getEncodedSemanticClassifications(fileName, createTextSpan(start, length2)))); + } + getSyntacticDiagnostics(fileName) { + return this.forwardJSONCall(`getSyntacticDiagnostics('${fileName}')`, ()=>{ + const diagnostics = this.languageService.getSyntacticDiagnostics(fileName); + return this.realizeDiagnostics(diagnostics); + }); + } + getSemanticDiagnostics(fileName) { + return this.forwardJSONCall(`getSemanticDiagnostics('${fileName}')`, ()=>{ + const diagnostics = this.languageService.getSemanticDiagnostics(fileName); + return this.realizeDiagnostics(diagnostics); + }); + } + getSuggestionDiagnostics(fileName) { + return this.forwardJSONCall(`getSuggestionDiagnostics('${fileName}')`, ()=>this.realizeDiagnostics(this.languageService.getSuggestionDiagnostics(fileName))); + } + getCompilerOptionsDiagnostics() { + return this.forwardJSONCall("getCompilerOptionsDiagnostics()", ()=>{ + const diagnostics = this.languageService.getCompilerOptionsDiagnostics(); + return this.realizeDiagnostics(diagnostics); + }); + } + /// QUICKINFO + /** + * Computes a string representation of the type at the requested position + * in the active file. + */ getQuickInfoAtPosition(fileName, position) { + return this.forwardJSONCall(`getQuickInfoAtPosition('${fileName}', ${position})`, ()=>this.languageService.getQuickInfoAtPosition(fileName, position)); + } + /// NAMEORDOTTEDNAMESPAN + /** + * Computes span information of the name or dotted name at the requested position + * in the active file. + */ getNameOrDottedNameSpan(fileName, startPos, endPos) { + return this.forwardJSONCall(`getNameOrDottedNameSpan('${fileName}', ${startPos}, ${endPos})`, ()=>this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos)); + } + /** + * STATEMENTSPAN + * Computes span information of statement at the requested position in the active file. + */ getBreakpointStatementAtPosition(fileName, position) { + return this.forwardJSONCall(`getBreakpointStatementAtPosition('${fileName}', ${position})`, ()=>this.languageService.getBreakpointStatementAtPosition(fileName, position)); + } + /// SIGNATUREHELP + getSignatureHelpItems(fileName, position, options) { + return this.forwardJSONCall(`getSignatureHelpItems('${fileName}', ${position})`, ()=>this.languageService.getSignatureHelpItems(fileName, position, options)); + } + /// GOTO DEFINITION + /** + * Computes the definition location and file for the symbol + * at the requested position. + */ getDefinitionAtPosition(fileName, position) { + return this.forwardJSONCall(`getDefinitionAtPosition('${fileName}', ${position})`, ()=>this.languageService.getDefinitionAtPosition(fileName, position)); + } + /** + * Computes the definition location and file for the symbol + * at the requested position. + */ getDefinitionAndBoundSpan(fileName, position) { + return this.forwardJSONCall(`getDefinitionAndBoundSpan('${fileName}', ${position})`, ()=>this.languageService.getDefinitionAndBoundSpan(fileName, position)); + } + /// GOTO Type + /** + * Computes the definition location of the type of the symbol + * at the requested position. + */ getTypeDefinitionAtPosition(fileName, position) { + return this.forwardJSONCall(`getTypeDefinitionAtPosition('${fileName}', ${position})`, ()=>this.languageService.getTypeDefinitionAtPosition(fileName, position)); + } + /// GOTO Implementation + /** + * Computes the implementation location of the symbol + * at the requested position. + */ getImplementationAtPosition(fileName, position) { + return this.forwardJSONCall(`getImplementationAtPosition('${fileName}', ${position})`, ()=>this.languageService.getImplementationAtPosition(fileName, position)); + } + getRenameInfo(fileName, position, preferences) { + return this.forwardJSONCall(`getRenameInfo('${fileName}', ${position})`, ()=>this.languageService.getRenameInfo(fileName, position, preferences)); + } + getSmartSelectionRange(fileName, position) { + return this.forwardJSONCall(`getSmartSelectionRange('${fileName}', ${position})`, ()=>this.languageService.getSmartSelectionRange(fileName, position)); + } + findRenameLocations(fileName, position, findInStrings, findInComments, preferences) { + return this.forwardJSONCall(`findRenameLocations('${fileName}', ${position}, ${findInStrings}, ${findInComments})`, ()=>this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, preferences)); + } + /// GET BRACE MATCHING + getBraceMatchingAtPosition(fileName, position) { + return this.forwardJSONCall(`getBraceMatchingAtPosition('${fileName}', ${position})`, ()=>this.languageService.getBraceMatchingAtPosition(fileName, position)); + } + isValidBraceCompletionAtPosition(fileName, position, openingBrace) { + return this.forwardJSONCall(`isValidBraceCompletionAtPosition('${fileName}', ${position}, ${openingBrace})`, ()=>this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace)); + } + getSpanOfEnclosingComment(fileName, position, onlyMultiLine) { + return this.forwardJSONCall(`getSpanOfEnclosingComment('${fileName}', ${position})`, ()=>this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine)); + } + /// GET SMART INDENT + getIndentationAtPosition(fileName, position, options) { + return this.forwardJSONCall(`getIndentationAtPosition('${fileName}', ${position})`, ()=>{ + const localOptions = JSON.parse(options); + return this.languageService.getIndentationAtPosition(fileName, position, localOptions); + }); + } + /// GET REFERENCES + getReferencesAtPosition(fileName, position) { + return this.forwardJSONCall(`getReferencesAtPosition('${fileName}', ${position})`, ()=>this.languageService.getReferencesAtPosition(fileName, position)); + } + findReferences(fileName, position) { + return this.forwardJSONCall(`findReferences('${fileName}', ${position})`, ()=>this.languageService.findReferences(fileName, position)); + } + getFileReferences(fileName) { + return this.forwardJSONCall(`getFileReferences('${fileName})`, ()=>this.languageService.getFileReferences(fileName)); + } + getDocumentHighlights(fileName, position, filesToSearch) { + return this.forwardJSONCall(`getDocumentHighlights('${fileName}', ${position})`, ()=>{ + const results = this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch)); + const normalizedName = toFileNameLowerCase(normalizeSlashes(fileName)); + return filter(results, (r)=>toFileNameLowerCase(normalizeSlashes(r.fileName)) === normalizedName); + }); + } + /// COMPLETION LISTS + /** + * Get a string based representation of the completions + * to provide at the given source position and providing a member completion + * list if requested. + */ getCompletionsAtPosition(fileName, position, preferences, formattingSettings) { + return this.forwardJSONCall(`getCompletionsAtPosition('${fileName}', ${position}, ${preferences}, ${formattingSettings})`, ()=>this.languageService.getCompletionsAtPosition(fileName, position, preferences, formattingSettings)); + } + /** Get a string based representation of a completion list entry details */ getCompletionEntryDetails(fileName, position, entryName, formatOptions, source, preferences, data) { + return this.forwardJSONCall(`getCompletionEntryDetails('${fileName}', ${position}, '${entryName}')`, ()=>{ + const localOptions = formatOptions === void 0 ? void 0 : JSON.parse(formatOptions); + return this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences, data); + }); + } + getFormattingEditsForRange(fileName, start, end, options) { + return this.forwardJSONCall(`getFormattingEditsForRange('${fileName}', ${start}, ${end})`, ()=>{ + const localOptions = JSON.parse(options); + return this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); + }); + } + getFormattingEditsForDocument(fileName, options) { + return this.forwardJSONCall(`getFormattingEditsForDocument('${fileName}')`, ()=>{ + const localOptions = JSON.parse(options); + return this.languageService.getFormattingEditsForDocument(fileName, localOptions); + }); + } + getFormattingEditsAfterKeystroke(fileName, position, key, options) { + return this.forwardJSONCall(`getFormattingEditsAfterKeystroke('${fileName}', ${position}, '${key}')`, ()=>{ + const localOptions = JSON.parse(options); + return this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); + }); + } + getDocCommentTemplateAtPosition(fileName, position, options, formatOptions) { + return this.forwardJSONCall(`getDocCommentTemplateAtPosition('${fileName}', ${position})`, ()=>this.languageService.getDocCommentTemplateAtPosition(fileName, position, options, formatOptions)); + } + /// NAVIGATE TO + /** Return a list of symbols that are interesting to navigate to */ getNavigateToItems(searchValue, maxResultCount, fileName) { + return this.forwardJSONCall(`getNavigateToItems('${searchValue}', ${maxResultCount}, ${fileName})`, ()=>this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName)); + } + getNavigationBarItems(fileName) { + return this.forwardJSONCall(`getNavigationBarItems('${fileName}')`, ()=>this.languageService.getNavigationBarItems(fileName)); + } + getNavigationTree(fileName) { + return this.forwardJSONCall(`getNavigationTree('${fileName}')`, ()=>this.languageService.getNavigationTree(fileName)); + } + getOutliningSpans(fileName) { + return this.forwardJSONCall(`getOutliningSpans('${fileName}')`, ()=>this.languageService.getOutliningSpans(fileName)); + } + getTodoComments(fileName, descriptors) { + return this.forwardJSONCall(`getTodoComments('${fileName}')`, ()=>this.languageService.getTodoComments(fileName, JSON.parse(descriptors))); + } + /// CALL HIERARCHY + prepareCallHierarchy(fileName, position) { + return this.forwardJSONCall(`prepareCallHierarchy('${fileName}', ${position})`, ()=>this.languageService.prepareCallHierarchy(fileName, position)); + } + provideCallHierarchyIncomingCalls(fileName, position) { + return this.forwardJSONCall(`provideCallHierarchyIncomingCalls('${fileName}', ${position})`, ()=>this.languageService.provideCallHierarchyIncomingCalls(fileName, position)); + } + provideCallHierarchyOutgoingCalls(fileName, position) { + return this.forwardJSONCall(`provideCallHierarchyOutgoingCalls('${fileName}', ${position})`, ()=>this.languageService.provideCallHierarchyOutgoingCalls(fileName, position)); + } + provideInlayHints(fileName, span, preference) { + return this.forwardJSONCall(`provideInlayHints('${fileName}', '${JSON.stringify(span)}', ${JSON.stringify(preference)})`, ()=>this.languageService.provideInlayHints(fileName, span, preference)); + } + /// Emit + getEmitOutput(fileName) { + return this.forwardJSONCall(`getEmitOutput('${fileName}')`, ()=>{ + const { diagnostics: diagnostics, ...rest } = this.languageService.getEmitOutput(fileName); + return { + ...rest, + diagnostics: this.realizeDiagnostics(diagnostics) + }; + }); + } + getEmitOutputObject(fileName) { + return forwardCall(this.logger, `getEmitOutput('${fileName}')`, /*returnJson*/ false, ()=>this.languageService.getEmitOutput(fileName), this.logPerformance); + } + toggleLineComment(fileName, textRange) { + return this.forwardJSONCall(`toggleLineComment('${fileName}', '${JSON.stringify(textRange)}')`, ()=>this.languageService.toggleLineComment(fileName, textRange)); + } + toggleMultilineComment(fileName, textRange) { + return this.forwardJSONCall(`toggleMultilineComment('${fileName}', '${JSON.stringify(textRange)}')`, ()=>this.languageService.toggleMultilineComment(fileName, textRange)); + } + commentSelection(fileName, textRange) { + return this.forwardJSONCall(`commentSelection('${fileName}', '${JSON.stringify(textRange)}')`, ()=>this.languageService.commentSelection(fileName, textRange)); + } + uncommentSelection(fileName, textRange) { + return this.forwardJSONCall(`uncommentSelection('${fileName}', '${JSON.stringify(textRange)}')`, ()=>this.languageService.uncommentSelection(fileName, textRange)); + } }; - const moduleSourceFile = find(symbol.declarations, isSourceFile); - if (sourceFile.commonJsModuleIndicator) return void 0; - if (moduleSourceFile && !isSourceFileFromLibrary(program, moduleSourceFile)) return { - kind: 2 /* Function */ , - token: token, - call: parent2.parent, - sourceFile: moduleSourceFile, - modifierFlags: 1 /* Export */ , - parentDeclaration: moduleSourceFile + ClassifierShimObject = class extends ShimBase { + constructor(factory2, logger){ + super(factory2); + this.logger = logger; + this.logPerformance = false; + this.classifier = createClassifier(); + } + getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent = false) { + return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", ()=>convertClassifications(this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)), this.logPerformance); + } + /// COLORIZATION + getClassificationsForLine(text, lexState, classifyKeywordsInGenerics = false) { + const classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics); + let result = ""; + for (const item of classification.entries){ + result += item.length + "\n"; + result += item.classification + "\n"; + } + result += classification.finalLexState; + return result; + } }; - } - const classDeclaration = find(symbol.declarations, isClassLike); - if (!classDeclaration && isPrivateIdentifier(token)) return void 0; - const declaration = classDeclaration || find(symbol.declarations, (d)=>isInterfaceDeclaration(d) || isTypeLiteralNode(d)); - if (declaration && !isSourceFileFromLibrary(program, declaration.getSourceFile())) { - const makeStatic = !isTypeLiteralNode(declaration) && (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); - if (makeStatic && (isPrivateIdentifier(token) || isInterfaceDeclaration(declaration))) return void 0; - const declSourceFile = declaration.getSourceFile(); - const modifierFlags = isTypeLiteralNode(declaration) ? 0 /* None */ : (makeStatic ? 32 /* Static */ : 0 /* None */ ) | (startsWithUnderscore(token.text) ? 8 /* Private */ : 0 /* None */ ); - const isJSFile = isSourceFileJS(declSourceFile); - const call = tryCast(parent2.parent, isCallExpression); - return { - kind: 0 /* TypeLikeDeclaration */ , - token: token, - call: call, - modifierFlags: modifierFlags, - parentDeclaration: declaration, - declSourceFile: declSourceFile, - isJSFile: isJSFile + CoreServicesShimObject = class extends ShimBase { + constructor(factory2, logger, host){ + super(factory2); + this.logger = logger; + this.host = host; + this.logPerformance = false; + } + forwardJSONCall(actionDescription2, action) { + return forwardJSONCall(this.logger, actionDescription2, action, this.logPerformance); + } + resolveModuleName(fileName, moduleName, compilerOptionsJson) { + return this.forwardJSONCall(`resolveModuleName('${fileName}')`, ()=>{ + const compilerOptions = JSON.parse(compilerOptionsJson); + const result = resolveModuleName(moduleName, normalizeSlashes(fileName), compilerOptions, this.host); + let resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : void 0; + if (result.resolvedModule && result.resolvedModule.extension !== ".ts" /* Ts */ && result.resolvedModule.extension !== ".tsx" /* Tsx */ && result.resolvedModule.extension !== ".d.ts" /* Dts */ ) resolvedFileName = void 0; + return { + resolvedFileName: resolvedFileName, + failedLookupLocations: result.failedLookupLocations, + affectingLocations: result.affectingLocations + }; + }); + } + resolveTypeReferenceDirective(fileName, typeReferenceDirective, compilerOptionsJson) { + return this.forwardJSONCall(`resolveTypeReferenceDirective(${fileName})`, ()=>{ + const compilerOptions = JSON.parse(compilerOptionsJson); + const result = resolveTypeReferenceDirective(typeReferenceDirective, normalizeSlashes(fileName), compilerOptions, this.host); + return { + resolvedFileName: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.resolvedFileName : void 0, + primary: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.primary : true, + failedLookupLocations: result.failedLookupLocations + }; + }); + } + getPreProcessedFileInfo(fileName, sourceTextSnapshot) { + return this.forwardJSONCall(`getPreProcessedFileInfo('${fileName}')`, ()=>{ + const result = preProcessFile(getSnapshotText(sourceTextSnapshot), /*readImportFiles*/ true, /*detectJavaScriptImports*/ true); + return { + referencedFiles: this.convertFileReferences(result.referencedFiles), + importedFiles: this.convertFileReferences(result.importedFiles), + ambientExternalModules: result.ambientExternalModules, + isLibFile: result.isLibFile, + typeReferenceDirectives: this.convertFileReferences(result.typeReferenceDirectives), + libReferenceDirectives: this.convertFileReferences(result.libReferenceDirectives) + }; + }); + } + getAutomaticTypeDirectiveNames(compilerOptionsJson) { + return this.forwardJSONCall(`getAutomaticTypeDirectiveNames('${compilerOptionsJson}')`, ()=>{ + const compilerOptions = JSON.parse(compilerOptionsJson); + return getAutomaticTypeDirectiveNames(compilerOptions, this.host); + }); + } + convertFileReferences(refs) { + if (!refs) return void 0; + const result = []; + for (const ref of refs)result.push({ + path: normalizeSlashes(ref.fileName), + position: ref.pos, + length: ref.end - ref.pos + }); + return result; + } + getTSConfigFileInfo(fileName, sourceTextSnapshot) { + return this.forwardJSONCall(`getTSConfigFileInfo('${fileName}')`, ()=>{ + const result = parseJsonText(fileName, getSnapshotText(sourceTextSnapshot)); + const normalizedFileName = normalizeSlashes(fileName); + const configFile = parseJsonSourceFileConfigFileContent(result, this.host, getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); + return { + options: configFile.options, + typeAcquisition: configFile.typeAcquisition, + files: configFile.fileNames, + raw: configFile.raw, + errors: realizeDiagnostics([ + ...result.parseDiagnostics, + ...configFile.errors + ], "\r\n") + }; + }); + } + getDefaultCompilationSettings() { + return this.forwardJSONCall("getDefaultCompilationSettings()", ()=>getDefaultCompilerOptions2()); + } + discoverTypings(discoverTypingsJson) { + const getCanonicalFileName = createGetCanonicalFileName(/*useCaseSensitiveFileNames*/ false); + return this.forwardJSONCall("discoverTypings()", ()=>{ + const info = JSON.parse(discoverTypingsJson); + if (this.safeList === void 0) this.safeList = ts_JsTyping_exports.loadSafeList(this.host, toPath(info.safeListPath, info.safeListPath, getCanonicalFileName)); + return ts_JsTyping_exports.discoverTypings(this.host, (msg)=>this.logger.log(msg), info.fileNames, toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports, info.typesRegistry, emptyOptions); + }); + } + }; + TypeScriptServicesFactory = class { + constructor(){ + this._shims = []; + } + /* + * Returns script API version. + */ getServicesVersion() { + return servicesVersion; + } + createLanguageServiceShim(host) { + try { + if (this.documentRegistry === void 0) this.documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); + const hostAdapter = new LanguageServiceShimHostAdapter(host); + const languageService = createLanguageService(hostAdapter, this.documentRegistry, /*syntaxOnlyOrLanguageServiceMode*/ false); + return new LanguageServiceShimObject(this, host, languageService); + } catch (err) { + logInternalError(host, err); + throw err; + } + } + createClassifierShim(logger) { + try { + return new ClassifierShimObject(this, logger); + } catch (err) { + logInternalError(logger, err); + throw err; + } + } + createCoreServicesShim(host) { + try { + const adapter = new CoreServicesShimHostAdapter(host); + return new CoreServicesShimObject(this, host, adapter); + } catch (err) { + logInternalError(host, err); + throw err; + } + } + close() { + clear(this._shims); + this.documentRegistry = void 0; + } + registerShim(shim) { + this._shims.push(shim); + } + unregisterShim(shim) { + for(let i = 0; i < this._shims.length; i++)if (this._shims[i] === shim) { + delete this._shims[i]; + return; + } + throw new Error("Invalid operation"); + } }; } - const enumDeclaration = find(symbol.declarations, isEnumDeclaration); - if (enumDeclaration && !(leftExpressionType.flags & 1056 /* EnumLike */ ) && !isPrivateIdentifier(token) && !isSourceFileFromLibrary(program, enumDeclaration.getSourceFile())) return { - kind: 1 /* Enum */ , - token: token, - parentDeclaration: enumDeclaration - }; - return void 0; - } - function getActionsForMissingMemberDeclaration(context, info) { - return info.isJSFile ? singleElementArray(createActionForAddMissingMemberInJavascriptFile(context, info)) : createActionsForAddMissingMemberInTypeScriptFile(context, info); - } - function createActionForAddMissingMemberInJavascriptFile(context, { parentDeclaration: parentDeclaration , declSourceFile: declSourceFile , modifierFlags: modifierFlags , token: token }) { - if (isInterfaceDeclaration(parentDeclaration) || isTypeLiteralNode(parentDeclaration)) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addMissingMemberInJs(t, declSourceFile, parentDeclaration, token, !!(modifierFlags & 32 /* Static */ ))); - if (changes.length === 0) return void 0; - const diagnostic = modifierFlags & 32 /* Static */ ? Diagnostics.Initialize_static_property_0 : isPrivateIdentifier(token) ? Diagnostics.Declare_a_private_field_named_0 : Diagnostics.Initialize_property_0_in_the_constructor; - return createCodeFixAction(fixMissingMember, changes, [ - diagnostic, - token.text - ], fixMissingMember, Diagnostics.Add_all_missing_members); - } - function addMissingMemberInJs(changeTracker, sourceFile, classDeclaration, token, makeStatic) { - const tokenName = token.text; - if (makeStatic) { - if (classDeclaration.kind === 228 /* ClassExpression */ ) return; - const className = classDeclaration.name.getText(); - const staticInitialization = initializePropertyToUndefined(factory.createIdentifier(className), tokenName); - changeTracker.insertNodeAfter(sourceFile, classDeclaration, staticInitialization); - } else if (isPrivateIdentifier(token)) { - const property = factory.createPropertyDeclaration(/*modifiers*/ void 0, tokenName, /*questionToken*/ void 0, /*type*/ void 0, /*initializer*/ void 0); - const lastProp = getNodeToInsertPropertyAfter(classDeclaration); - if (lastProp) changeTracker.insertNodeAfter(sourceFile, lastProp, property); - else changeTracker.insertMemberAtStart(sourceFile, classDeclaration, property); - } else { - const classConstructor = getFirstConstructorWithBody(classDeclaration); - if (!classConstructor) return; - const propertyInitialization = initializePropertyToUndefined(factory.createThis(), tokenName); - changeTracker.insertNodeAtConstructorEnd(sourceFile, classConstructor, propertyInitialization); - } - } - function initializePropertyToUndefined(obj, propertyName) { - return factory.createExpressionStatement(factory.createAssignment(factory.createPropertyAccessExpression(obj, propertyName), createUndefined())); - } - function createActionsForAddMissingMemberInTypeScriptFile(context, { parentDeclaration: parentDeclaration , declSourceFile: declSourceFile , modifierFlags: modifierFlags , token: token }) { - const memberName = token.text; - const isStatic2 = modifierFlags & 32 /* Static */ ; - const typeNode = getTypeNode2(context.program.getTypeChecker(), parentDeclaration, token); - const addPropertyDeclarationChanges = (modifierFlags2)=>ts_textChanges_exports.ChangeTracker.with(context, (t)=>addPropertyDeclaration(t, declSourceFile, parentDeclaration, memberName, typeNode, modifierFlags2)); - const actions2 = [ - createCodeFixAction(fixMissingMember, addPropertyDeclarationChanges(modifierFlags & 32 /* Static */ ), [ - isStatic2 ? Diagnostics.Declare_static_property_0 : Diagnostics.Declare_property_0, - memberName - ], fixMissingMember, Diagnostics.Add_all_missing_members) - ]; - if (isStatic2 || isPrivateIdentifier(token)) return actions2; - if (modifierFlags & 8 /* Private */ ) actions2.unshift(createCodeFixActionWithoutFixAll(fixMissingMember, addPropertyDeclarationChanges(8 /* Private */ ), [ - Diagnostics.Declare_private_property_0, - memberName - ])); - actions2.push(createAddIndexSignatureAction(context, declSourceFile, parentDeclaration, token.text, typeNode)); - return actions2; - } - function getTypeNode2(checker, node, token) { - let typeNode; - if (token.parent.parent.kind === 223 /* BinaryExpression */ ) { - const binaryExpression = token.parent.parent; - const otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; - const widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); - typeNode = checker.typeToTypeNode(widenedType, node, 1 /* NoTruncation */ ); - } else { - const contextualType = checker.getContextualType(token.parent); - typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ void 0, 1 /* NoTruncation */ ) : void 0; - } - return typeNode || factory.createKeywordTypeNode(131 /* AnyKeyword */ ); - } - function addPropertyDeclaration(changeTracker, sourceFile, node, tokenName, typeNode, modifierFlags) { - const modifiers = modifierFlags ? factory.createNodeArray(factory.createModifiersFromModifierFlags(modifierFlags)) : void 0; - const property = isClassLike(node) ? factory.createPropertyDeclaration(modifiers, tokenName, /*questionToken*/ void 0, typeNode, /*initializer*/ void 0) : factory.createPropertySignature(/*modifiers*/ void 0, tokenName, /*questionToken*/ void 0, typeNode); - const lastProp = getNodeToInsertPropertyAfter(node); - if (lastProp) changeTracker.insertNodeAfter(sourceFile, lastProp, property); - else changeTracker.insertMemberAtStart(sourceFile, node, property); - } - function getNodeToInsertPropertyAfter(node) { - let res; - for (const member of node.members){ - if (!isPropertyDeclaration(member)) break; - res = member; - } - return res; - } - function createAddIndexSignatureAction(context, sourceFile, node, tokenName, typeNode) { - const stringTypeNode = factory.createKeywordTypeNode(152 /* StringKeyword */ ); - const indexingParameter = factory.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, "x", /*questionToken*/ void 0, stringTypeNode, /*initializer*/ void 0); - const indexSignature = factory.createIndexSignature(/*modifiers*/ void 0, [ - indexingParameter - ], typeNode); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>t.insertMemberAtStart(sourceFile, node, indexSignature)); - return createCodeFixActionWithoutFixAll(fixMissingMember, changes, [ - Diagnostics.Add_index_signature_for_property_0, - tokenName - ]); - } - function getActionsForMissingMethodDeclaration(context, info) { - const { parentDeclaration: parentDeclaration , declSourceFile: declSourceFile , modifierFlags: modifierFlags , token: token , call: call } = info; - if (call === void 0) return void 0; - if (isPrivateIdentifier(token)) return void 0; - const methodName = token.text; - const addMethodDeclarationChanges = (modifierFlags2)=>ts_textChanges_exports.ChangeTracker.with(context, (t)=>addMethodDeclaration(context, t, call, token, modifierFlags2, parentDeclaration, declSourceFile)); - const actions2 = [ - createCodeFixAction(fixMissingMember, addMethodDeclarationChanges(modifierFlags & 32 /* Static */ ), [ - modifierFlags & 32 /* Static */ ? Diagnostics.Declare_static_method_0 : Diagnostics.Declare_method_0, - methodName - ], fixMissingMember, Diagnostics.Add_all_missing_members) - ]; - if (modifierFlags & 8 /* Private */ ) actions2.unshift(createCodeFixActionWithoutFixAll(fixMissingMember, addMethodDeclarationChanges(8 /* Private */ ), [ - Diagnostics.Declare_private_method_0, - methodName - ])); - return actions2; - } - function addMethodDeclaration(context, changes, callExpression, name, modifierFlags, parentDeclaration, sourceFile) { - const importAdder = createImportAdder(sourceFile, context.program, context.preferences, context.host); - const kind = isClassLike(parentDeclaration) ? 171 /* MethodDeclaration */ : 170 /* MethodSignature */ ; - const signatureDeclaration = createSignatureDeclarationFromCallExpression(kind, context, importAdder, callExpression, name, modifierFlags, parentDeclaration); - const containingMethodDeclaration = tryGetContainingMethodDeclaration(parentDeclaration, callExpression); - if (containingMethodDeclaration) changes.insertNodeAfter(sourceFile, containingMethodDeclaration, signatureDeclaration); - else changes.insertMemberAtStart(sourceFile, parentDeclaration, signatureDeclaration); - importAdder.writeFixes(changes); - } - function addEnumMemberDeclaration(changes, checker, { token: token , parentDeclaration: parentDeclaration }) { - const hasStringInitializer = some(parentDeclaration.members, (member)=>{ - const type = checker.getTypeAtLocation(member); - return !!(type && type.flags & 402653316 /* StringLike */ ); - }); - const enumMember = factory.createEnumMember(token, hasStringInitializer ? factory.createStringLiteral(token.text) : void 0); - changes.replaceNode(parentDeclaration.getSourceFile(), parentDeclaration, factory.updateEnumDeclaration(parentDeclaration, parentDeclaration.modifiers, parentDeclaration.name, concatenate(parentDeclaration.members, singleElementArray(enumMember))), { - leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, - trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Exclude - }); - } - function addFunctionDeclaration(changes, context, info) { - const quotePreference = getQuotePreference(context.sourceFile, context.preferences); - const importAdder = createImportAdder(context.sourceFile, context.program, context.preferences, context.host); - const functionDeclaration = info.kind === 2 /* Function */ ? createSignatureDeclarationFromCallExpression(259 /* FunctionDeclaration */ , context, importAdder, info.call, idText(info.token), info.modifierFlags, info.parentDeclaration) : createSignatureDeclarationFromSignature(259 /* FunctionDeclaration */ , context, quotePreference, info.signature, createStubbedBody(Diagnostics.Function_not_implemented.message, quotePreference), info.token, /*modifiers*/ void 0, /*optional*/ void 0, /*enclosingDeclaration*/ void 0, importAdder); - if (functionDeclaration === void 0) Debug.fail("fixMissingFunctionDeclaration codefix got unexpected error."); - isReturnStatement(info.parentDeclaration) ? changes.insertNodeBefore(info.sourceFile, info.parentDeclaration, functionDeclaration, /*blankLineBetween*/ true) : changes.insertNodeAtEndOfScope(info.sourceFile, info.parentDeclaration, functionDeclaration); - importAdder.writeFixes(changes); - } - function addJsxAttributes(changes, context, info) { - const importAdder = createImportAdder(context.sourceFile, context.program, context.preferences, context.host); - const quotePreference = getQuotePreference(context.sourceFile, context.preferences); - const checker = context.program.getTypeChecker(); - const jsxAttributesNode = info.parentDeclaration.attributes; - const hasSpreadAttribute = some(jsxAttributesNode.properties, isJsxSpreadAttribute); - const attrs = map(info.attributes, (attr)=>{ - const value1 = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(attr), info.parentDeclaration); - const name = factory.createIdentifier(attr.name); - const jsxAttribute = factory.createJsxAttribute(name, factory.createJsxExpression(/*dotDotDotToken*/ void 0, value1)); - setParent(name, jsxAttribute); - return jsxAttribute; - }); - const jsxAttributes = factory.createJsxAttributes(hasSpreadAttribute ? [ - ...attrs, - ...jsxAttributesNode.properties - ] : [ - ...jsxAttributesNode.properties, - ...attrs - ]); - const options = { - prefix: jsxAttributesNode.pos === jsxAttributesNode.end ? " " : void 0 - }; - changes.replaceNode(context.sourceFile, jsxAttributesNode, jsxAttributes, options); - importAdder.writeFixes(changes); - } - function addObjectLiteralProperties(changes, context, info) { - const importAdder = createImportAdder(context.sourceFile, context.program, context.preferences, context.host); - const quotePreference = getQuotePreference(context.sourceFile, context.preferences); - const target = getEmitScriptTarget(context.program.getCompilerOptions()); - const checker = context.program.getTypeChecker(); - const props = map(info.properties, (prop)=>{ - const initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop), info.parentDeclaration); - return factory.createPropertyAssignment(createPropertyNameFromSymbol(prop, target, quotePreference, checker), initializer); - }); - const options = { - leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, - trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Exclude, - indentation: info.indentation - }; - changes.replaceNode(context.sourceFile, info.parentDeclaration, factory.createObjectLiteralExpression([ - ...info.parentDeclaration.properties, - ...props - ], /*multiLine*/ true), options); - importAdder.writeFixes(changes); - } - function tryGetValueFromType(context, checker, importAdder, quotePreference, type, enclosingDeclaration) { - if (type.flags & 3 /* AnyOrUnknown */ ) return createUndefined(); - if (type.flags & 134217732 /* TemplateLiteral */ ) return factory.createStringLiteral("", /* isSingleQuote */ quotePreference === 0 /* Single */ ); - if (type.flags & 8 /* Number */ ) return factory.createNumericLiteral(0); - if (type.flags & 64 /* BigInt */ ) return factory.createBigIntLiteral("0n"); - if (type.flags & 16 /* Boolean */ ) return factory.createFalse(); - if (type.flags & 1056 /* EnumLike */ ) { - const enumMember = type.symbol.exports ? firstOrUndefinedIterator(type.symbol.exports.values()) : type.symbol; - const name = checker.symbolToExpression(type.symbol.parent ? type.symbol.parent : type.symbol, 111551 /* Value */ , /*enclosingDeclaration*/ void 0, /*flags*/ void 0); - return enumMember === void 0 || name === void 0 ? factory.createNumericLiteral(0) : factory.createPropertyAccessExpression(name, checker.symbolToString(enumMember)); - } - if (type.flags & 256 /* NumberLiteral */ ) return factory.createNumericLiteral(type.value); - if (type.flags & 2048 /* BigIntLiteral */ ) return factory.createBigIntLiteral(type.value); - if (type.flags & 128 /* StringLiteral */ ) return factory.createStringLiteral(type.value, /* isSingleQuote */ quotePreference === 0 /* Single */ ); - if (type.flags & 512 /* BooleanLiteral */ ) return type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true) ? factory.createFalse() : factory.createTrue(); - if (type.flags & 65536 /* Null */ ) return factory.createNull(); - if (type.flags & 1048576 /* Union */ ) { - const expression = firstDefined(type.types, (t)=>tryGetValueFromType(context, checker, importAdder, quotePreference, t, enclosingDeclaration)); - return expression != null ? expression : createUndefined(); + }); + // src/services/breakpoints.ts + function spanInSourceFileAtLocation(sourceFile, position) { + if (sourceFile.isDeclarationFile) return void 0; + let tokenAtLocation = getTokenAtPosition(sourceFile, position); + const lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; + if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { + const preceding = findPrecedingToken(tokenAtLocation.pos, sourceFile); + if (!preceding || sourceFile.getLineAndCharacterOfPosition(preceding.getEnd()).line !== lineOfPosition) return void 0; + tokenAtLocation = preceding; } - if (checker.isArrayLikeType(type)) return factory.createArrayLiteralExpression(); - if (isObjectLiteralType(type)) { - const props = map(checker.getPropertiesOfType(type), (prop)=>{ - const initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop), enclosingDeclaration); - return factory.createPropertyAssignment(prop.name, initializer); - }); - return factory.createObjectLiteralExpression(props, /*multiLine*/ true); + if (tokenAtLocation.flags & 33554432 /* Ambient */ ) return void 0; + return spanInNode(tokenAtLocation); + function textSpan(startNode2, endNode2) { + const lastDecorator = canHaveDecorators(startNode2) ? findLast(startNode2.modifiers, isDecorator) : void 0; + const start = lastDecorator ? skipTrivia(sourceFile.text, lastDecorator.end) : startNode2.getStart(sourceFile); + return createTextSpanFromBounds(start, (endNode2 || startNode2).getEnd()); } - if (getObjectFlags(type) & 16 /* Anonymous */ ) { - const decl = find(type.symbol.declarations || emptyArray, or(isFunctionTypeNode, isMethodSignature, isMethodDeclaration)); - if (decl === void 0) return createUndefined(); - const signature = checker.getSignaturesOfType(type, 0 /* Call */ ); - if (signature === void 0) return createUndefined(); - const func = createSignatureDeclarationFromSignature(215 /* FunctionExpression */ , context, quotePreference, signature[0], createStubbedBody(Diagnostics.Function_not_implemented.message, quotePreference), /*name*/ void 0, /*modifiers*/ void 0, /*optional*/ void 0, /*enclosingDeclaration*/ enclosingDeclaration, importAdder); - return func != null ? func : createUndefined(); + function textSpanEndingAtNextToken(startNode2, previousTokenToFindNextEndToken) { + return textSpan(startNode2, findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile)); } - if (getObjectFlags(type) & 1 /* Class */ ) { - const classDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); - if (classDeclaration === void 0 || hasAbstractModifier(classDeclaration)) return createUndefined(); - const constructorDeclaration = getFirstConstructorWithBody(classDeclaration); - if (constructorDeclaration && length(constructorDeclaration.parameters)) return createUndefined(); - return factory.createNewExpression(factory.createIdentifier(type.symbol.name), /*typeArguments*/ void 0, /*argumentsArray*/ void 0); + function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { + if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) return spanInNode(node); + return spanInNode(otherwiseOnNode); } - return createUndefined(); - } - function createUndefined() { - return factory.createIdentifier("undefined"); - } - function isObjectLiteralType(type) { - return type.flags & 524288 /* Object */ && (getObjectFlags(type) & 128 /* ObjectLiteral */ || type.symbol && tryCast(singleOrUndefined(type.symbol.declarations), isTypeLiteralNode)); - } - function getUnmatchedAttributes(checker, target, source) { - const attrsType = checker.getContextualType(source.attributes); - if (attrsType === void 0) return emptyArray; - const targetProps = attrsType.getProperties(); - if (!length(targetProps)) return emptyArray; - const seenNames = /* @__PURE__ */ new Set(); - for (const sourceProp of source.attributes.properties){ - if (isJsxAttribute(sourceProp)) seenNames.add(sourceProp.name.escapedText); - if (isJsxSpreadAttribute(sourceProp)) { - const type = checker.getTypeAtLocation(sourceProp.expression); - for (const prop of type.getProperties())seenNames.add(prop.escapedName); + function spanInNodeArray(nodeArray, node, match) { + if (nodeArray) { + const index = nodeArray.indexOf(node); + if (index >= 0) { + let start = index; + let end = index + 1; + while(start > 0 && match(nodeArray[start - 1]))start--; + while(end < nodeArray.length && match(nodeArray[end]))end++; + return createTextSpanFromBounds(skipTrivia(sourceFile.text, nodeArray[start].pos), nodeArray[end - 1].end); + } } + return textSpan(node); } - return filter(targetProps, (targetProp)=>isIdentifierText(targetProp.name, target, 1 /* JSX */ ) && !(targetProp.flags & 16777216 /* Optional */ || getCheckFlags(targetProp) & 48 /* Partial */ || seenNames.has(targetProp.escapedName))); - } - function tryGetContainingMethodDeclaration(node, callExpression) { - if (isTypeLiteralNode(node)) return void 0; - const declaration = findAncestor(callExpression, (n)=>isMethodDeclaration(n) || isConstructorDeclaration(n)); - return declaration && declaration.parent === node ? declaration : void 0; - } - function createPropertyNameFromSymbol(symbol, target, quotePreference, checker) { - if (isTransientSymbol(symbol)) { - const prop = checker.symbolToNode(symbol, 111551 /* Value */ , /*enclosingDeclaration*/ void 0, 1073741824 /* WriteComputedProps */ ); - if (prop && isComputedPropertyName(prop)) return prop; + function spanInPreviousNode(node) { + return spanInNode(findPrecedingToken(node.pos, sourceFile)); } - return createPropertyNameNodeForIdentifierOrLiteral(symbol.name, target, quotePreference === 0 /* Single */ ); - } - function findScope(node) { - if (findAncestor(node, isJsxExpression)) { - const returnStatement = findAncestor(node.parent, isReturnStatement); - if (returnStatement) return returnStatement; + function spanInNextNode(node) { + return spanInNode(findNextToken(node, node.parent, sourceFile)); } - return getSourceFileOfNode(node); - } - var fixMissingMember, fixMissingProperties, fixMissingAttributes, fixMissingFunctionDeclaration, errorCodes26; - var init_fixAddMissingMember = __esm({ - "src/services/codefixes/fixAddMissingMember.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixMissingMember = "fixMissingMember"; - fixMissingProperties = "fixMissingProperties"; - fixMissingAttributes = "fixMissingAttributes"; - fixMissingFunctionDeclaration = "fixMissingFunctionDeclaration"; - errorCodes26 = [ - Diagnostics.Property_0_does_not_exist_on_type_1.code, - Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, - Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2.code, - Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2.code, - Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code, - Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, - Diagnostics.Cannot_find_name_0.code - ]; - registerCodeFix({ - errorCodes: errorCodes26, - getCodeActions (context) { - const typeChecker = context.program.getTypeChecker(); - const info = getInfo7(context.sourceFile, context.span.start, context.errorCode, typeChecker, context.program); - if (!info) return void 0; - if (info.kind === 3 /* ObjectLiteral */ ) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addObjectLiteralProperties(t, context, info)); - return [ - createCodeFixAction(fixMissingProperties, changes, Diagnostics.Add_missing_properties, fixMissingProperties, Diagnostics.Add_all_missing_properties) - ]; - } - if (info.kind === 4 /* JsxAttributes */ ) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addJsxAttributes(t, context, info)); - return [ - createCodeFixAction(fixMissingAttributes, changes, Diagnostics.Add_missing_attributes, fixMissingAttributes, Diagnostics.Add_all_missing_attributes) - ]; - } - if (info.kind === 2 /* Function */ || info.kind === 5 /* Signature */ ) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addFunctionDeclaration(t, context, info)); - return [ - createCodeFixAction(fixMissingFunctionDeclaration, changes, [ - Diagnostics.Add_missing_function_declaration_0, - info.token.text - ], fixMissingFunctionDeclaration, Diagnostics.Add_all_missing_function_declarations) - ]; - } - if (info.kind === 1 /* Enum */ ) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addEnumMemberDeclaration(t, context.program.getTypeChecker(), info)); - return [ - createCodeFixAction(fixMissingMember, changes, [ - Diagnostics.Add_missing_enum_member_0, - info.token.text - ], fixMissingMember, Diagnostics.Add_all_missing_members) - ]; - } - return concatenate(getActionsForMissingMethodDeclaration(context, info), getActionsForMissingMemberDeclaration(context, info)); - }, - fixIds: [ - fixMissingMember, - fixMissingFunctionDeclaration, - fixMissingProperties, - fixMissingAttributes - ], - getAllCodeActions: (context)=>{ - const { program: program , fixId: fixId51 } = context; - const checker = program.getTypeChecker(); - const seen = /* @__PURE__ */ new Map(); - const typeDeclToMembers = /* @__PURE__ */ new Map(); - return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes)=>{ - eachDiagnostic(context, errorCodes26, (diag2)=>{ - const info = getInfo7(diag2.file, diag2.start, diag2.code, checker, context.program); - if (!info || !addToSeen(seen, getNodeId(info.parentDeclaration) + "#" + info.token.text)) return; - if (fixId51 === fixMissingFunctionDeclaration && (info.kind === 2 /* Function */ || info.kind === 5 /* Signature */ )) addFunctionDeclaration(changes, context, info); - else if (fixId51 === fixMissingProperties && info.kind === 3 /* ObjectLiteral */ ) addObjectLiteralProperties(changes, context, info); - else if (fixId51 === fixMissingAttributes && info.kind === 4 /* JsxAttributes */ ) addJsxAttributes(changes, context, info); - else { - if (info.kind === 1 /* Enum */ ) addEnumMemberDeclaration(changes, checker, info); - if (info.kind === 0 /* TypeLikeDeclaration */ ) { - const { parentDeclaration: parentDeclaration , token: token } = info; - const infos = getOrUpdate(typeDeclToMembers, parentDeclaration, ()=>[]); - if (!infos.some((i)=>i.token.text === token.text)) infos.push(info); + function spanInNode(node) { + if (node) { + const { parent: parent2 } = node; + switch(node.kind){ + case 243 /* VariableStatement */ : + return spanInVariableDeclaration(node.declarationList.declarations[0]); + case 260 /* VariableDeclaration */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : + return spanInVariableDeclaration(node); + case 169 /* Parameter */ : + return spanInParameterDeclaration(node); + case 262 /* FunctionDeclaration */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 176 /* Constructor */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + return spanInFunctionDeclaration(node); + case 241 /* Block */ : + if (isFunctionBlock(node)) return spanInFunctionBlock(node); + case 268 /* ModuleBlock */ : + return spanInBlock(node); + case 299 /* CatchClause */ : + return spanInBlock(node.block); + case 244 /* ExpressionStatement */ : + return textSpan(node.expression); + case 253 /* ReturnStatement */ : + return textSpan(node.getChildAt(0), node.expression); + case 247 /* WhileStatement */ : + return textSpanEndingAtNextToken(node, node.expression); + case 246 /* DoStatement */ : + return spanInNode(node.statement); + case 259 /* DebuggerStatement */ : + return textSpan(node.getChildAt(0)); + case 245 /* IfStatement */ : + return textSpanEndingAtNextToken(node, node.expression); + case 256 /* LabeledStatement */ : + return spanInNode(node.statement); + case 252 /* BreakStatement */ : + case 251 /* ContinueStatement */ : + return textSpan(node.getChildAt(0), node.label); + case 248 /* ForStatement */ : + return spanInForStatement(node); + case 249 /* ForInStatement */ : + return textSpanEndingAtNextToken(node, node.expression); + case 250 /* ForOfStatement */ : + return spanInInitializerOfForLike(node); + case 255 /* SwitchStatement */ : + return textSpanEndingAtNextToken(node, node.expression); + case 296 /* CaseClause */ : + case 297 /* DefaultClause */ : + return spanInNode(node.statements[0]); + case 258 /* TryStatement */ : + return spanInBlock(node.tryBlock); + case 257 /* ThrowStatement */ : + return textSpan(node, node.expression); + case 277 /* ExportAssignment */ : + return textSpan(node, node.expression); + case 271 /* ImportEqualsDeclaration */ : + return textSpan(node, node.moduleReference); + case 272 /* ImportDeclaration */ : + return textSpan(node, node.moduleSpecifier); + case 278 /* ExportDeclaration */ : + return textSpan(node, node.moduleSpecifier); + case 267 /* ModuleDeclaration */ : + if (getModuleInstanceState(node) !== 1 /* Instantiated */ ) return void 0; + case 263 /* ClassDeclaration */ : + case 266 /* EnumDeclaration */ : + case 306 /* EnumMember */ : + case 208 /* BindingElement */ : + return textSpan(node); + case 254 /* WithStatement */ : + return spanInNode(node.statement); + case 170 /* Decorator */ : + return spanInNodeArray(parent2.modifiers, node, isDecorator); + case 206 /* ObjectBindingPattern */ : + case 207 /* ArrayBindingPattern */ : + return spanInBindingPattern(node); + case 264 /* InterfaceDeclaration */ : + case 265 /* TypeAliasDeclaration */ : + return void 0; + case 27 /* SemicolonToken */ : + case 1 /* EndOfFileToken */ : + return spanInNodeIfStartsOnSameLine(findPrecedingToken(node.pos, sourceFile)); + case 28 /* CommaToken */ : + return spanInPreviousNode(node); + case 19 /* OpenBraceToken */ : + return spanInOpenBraceToken(node); + case 20 /* CloseBraceToken */ : + return spanInCloseBraceToken(node); + case 24 /* CloseBracketToken */ : + return spanInCloseBracketToken(node); + case 21 /* OpenParenToken */ : + return spanInOpenParenToken(node); + case 22 /* CloseParenToken */ : + return spanInCloseParenToken(node); + case 59 /* ColonToken */ : + return spanInColonToken(node); + case 32 /* GreaterThanToken */ : + case 30 /* LessThanToken */ : + return spanInGreaterThanOrLessThanToken(node); + case 117 /* WhileKeyword */ : + return spanInWhileKeyword(node); + case 93 /* ElseKeyword */ : + case 85 /* CatchKeyword */ : + case 98 /* FinallyKeyword */ : + return spanInNextNode(node); + case 165 /* OfKeyword */ : + return spanInOfKeyword(node); + default: + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node)) return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node); + if ((node.kind === 80 /* Identifier */ || node.kind === 230 /* SpreadElement */ || node.kind === 303 /* PropertyAssignment */ || node.kind === 304 /* ShorthandPropertyAssignment */ ) && isArrayLiteralOrObjectLiteralDestructuringPattern(parent2)) return textSpan(node); + if (node.kind === 226 /* BinaryExpression */ ) { + const { left: left, operatorToken: operatorToken } = node; + if (isArrayLiteralOrObjectLiteralDestructuringPattern(left)) return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left); + if (operatorToken.kind === 64 /* EqualsToken */ && isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) return textSpan(node); + if (operatorToken.kind === 28 /* CommaToken */ ) return spanInNode(left); + } + if (isExpressionNode(node)) switch(parent2.kind){ + case 246 /* DoStatement */ : + return spanInPreviousNode(node); + case 170 /* Decorator */ : + return spanInNode(node.parent); + case 248 /* ForStatement */ : + case 250 /* ForOfStatement */ : + return textSpan(node); + case 226 /* BinaryExpression */ : + if (node.parent.operatorToken.kind === 28 /* CommaToken */ ) return textSpan(node); + break; + case 219 /* ArrowFunction */ : + if (node.parent.body === node) return textSpan(node); + break; + } + switch(node.parent.kind){ + case 303 /* PropertyAssignment */ : + if (node.parent.name === node && !isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) return spanInNode(node.parent.initializer); + break; + case 216 /* TypeAssertionExpression */ : + if (node.parent.type === node) return spanInNextNode(node.parent.type); + break; + case 260 /* VariableDeclaration */ : + case 169 /* Parameter */ : + { + const { initializer: initializer, type: type } = node.parent; + if (initializer === node || type === node || isAssignmentOperator(node.kind)) return spanInPreviousNode(node); + break; } - } - }); - typeDeclToMembers.forEach((infos, declaration)=>{ - const supers = isTypeLiteralNode(declaration) ? void 0 : getAllSupers(declaration, checker); - for (const info of infos){ - if (supers == null ? void 0 : supers.some((superClassOrInterface)=>{ - const superInfos = typeDeclToMembers.get(superClassOrInterface); - return !!superInfos && superInfos.some(({ token: token2 })=>token2.text === info.token.text); - })) continue; - const { parentDeclaration: parentDeclaration , declSourceFile: declSourceFile , modifierFlags: modifierFlags , token: token , call: call , isJSFile: isJSFile } = info; - if (call && !isPrivateIdentifier(token)) addMethodDeclaration(context, changes, call, token, modifierFlags & 32 /* Static */ , parentDeclaration, declSourceFile); - else if (isJSFile && !isInterfaceDeclaration(parentDeclaration) && !isTypeLiteralNode(parentDeclaration)) addMissingMemberInJs(changes, declSourceFile, parentDeclaration, token, !!(modifierFlags & 32 /* Static */ )); - else { - const typeNode = getTypeNode2(checker, parentDeclaration, token); - addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, modifierFlags & 32 /* Static */ ); + case 226 /* BinaryExpression */ : + { + const { left: left } = node.parent; + if (isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) return spanInPreviousNode(node); + break; } - } - }); - })); + default: + if (isFunctionLike(node.parent) && node.parent.type === node) return spanInPreviousNode(node); + } + return spanInNode(node.parent); } - }); + } + function textSpanFromVariableDeclaration(variableDeclaration) { + if (isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] === variableDeclaration) return textSpan(findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); + else return textSpan(variableDeclaration); + } + function spanInVariableDeclaration(variableDeclaration) { + if (variableDeclaration.parent.parent.kind === 249 /* ForInStatement */ ) return spanInNode(variableDeclaration.parent.parent); + const parent2 = variableDeclaration.parent; + if (isBindingPattern(variableDeclaration.name)) return spanInBindingPattern(variableDeclaration.name); + if (hasOnlyExpressionInitializer(variableDeclaration) && variableDeclaration.initializer || hasSyntacticModifier(variableDeclaration, 1 /* Export */ ) || parent2.parent.kind === 250 /* ForOfStatement */ ) return textSpanFromVariableDeclaration(variableDeclaration); + if (isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] !== variableDeclaration) return spanInNode(findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent)); + } + function canHaveSpanInParameterDeclaration(parameter) { + return !!parameter.initializer || parameter.dotDotDotToken !== void 0 || hasSyntacticModifier(parameter, 12 /* Private */ ); + } + function spanInParameterDeclaration(parameter) { + if (isBindingPattern(parameter.name)) return spanInBindingPattern(parameter.name); + else if (canHaveSpanInParameterDeclaration(parameter)) return textSpan(parameter); + else { + const functionDeclaration = parameter.parent; + const indexOfParameter = functionDeclaration.parameters.indexOf(parameter); + Debug.assert(indexOfParameter !== -1); + if (indexOfParameter !== 0) return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]); + else return spanInNode(functionDeclaration.body); + } + } + function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { + return hasSyntacticModifier(functionDeclaration, 1 /* Export */ ) || functionDeclaration.parent.kind === 263 /* ClassDeclaration */ && functionDeclaration.kind !== 176 /* Constructor */ ; + } + function spanInFunctionDeclaration(functionDeclaration) { + if (!functionDeclaration.body) return void 0; + if (canFunctionHaveSpanInWholeDeclaration(functionDeclaration)) return textSpan(functionDeclaration); + return spanInNode(functionDeclaration.body); + } + function spanInFunctionBlock(block) { + const nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken(); + if (canFunctionHaveSpanInWholeDeclaration(block.parent)) return spanInNodeIfStartsOnSameLine(block.parent, nodeForSpanInBlock); + return spanInNode(nodeForSpanInBlock); + } + function spanInBlock(block) { + switch(block.parent.kind){ + case 267 /* ModuleDeclaration */ : + if (getModuleInstanceState(block.parent) !== 1 /* Instantiated */ ) return void 0; + case 247 /* WhileStatement */ : + case 245 /* IfStatement */ : + case 249 /* ForInStatement */ : + return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); + case 248 /* ForStatement */ : + case 250 /* ForOfStatement */ : + return spanInNodeIfStartsOnSameLine(findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); + } + return spanInNode(block.statements[0]); + } + function spanInInitializerOfForLike(forLikeStatement) { + if (forLikeStatement.initializer.kind === 261 /* VariableDeclarationList */ ) { + const variableDeclarationList = forLikeStatement.initializer; + if (variableDeclarationList.declarations.length > 0) return spanInNode(variableDeclarationList.declarations[0]); + } else return spanInNode(forLikeStatement.initializer); + } + function spanInForStatement(forStatement) { + if (forStatement.initializer) return spanInInitializerOfForLike(forStatement); + if (forStatement.condition) return textSpan(forStatement.condition); + if (forStatement.incrementor) return textSpan(forStatement.incrementor); + } + function spanInBindingPattern(bindingPattern) { + const firstBindingElement = forEach(bindingPattern.elements, (element)=>element.kind !== 232 /* OmittedExpression */ ? element : void 0); + if (firstBindingElement) return spanInNode(firstBindingElement); + if (bindingPattern.parent.kind === 208 /* BindingElement */ ) return textSpan(bindingPattern.parent); + return textSpanFromVariableDeclaration(bindingPattern.parent); + } + function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node2) { + Debug.assert(node2.kind !== 207 /* ArrayBindingPattern */ && node2.kind !== 206 /* ObjectBindingPattern */ ); + const elements = node2.kind === 209 /* ArrayLiteralExpression */ ? node2.elements : node2.properties; + const firstBindingElement = forEach(elements, (element)=>element.kind !== 232 /* OmittedExpression */ ? element : void 0); + if (firstBindingElement) return spanInNode(firstBindingElement); + return textSpan(node2.parent.kind === 226 /* BinaryExpression */ ? node2.parent : node2); + } + function spanInOpenBraceToken(node2) { + switch(node2.parent.kind){ + case 266 /* EnumDeclaration */ : + const enumDeclaration = node2.parent; + return spanInNodeIfStartsOnSameLine(findPrecedingToken(node2.pos, sourceFile, node2.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); + case 263 /* ClassDeclaration */ : + const classDeclaration = node2.parent; + return spanInNodeIfStartsOnSameLine(findPrecedingToken(node2.pos, sourceFile, node2.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); + case 269 /* CaseBlock */ : + return spanInNodeIfStartsOnSameLine(node2.parent.parent, node2.parent.clauses[0]); + } + return spanInNode(node2.parent); + } + function spanInCloseBraceToken(node2) { + switch(node2.parent.kind){ + case 268 /* ModuleBlock */ : + if (getModuleInstanceState(node2.parent.parent) !== 1 /* Instantiated */ ) return void 0; + case 266 /* EnumDeclaration */ : + case 263 /* ClassDeclaration */ : + return textSpan(node2); + case 241 /* Block */ : + if (isFunctionBlock(node2.parent)) return textSpan(node2); + case 299 /* CatchClause */ : + return spanInNode(lastOrUndefined(node2.parent.statements)); + case 269 /* CaseBlock */ : + const caseBlock = node2.parent; + const lastClause = lastOrUndefined(caseBlock.clauses); + if (lastClause) return spanInNode(lastOrUndefined(lastClause.statements)); + return void 0; + case 206 /* ObjectBindingPattern */ : + const bindingPattern = node2.parent; + return spanInNode(lastOrUndefined(bindingPattern.elements) || bindingPattern); + default: + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node2.parent)) { + const objectLiteral = node2.parent; + return textSpan(lastOrUndefined(objectLiteral.properties) || objectLiteral); + } + return spanInNode(node2.parent); + } + } + function spanInCloseBracketToken(node2) { + switch(node2.parent.kind){ + case 207 /* ArrayBindingPattern */ : + const bindingPattern = node2.parent; + return textSpan(lastOrUndefined(bindingPattern.elements) || bindingPattern); + default: + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node2.parent)) { + const arrayLiteral = node2.parent; + return textSpan(lastOrUndefined(arrayLiteral.elements) || arrayLiteral); + } + return spanInNode(node2.parent); + } + } + function spanInOpenParenToken(node2) { + if (node2.parent.kind === 246 /* DoStatement */ || // Go to while keyword and do action instead + node2.parent.kind === 213 /* CallExpression */ || node2.parent.kind === 214 /* NewExpression */ ) return spanInPreviousNode(node2); + if (node2.parent.kind === 217 /* ParenthesizedExpression */ ) return spanInNextNode(node2); + return spanInNode(node2.parent); + } + function spanInCloseParenToken(node2) { + switch(node2.parent.kind){ + case 218 /* FunctionExpression */ : + case 262 /* FunctionDeclaration */ : + case 219 /* ArrowFunction */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 176 /* Constructor */ : + case 247 /* WhileStatement */ : + case 246 /* DoStatement */ : + case 248 /* ForStatement */ : + case 250 /* ForOfStatement */ : + case 213 /* CallExpression */ : + case 214 /* NewExpression */ : + case 217 /* ParenthesizedExpression */ : + return spanInPreviousNode(node2); + default: + return spanInNode(node2.parent); + } + } + function spanInColonToken(node2) { + if (isFunctionLike(node2.parent) || node2.parent.kind === 303 /* PropertyAssignment */ || node2.parent.kind === 169 /* Parameter */ ) return spanInPreviousNode(node2); + return spanInNode(node2.parent); + } + function spanInGreaterThanOrLessThanToken(node2) { + if (node2.parent.kind === 216 /* TypeAssertionExpression */ ) return spanInNextNode(node2); + return spanInNode(node2.parent); + } + function spanInWhileKeyword(node2) { + if (node2.parent.kind === 246 /* DoStatement */ ) return textSpanEndingAtNextToken(node2, node2.parent.expression); + return spanInNode(node2.parent); + } + function spanInOfKeyword(node2) { + if (node2.parent.kind === 250 /* ForOfStatement */ ) return spanInNextNode(node2); + return spanInNode(node2.parent); + } } - }); - // src/services/codefixes/fixAddMissingNewOperator.ts - function addMissingNewOperator(changes, sourceFile, span) { - const call = cast(findAncestorMatchingSpan2(sourceFile, span), isCallExpression); - const newExpression = factory.createNewExpression(call.expression, call.typeArguments, call.arguments); - changes.replaceNode(sourceFile, call, newExpression); - } - function findAncestorMatchingSpan2(sourceFile, span) { - let token = getTokenAtPosition(sourceFile, span.start); - const end = textSpanEnd(span); - while(token.end < end)token = token.parent; - return token; } - var fixId23, errorCodes27; - var init_fixAddMissingNewOperator = __esm({ - "src/services/codefixes/fixAddMissingNewOperator.ts" () { + var init_breakpoints = __esm({ + "src/services/breakpoints.ts" () { "use strict"; init_ts4(); - init_ts_codefix(); - fixId23 = "addMissingNewOperator"; - errorCodes27 = [ - Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new.code - ]; - registerCodeFix({ - errorCodes: errorCodes27, - getCodeActions (context) { - const { sourceFile: sourceFile , span: span } = context; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addMissingNewOperator(t, sourceFile, span)); - return [ - createCodeFixAction(fixId23, changes, Diagnostics.Add_missing_new_operator_to_call, fixId23, Diagnostics.Add_missing_new_operator_to_all_calls) - ]; - }, - fixIds: [ - fixId23 - ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes27, (changes, diag2)=>addMissingNewOperator(changes, context.sourceFile, diag2)) - }); } }); - // src/services/codefixes/fixCannotFindModule.ts - function getInstallCommand(fileName, packageName) { - return { - type: "install package", - file: fileName, - packageName: packageName - }; - } - function tryGetImportedPackageName(sourceFile, pos) { - const moduleSpecifierText = tryCast(getTokenAtPosition(sourceFile, pos), isStringLiteral); - if (!moduleSpecifierText) return void 0; - const moduleName = moduleSpecifierText.text; - const { packageName: packageName } = parsePackageName(moduleName); - return isExternalModuleNameRelative(packageName) ? void 0 : packageName; - } - function getTypesPackageNameToInstall(packageName, host, diagCode) { - var _a2; - return diagCode === errorCodeCannotFindModule ? ts_JsTyping_exports.nodeCoreModules.has(packageName) ? "@types/node" : void 0 : ((_a2 = host.isKnownTypesPackageName) == null ? void 0 : _a2.call(host, packageName)) ? getTypesPackageName(packageName) : void 0; - } - var fixName2, fixIdInstallTypesPackage, errorCodeCannotFindModule, errorCodes28; - var init_fixCannotFindModule = __esm({ - "src/services/codefixes/fixCannotFindModule.ts" () { + // src/services/_namespaces/ts.BreakpointResolver.ts + var ts_BreakpointResolver_exports = {}; + __export(ts_BreakpointResolver_exports, { + spanInSourceFileAtLocation: ()=>spanInSourceFileAtLocation + }); + var init_ts_BreakpointResolver = __esm({ + "src/services/_namespaces/ts.BreakpointResolver.ts" () { "use strict"; - init_ts4(); - init_ts_codefix(); - fixName2 = "fixCannotFindModule"; - fixIdInstallTypesPackage = "installTypesPackage"; - errorCodeCannotFindModule = Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations.code; - errorCodes28 = [ - errorCodeCannotFindModule, - Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code - ]; - registerCodeFix({ - errorCodes: errorCodes28, - getCodeActions: function getCodeActionsToFixNotFoundModule(context) { - const { host: host , sourceFile: sourceFile , span: { start: start } } = context; - const packageName = tryGetImportedPackageName(sourceFile, start); - if (packageName === void 0) return void 0; - const typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); - return typesPackageName === void 0 ? [] : [ - createCodeFixAction(fixName2, /*changes*/ [], [ - Diagnostics.Install_0, - typesPackageName - ], fixIdInstallTypesPackage, Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName)) - ]; - }, - fixIds: [ - fixIdInstallTypesPackage - ], - getAllCodeActions: (context)=>{ - return codeFixAll(context, errorCodes28, (_changes, diag2, commands)=>{ - const packageName = tryGetImportedPackageName(diag2.file, diag2.start); - if (packageName === void 0) return void 0; - switch(context.fixId){ - case fixIdInstallTypesPackage: - { - const pkg = getTypesPackageNameToInstall(packageName, context.host, diag2.code); - if (pkg) commands.push(getInstallCommand(diag2.file.fileName, pkg)); - break; - } - default: - Debug.fail(`Bad fixId: ${context.fixId}`); - } - }); - } - }); + init_breakpoints(); } }); - // src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts - function getClass2(sourceFile, pos) { - const token = getTokenAtPosition(sourceFile, pos); - return cast(token.parent, isClassLike); + // src/services/callHierarchy.ts + function isNamedExpression(node) { + return (isFunctionExpression(node) || isClassExpression(node)) && isNamedDeclaration(node); } - function addMissingMembers(classDeclaration, sourceFile, context, changeTracker, preferences) { - const extendsNode = getEffectiveBaseTypeNode(classDeclaration); - const checker = context.program.getTypeChecker(); - const instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); - const abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); - const importAdder = createImportAdder(sourceFile, context.program, preferences, context.host); - createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, sourceFile, context, preferences, importAdder, (member)=>changeTracker.insertMemberAtStart(sourceFile, classDeclaration, member)); - importAdder.writeFixes(changeTracker); + function isConstNamedExpression(node) { + return (isFunctionExpression(node) || isArrowFunction(node) || isClassExpression(node)) && isVariableDeclaration(node.parent) && node === node.parent.initializer && isIdentifier(node.parent.name) && !!(getCombinedNodeFlags(node.parent) & 2 /* Const */ ); } - function symbolPointsToNonPrivateAndAbstractMember(symbol) { - const flags = getSyntacticModifierFlags(first(symbol.getDeclarations())); - return !(flags & 8 /* Private */ ) && !!(flags & 256 /* Abstract */ ); + function isPossibleCallHierarchyDeclaration(node) { + return isSourceFile(node) || isModuleDeclaration(node) || isFunctionDeclaration(node) || isFunctionExpression(node) || isClassDeclaration(node) || isClassExpression(node) || isClassStaticBlockDeclaration(node) || isMethodDeclaration(node) || isMethodSignature(node) || isGetAccessorDeclaration(node) || isSetAccessorDeclaration(node); } - var errorCodes29, fixId24; - var init_fixClassDoesntImplementInheritedAbstractMember = __esm({ - "src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - errorCodes29 = [ - Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code, - Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code - ]; - fixId24 = "fixClassDoesntImplementInheritedAbstractMember"; - registerCodeFix({ - errorCodes: errorCodes29, - getCodeActions: function getCodeActionsToFixClassNotImplementingInheritedMembers(context) { - const { sourceFile: sourceFile , span: span } = context; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addMissingMembers(getClass2(sourceFile, span.start), sourceFile, context, t, context.preferences)); - return changes.length === 0 ? void 0 : [ - createCodeFixAction(fixId24, changes, Diagnostics.Implement_inherited_abstract_class, fixId24, Diagnostics.Implement_all_inherited_abstract_classes) - ]; - }, - fixIds: [ - fixId24 - ], - getAllCodeActions: function getAllCodeActionsToFixClassDoesntImplementInheritedAbstractMember(context) { - const seenClassDeclarations = /* @__PURE__ */ new Map(); - return codeFixAll(context, errorCodes29, (changes, diag2)=>{ - const classDeclaration = getClass2(diag2.file, diag2.start); - if (addToSeen(seenClassDeclarations, getNodeId(classDeclaration))) addMissingMembers(classDeclaration, context.sourceFile, context, changes, context.preferences); - }); - } - }); - } - }); - // src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts - function doChange11(changes, sourceFile, constructor, superCall) { - changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall); - changes.delete(sourceFile, superCall); + function isValidCallHierarchyDeclaration(node) { + return isSourceFile(node) || isModuleDeclaration(node) && isIdentifier(node.name) || isFunctionDeclaration(node) || isClassDeclaration(node) || isClassStaticBlockDeclaration(node) || isMethodDeclaration(node) || isMethodSignature(node) || isGetAccessorDeclaration(node) || isSetAccessorDeclaration(node) || isNamedExpression(node) || isConstNamedExpression(node); } - function getNodes(sourceFile, pos) { - const token = getTokenAtPosition(sourceFile, pos); - if (token.kind !== 108 /* ThisKeyword */ ) return void 0; - const constructor = getContainingFunction(token); - const superCall = findSuperCall(constructor.body); - return superCall && !superCall.expression.arguments.some((arg)=>isPropertyAccessExpression(arg) && arg.expression === token) ? { - constructor: constructor, - superCall: superCall - } : void 0; + function getCallHierarchyDeclarationReferenceNode(node) { + if (isSourceFile(node)) return node; + if (isNamedDeclaration(node)) return node.name; + if (isConstNamedExpression(node)) return node.parent.name; + return Debug.checkDefined(node.modifiers && find(node.modifiers, isDefaultModifier3)); } - function findSuperCall(n) { - return isExpressionStatement(n) && isSuperCall(n.expression) ? n : isFunctionLike(n) ? void 0 : forEachChild(n, findSuperCall); + function isDefaultModifier3(node) { + return node.kind === 90 /* DefaultKeyword */ ; } - var fixId25, errorCodes30; - var init_fixClassSuperMustPrecedeThisAccess = __esm({ - "src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId25 = "classSuperMustPrecedeThisAccess"; - errorCodes30 = [ - Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code - ]; - registerCodeFix({ - errorCodes: errorCodes30, - getCodeActions (context) { - const { sourceFile: sourceFile , span: span } = context; - const nodes = getNodes(sourceFile, span.start); - if (!nodes) return void 0; - const { constructor: constructor , superCall: superCall } = nodes; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange11(t, sourceFile, constructor, superCall)); - return [ - createCodeFixAction(fixId25, changes, Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId25, Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor) - ]; - }, - fixIds: [ - fixId25 - ], - getAllCodeActions (context) { - const { sourceFile: sourceFile } = context; - const seenClasses = /* @__PURE__ */ new Map(); - return codeFixAll(context, errorCodes30, (changes, diag2)=>{ - const nodes = getNodes(diag2.file, diag2.start); - if (!nodes) return; - const { constructor: constructor , superCall: superCall } = nodes; - if (addToSeen(seenClasses, getNodeId(constructor.parent))) doChange11(changes, sourceFile, constructor, superCall); - }); - } - }); + function getSymbolOfCallHierarchyDeclaration(typeChecker, node) { + const location = getCallHierarchyDeclarationReferenceNode(node); + return location && typeChecker.getSymbolAtLocation(location); + } + function getCallHierarchyItemName(program, node) { + if (isSourceFile(node)) return { + text: node.fileName, + pos: 0, + end: 0 + }; + if ((isFunctionDeclaration(node) || isClassDeclaration(node)) && !isNamedDeclaration(node)) { + const defaultModifier = node.modifiers && find(node.modifiers, isDefaultModifier3); + if (defaultModifier) return { + text: "default", + pos: defaultModifier.getStart(), + end: defaultModifier.getEnd() + }; } - }); - // src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts - function getNode(sourceFile, pos) { - const token = getTokenAtPosition(sourceFile, pos); - Debug.assert(isConstructorDeclaration(token.parent), "token should be at the constructor declaration"); - return token.parent; + if (isClassStaticBlockDeclaration(node)) { + const sourceFile = node.getSourceFile(); + const pos = skipTrivia(sourceFile.text, moveRangePastModifiers(node).pos); + const end = pos + 6; + const typeChecker = program.getTypeChecker(); + const symbol = typeChecker.getSymbolAtLocation(node.parent); + const prefix = symbol ? `${typeChecker.symbolToString(symbol, node.parent)} ` : ""; + return { + text: `${prefix}static {}`, + pos: pos, + end: end + }; + } + const declName = isConstNamedExpression(node) ? node.parent.name : Debug.checkDefined(getNameOfDeclaration(node), "Expected call hierarchy item to have a name"); + let text = isIdentifier(declName) ? idText(declName) : isStringOrNumericLiteralLike(declName) ? declName.text : isComputedPropertyName(declName) ? isStringOrNumericLiteralLike(declName.expression) ? declName.expression.text : void 0 : void 0; + if (text === void 0) { + const typeChecker = program.getTypeChecker(); + const symbol = typeChecker.getSymbolAtLocation(declName); + if (symbol) text = typeChecker.symbolToString(symbol, node); + } + if (text === void 0) { + const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon(); + text = usingSingleLineStringWriter((writer)=>printer.writeNode(4 /* Unspecified */ , node, node.getSourceFile(), writer)); + } + return { + text: text, + pos: declName.getStart(), + end: declName.getEnd() + }; } - function doChange12(changes, sourceFile, ctr) { - const superCall = factory.createExpressionStatement(factory.createCallExpression(factory.createSuper(), /*typeArguments*/ void 0, /*argumentsArray*/ emptyArray)); - changes.insertNodeAtConstructorStart(sourceFile, ctr, superCall); + function getCallHierarchItemContainerName(node) { + var _a, _b; + if (isConstNamedExpression(node)) { + if (isModuleBlock(node.parent.parent.parent.parent) && isIdentifier(node.parent.parent.parent.parent.parent.name)) return node.parent.parent.parent.parent.parent.name.getText(); + return; + } + switch(node.kind){ + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 174 /* MethodDeclaration */ : + if (node.parent.kind === 210 /* ObjectLiteralExpression */ ) return (_a = getAssignedName(node.parent)) == null ? void 0 : _a.getText(); + return (_b = getNameOfDeclaration(node.parent)) == null ? void 0 : _b.getText(); + case 262 /* FunctionDeclaration */ : + case 263 /* ClassDeclaration */ : + case 267 /* ModuleDeclaration */ : + if (isModuleBlock(node.parent) && isIdentifier(node.parent.parent.name)) return node.parent.parent.name.getText(); + } } - var fixId26, errorCodes31; - var init_fixConstructorForDerivedNeedSuperCall = __esm({ - "src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId26 = "constructorForDerivedNeedSuperCall"; - errorCodes31 = [ - Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code - ]; - registerCodeFix({ - errorCodes: errorCodes31, - getCodeActions (context) { - const { sourceFile: sourceFile , span: span } = context; - const ctr = getNode(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange12(t, sourceFile, ctr)); - return [ - createCodeFixAction(fixId26, changes, Diagnostics.Add_missing_super_call, fixId26, Diagnostics.Add_all_missing_super_calls) - ]; - }, - fixIds: [ - fixId26 - ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes31, (changes, diag2)=>doChange12(changes, context.sourceFile, getNode(diag2.file, diag2.start))) - }); + function findImplementation(typeChecker, node) { + if (node.body) return node; + if (isConstructorDeclaration(node)) return getFirstConstructorWithBody(node.parent); + if (isFunctionDeclaration(node) || isMethodDeclaration(node)) { + const symbol = getSymbolOfCallHierarchyDeclaration(typeChecker, node); + if (symbol && symbol.valueDeclaration && isFunctionLikeDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.body) return symbol.valueDeclaration; + return void 0; } - }); - // src/services/codefixes/fixEnableJsxFlag.ts - function doChange13(changeTracker, configFile) { - setJsonCompilerOptionValue(changeTracker, configFile, "jsx", factory.createStringLiteral("react")); + return node; } - var fixID, errorCodes32; - var init_fixEnableJsxFlag = __esm({ - "src/services/codefixes/fixEnableJsxFlag.ts" () { + function findAllInitialDeclarations(typeChecker, node) { + const symbol = getSymbolOfCallHierarchyDeclaration(typeChecker, node); + let declarations; + if (symbol && symbol.declarations) { + const indices = indicesOf(symbol.declarations); + const keys = map(symbol.declarations, (decl)=>({ + file: decl.getSourceFile().fileName, + pos: decl.pos + })); + indices.sort((a, b)=>compareStringsCaseSensitive(keys[a].file, keys[b].file) || keys[a].pos - keys[b].pos); + const sortedDeclarations = map(indices, (i)=>symbol.declarations[i]); + let lastDecl; + for (const decl of sortedDeclarations)if (isValidCallHierarchyDeclaration(decl)) { + if (!lastDecl || lastDecl.parent !== decl.parent || lastDecl.end !== decl.pos) declarations = append(declarations, decl); + lastDecl = decl; + } + } + return declarations; + } + function findImplementationOrAllInitialDeclarations(typeChecker, node) { + if (isClassStaticBlockDeclaration(node)) return node; + if (isFunctionLikeDeclaration(node)) return findImplementation(typeChecker, node) ?? findAllInitialDeclarations(typeChecker, node) ?? node; + return findAllInitialDeclarations(typeChecker, node) ?? node; + } + function resolveCallHierarchyDeclaration(program, location) { + const typeChecker = program.getTypeChecker(); + let followingSymbol = false; + while(true){ + if (isValidCallHierarchyDeclaration(location)) return findImplementationOrAllInitialDeclarations(typeChecker, location); + if (isPossibleCallHierarchyDeclaration(location)) { + const ancestor = findAncestor(location, isValidCallHierarchyDeclaration); + return ancestor && findImplementationOrAllInitialDeclarations(typeChecker, ancestor); + } + if (isDeclarationName(location)) { + if (isValidCallHierarchyDeclaration(location.parent)) return findImplementationOrAllInitialDeclarations(typeChecker, location.parent); + if (isPossibleCallHierarchyDeclaration(location.parent)) { + const ancestor = findAncestor(location.parent, isValidCallHierarchyDeclaration); + return ancestor && findImplementationOrAllInitialDeclarations(typeChecker, ancestor); + } + if (isVariableDeclaration(location.parent) && location.parent.initializer && isConstNamedExpression(location.parent.initializer)) return location.parent.initializer; + return void 0; + } + if (isConstructorDeclaration(location)) { + if (isValidCallHierarchyDeclaration(location.parent)) return location.parent; + return void 0; + } + if (location.kind === 126 /* StaticKeyword */ && isClassStaticBlockDeclaration(location.parent)) { + location = location.parent; + continue; + } + if (isVariableDeclaration(location) && location.initializer && isConstNamedExpression(location.initializer)) return location.initializer; + if (!followingSymbol) { + let symbol = typeChecker.getSymbolAtLocation(location); + if (symbol) { + if (symbol.flags & 2097152 /* Alias */ ) symbol = typeChecker.getAliasedSymbol(symbol); + if (symbol.valueDeclaration) { + followingSymbol = true; + location = symbol.valueDeclaration; + continue; + } + } + } + return void 0; + } + } + function createCallHierarchyItem(program, node) { + const sourceFile = node.getSourceFile(); + const name = getCallHierarchyItemName(program, node); + const containerName = getCallHierarchItemContainerName(node); + const kind = getNodeKind(node); + const kindModifiers = getNodeModifiers(node); + const span = createTextSpanFromBounds(skipTrivia(sourceFile.text, node.getFullStart(), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true), node.getEnd()); + const selectionSpan = createTextSpanFromBounds(name.pos, name.end); + return { + file: sourceFile.fileName, + kind: kind, + kindModifiers: kindModifiers, + name: name.text, + containerName: containerName, + span: span, + selectionSpan: selectionSpan + }; + } + function isDefined(x) { + return x !== void 0; + } + function convertEntryToCallSite(entry) { + if (entry.kind === ts_FindAllReferences_exports.EntryKind.Node) { + const { node: node } = entry; + if (isCallOrNewExpressionTarget(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true) || isTaggedTemplateTag(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true) || isDecoratorTarget(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true) || isJsxOpeningLikeElementTagName(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true) || isRightSideOfPropertyAccess(node) || isArgumentExpressionOfElementAccess(node)) { + const sourceFile = node.getSourceFile(); + const ancestor = findAncestor(node, isValidCallHierarchyDeclaration) || sourceFile; + return { + declaration: ancestor, + range: createTextRangeFromNode(node, sourceFile) + }; + } + } + } + function getCallSiteGroupKey(entry) { + return getNodeId(entry.declaration); + } + function createCallHierarchyIncomingCall(from, fromSpans) { + return { + from: from, + fromSpans: fromSpans + }; + } + function convertCallSiteGroupToIncomingCall(program, entries) { + return createCallHierarchyIncomingCall(createCallHierarchyItem(program, entries[0].declaration), map(entries, (entry)=>createTextSpanFromRange(entry.range))); + } + function getIncomingCalls(program, declaration, cancellationToken) { + if (isSourceFile(declaration) || isModuleDeclaration(declaration) || isClassStaticBlockDeclaration(declaration)) return []; + const location = getCallHierarchyDeclarationReferenceNode(declaration); + const calls = filter(ts_FindAllReferences_exports.findReferenceOrRenameEntries(program, cancellationToken, program.getSourceFiles(), location, /*position*/ 0, { + use: ts_FindAllReferences_exports.FindReferencesUse.References + }, convertEntryToCallSite), isDefined); + return calls ? group(calls, getCallSiteGroupKey, (entries)=>convertCallSiteGroupToIncomingCall(program, entries)) : []; + } + function createCallSiteCollector(program, callSites) { + function recordCallSite(node) { + const target = isTaggedTemplateExpression(node) ? node.tag : isJsxOpeningLikeElement(node) ? node.tagName : isAccessExpression(node) ? node : isClassStaticBlockDeclaration(node) ? node : node.expression; + const declaration = resolveCallHierarchyDeclaration(program, target); + if (declaration) { + const range = createTextRangeFromNode(target, node.getSourceFile()); + if (isArray(declaration)) for (const decl of declaration)callSites.push({ + declaration: decl, + range: range + }); + else callSites.push({ + declaration: declaration, + range: range + }); + } + } + function collect(node) { + if (!node) return; + if (node.flags & 33554432 /* Ambient */ ) return; + if (isValidCallHierarchyDeclaration(node)) { + if (isClassLike(node)) { + for (const member of node.members)if (member.name && isComputedPropertyName(member.name)) collect(member.name.expression); + } + return; + } + switch(node.kind){ + case 80 /* Identifier */ : + case 271 /* ImportEqualsDeclaration */ : + case 272 /* ImportDeclaration */ : + case 278 /* ExportDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 265 /* TypeAliasDeclaration */ : + return; + case 175 /* ClassStaticBlockDeclaration */ : + recordCallSite(node); + return; + case 216 /* TypeAssertionExpression */ : + case 234 /* AsExpression */ : + collect(node.expression); + return; + case 260 /* VariableDeclaration */ : + case 169 /* Parameter */ : + collect(node.name); + collect(node.initializer); + return; + case 213 /* CallExpression */ : + recordCallSite(node); + collect(node.expression); + forEach(node.arguments, collect); + return; + case 214 /* NewExpression */ : + recordCallSite(node); + collect(node.expression); + forEach(node.arguments, collect); + return; + case 215 /* TaggedTemplateExpression */ : + recordCallSite(node); + collect(node.tag); + collect(node.template); + return; + case 286 /* JsxOpeningElement */ : + case 285 /* JsxSelfClosingElement */ : + recordCallSite(node); + collect(node.tagName); + collect(node.attributes); + return; + case 170 /* Decorator */ : + recordCallSite(node); + collect(node.expression); + return; + case 211 /* PropertyAccessExpression */ : + case 212 /* ElementAccessExpression */ : + recordCallSite(node); + forEachChild(node, collect); + break; + case 238 /* SatisfiesExpression */ : + collect(node.expression); + return; + } + if (isPartOfTypeNode(node)) return; + forEachChild(node, collect); + } + return collect; + } + function collectCallSitesOfSourceFile(node, collect) { + forEach(node.statements, collect); + } + function collectCallSitesOfModuleDeclaration(node, collect) { + if (!hasSyntacticModifier(node, 2 /* Ambient */ ) && node.body && isModuleBlock(node.body)) forEach(node.body.statements, collect); + } + function collectCallSitesOfFunctionLikeDeclaration(typeChecker, node, collect) { + const implementation = findImplementation(typeChecker, node); + if (implementation) { + forEach(implementation.parameters, collect); + collect(implementation.body); + } + } + function collectCallSitesOfClassStaticBlockDeclaration(node, collect) { + collect(node.body); + } + function collectCallSitesOfClassLikeDeclaration(node, collect) { + forEach(node.modifiers, collect); + const heritage = getClassExtendsHeritageElement(node); + if (heritage) collect(heritage.expression); + for (const member of node.members){ + if (canHaveModifiers(member)) forEach(member.modifiers, collect); + if (isPropertyDeclaration(member)) collect(member.initializer); + else if (isConstructorDeclaration(member) && member.body) { + forEach(member.parameters, collect); + collect(member.body); + } else if (isClassStaticBlockDeclaration(member)) collect(member); + } + } + function collectCallSites(program, node) { + const callSites = []; + const collect = createCallSiteCollector(program, callSites); + switch(node.kind){ + case 312 /* SourceFile */ : + collectCallSitesOfSourceFile(node, collect); + break; + case 267 /* ModuleDeclaration */ : + collectCallSitesOfModuleDeclaration(node, collect); + break; + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + collectCallSitesOfFunctionLikeDeclaration(program.getTypeChecker(), node, collect); + break; + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + collectCallSitesOfClassLikeDeclaration(node, collect); + break; + case 175 /* ClassStaticBlockDeclaration */ : + collectCallSitesOfClassStaticBlockDeclaration(node, collect); + break; + default: + Debug.assertNever(node); + } + return callSites; + } + function createCallHierarchyOutgoingCall(to, fromSpans) { + return { + to: to, + fromSpans: fromSpans + }; + } + function convertCallSiteGroupToOutgoingCall(program, entries) { + return createCallHierarchyOutgoingCall(createCallHierarchyItem(program, entries[0].declaration), map(entries, (entry)=>createTextSpanFromRange(entry.range))); + } + function getOutgoingCalls(program, declaration) { + if (declaration.flags & 33554432 /* Ambient */ || isMethodSignature(declaration)) return []; + return group(collectCallSites(program, declaration), getCallSiteGroupKey, (entries)=>convertCallSiteGroupToOutgoingCall(program, entries)); + } + var init_callHierarchy = __esm({ + "src/services/callHierarchy.ts" () { "use strict"; init_ts4(); - init_ts_codefix(); - fixID = "fixEnableJsxFlag"; - errorCodes32 = [ - Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided.code - ]; - registerCodeFix({ - errorCodes: errorCodes32, - getCodeActions: function getCodeActionsToFixEnableJsxFlag(context) { - const { configFile: configFile } = context.program.getCompilerOptions(); - if (configFile === void 0) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (changeTracker)=>doChange13(changeTracker, configFile)); - return [ - createCodeFixActionWithoutFixAll(fixID, changes, Diagnostics.Enable_the_jsx_flag_in_your_configuration_file) - ]; - }, - fixIds: [ - fixID - ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes32, (changes)=>{ - const { configFile: configFile } = context.program.getCompilerOptions(); - if (configFile === void 0) return void 0; - doChange13(changes, configFile); - }) - }); } }); - // src/services/codefixes/fixNaNEquality.ts - function getInfo8(program, sourceFile, span) { - const diag2 = find(program.getSemanticDiagnostics(sourceFile), (diag3)=>diag3.start === span.start && diag3.length === span.length); - if (diag2 === void 0 || diag2.relatedInformation === void 0) return; - const related = find(diag2.relatedInformation, (related2)=>related2.code === Diagnostics.Did_you_mean_0.code); - if (related === void 0 || related.file === void 0 || related.start === void 0 || related.length === void 0) return; - const token = findAncestorMatchingSpan(related.file, createTextSpan(related.start, related.length)); - if (token === void 0) return; - if (isExpression(token) && isBinaryExpression(token.parent)) return { - suggestion: getSuggestion(related.messageText), - expression: token.parent, - arg: token + // src/services/_namespaces/ts.CallHierarchy.ts + var ts_CallHierarchy_exports = {}; + __export(ts_CallHierarchy_exports, { + createCallHierarchyItem: ()=>createCallHierarchyItem, + getIncomingCalls: ()=>getIncomingCalls, + getOutgoingCalls: ()=>getOutgoingCalls, + resolveCallHierarchyDeclaration: ()=>resolveCallHierarchyDeclaration + }); + var init_ts_CallHierarchy = __esm({ + "src/services/_namespaces/ts.CallHierarchy.ts" () { + "use strict"; + init_callHierarchy(); + } + }); + // src/services/_namespaces/ts.classifier.v2020.ts + var ts_classifier_v2020_exports = {}; + __export(ts_classifier_v2020_exports, { + TokenEncodingConsts: ()=>TokenEncodingConsts, + TokenModifier: ()=>TokenModifier, + TokenType: ()=>TokenType, + getEncodedSemanticClassifications: ()=>getEncodedSemanticClassifications2, + getSemanticClassifications: ()=>getSemanticClassifications2 + }); + var init_ts_classifier_v2020 = __esm({ + "src/services/_namespaces/ts.classifier.v2020.ts" () { + "use strict"; + init_classifier2020(); + } + }); + // src/services/_namespaces/ts.classifier.ts + var ts_classifier_exports = {}; + __export(ts_classifier_exports, { + v2020: ()=>ts_classifier_v2020_exports + }); + var init_ts_classifier = __esm({ + "src/services/_namespaces/ts.classifier.ts" () { + "use strict"; + init_ts_classifier_v2020(); + } + }); + // src/services/codeFixProvider.ts + function createCodeFixActionWithoutFixAll(fixName8, changes, description3) { + return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, /*fixId*/ void 0, /*fixAllDescription*/ void 0); + } + function createCodeFixAction(fixName8, changes, description3, fixId52, fixAllDescription, command) { + return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, fixId52, diagnosticToString(fixAllDescription), command); + } + function createCodeFixActionMaybeFixAll(fixName8, changes, description3, fixId52, fixAllDescription, command) { + return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, fixId52, fixAllDescription && diagnosticToString(fixAllDescription), command); + } + function createCodeFixActionWorker(fixName8, description3, changes, fixId52, fixAllDescription, command) { + return { + fixName: fixName8, + description: description3, + changes: changes, + fixId: fixId52, + fixAllDescription: fixAllDescription, + commands: command ? [ + command + ] : void 0 }; - return void 0; } - function doChange14(changes, sourceFile, arg, expression) { - const callExpression = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Number"), factory.createIdentifier("isNaN")), /*typeArguments*/ void 0, [ - arg - ]); - const operator = expression.operatorToken.kind; - changes.replaceNode(sourceFile, expression, operator === 37 /* ExclamationEqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */ ? factory.createPrefixUnaryExpression(53 /* ExclamationToken */ , callExpression) : callExpression); + function registerCodeFix(reg) { + for (const error2 of reg.errorCodes){ + errorCodeToFixesArray = void 0; + errorCodeToFixes.add(String(error2), reg); + } + if (reg.fixIds) for (const fixId52 of reg.fixIds){ + Debug.assert(!fixIdToRegistration.has(fixId52)); + fixIdToRegistration.set(fixId52, reg); + } } - function getSuggestion(messageText) { - const [_, suggestion] = flattenDiagnosticMessageText(messageText, "\n", 0).match(/\'(.*)\'/) || []; - return suggestion; + function getSupportedErrorCodes() { + return errorCodeToFixesArray ?? (errorCodeToFixesArray = arrayFrom(errorCodeToFixes.keys())); } - var fixId27, errorCodes33; - var init_fixNaNEquality = __esm({ - "src/services/codefixes/fixNaNEquality.ts" () { + function removeFixIdIfFixAllUnavailable(registration, diagnostics) { + const { errorCodes: errorCodes64 } = registration; + let maybeFixableDiagnostics = 0; + for (const diag2 of diagnostics){ + if (contains(errorCodes64, diag2.code)) maybeFixableDiagnostics++; + if (maybeFixableDiagnostics > 1) break; + } + const fixAllUnavailable = maybeFixableDiagnostics < 2; + return ({ fixId: fixId52, fixAllDescription: fixAllDescription, ...action })=>{ + return fixAllUnavailable ? action : { + ...action, + fixId: fixId52, + fixAllDescription: fixAllDescription + }; + }; + } + function getFixes(context) { + const diagnostics = getDiagnostics(context); + const registrations = errorCodeToFixes.get(String(context.errorCode)); + return flatMap(registrations, (f)=>map(f.getCodeActions(context), removeFixIdIfFixAllUnavailable(f, diagnostics))); + } + function getAllFixes(context) { + return fixIdToRegistration.get(cast(context.fixId, isString)).getAllCodeActions(context); + } + function createCombinedCodeActions(changes, commands) { + return { + changes: changes, + commands: commands + }; + } + function createFileTextChanges(fileName, textChanges2) { + return { + fileName: fileName, + textChanges: textChanges2 + }; + } + function codeFixAll(context, errorCodes64, use) { + const commands = []; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>eachDiagnostic(context, errorCodes64, (diag2)=>use(t, diag2, commands))); + return createCombinedCodeActions(changes, commands.length === 0 ? void 0 : commands); + } + function eachDiagnostic(context, errorCodes64, cb) { + for (const diag2 of getDiagnostics(context))if (contains(errorCodes64, diag2.code)) cb(diag2); + } + function getDiagnostics({ program: program, sourceFile: sourceFile, cancellationToken: cancellationToken }) { + return [ + ...program.getSemanticDiagnostics(sourceFile, cancellationToken), + ...program.getSyntacticDiagnostics(sourceFile, cancellationToken), + ...computeSuggestionDiagnostics(sourceFile, program, cancellationToken) + ]; + } + var errorCodeToFixes, fixIdToRegistration, errorCodeToFixesArray; + var init_codeFixProvider = __esm({ + "src/services/codeFixProvider.ts" () { + "use strict"; + init_ts4(); + errorCodeToFixes = createMultiMap(); + fixIdToRegistration = /* @__PURE__ */ new Map(); + } + }); + // src/services/codefixes/addConvertToUnknownForNonOverlappingTypes.ts + function makeChange(changeTracker, sourceFile, assertion) { + const replacement = isAsExpression(assertion) ? factory.createAsExpression(assertion.expression, factory.createKeywordTypeNode(159 /* UnknownKeyword */ )) : factory.createTypeAssertion(factory.createKeywordTypeNode(159 /* UnknownKeyword */ ), assertion.expression); + changeTracker.replaceNode(sourceFile, assertion.expression, replacement); + } + function getAssertion(sourceFile, pos) { + if (isInJSFile(sourceFile)) return void 0; + return findAncestor(getTokenAtPosition(sourceFile, pos), (n)=>isAsExpression(n) || isTypeAssertionExpression(n)); + } + var fixId, errorCodes; + var init_addConvertToUnknownForNonOverlappingTypes = __esm({ + "src/services/codefixes/addConvertToUnknownForNonOverlappingTypes.ts" () { "use strict"; init_ts4(); init_ts_codefix(); - fixId27 = "fixNaNEquality"; - errorCodes33 = [ - Diagnostics.This_condition_will_always_return_0.code + fixId = "addConvertToUnknownForNonOverlappingTypes"; + errorCodes = [ + Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first.code ]; registerCodeFix({ - errorCodes: errorCodes33, - getCodeActions (context) { - const { sourceFile: sourceFile , span: span , program: program } = context; - const info = getInfo8(program, sourceFile, span); - if (info === void 0) return; - const { suggestion: suggestion , expression: expression , arg: arg } = info; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange14(t, sourceFile, arg, expression)); + errorCodes: errorCodes, + getCodeActions: function getCodeActionsToAddConvertToUnknownForNonOverlappingTypes(context) { + const assertion = getAssertion(context.sourceFile, context.span.start); + if (assertion === void 0) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>makeChange(t, context.sourceFile, assertion)); return [ - createCodeFixAction(fixId27, changes, [ - Diagnostics.Use_0, - suggestion - ], fixId27, Diagnostics.Use_Number_isNaN_in_all_conditions) + createCodeFixAction(fixId, changes, Diagnostics.Add_unknown_conversion_for_non_overlapping_types, fixId, Diagnostics.Add_unknown_to_all_conversions_of_non_overlapping_types) ]; }, fixIds: [ - fixId27 + fixId ], - getAllCodeActions: (context)=>{ - return codeFixAll(context, errorCodes33, (changes, diag2)=>{ - const info = getInfo8(context.program, diag2.file, createTextSpan(diag2.start, diag2.length)); - if (info) doChange14(changes, diag2.file, info.arg, info.expression); - }); - } + getAllCodeActions: (context)=>codeFixAll(context, errorCodes, (changes, diag2)=>{ + const assertion = getAssertion(diag2.file, diag2.start); + if (assertion) makeChange(changes, diag2.file, assertion); + }) }); } }); - // src/services/codefixes/fixModuleAndTargetOptions.ts - var init_fixModuleAndTargetOptions = __esm({ - "src/services/codefixes/fixModuleAndTargetOptions.ts" () { + // src/services/codefixes/addEmptyExportDeclaration.ts + var init_addEmptyExportDeclaration = __esm({ + "src/services/codefixes/addEmptyExportDeclaration.ts" () { "use strict"; init_ts4(); init_ts_codefix(); registerCodeFix({ errorCodes: [ - Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code, - Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code + Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, + Diagnostics.await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, + Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code ], - getCodeActions: function getCodeActionsToFixModuleAndTarget(context) { - const compilerOptions = context.program.getCompilerOptions(); - const { configFile: configFile } = compilerOptions; - if (configFile === void 0) return void 0; - const codeFixes = []; - const moduleKind = getEmitModuleKind(compilerOptions); - const moduleOutOfRange = moduleKind >= 5 /* ES2015 */ && moduleKind < 99 /* ESNext */ ; - if (moduleOutOfRange) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2)=>{ - setJsonCompilerOptionValue(changes2, configFile, "module", factory.createStringLiteral("esnext")); - }); - codeFixes.push(createCodeFixActionWithoutFixAll("fixModuleOption", changes, [ - Diagnostics.Set_the_module_option_in_your_configuration_file_to_0, - "esnext" - ])); - } - const target = getEmitScriptTarget(compilerOptions); - const targetOutOfRange = target < 4 /* ES2017 */ || target > 99 /* ESNext */ ; - if (targetOutOfRange) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (tracker)=>{ - const configObject = getTsConfigObjectLiteralExpression(configFile); - if (!configObject) return; - const options = [ - [ - "target", - factory.createStringLiteral("es2017") - ] - ]; - if (moduleKind === 1 /* CommonJS */ ) options.push([ - "module", - factory.createStringLiteral("commonjs") - ]); - setJsonCompilerOptionValues(tracker, configFile, options); - }); - codeFixes.push(createCodeFixActionWithoutFixAll("fixTargetOption", changes, [ - Diagnostics.Set_the_target_option_in_your_configuration_file_to_0, - "es2017" - ])); - } - return codeFixes.length ? codeFixes : void 0; + getCodeActions: function getCodeActionsToAddEmptyExportDeclaration(context) { + const { sourceFile: sourceFile } = context; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2)=>{ + const exportDeclaration = factory.createExportDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ void 0); + changes2.insertNodeAtEndOfScope(sourceFile, sourceFile, exportDeclaration); + }); + return [ + createCodeFixActionWithoutFixAll("addEmptyExportDeclaration", changes, Diagnostics.Add_export_to_make_this_file_into_a_module) + ]; } }); } }); - // src/services/codefixes/fixPropertyAssignment.ts - function doChange15(changes, sourceFile, node) { - changes.replaceNode(sourceFile, node, factory.createPropertyAssignment(node.name, node.objectAssignmentInitializer)); + // src/services/codefixes/addMissingAsync.ts + function getFix(context, decl, trackChanges, fixedDeclarations) { + const changes = trackChanges((t)=>makeChange2(t, context.sourceFile, decl, fixedDeclarations)); + return createCodeFixAction(fixId2, changes, Diagnostics.Add_async_modifier_to_containing_function, fixId2, Diagnostics.Add_all_missing_async_modifiers); } - function getProperty2(sourceFile, pos) { - return cast(getTokenAtPosition(sourceFile, pos).parent, isShorthandPropertyAssignment); + function makeChange2(changeTracker, sourceFile, insertionSite, fixedDeclarations) { + if (fixedDeclarations) { + if (fixedDeclarations.has(getNodeId(insertionSite))) return; + } + fixedDeclarations == null || fixedDeclarations.add(getNodeId(insertionSite)); + const cloneWithModifier = factory.updateModifiers(getSynthesizedDeepClone(insertionSite, /*includeTrivia*/ true), factory.createNodeArray(factory.createModifiersFromModifierFlags(getSyntacticModifierFlags(insertionSite) | 512 /* Async */ ))); + changeTracker.replaceNode(sourceFile, insertionSite, cloneWithModifier); } - var fixId28, errorCodes34; - var init_fixPropertyAssignment = __esm({ - "src/services/codefixes/fixPropertyAssignment.ts" () { + function getFixableErrorSpanDeclaration(sourceFile, span) { + if (!span) return void 0; + const token = getTokenAtPosition(sourceFile, span.start); + const decl = findAncestor(token, (node)=>{ + if (node.getStart(sourceFile) < span.start || node.getEnd() > textSpanEnd(span)) return "quit"; + return (isArrowFunction(node) || isMethodDeclaration(node) || isFunctionExpression(node) || isFunctionDeclaration(node)) && textSpansEqual(span, createTextSpanFromNode(node, sourceFile)); + }); + return decl; + } + function getIsMatchingAsyncError(span, errorCode) { + return ({ start: start, length: length2, relatedInformation: relatedInformation, code: code })=>isNumber(start) && isNumber(length2) && textSpansEqual({ + start: start, + length: length2 + }, span) && code === errorCode && !!relatedInformation && some(relatedInformation, (related)=>related.code === Diagnostics.Did_you_mean_to_mark_this_function_as_async.code); + } + var fixId2, errorCodes2; + var init_addMissingAsync = __esm({ + "src/services/codefixes/addMissingAsync.ts" () { "use strict"; init_ts4(); init_ts_codefix(); - fixId28 = "fixPropertyAssignment"; - errorCodes34 = [ - 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 + fixId2 = "addMissingAsync"; + errorCodes2 = [ + Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, + Diagnostics.Type_0_is_not_assignable_to_type_1.code, + Diagnostics.Type_0_is_not_comparable_to_type_1.code ]; registerCodeFix({ - errorCodes: errorCodes34, fixIds: [ - fixId28 + fixId2 ], - getCodeActions (context) { - const { sourceFile: sourceFile , span: span } = context; - const property = getProperty2(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange15(t, context.sourceFile, property)); + errorCodes: errorCodes2, + getCodeActions: function getCodeActionsToAddMissingAsync(context) { + const { sourceFile: sourceFile, errorCode: errorCode, cancellationToken: cancellationToken, program: program, span: span } = context; + const diagnostic = find(program.getTypeChecker().getDiagnostics(sourceFile, cancellationToken), getIsMatchingAsyncError(span, errorCode)); + const directSpan = diagnostic && diagnostic.relatedInformation && find(diagnostic.relatedInformation, (r)=>r.code === Diagnostics.Did_you_mean_to_mark_this_function_as_async.code); + const decl = getFixableErrorSpanDeclaration(sourceFile, directSpan); + if (!decl) return; + const trackChanges = (cb)=>ts_textChanges_exports.ChangeTracker.with(context, cb); return [ - createCodeFixAction(fixId28, changes, [ - Diagnostics.Change_0_to_1, - "=", - ":" - ], fixId28, [ - Diagnostics.Switch_each_misused_0_to_1, - "=", - ":" - ]) + getFix(context, decl, trackChanges) ]; }, - getAllCodeActions: (context)=>codeFixAll(context, errorCodes34, (changes, diag2)=>doChange15(changes, diag2.file, getProperty2(diag2.file, diag2.start))) + getAllCodeActions: (context)=>{ + const { sourceFile: sourceFile } = context; + const fixedDeclarations = /* @__PURE__ */ new Set(); + return codeFixAll(context, errorCodes2, (t, diagnostic)=>{ + const span = diagnostic.relatedInformation && find(diagnostic.relatedInformation, (r)=>r.code === Diagnostics.Did_you_mean_to_mark_this_function_as_async.code); + const decl = getFixableErrorSpanDeclaration(sourceFile, span); + if (!decl) return; + const trackChanges = (cb)=>(cb(t), []); + return getFix(context, decl, trackChanges, fixedDeclarations); + }); + } }); } }); - // src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts - function getNodes2(sourceFile, pos) { - const token = getTokenAtPosition(sourceFile, pos); - const heritageClauses = getContainingClass(token).heritageClauses; - const extendsToken = heritageClauses[0].getFirstToken(); - return extendsToken.kind === 94 /* ExtendsKeyword */ ? { - extendsToken: extendsToken, - heritageClauses: heritageClauses - } : void 0; + // src/services/codefixes/addMissingAwait.ts + function getAwaitErrorSpanExpression(sourceFile, errorCode, span, cancellationToken, program) { + const expression = getFixableErrorSpanExpression(sourceFile, span); + return expression && isMissingAwaitError(sourceFile, errorCode, span, cancellationToken, program) && isInsideAwaitableBody(expression) ? expression : void 0; } - function doChanges2(changes, sourceFile, extendsToken, heritageClauses) { - changes.replaceNode(sourceFile, extendsToken, factory.createToken(117 /* ImplementsKeyword */ )); - if (heritageClauses.length === 2 && heritageClauses[0].token === 94 /* ExtendsKeyword */ && heritageClauses[1].token === 117 /* ImplementsKeyword */ ) { - const implementsToken = heritageClauses[1].getFirstToken(); - const implementsFullStart = implementsToken.getFullStart(); - changes.replaceRange(sourceFile, { - pos: implementsFullStart, - end: implementsFullStart - }, factory.createToken(27 /* CommaToken */ )); - const text = sourceFile.text; - let end = implementsToken.end; - while(end < text.length && isWhiteSpaceSingleLine(text.charCodeAt(end)))end++; - changes.deleteRange(sourceFile, { - pos: implementsToken.getStart(), - end: end + function getDeclarationSiteFix(context, expression, errorCode, checker, trackChanges, fixedDeclarations) { + const { sourceFile: sourceFile, program: program, cancellationToken: cancellationToken } = context; + const awaitableInitializers = findAwaitableInitializers(expression, sourceFile, cancellationToken, program, checker); + if (awaitableInitializers) { + const initializerChanges = trackChanges((t)=>{ + forEach(awaitableInitializers.initializers, ({ expression: expression2 })=>makeChange3(t, errorCode, sourceFile, checker, expression2, fixedDeclarations)); + if (fixedDeclarations && awaitableInitializers.needsSecondPassForFixAll) makeChange3(t, errorCode, sourceFile, checker, expression, fixedDeclarations); }); + return createCodeFixActionWithoutFixAll("addMissingAwaitToInitializer", initializerChanges, awaitableInitializers.initializers.length === 1 ? [ + Diagnostics.Add_await_to_initializer_for_0, + awaitableInitializers.initializers[0].declarationSymbol.name + ] : Diagnostics.Add_await_to_initializers); } } - var fixId29, errorCodes35; - var init_fixExtendsInterfaceBecomesImplements = __esm({ - "src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts" () { + function getUseSiteFix(context, expression, errorCode, checker, trackChanges, fixedDeclarations) { + const changes = trackChanges((t)=>makeChange3(t, errorCode, context.sourceFile, checker, expression, fixedDeclarations)); + return createCodeFixAction(fixId3, changes, Diagnostics.Add_await, fixId3, Diagnostics.Fix_all_expressions_possibly_missing_await); + } + function isMissingAwaitError(sourceFile, errorCode, span, cancellationToken, program) { + const checker = program.getTypeChecker(); + const diagnostics = checker.getDiagnostics(sourceFile, cancellationToken); + return some(diagnostics, ({ start: start, length: length2, relatedInformation: relatedInformation, code: code })=>isNumber(start) && isNumber(length2) && textSpansEqual({ + start: start, + length: length2 + }, span) && code === errorCode && !!relatedInformation && some(relatedInformation, (related)=>related.code === Diagnostics.Did_you_forget_to_use_await.code)); + } + function findAwaitableInitializers(expression, sourceFile, cancellationToken, program, checker) { + const identifiers = getIdentifiersFromErrorSpanExpression(expression, checker); + if (!identifiers) return; + let isCompleteFix = identifiers.isCompleteFix; + let initializers; + for (const identifier of identifiers.identifiers){ + const symbol = checker.getSymbolAtLocation(identifier); + if (!symbol) continue; + const declaration = tryCast(symbol.valueDeclaration, isVariableDeclaration); + const variableName = declaration && tryCast(declaration.name, isIdentifier); + const variableStatement = getAncestor(declaration, 243 /* VariableStatement */ ); + if (!declaration || !variableStatement || declaration.type || !declaration.initializer || variableStatement.getSourceFile() !== sourceFile || hasSyntacticModifier(variableStatement, 1 /* Export */ ) || !variableName || !isInsideAwaitableBody(declaration.initializer)) { + isCompleteFix = false; + continue; + } + const diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken); + const isUsedElsewhere = ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(variableName, checker, sourceFile, (reference)=>{ + return identifier !== reference && !symbolReferenceIsAlsoMissingAwait(reference, diagnostics, sourceFile, checker); + }); + if (isUsedElsewhere) { + isCompleteFix = false; + continue; + } + (initializers || (initializers = [])).push({ + expression: declaration.initializer, + declarationSymbol: symbol + }); + } + return initializers && { + initializers: initializers, + needsSecondPassForFixAll: !isCompleteFix + }; + } + function getIdentifiersFromErrorSpanExpression(expression, checker) { + if (isPropertyAccessExpression(expression.parent) && isIdentifier(expression.parent.expression)) return { + identifiers: [ + expression.parent.expression + ], + isCompleteFix: true + }; + if (isIdentifier(expression)) return { + identifiers: [ + expression + ], + isCompleteFix: true + }; + if (isBinaryExpression(expression)) { + let sides; + let isCompleteFix = true; + for (const side of [ + expression.left, + expression.right + ]){ + const type = checker.getTypeAtLocation(side); + if (checker.getPromisedTypeOfPromise(type)) { + if (!isIdentifier(side)) { + isCompleteFix = false; + continue; + } + (sides || (sides = [])).push(side); + } + } + return sides && { + identifiers: sides, + isCompleteFix: isCompleteFix + }; + } + } + function symbolReferenceIsAlsoMissingAwait(reference, diagnostics, sourceFile, checker) { + const errorNode = isPropertyAccessExpression(reference.parent) ? reference.parent.name : isBinaryExpression(reference.parent) ? reference.parent : reference; + const diagnostic = find(diagnostics, (diagnostic2)=>diagnostic2.start === errorNode.getStart(sourceFile) && diagnostic2.start + diagnostic2.length === errorNode.getEnd()); + return diagnostic && contains(errorCodes3, diagnostic.code) || // A Promise is usually not correct in a binary expression (it's not valid + // in an arithmetic expression and an equality comparison seems unusual), + // but if the other side of the binary expression has an error, the side + // is typed `any` which will squash the error that would identify this + // Promise as an invalid operand. So if the whole binary expression is + // typed `any` as a result, there is a strong likelihood that this Promise + // is accidentally missing `await`. + checker.getTypeAtLocation(errorNode).flags & 1 /* Any */ ; + } + function isInsideAwaitableBody(node) { + return node.kind & 65536 /* AwaitContext */ || !!findAncestor(node, (ancestor)=>ancestor.parent && isArrowFunction(ancestor.parent) && ancestor.parent.body === ancestor || isBlock(ancestor) && (ancestor.parent.kind === 262 /* FunctionDeclaration */ || ancestor.parent.kind === 218 /* FunctionExpression */ || ancestor.parent.kind === 219 /* ArrowFunction */ || ancestor.parent.kind === 174 /* MethodDeclaration */ )); + } + function makeChange3(changeTracker, errorCode, sourceFile, checker, insertionSite, fixedDeclarations) { + if (isForOfStatement(insertionSite.parent) && !insertionSite.parent.awaitModifier) { + const exprType = checker.getTypeAtLocation(insertionSite); + const asyncIter = checker.getAsyncIterableType(); + if (asyncIter && checker.isTypeAssignableTo(exprType, asyncIter)) { + const forOf = insertionSite.parent; + changeTracker.replaceNode(sourceFile, forOf, factory.updateForOfStatement(forOf, factory.createToken(135 /* AwaitKeyword */ ), forOf.initializer, forOf.expression, forOf.statement)); + return; + } + } + if (isBinaryExpression(insertionSite)) for (const side of [ + insertionSite.left, + insertionSite.right + ]){ + if (fixedDeclarations && isIdentifier(side)) { + const symbol = checker.getSymbolAtLocation(side); + if (symbol && fixedDeclarations.has(getSymbolId(symbol))) continue; + } + const type = checker.getTypeAtLocation(side); + const newNode = checker.getPromisedTypeOfPromise(type) ? factory.createAwaitExpression(side) : side; + changeTracker.replaceNode(sourceFile, side, newNode); + } + else if (errorCode === propertyAccessCode && isPropertyAccessExpression(insertionSite.parent)) { + if (fixedDeclarations && isIdentifier(insertionSite.parent.expression)) { + const symbol = checker.getSymbolAtLocation(insertionSite.parent.expression); + if (symbol && fixedDeclarations.has(getSymbolId(symbol))) return; + } + changeTracker.replaceNode(sourceFile, insertionSite.parent.expression, factory.createParenthesizedExpression(factory.createAwaitExpression(insertionSite.parent.expression))); + insertLeadingSemicolonIfNeeded(changeTracker, insertionSite.parent.expression, sourceFile); + } else if (contains(callableConstructableErrorCodes, errorCode) && isCallOrNewExpression(insertionSite.parent)) { + if (fixedDeclarations && isIdentifier(insertionSite)) { + const symbol = checker.getSymbolAtLocation(insertionSite); + if (symbol && fixedDeclarations.has(getSymbolId(symbol))) return; + } + changeTracker.replaceNode(sourceFile, insertionSite, factory.createParenthesizedExpression(factory.createAwaitExpression(insertionSite))); + insertLeadingSemicolonIfNeeded(changeTracker, insertionSite, sourceFile); + } else { + if (fixedDeclarations && isVariableDeclaration(insertionSite.parent) && isIdentifier(insertionSite.parent.name)) { + const symbol = checker.getSymbolAtLocation(insertionSite.parent.name); + if (symbol && !tryAddToSet(fixedDeclarations, getSymbolId(symbol))) return; + } + changeTracker.replaceNode(sourceFile, insertionSite, factory.createAwaitExpression(insertionSite)); + } + } + function insertLeadingSemicolonIfNeeded(changeTracker, beforeNode, sourceFile) { + const precedingToken = findPrecedingToken(beforeNode.pos, sourceFile); + if (precedingToken && positionIsASICandidate(precedingToken.end, precedingToken.parent, sourceFile)) changeTracker.insertText(sourceFile, beforeNode.getStart(sourceFile), ";"); + } + var fixId3, propertyAccessCode, callableConstructableErrorCodes, errorCodes3; + var init_addMissingAwait = __esm({ + "src/services/codefixes/addMissingAwait.ts" () { "use strict"; init_ts4(); init_ts_codefix(); - fixId29 = "extendsInterfaceBecomesImplements"; - errorCodes35 = [ - Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code + fixId3 = "addMissingAwait"; + propertyAccessCode = Diagnostics.Property_0_does_not_exist_on_type_1.code; + callableConstructableErrorCodes = [ + Diagnostics.This_expression_is_not_callable.code, + Diagnostics.This_expression_is_not_constructable.code + ]; + errorCodes3 = [ + Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type.code, + Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type.code, + Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type.code, + Diagnostics.Operator_0_cannot_be_applied_to_type_1.code, + Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2.code, + Diagnostics.This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap.code, + Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined.code, + Diagnostics.Type_0_is_not_an_array_type.code, + Diagnostics.Type_0_is_not_an_array_type_or_a_string_type.code, + Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher.code, + Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator.code, + Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator.code, + Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator.code, + Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator.code, + Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, + propertyAccessCode, + ...callableConstructableErrorCodes ]; registerCodeFix({ - errorCodes: errorCodes35, - getCodeActions (context) { - const { sourceFile: sourceFile } = context; - const nodes = getNodes2(sourceFile, context.span.start); - if (!nodes) return void 0; - const { extendsToken: extendsToken , heritageClauses: heritageClauses } = nodes; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChanges2(t, sourceFile, extendsToken, heritageClauses)); - return [ - createCodeFixAction(fixId29, changes, Diagnostics.Change_extends_to_implements, fixId29, Diagnostics.Change_all_extended_interfaces_to_implements) - ]; - }, fixIds: [ - fixId29 + fixId3 ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes35, (changes, diag2)=>{ - const nodes = getNodes2(diag2.file, diag2.start); - if (nodes) doChanges2(changes, diag2.file, nodes.extendsToken, nodes.heritageClauses); - }) + errorCodes: errorCodes3, + getCodeActions: function getCodeActionsToAddMissingAwait(context) { + const { sourceFile: sourceFile, errorCode: errorCode, span: span, cancellationToken: cancellationToken, program: program } = context; + const expression = getAwaitErrorSpanExpression(sourceFile, errorCode, span, cancellationToken, program); + if (!expression) return; + const checker = context.program.getTypeChecker(); + const trackChanges = (cb)=>ts_textChanges_exports.ChangeTracker.with(context, cb); + return compact([ + getDeclarationSiteFix(context, expression, errorCode, checker, trackChanges), + getUseSiteFix(context, expression, errorCode, checker, trackChanges) + ]); + }, + getAllCodeActions: (context)=>{ + const { sourceFile: sourceFile, program: program, cancellationToken: cancellationToken } = context; + const checker = context.program.getTypeChecker(); + const fixedDeclarations = /* @__PURE__ */ new Set(); + return codeFixAll(context, errorCodes3, (t, diagnostic)=>{ + const expression = getAwaitErrorSpanExpression(sourceFile, diagnostic.code, diagnostic, cancellationToken, program); + if (!expression) return; + const trackChanges = (cb)=>(cb(t), []); + return getDeclarationSiteFix(context, expression, diagnostic.code, checker, trackChanges, fixedDeclarations) || getUseSiteFix(context, expression, diagnostic.code, checker, trackChanges, fixedDeclarations); + }); + } }); } }); - // src/services/codefixes/fixForgottenThisPropertyAccess.ts - function getInfo9(sourceFile, pos, diagCode) { - const node = getTokenAtPosition(sourceFile, pos); - if (isIdentifier(node) || isPrivateIdentifier(node)) return { - node: node, - className: diagCode === didYouMeanStaticMemberCode ? getContainingClass(node).name.text : void 0 - }; + // src/services/codefixes/addMissingConst.ts + function makeChange4(changeTracker, sourceFile, pos, program, fixedNodes) { + const token = getTokenAtPosition(sourceFile, pos); + const forInitializer = findAncestor(token, (node)=>isForInOrOfStatement(node.parent) ? node.parent.initializer === node : isPossiblyPartOfDestructuring(node) ? false : "quit"); + if (forInitializer) return applyChange(changeTracker, forInitializer, sourceFile, fixedNodes); + const parent2 = token.parent; + if (isBinaryExpression(parent2) && parent2.operatorToken.kind === 64 /* EqualsToken */ && isExpressionStatement(parent2.parent)) return applyChange(changeTracker, token, sourceFile, fixedNodes); + if (isArrayLiteralExpression(parent2)) { + const checker = program.getTypeChecker(); + if (!every(parent2.elements, (element)=>arrayElementCouldBeVariableDeclaration(element, checker))) return; + return applyChange(changeTracker, parent2, sourceFile, fixedNodes); + } + const commaExpression = findAncestor(token, (node)=>isExpressionStatement(node.parent) ? true : isPossiblyPartOfCommaSeperatedInitializer(node) ? false : "quit"); + if (commaExpression) { + const checker = program.getTypeChecker(); + if (!expressionCouldBeVariableDeclaration(commaExpression, checker)) return; + return applyChange(changeTracker, commaExpression, sourceFile, fixedNodes); + } } - function doChange16(changes, sourceFile, { node: node , className: className }) { - suppressLeadingAndTrailingTrivia(node); - changes.replaceNode(sourceFile, node, factory.createPropertyAccessExpression(className ? factory.createIdentifier(className) : factory.createThis(), node)); + function applyChange(changeTracker, initializer, sourceFile, fixedNodes) { + if (!fixedNodes || tryAddToSet(fixedNodes, initializer)) changeTracker.insertModifierBefore(sourceFile, 87 /* ConstKeyword */ , initializer); } - var fixId30, didYouMeanStaticMemberCode, errorCodes36; - var init_fixForgottenThisPropertyAccess = __esm({ - "src/services/codefixes/fixForgottenThisPropertyAccess.ts" () { + function isPossiblyPartOfDestructuring(node) { + switch(node.kind){ + case 80 /* Identifier */ : + case 209 /* ArrayLiteralExpression */ : + case 210 /* ObjectLiteralExpression */ : + case 303 /* PropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : + return true; + default: + return false; + } + } + function arrayElementCouldBeVariableDeclaration(expression, checker) { + const identifier = isIdentifier(expression) ? expression : isAssignmentExpression(expression, /*excludeCompoundAssignment*/ true) && isIdentifier(expression.left) ? expression.left : void 0; + return !!identifier && !checker.getSymbolAtLocation(identifier); + } + function isPossiblyPartOfCommaSeperatedInitializer(node) { + switch(node.kind){ + case 80 /* Identifier */ : + case 226 /* BinaryExpression */ : + case 28 /* CommaToken */ : + return true; + default: + return false; + } + } + function expressionCouldBeVariableDeclaration(expression, checker) { + if (!isBinaryExpression(expression)) return false; + if (expression.operatorToken.kind === 28 /* CommaToken */ ) return every([ + expression.left, + expression.right + ], (expression2)=>expressionCouldBeVariableDeclaration(expression2, checker)); + return expression.operatorToken.kind === 64 /* EqualsToken */ && isIdentifier(expression.left) && !checker.getSymbolAtLocation(expression.left); + } + var fixId4, errorCodes4; + var init_addMissingConst = __esm({ + "src/services/codefixes/addMissingConst.ts" () { "use strict"; init_ts4(); init_ts_codefix(); - fixId30 = "forgottenThisPropertyAccess"; - didYouMeanStaticMemberCode = Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code; - errorCodes36 = [ - Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.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, - didYouMeanStaticMemberCode + fixId4 = "addMissingConst"; + errorCodes4 = [ + Diagnostics.Cannot_find_name_0.code, + Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer.code ]; registerCodeFix({ - errorCodes: errorCodes36, - getCodeActions (context) { - const { sourceFile: sourceFile } = context; - const info = getInfo9(sourceFile, context.span.start, context.errorCode); - if (!info) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange16(t, sourceFile, info)); - return [ - createCodeFixAction(fixId30, changes, [ - Diagnostics.Add_0_to_unresolved_variable, - info.className || "this" - ], fixId30, Diagnostics.Add_qualifier_to_all_unresolved_variables_matching_a_member_name) + errorCodes: errorCodes4, + getCodeActions: function getCodeActionsToAddMissingConst(context) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>makeChange4(t, context.sourceFile, context.span.start, context.program)); + if (changes.length > 0) return [ + createCodeFixAction(fixId4, changes, Diagnostics.Add_const_to_unresolved_variable, fixId4, Diagnostics.Add_const_to_all_unresolved_variables) ]; }, fixIds: [ - fixId30 + fixId4 ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes36, (changes, diag2)=>{ - const info = getInfo9(diag2.file, diag2.start, diag2.code); - if (info) doChange16(changes, context.sourceFile, info); - }) + getAllCodeActions: (context)=>{ + const fixedNodes = /* @__PURE__ */ new Set(); + return codeFixAll(context, errorCodes4, (changes, diag2)=>makeChange4(changes, diag2.file, diag2.start, context.program, fixedNodes)); + } }); } }); - // src/services/codefixes/fixInvalidJsxCharacters.ts - function isValidCharacter(character) { - return hasProperty(htmlEntity, character); - } - function doChange17(changes, preferences, sourceFile, start, useHtmlEntity) { - const character = sourceFile.getText()[start]; - if (!isValidCharacter(character)) return; - const replacement = useHtmlEntity ? htmlEntity[character] : `{${quote(sourceFile, preferences, character)}}`; - changes.replaceRangeWithText(sourceFile, { - pos: start, - end: start + 1 - }, replacement); + // src/services/codefixes/addMissingDeclareProperty.ts + function makeChange5(changeTracker, sourceFile, pos, fixedNodes) { + const token = getTokenAtPosition(sourceFile, pos); + if (!isIdentifier(token)) return; + const declaration = token.parent; + if (declaration.kind === 172 /* PropertyDeclaration */ && (!fixedNodes || tryAddToSet(fixedNodes, declaration))) changeTracker.insertModifierBefore(sourceFile, 138 /* DeclareKeyword */ , declaration); } - var fixIdExpression, fixIdHtmlEntity, errorCodes37, htmlEntity; - var init_fixInvalidJsxCharacters = __esm({ - "src/services/codefixes/fixInvalidJsxCharacters.ts" () { + var fixId5, errorCodes5; + var init_addMissingDeclareProperty = __esm({ + "src/services/codefixes/addMissingDeclareProperty.ts" () { "use strict"; init_ts4(); init_ts_codefix(); - fixIdExpression = "fixInvalidJsxCharacters_expression"; - fixIdHtmlEntity = "fixInvalidJsxCharacters_htmlEntity"; - errorCodes37 = [ - Diagnostics.Unexpected_token_Did_you_mean_or_gt.code, - Diagnostics.Unexpected_token_Did_you_mean_or_rbrace.code + fixId5 = "addMissingDeclareProperty"; + errorCodes5 = [ + Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration.code ]; registerCodeFix({ - errorCodes: errorCodes37, - fixIds: [ - fixIdExpression, - fixIdHtmlEntity - ], - getCodeActions (context) { - const { sourceFile: sourceFile , preferences: preferences , span: span } = context; - const changeToExpression = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange17(t, preferences, sourceFile, span.start, /* useHtmlEntity */ false)); - const changeToHtmlEntity = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange17(t, preferences, sourceFile, span.start, /* useHtmlEntity */ true)); - return [ - createCodeFixAction(fixIdExpression, changeToExpression, Diagnostics.Wrap_invalid_character_in_an_expression_container, fixIdExpression, Diagnostics.Wrap_all_invalid_characters_in_an_expression_container), - createCodeFixAction(fixIdHtmlEntity, changeToHtmlEntity, Diagnostics.Convert_invalid_character_to_its_html_entity_code, fixIdHtmlEntity, Diagnostics.Convert_all_invalid_characters_to_HTML_entity_code) + errorCodes: errorCodes5, + getCodeActions: function getCodeActionsToAddMissingDeclareOnProperty(context) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>makeChange5(t, context.sourceFile, context.span.start)); + if (changes.length > 0) return [ + createCodeFixAction(fixId5, changes, Diagnostics.Prefix_with_declare, fixId5, Diagnostics.Prefix_all_incorrect_property_declarations_with_declare) ]; }, - getAllCodeActions (context) { - return codeFixAll(context, errorCodes37, (changes, diagnostic)=>doChange17(changes, context.preferences, diagnostic.file, diagnostic.start, context.fixId === fixIdHtmlEntity)); + fixIds: [ + fixId5 + ], + getAllCodeActions: (context)=>{ + const fixedNodes = /* @__PURE__ */ new Set(); + return codeFixAll(context, errorCodes5, (changes, diag2)=>makeChange5(changes, diag2.file, diag2.start, fixedNodes)); } }); - htmlEntity = { - ">": ">", - "}": "}" - }; } }); - // src/services/codefixes/fixUnmatchedParameter.ts - function getDeleteAction(context, { name: name , jsDocHost: jsDocHost , jsDocParameterTag: jsDocParameterTag }) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (changeTracker)=>changeTracker.filterJSDocTags(context.sourceFile, jsDocHost, (t)=>t !== jsDocParameterTag)); - return createCodeFixAction(deleteUnmatchedParameter, changes, [ - Diagnostics.Delete_unused_param_tag_0, - name.getText(context.sourceFile) - ], deleteUnmatchedParameter, Diagnostics.Delete_all_unused_param_tags); - } - function getRenameAction(context, { name: name , jsDocHost: jsDocHost , signature: signature , jsDocParameterTag: jsDocParameterTag }) { - if (!length(signature.parameters)) return void 0; - const sourceFile = context.sourceFile; - const tags = getJSDocTags(signature); - const names = /* @__PURE__ */ new Set(); - for (const tag of tags)if (isJSDocParameterTag(tag) && isIdentifier(tag.name)) names.add(tag.name.escapedText); - const parameterName = firstDefined(signature.parameters, (p)=>isIdentifier(p.name) && !names.has(p.name.escapedText) ? p.name.getText(sourceFile) : void 0); - if (parameterName === void 0) return void 0; - const newJSDocParameterTag = factory.updateJSDocParameterTag(jsDocParameterTag, jsDocParameterTag.tagName, factory.createIdentifier(parameterName), jsDocParameterTag.isBracketed, jsDocParameterTag.typeExpression, jsDocParameterTag.isNameFirst, jsDocParameterTag.comment); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (changeTracker)=>changeTracker.replaceJSDocComment(sourceFile, jsDocHost, map(tags, (t)=>t === jsDocParameterTag ? newJSDocParameterTag : t))); - return createCodeFixActionWithoutFixAll(renameUnmatchedParameter, changes, [ - Diagnostics.Rename_param_tag_name_0_to_1, - name.getText(sourceFile), - parameterName - ]); - } - function getInfo10(sourceFile, pos) { + // src/services/codefixes/addMissingInvocationForDecorator.ts + function makeChange6(changeTracker, sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); - if (token.parent && isJSDocParameterTag(token.parent) && isIdentifier(token.parent.name)) { - const jsDocParameterTag = token.parent; - const jsDocHost = getJSDocHost(jsDocParameterTag); - const signature = getHostSignatureFromJSDoc(jsDocParameterTag); - if (jsDocHost && signature) return { - jsDocHost: jsDocHost, - signature: signature, - name: token.parent.name, - jsDocParameterTag: jsDocParameterTag - }; - } - return void 0; + const decorator = findAncestor(token, isDecorator); + Debug.assert(!!decorator, "Expected position to be owned by a decorator."); + const replacement = factory.createCallExpression(decorator.expression, /*typeArguments*/ void 0, /*argumentsArray*/ void 0); + changeTracker.replaceNode(sourceFile, decorator.expression, replacement); } - var deleteUnmatchedParameter, renameUnmatchedParameter, errorCodes38; - var init_fixUnmatchedParameter = __esm({ - "src/services/codefixes/fixUnmatchedParameter.ts" () { + var fixId6, errorCodes6; + var init_addMissingInvocationForDecorator = __esm({ + "src/services/codefixes/addMissingInvocationForDecorator.ts" () { "use strict"; init_ts4(); init_ts_codefix(); - deleteUnmatchedParameter = "deleteUnmatchedParameter"; - renameUnmatchedParameter = "renameUnmatchedParameter"; - errorCodes38 = [ - Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name.code + fixId6 = "addMissingInvocationForDecorator"; + errorCodes6 = [ + Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code ]; registerCodeFix({ + errorCodes: errorCodes6, + getCodeActions: function getCodeActionsToAddMissingInvocationForDecorator(context) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>makeChange6(t, context.sourceFile, context.span.start)); + return [ + createCodeFixAction(fixId6, changes, Diagnostics.Call_decorator_expression, fixId6, Diagnostics.Add_to_all_uncalled_decorators) + ]; + }, fixIds: [ - deleteUnmatchedParameter, - renameUnmatchedParameter + fixId6 ], - errorCodes: errorCodes38, - getCodeActions: function getCodeActionsToFixUnmatchedParameter(context) { - const { sourceFile: sourceFile , span: span } = context; - const actions2 = []; - const info = getInfo10(sourceFile, span.start); - if (info) { - append(actions2, getDeleteAction(context, info)); - append(actions2, getRenameAction(context, info)); - return actions2; - } - return void 0; - }, - getAllCodeActions: function getAllCodeActionsToFixUnmatchedParameter(context) { - const tagsToSignature = /* @__PURE__ */ new Map(); - return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes)=>{ - eachDiagnostic(context, errorCodes38, ({ file: file , start: start })=>{ - const info = getInfo10(file, start); - if (info) tagsToSignature.set(info.signature, append(tagsToSignature.get(info.signature), info.jsDocParameterTag)); - }); - tagsToSignature.forEach((tags, signature)=>{ - if (context.fixId === deleteUnmatchedParameter) { - const tagsSet = new Set(tags); - changes.filterJSDocTags(signature.getSourceFile(), signature, (t)=>!tagsSet.has(t)); - } - }); - })); - } + getAllCodeActions: (context)=>codeFixAll(context, errorCodes6, (changes, diag2)=>makeChange6(changes, diag2.file, diag2.start)) }); } }); - // src/services/codefixes/fixUnreferenceableDecoratorMetadata.ts - function getImportDeclaration(sourceFile, program, start) { - const identifier = tryCast(getTokenAtPosition(sourceFile, start), isIdentifier); - if (!identifier || identifier.parent.kind !== 180 /* TypeReference */ ) return; - const checker = program.getTypeChecker(); - const symbol = checker.getSymbolAtLocation(identifier); - return find((symbol == null ? void 0 : symbol.declarations) || emptyArray, or(isImportClause, isImportSpecifier, isImportEqualsDeclaration)); - } - function doTypeOnlyImportChange(changes, sourceFile, importDeclaration, program) { - if (importDeclaration.kind === 268 /* ImportEqualsDeclaration */ ) { - changes.insertModifierBefore(sourceFile, 154 /* TypeKeyword */ , importDeclaration.name); - return; - } - const importClause = importDeclaration.kind === 270 /* ImportClause */ ? importDeclaration : importDeclaration.parent.parent; - if (importClause.name && importClause.namedBindings) return; - const checker = program.getTypeChecker(); - const importsValue = !!forEachImportClauseDeclaration(importClause, (decl)=>{ - if (skipAlias(decl.symbol, checker).flags & 111551 /* Value */ ) return true; - }); - if (importsValue) return; - changes.insertModifierBefore(sourceFile, 154 /* TypeKeyword */ , importClause); - } - function doNamespaceImportChange(changes, sourceFile, importDeclaration, program) { - ts_refactor_exports.doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, importDeclaration.parent); + // src/services/codefixes/addNameToNamelessParameter.ts + function makeChange7(changeTracker, sourceFile, pos) { + const token = getTokenAtPosition(sourceFile, pos); + const param = token.parent; + if (!isParameter(param)) return Debug.fail("Tried to add a parameter name to a non-parameter: " + Debug.formatSyntaxKind(token.kind)); + const i = param.parent.parameters.indexOf(param); + Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one."); + Debug.assert(i > -1, "Parameter not found in parent parameter list."); + const typeNode = factory.createTypeReferenceNode(param.name, /*typeArguments*/ void 0); + const replacement = factory.createParameterDeclaration(param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, param.dotDotDotToken ? factory.createArrayTypeNode(typeNode) : typeNode, param.initializer); + changeTracker.replaceNode(sourceFile, param, replacement); } - var fixId31, errorCodes39; - var init_fixUnreferenceableDecoratorMetadata = __esm({ - "src/services/codefixes/fixUnreferenceableDecoratorMetadata.ts" () { + var fixId7, errorCodes7; + var init_addNameToNamelessParameter = __esm({ + "src/services/codefixes/addNameToNamelessParameter.ts" () { "use strict"; init_ts4(); init_ts_codefix(); - fixId31 = "fixUnreferenceableDecoratorMetadata"; - errorCodes39 = [ - Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled.code + fixId7 = "addNameToNamelessParameter"; + errorCodes7 = [ + Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1.code ]; registerCodeFix({ - errorCodes: errorCodes39, - getCodeActions: (context)=>{ - const importDeclaration = getImportDeclaration(context.sourceFile, context.program, context.span.start); - if (!importDeclaration) return; - const namespaceChanges = ts_textChanges_exports.ChangeTracker.with(context, (t)=>importDeclaration.kind === 273 /* ImportSpecifier */ && doNamespaceImportChange(t, context.sourceFile, importDeclaration, context.program)); - const typeOnlyChanges = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doTypeOnlyImportChange(t, context.sourceFile, importDeclaration, context.program)); - let actions2; - if (namespaceChanges.length) actions2 = append(actions2, createCodeFixActionWithoutFixAll(fixId31, namespaceChanges, Diagnostics.Convert_named_imports_to_namespace_import)); - if (typeOnlyChanges.length) actions2 = append(actions2, createCodeFixActionWithoutFixAll(fixId31, typeOnlyChanges, Diagnostics.Convert_to_type_only_import)); - return actions2; + errorCodes: errorCodes7, + getCodeActions: function getCodeActionsToAddNameToNamelessParameter(context) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>makeChange7(t, context.sourceFile, context.span.start)); + return [ + createCodeFixAction(fixId7, changes, Diagnostics.Add_parameter_name, fixId7, Diagnostics.Add_names_to_all_parameters_without_names) + ]; }, fixIds: [ - fixId31 - ] + fixId7 + ], + getAllCodeActions: (context)=>codeFixAll(context, errorCodes7, (changes, diag2)=>makeChange7(changes, diag2.file, diag2.start)) }); } }); - // src/services/codefixes/fixUnusedIdentifier.ts - function changeInferToUnknown(changes, sourceFile, token) { - changes.replaceNode(sourceFile, token.parent, factory.createKeywordTypeNode(157 /* UnknownKeyword */ )); - } - function createDeleteFix(changes, diag2) { - return createCodeFixAction(fixName3, changes, diag2, fixIdDelete, Diagnostics.Delete_all_unused_declarations); - } - function deleteTypeParameters(changes, sourceFile, token) { - changes.delete(sourceFile, Debug.checkDefined(cast(token.parent, isDeclarationWithTypeParameterChildren).typeParameters, "The type parameter to delete should exist")); - } - function isImport(token) { - return token.kind === 100 /* ImportKeyword */ || token.kind === 79 /* Identifier */ && (token.parent.kind === 273 /* ImportSpecifier */ || token.parent.kind === 270 /* ImportClause */ ); - } - function tryGetFullImport(token) { - return token.kind === 100 /* ImportKeyword */ ? tryCast(token.parent, isImportDeclaration) : void 0; - } - function canDeleteEntireVariableStatement(sourceFile, token) { - return isVariableDeclarationList(token.parent) && first(token.parent.getChildren(sourceFile)) === token; - } - function deleteEntireVariableStatement(changes, sourceFile, node) { - changes.delete(sourceFile, node.parent.kind === 240 /* VariableStatement */ ? node.parent : node); - } - function deleteDestructuringElements(changes, sourceFile, node) { - forEach(node.elements, (n)=>changes.delete(sourceFile, n)); - } - function tryPrefixDeclaration(changes, errorCode, sourceFile, token) { - if (errorCode === Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code) return; - if (token.kind === 138 /* InferKeyword */ ) token = cast(token.parent, isInferTypeNode).typeParameter.name; - if (isIdentifier(token) && canPrefix(token)) { - changes.replaceNode(sourceFile, token, factory.createIdentifier(`_${token.text}`)); - if (isParameter(token.parent)) getJSDocParameterTags(token.parent).forEach((tag)=>{ - if (isIdentifier(tag.name)) changes.replaceNode(sourceFile, tag.name, factory.createIdentifier(`_${tag.name.text}`)); - }); - } - } - function canPrefix(token) { - switch(token.parent.kind){ - case 166 /* Parameter */ : - case 165 /* TypeParameter */ : - return true; - case 257 /* VariableDeclaration */ : - { - const varDecl = token.parent; - switch(varDecl.parent.parent.kind){ - case 247 /* ForOfStatement */ : - case 246 /* ForInStatement */ : - return true; - } - } - } - return false; - } - function tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, program, cancellationToken, isFixAll) { - tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, program, cancellationToken, isFixAll); - if (isIdentifier(token)) ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(token, checker, sourceFile, (ref)=>{ - if (isPropertyAccessExpression(ref.parent) && ref.parent.name === ref) ref = ref.parent; - if (!isFixAll && mayDeleteExpression(ref)) changes.delete(sourceFile, ref.parent.parent); - }); + // src/services/codefixes/addOptionalPropertyUndefined.ts + function getPropertiesToAdd(file, span, checker) { + var _a, _b; + const sourceTarget = getSourceTarget(getFixableErrorSpanExpression(file, span), checker); + if (!sourceTarget) return emptyArray; + const { source: sourceNode, target: targetNode } = sourceTarget; + const target = shouldUseParentTypeOfProperty(sourceNode, targetNode, checker) ? checker.getTypeAtLocation(targetNode.expression) : checker.getTypeAtLocation(targetNode); + if ((_b = (_a = target.symbol) == null ? void 0 : _a.declarations) == null ? void 0 : _b.some((d)=>getSourceFileOfNode(d).fileName.match(/\.d\.ts$/))) return emptyArray; + return checker.getExactOptionalProperties(target); } - function tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, program, cancellationToken, isFixAll) { - const { parent: parent2 } = token; - if (isParameter(parent2)) tryDeleteParameter(changes, sourceFile, parent2, checker, sourceFiles, program, cancellationToken, isFixAll); - else if (!(isFixAll && isIdentifier(token) && ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(token, checker, sourceFile))) { - const node = isImportClause(parent2) ? token : isComputedPropertyName(parent2) ? parent2.parent : parent2; - Debug.assert(node !== sourceFile, "should not delete whole source file"); - changes.delete(sourceFile, node); - } + function shouldUseParentTypeOfProperty(sourceNode, targetNode, checker) { + return isPropertyAccessExpression(targetNode) && !!checker.getExactOptionalProperties(checker.getTypeAtLocation(targetNode.expression)).length && checker.getTypeAtLocation(sourceNode) === checker.getUndefinedType(); } - function tryDeleteParameter(changes, sourceFile, parameter, checker, sourceFiles, program, cancellationToken, isFixAll = false) { - if (mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program, cancellationToken, isFixAll)) { - if (parameter.modifiers && parameter.modifiers.length > 0 && (!isIdentifier(parameter.name) || ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(parameter.name, checker, sourceFile))) { - for (const modifier of parameter.modifiers)if (isModifier(modifier)) changes.deleteModifier(sourceFile, modifier); - } else if (!parameter.initializer && isNotProvidedArguments(parameter, checker, sourceFiles)) changes.delete(sourceFile, parameter); + function getSourceTarget(errorNode, checker) { + var _a; + if (!errorNode) return void 0; + else if (isBinaryExpression(errorNode.parent) && errorNode.parent.operatorToken.kind === 64 /* EqualsToken */ ) return { + source: errorNode.parent.right, + target: errorNode.parent.left + }; + else if (isVariableDeclaration(errorNode.parent) && errorNode.parent.initializer) return { + source: errorNode.parent.initializer, + target: errorNode.parent.name + }; + else if (isCallExpression(errorNode.parent)) { + const n = checker.getSymbolAtLocation(errorNode.parent.expression); + if (!(n == null ? void 0 : n.valueDeclaration) || !isFunctionLikeKind(n.valueDeclaration.kind)) return void 0; + if (!isExpression(errorNode)) return void 0; + const i = errorNode.parent.arguments.indexOf(errorNode); + if (i === -1) return void 0; + const name = n.valueDeclaration.parameters[i].name; + if (isIdentifier(name)) return { + source: errorNode, + target: name + }; + } else if (isPropertyAssignment(errorNode.parent) && isIdentifier(errorNode.parent.name) || isShorthandPropertyAssignment(errorNode.parent)) { + const parentTarget = getSourceTarget(errorNode.parent.parent, checker); + if (!parentTarget) return void 0; + const prop = checker.getPropertyOfType(checker.getTypeAtLocation(parentTarget.target), errorNode.parent.name.text); + const declaration = (_a = prop == null ? void 0 : prop.declarations) == null ? void 0 : _a[0]; + if (!declaration) return void 0; + return { + source: isPropertyAssignment(errorNode.parent) ? errorNode.parent.initializer : errorNode.parent.name, + target: declaration + }; } + return void 0; } - function isNotProvidedArguments(parameter, checker, sourceFiles) { - const index = parameter.parent.parameters.indexOf(parameter); - return !ts_FindAllReferences_exports.Core.someSignatureUsage(parameter.parent, sourceFiles, checker, (_, call)=>!call || call.arguments.length > index); - } - function mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program, cancellationToken, isFixAll) { - const { parent: parent2 } = parameter; - switch(parent2.kind){ - case 171 /* MethodDeclaration */ : - case 173 /* Constructor */ : - const index = parent2.parameters.indexOf(parameter); - const referent = isMethodDeclaration(parent2) ? parent2.name : parent2; - const entries = ts_FindAllReferences_exports.Core.getReferencedSymbolsForNode(parent2.pos, referent, program, sourceFiles, cancellationToken); - if (entries) for (const entry of entries){ - for (const reference of entry.references)if (reference.kind === ts_FindAllReferences_exports.EntryKind.Node) { - const isSuperCall2 = isSuperKeyword(reference.node) && isCallExpression(reference.node.parent) && reference.node.parent.arguments.length > index; - const isSuperMethodCall = isPropertyAccessExpression(reference.node.parent) && isSuperKeyword(reference.node.parent.expression) && isCallExpression(reference.node.parent.parent) && reference.node.parent.parent.arguments.length > index; - const isOverriddenMethod = (isMethodDeclaration(reference.node.parent) || isMethodSignature(reference.node.parent)) && reference.node.parent !== parameter.parent && reference.node.parent.parameters.length > index; - if (isSuperCall2 || isSuperMethodCall || isOverriddenMethod) return false; - } - } - return true; - case 259 /* FunctionDeclaration */ : - if (parent2.name && isCallbackLike(checker, sourceFile, parent2.name)) return isLastParameter(parent2, parameter, isFixAll); - return true; - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - return isLastParameter(parent2, parameter, isFixAll); - case 175 /* SetAccessor */ : - return false; - case 174 /* GetAccessor */ : - return true; - default: - return Debug.failBadSyntaxKind(parent2); + function addUndefinedToOptionalProperty(changes, toAdd) { + for (const add of toAdd){ + const d = add.valueDeclaration; + if (d && (isPropertySignature(d) || isPropertyDeclaration(d)) && d.type) { + const t = factory.createUnionTypeNode([ + ...d.type.kind === 192 /* UnionType */ ? d.type.types : [ + d.type + ], + factory.createTypeReferenceNode("undefined") + ]); + changes.replaceNode(d.getSourceFile(), d.type, t); + } } } - function isCallbackLike(checker, sourceFile, name) { - return !!ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(name, checker, sourceFile, (reference)=>isIdentifier(reference) && isCallExpression(reference.parent) && reference.parent.arguments.indexOf(reference) >= 0); - } - function isLastParameter(func, parameter, isFixAll) { - const parameters = func.parameters; - const index = parameters.indexOf(parameter); - Debug.assert(index !== -1, "The parameter should already be in the list"); - return isFixAll ? parameters.slice(index + 1).every((p)=>isIdentifier(p.name) && !p.symbol.isReferenced) : index === parameters.length - 1; - } - function mayDeleteExpression(node) { - return (isBinaryExpression(node.parent) && node.parent.left === node || (isPostfixUnaryExpression(node.parent) || isPrefixUnaryExpression(node.parent)) && node.parent.operand === node) && isExpressionStatement(node.parent.parent); - } - var fixName3, fixIdPrefix, fixIdDelete, fixIdDeleteImports, fixIdInfer, errorCodes40; - var init_fixUnusedIdentifier = __esm({ - "src/services/codefixes/fixUnusedIdentifier.ts" () { + var addOptionalPropertyUndefined, errorCodes8; + var init_addOptionalPropertyUndefined = __esm({ + "src/services/codefixes/addOptionalPropertyUndefined.ts" () { "use strict"; init_ts4(); init_ts_codefix(); - fixName3 = "unusedIdentifier"; - fixIdPrefix = "unusedIdentifier_prefix"; - fixIdDelete = "unusedIdentifier_delete"; - fixIdDeleteImports = "unusedIdentifier_deleteImports"; - fixIdInfer = "unusedIdentifier_infer"; - errorCodes40 = [ - Diagnostics._0_is_declared_but_its_value_is_never_read.code, - Diagnostics._0_is_declared_but_never_used.code, - Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, - Diagnostics.All_imports_in_import_declaration_are_unused.code, - Diagnostics.All_destructured_elements_are_unused.code, - Diagnostics.All_variables_are_unused.code, - Diagnostics.All_type_parameters_are_unused.code + addOptionalPropertyUndefined = "addOptionalPropertyUndefined"; + errorCodes8 = [ + Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_type_of_the_target.code, + Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, + Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code ]; registerCodeFix({ - errorCodes: errorCodes40, + errorCodes: errorCodes8, getCodeActions (context) { - const { errorCode: errorCode , sourceFile: sourceFile , program: program , cancellationToken: cancellationToken } = context; - const checker = program.getTypeChecker(); - const sourceFiles = program.getSourceFiles(); - const token = getTokenAtPosition(sourceFile, context.span.start); - if (isJSDocTemplateTag(token)) return [ - createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, (t)=>t.delete(sourceFile, token)), Diagnostics.Remove_template_tag) - ]; - if (token.kind === 29 /* LessThanToken */ ) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>deleteTypeParameters(t, sourceFile, token)); - return [ - createDeleteFix(changes, Diagnostics.Remove_type_parameters) - ]; - } - const importDecl = tryGetFullImport(token); - if (importDecl) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>t.delete(sourceFile, importDecl)); - return [ - createCodeFixAction(fixName3, changes, [ - Diagnostics.Remove_import_from_0, - showModuleSpecifier(importDecl) - ], fixIdDeleteImports, Diagnostics.Delete_all_unused_imports) - ]; - } else if (isImport(token)) { - const deletion = ts_textChanges_exports.ChangeTracker.with(context, (t)=>tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, program, cancellationToken, /*isFixAll*/ false)); - if (deletion.length) return [ - createCodeFixAction(fixName3, deletion, [ - Diagnostics.Remove_unused_declaration_for_Colon_0, - token.getText(sourceFile) - ], fixIdDeleteImports, Diagnostics.Delete_all_unused_imports) - ]; - } - if (isObjectBindingPattern(token.parent) || isArrayBindingPattern(token.parent)) { - if (isParameter(token.parent.parent)) { - const elements = token.parent.elements; - const diagnostic = [ - elements.length > 1 ? Diagnostics.Remove_unused_declarations_for_Colon_0 : Diagnostics.Remove_unused_declaration_for_Colon_0, - map(elements, (e)=>e.getText(sourceFile)).join(", ") - ]; - return [ - createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, (t)=>deleteDestructuringElements(t, sourceFile, token.parent)), diagnostic) - ]; - } - return [ - createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, (t)=>t.delete(sourceFile, token.parent.parent)), Diagnostics.Remove_unused_destructuring_declaration) - ]; - } - if (canDeleteEntireVariableStatement(sourceFile, token)) return [ - createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, (t)=>deleteEntireVariableStatement(t, sourceFile, token.parent)), Diagnostics.Remove_variable_statement) + const typeChecker = context.program.getTypeChecker(); + const toAdd = getPropertiesToAdd(context.sourceFile, context.span, typeChecker); + if (!toAdd.length) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addUndefinedToOptionalProperty(t, toAdd)); + return [ + createCodeFixActionWithoutFixAll(addOptionalPropertyUndefined, changes, Diagnostics.Add_undefined_to_optional_property_type) ]; - const result = []; - if (token.kind === 138 /* InferKeyword */ ) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>changeInferToUnknown(t, sourceFile, token)); - const name = cast(token.parent, isInferTypeNode).typeParameter.name.text; - result.push(createCodeFixAction(fixName3, changes, [ - Diagnostics.Replace_infer_0_with_unknown, - name - ], fixIdInfer, Diagnostics.Replace_all_unused_infer_with_unknown)); - } else { - const deletion = ts_textChanges_exports.ChangeTracker.with(context, (t)=>tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, program, cancellationToken, /*isFixAll*/ false)); - if (deletion.length) { - const name = isComputedPropertyName(token.parent) ? token.parent : token; - result.push(createDeleteFix(deletion, [ - Diagnostics.Remove_unused_declaration_for_Colon_0, - name.getText(sourceFile) - ])); - } - } - const prefix = ts_textChanges_exports.ChangeTracker.with(context, (t)=>tryPrefixDeclaration(t, errorCode, sourceFile, token)); - if (prefix.length) result.push(createCodeFixAction(fixName3, prefix, [ - Diagnostics.Prefix_0_with_an_underscore, - token.getText(sourceFile) - ], fixIdPrefix, Diagnostics.Prefix_all_unused_declarations_with_where_possible)); - return result; }, fixIds: [ - fixIdPrefix, - fixIdDelete, - fixIdDeleteImports, - fixIdInfer - ], - getAllCodeActions: (context)=>{ - const { sourceFile: sourceFile , program: program , cancellationToken: cancellationToken } = context; - const checker = program.getTypeChecker(); - const sourceFiles = program.getSourceFiles(); - return codeFixAll(context, errorCodes40, (changes, diag2)=>{ - const token = getTokenAtPosition(sourceFile, diag2.start); - switch(context.fixId){ - case fixIdPrefix: - tryPrefixDeclaration(changes, diag2.code, sourceFile, token); - break; - case fixIdDeleteImports: - { - const importDecl = tryGetFullImport(token); - if (importDecl) changes.delete(sourceFile, importDecl); - else if (isImport(token)) tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, program, cancellationToken, /*isFixAll*/ true); - break; - } - case fixIdDelete: - if (token.kind === 138 /* InferKeyword */ || isImport(token)) break; - else if (isJSDocTemplateTag(token)) changes.delete(sourceFile, token); - else if (token.kind === 29 /* LessThanToken */ ) deleteTypeParameters(changes, sourceFile, token); - else if (isObjectBindingPattern(token.parent)) { - if (token.parent.parent.initializer) break; - else if (!isParameter(token.parent.parent) || isNotProvidedArguments(token.parent.parent, checker, sourceFiles)) changes.delete(sourceFile, token.parent.parent); - } else if (isArrayBindingPattern(token.parent.parent) && token.parent.parent.parent.initializer) break; - else if (canDeleteEntireVariableStatement(sourceFile, token)) deleteEntireVariableStatement(changes, sourceFile, token.parent); - else tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, program, cancellationToken, /*isFixAll*/ true); - break; - case fixIdInfer: - if (token.kind === 138 /* InferKeyword */ ) changeInferToUnknown(changes, sourceFile, token); - break; - default: - Debug.fail(JSON.stringify(context.fixId)); - } - }); - } + addOptionalPropertyUndefined + ] }); } }); - // src/services/codefixes/fixUnreachableCode.ts - function doChange18(changes, sourceFile, start, length2, errorCode) { - const token = getTokenAtPosition(sourceFile, start); - const statement = findAncestor(token, isStatement); - if (statement.getStart(sourceFile) !== token.getStart(sourceFile)) { - const logData = JSON.stringify({ - statementKind: Debug.formatSyntaxKind(statement.kind), - tokenKind: Debug.formatSyntaxKind(token.kind), - errorCode: errorCode, - start: start, - length: length2 - }); - Debug.fail("Token and statement should start at the same point. " + logData); + // src/services/codefixes/annotateWithTypeFromJSDoc.ts + function getDeclaration(file, pos) { + const name = getTokenAtPosition(file, pos); + return tryCast(isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc); + } + function parameterShouldGetTypeFromJSDoc(node) { + return isDeclarationWithType(node) && hasUsableJSDoc(node); + } + function hasUsableJSDoc(decl) { + return isFunctionLikeDeclaration(decl) ? decl.parameters.some(hasUsableJSDoc) || !decl.type && !!getJSDocReturnType(decl) : !decl.type && !!getJSDocType(decl); + } + function doChange8(changes, sourceFile, decl) { + if (isFunctionLikeDeclaration(decl) && (getJSDocReturnType(decl) || decl.parameters.some((p)=>!!getJSDocType(p)))) { + if (!decl.typeParameters) { + const typeParameters = getJSDocTypeParameterDeclarations(decl); + if (typeParameters.length) changes.insertTypeParameters(sourceFile, decl, typeParameters); + } + const needParens = isArrowFunction(decl) && !findChildOfKind(decl, 21 /* OpenParenToken */ , sourceFile); + if (needParens) changes.insertNodeBefore(sourceFile, first(decl.parameters), factory.createToken(21 /* OpenParenToken */ )); + for (const param of decl.parameters)if (!param.type) { + const paramType = getJSDocType(param); + if (paramType) changes.tryInsertTypeAnnotation(sourceFile, param, visitNode(paramType, transformJSDocType, isTypeNode)); + } + if (needParens) changes.insertNodeAfter(sourceFile, last(decl.parameters), factory.createToken(22 /* CloseParenToken */ )); + if (!decl.type) { + const returnType = getJSDocReturnType(decl); + if (returnType) changes.tryInsertTypeAnnotation(sourceFile, decl, visitNode(returnType, transformJSDocType, isTypeNode)); + } + } else { + const jsdocType = Debug.checkDefined(getJSDocType(decl), "A JSDocType for this declaration should exist"); + Debug.assert(!decl.type, "The JSDocType decl should have a type"); + changes.tryInsertTypeAnnotation(sourceFile, decl, visitNode(jsdocType, transformJSDocType, isTypeNode)); } - const container = (isBlock(statement.parent) ? statement.parent : statement).parent; - if (!isBlock(statement.parent) || statement === first(statement.parent.statements)) switch(container.kind){ - case 242 /* IfStatement */ : - if (container.elseStatement) { - if (isBlock(statement.parent)) break; - else changes.replaceNode(sourceFile, statement, factory.createBlock(emptyArray)); - return; - } - case 244 /* WhileStatement */ : - case 245 /* ForStatement */ : - changes.delete(sourceFile, container); - return; + } + function isDeclarationWithType(node) { + return isFunctionLikeDeclaration(node) || node.kind === 260 /* VariableDeclaration */ || node.kind === 171 /* PropertySignature */ || node.kind === 172 /* PropertyDeclaration */ ; + } + function transformJSDocType(node) { + switch(node.kind){ + case 319 /* JSDocAllType */ : + case 320 /* JSDocUnknownType */ : + return factory.createTypeReferenceNode("any", emptyArray); + case 323 /* JSDocOptionalType */ : + return transformJSDocOptionalType(node); + case 322 /* JSDocNonNullableType */ : + return transformJSDocType(node.type); + case 321 /* JSDocNullableType */ : + return transformJSDocNullableType(node); + case 325 /* JSDocVariadicType */ : + return transformJSDocVariadicType(node); + case 324 /* JSDocFunctionType */ : + return transformJSDocFunctionType(node); + case 183 /* TypeReference */ : + return transformJSDocTypeReference(node); + case 329 /* JSDocTypeLiteral */ : + return transformJSDocTypeLiteral(node); + default: + const visited = visitEachChild(node, transformJSDocType, nullTransformationContext); + setEmitFlags(visited, 1 /* SingleLine */ ); + return visited; } - if (isBlock(statement.parent)) { - const end = start + length2; - const lastStatement = Debug.checkDefined(lastWhere(sliceAfter(statement.parent.statements, statement), (s)=>s.pos < end), "Some statement should be last"); - changes.deleteNodeRange(sourceFile, statement, lastStatement); - } else changes.delete(sourceFile, statement); } - function lastWhere(a, pred) { - let last2; - for (const value1 of a){ - if (!pred(value1)) break; - last2 = value1; + function transformJSDocTypeLiteral(node) { + const typeNode = factory.createTypeLiteralNode(map(node.jsDocPropertyTags, (tag)=>factory.createPropertySignature(/*modifiers*/ void 0, isIdentifier(tag.name) ? tag.name : tag.name.right, isOptionalJSDocPropertyLikeTag(tag) ? factory.createToken(58 /* QuestionToken */ ) : void 0, tag.typeExpression && visitNode(tag.typeExpression.type, transformJSDocType, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */ )))); + setEmitFlags(typeNode, 1 /* SingleLine */ ); + return typeNode; + } + function transformJSDocOptionalType(node) { + return factory.createUnionTypeNode([ + visitNode(node.type, transformJSDocType, isTypeNode), + factory.createTypeReferenceNode("undefined", emptyArray) + ]); + } + function transformJSDocNullableType(node) { + return factory.createUnionTypeNode([ + visitNode(node.type, transformJSDocType, isTypeNode), + factory.createTypeReferenceNode("null", emptyArray) + ]); + } + function transformJSDocVariadicType(node) { + return factory.createArrayTypeNode(visitNode(node.type, transformJSDocType, isTypeNode)); + } + function transformJSDocFunctionType(node) { + return factory.createFunctionTypeNode(emptyArray, node.parameters.map(transformJSDocParameter), node.type ?? factory.createKeywordTypeNode(133 /* AnyKeyword */ )); + } + function transformJSDocParameter(node) { + const index = node.parent.parameters.indexOf(node); + const isRest = node.type.kind === 325 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; + const name = node.name || (isRest ? "rest" : "arg" + index); + const dotdotdot = isRest ? factory.createToken(26 /* DotDotDotToken */ ) : node.dotDotDotToken; + return factory.createParameterDeclaration(node.modifiers, dotdotdot, name, node.questionToken, visitNode(node.type, transformJSDocType, isTypeNode), node.initializer); + } + function transformJSDocTypeReference(node) { + let name = node.typeName; + let args = node.typeArguments; + if (isIdentifier(node.typeName)) { + if (isJSDocIndexSignature(node)) return transformJSDocIndexSignature(node); + let text = node.typeName.text; + switch(node.typeName.text){ + case "String": + case "Boolean": + case "Object": + case "Number": + text = text.toLowerCase(); + break; + case "array": + case "date": + case "promise": + text = text[0].toUpperCase() + text.slice(1); + break; + } + name = factory.createIdentifier(text); + if ((text === "Array" || text === "Promise") && !node.typeArguments) args = factory.createNodeArray([ + factory.createTypeReferenceNode("any", emptyArray) + ]); + else args = visitNodes2(node.typeArguments, transformJSDocType, isTypeNode); } - return last2; + return factory.createTypeReferenceNode(name, args); } - var fixId32, errorCodes41; - var init_fixUnreachableCode = __esm({ - "src/services/codefixes/fixUnreachableCode.ts" () { + function transformJSDocIndexSignature(node) { + const index = factory.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, node.typeArguments[0].kind === 150 /* NumberKeyword */ ? "n" : "s", /*questionToken*/ void 0, factory.createTypeReferenceNode(node.typeArguments[0].kind === 150 /* NumberKeyword */ ? "number" : "string", []), /*initializer*/ void 0); + const indexSignature = factory.createTypeLiteralNode([ + factory.createIndexSignature(/*modifiers*/ void 0, [ + index + ], node.typeArguments[1]) + ]); + setEmitFlags(indexSignature, 1 /* SingleLine */ ); + return indexSignature; + } + var fixId8, errorCodes9; + var init_annotateWithTypeFromJSDoc = __esm({ + "src/services/codefixes/annotateWithTypeFromJSDoc.ts" () { "use strict"; init_ts4(); init_ts_codefix(); - fixId32 = "fixUnreachableCode"; - errorCodes41 = [ - Diagnostics.Unreachable_code_detected.code + fixId8 = "annotateWithTypeFromJSDoc"; + errorCodes9 = [ + Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code ]; registerCodeFix({ - errorCodes: errorCodes41, + errorCodes: errorCodes9, getCodeActions (context) { - const syntacticDiagnostics = context.program.getSyntacticDiagnostics(context.sourceFile, context.cancellationToken); - if (syntacticDiagnostics.length) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange18(t, context.sourceFile, context.span.start, context.span.length, context.errorCode)); + const decl = getDeclaration(context.sourceFile, context.span.start); + if (!decl) return; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange8(t, context.sourceFile, decl)); return [ - createCodeFixAction(fixId32, changes, Diagnostics.Remove_unreachable_code, fixId32, Diagnostics.Remove_all_unreachable_code) + createCodeFixAction(fixId8, changes, Diagnostics.Annotate_with_type_from_JSDoc, fixId8, Diagnostics.Annotate_everything_with_types_from_JSDoc) ]; }, fixIds: [ - fixId32 + fixId8 ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes41, (changes, diag2)=>doChange18(changes, diag2.file, diag2.start, diag2.length, diag2.code)) + getAllCodeActions: (context)=>codeFixAll(context, errorCodes9, (changes, diag2)=>{ + const decl = getDeclaration(diag2.file, diag2.start); + if (decl) doChange8(changes, diag2.file, decl); + }) }); } }); - // src/services/codefixes/fixUnusedLabel.ts - function doChange19(changes, sourceFile, start) { - const token = getTokenAtPosition(sourceFile, start); - const labeledStatement = cast(token.parent, isLabeledStatement); - const pos = token.getStart(sourceFile); - const statementPos = labeledStatement.statement.getStart(sourceFile); - const end = positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos : skipTrivia(sourceFile.text, findChildOfKind(labeledStatement, 58 /* ColonToken */ , sourceFile).end, /*stopAfterLineBreak*/ true); - changes.deleteRange(sourceFile, { - pos: pos, - end: end - }); - } - var fixId33, errorCodes42; - var init_fixUnusedLabel = __esm({ - "src/services/codefixes/fixUnusedLabel.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId33 = "fixUnusedLabel"; - errorCodes42 = [ - Diagnostics.Unused_label.code - ]; - registerCodeFix({ - errorCodes: errorCodes42, - getCodeActions (context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange19(t, context.sourceFile, context.span.start)); - return [ - createCodeFixAction(fixId33, changes, Diagnostics.Remove_unused_label, fixId33, Diagnostics.Remove_all_unused_labels) - ]; - }, - fixIds: [ - fixId33 - ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes42, (changes, diag2)=>doChange19(changes, diag2.file, diag2.start)) - }); - } - }); - // src/services/codefixes/fixJSDocTypes.ts - function doChange20(changes, sourceFile, oldTypeNode, newType, checker) { - changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode, /*flags*/ void 0)); - } - function getInfo11(sourceFile, pos, checker) { - const decl = findAncestor(getTokenAtPosition(sourceFile, pos), isTypeContainer); - const typeNode = decl && decl.type; - return typeNode && { - typeNode: typeNode, - type: getType(checker, typeNode) - }; - } - function isTypeContainer(node) { - switch(node.kind){ - case 231 /* AsExpression */ : - case 176 /* CallSignature */ : - case 177 /* ConstructSignature */ : - case 259 /* FunctionDeclaration */ : - case 174 /* GetAccessor */ : - case 178 /* IndexSignature */ : - case 197 /* MappedType */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 166 /* Parameter */ : - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : - case 175 /* SetAccessor */ : - case 262 /* TypeAliasDeclaration */ : - case 213 /* TypeAssertionExpression */ : - case 257 /* VariableDeclaration */ : - return true; - default: - return false; - } - } - function getType(checker, node) { - if (isJSDocNullableType(node)) { - const type = checker.getTypeFromTypeNode(node.type); - if (type === checker.getNeverType() || type === checker.getVoidType()) return type; - return checker.getUnionType(append([ - type, - checker.getUndefinedType() - ], node.postfix ? void 0 : checker.getNullType())); + // src/services/codefixes/convertFunctionToEs6Class.ts + function doChange9(changes, sourceFile, position, checker, preferences, compilerOptions) { + const ctorSymbol = checker.getSymbolAtLocation(getTokenAtPosition(sourceFile, position)); + if (!ctorSymbol || !ctorSymbol.valueDeclaration || !(ctorSymbol.flags & 19 /* Variable */ )) return void 0; + const ctorDeclaration = ctorSymbol.valueDeclaration; + if (isFunctionDeclaration(ctorDeclaration) || isFunctionExpression(ctorDeclaration)) changes.replaceNode(sourceFile, ctorDeclaration, createClassFromFunction(ctorDeclaration)); + else if (isVariableDeclaration(ctorDeclaration)) { + const classDeclaration = createClassFromVariableDeclaration(ctorDeclaration); + if (!classDeclaration) return void 0; + const ancestor = ctorDeclaration.parent.parent; + if (isVariableDeclarationList(ctorDeclaration.parent) && ctorDeclaration.parent.declarations.length > 1) { + changes.delete(sourceFile, ctorDeclaration); + changes.insertNodeAfter(sourceFile, ancestor, classDeclaration); + } else changes.replaceNode(sourceFile, ancestor, classDeclaration); } - return checker.getTypeFromTypeNode(node); - } - var fixIdPlain, fixIdNullable, errorCodes43; - var init_fixJSDocTypes = __esm({ - "src/services/codefixes/fixJSDocTypes.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixIdPlain = "fixJSDocTypes_plain"; - fixIdNullable = "fixJSDocTypes_nullable"; - errorCodes43 = [ - Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code, - Diagnostics._0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1.code, - Diagnostics._0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1.code - ]; - registerCodeFix({ - errorCodes: errorCodes43, - getCodeActions (context) { - const { sourceFile: sourceFile } = context; - const checker = context.program.getTypeChecker(); - const info = getInfo11(sourceFile, context.span.start, checker); - if (!info) return void 0; - const { typeNode: typeNode , type: type } = info; - const original = typeNode.getText(sourceFile); - const actions2 = [ - fix(type, fixIdPlain, Diagnostics.Change_all_jsdoc_style_types_to_TypeScript) - ]; - if (typeNode.kind === 317 /* JSDocNullableType */ ) actions2.push(fix(type, fixIdNullable, Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); - return actions2; - function fix(type2, fixId51, fixAllDescription) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange20(t, sourceFile, typeNode, type2, checker)); - return createCodeFixAction("jdocTypes", changes, [ - Diagnostics.Change_0_to_1, - original, - checker.typeToString(type2) - ], fixId51, fixAllDescription); + function createClassElementsFromSymbol(symbol) { + const memberElements = []; + if (symbol.exports) symbol.exports.forEach((member)=>{ + if (member.name === "prototype" && member.declarations) { + const firstDeclaration = member.declarations[0]; + if (member.declarations.length === 1 && isPropertyAccessExpression(firstDeclaration) && isBinaryExpression(firstDeclaration.parent) && firstDeclaration.parent.operatorToken.kind === 64 /* EqualsToken */ && isObjectLiteralExpression(firstDeclaration.parent.right)) { + const prototypes = firstDeclaration.parent.right; + createClassElement(prototypes.symbol, /*modifiers*/ void 0, memberElements); } - }, - fixIds: [ - fixIdPlain, - fixIdNullable - ], - getAllCodeActions (context) { - const { fixId: fixId51 , program: program , sourceFile: sourceFile } = context; - const checker = program.getTypeChecker(); - return codeFixAll(context, errorCodes43, (changes, err)=>{ - const info = getInfo11(err.file, err.start, checker); - if (!info) return; - const { typeNode: typeNode , type: type } = info; - const fixedType = typeNode.kind === 317 /* JSDocNullableType */ && fixId51 === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */ ) : type; - doChange20(changes, sourceFile, typeNode, fixedType, checker); - }); + } else createClassElement(member, [ + factory.createToken(126 /* StaticKeyword */ ) + ], memberElements); + }); + if (symbol.members) symbol.members.forEach((member, key)=>{ + var _a, _b, _c, _d; + if (key === "constructor" && member.valueDeclaration) { + const prototypeAssignment = (_d = (_c = (_b = (_a = symbol.exports) == null ? void 0 : _a.get("prototype")) == null ? void 0 : _b.declarations) == null ? void 0 : _c[0]) == null ? void 0 : _d.parent; + if (prototypeAssignment && isBinaryExpression(prototypeAssignment) && isObjectLiteralExpression(prototypeAssignment.right) && some(prototypeAssignment.right.properties, isConstructorAssignment)) ; + else changes.delete(sourceFile, member.valueDeclaration.parent); + return; } + createClassElement(member, /*modifiers*/ void 0, memberElements); }); + return memberElements; + function shouldConvertDeclaration(_target, source) { + if (isAccessExpression(_target)) { + if (isPropertyAccessExpression(_target) && isConstructorAssignment(_target)) return true; + return isFunctionLike(source); + } else return every(_target.properties, (property)=>{ + if (isMethodDeclaration(property) || isGetOrSetAccessorDeclaration(property)) return true; + if (isPropertyAssignment(property) && isFunctionExpression(property.initializer) && !!property.name) return true; + if (isConstructorAssignment(property)) return true; + return false; + }); + } + function createClassElement(symbol2, modifiers, members) { + if (!(symbol2.flags & 8192 /* Method */ ) && !(symbol2.flags & 4096 /* ObjectLiteral */ )) return; + const memberDeclaration = symbol2.valueDeclaration; + const assignmentBinaryExpression = memberDeclaration.parent; + const assignmentExpr = assignmentBinaryExpression.right; + if (!shouldConvertDeclaration(memberDeclaration, assignmentExpr)) return; + if (some(members, (m)=>{ + const name = getNameOfDeclaration(m); + if (name && isIdentifier(name) && idText(name) === symbolName(symbol2)) return true; + return false; + })) return; + const nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 244 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + changes.delete(sourceFile, nodeToDelete); + if (!assignmentExpr) { + members.push(factory.createPropertyDeclaration(modifiers, symbol2.name, /*questionOrExclamationToken*/ void 0, /*type*/ void 0, /*initializer*/ void 0)); + return; + } + if (isAccessExpression(memberDeclaration) && (isFunctionExpression(assignmentExpr) || isArrowFunction(assignmentExpr))) { + const quotePreference = getQuotePreference(sourceFile, preferences); + const name = tryGetPropertyName(memberDeclaration, compilerOptions, quotePreference); + if (name) createFunctionLikeExpressionMember(members, assignmentExpr, name); + return; + } else if (isObjectLiteralExpression(assignmentExpr)) { + forEach(assignmentExpr.properties, (property)=>{ + if (isMethodDeclaration(property) || isGetOrSetAccessorDeclaration(property)) members.push(property); + if (isPropertyAssignment(property) && isFunctionExpression(property.initializer)) createFunctionLikeExpressionMember(members, property.initializer, property.name); + if (isConstructorAssignment(property)) return; + return; + }); + return; + } else { + if (isSourceFileJS(sourceFile)) return; + if (!isPropertyAccessExpression(memberDeclaration)) return; + const prop = factory.createPropertyDeclaration(modifiers, memberDeclaration.name, /*questionOrExclamationToken*/ void 0, /*type*/ void 0, assignmentExpr); + copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile); + members.push(prop); + return; + } + function createFunctionLikeExpressionMember(members2, expression, name) { + if (isFunctionExpression(expression)) return createFunctionExpressionMember(members2, expression, name); + else return createArrowFunctionExpressionMember(members2, expression, name); + } + function createFunctionExpressionMember(members2, functionExpression, name) { + const fullModifiers = concatenate(modifiers, getModifierKindFromSource(functionExpression, 134 /* AsyncKeyword */ )); + const method = factory.createMethodDeclaration(fullModifiers, /*asteriskToken*/ void 0, name, /*questionToken*/ void 0, /*typeParameters*/ void 0, functionExpression.parameters, /*type*/ void 0, functionExpression.body); + copyLeadingComments(assignmentBinaryExpression, method, sourceFile); + members2.push(method); + return; + } + function createArrowFunctionExpressionMember(members2, arrowFunction, name) { + const arrowFunctionBody = arrowFunction.body; + let bodyBlock; + if (arrowFunctionBody.kind === 241 /* Block */ ) bodyBlock = arrowFunctionBody; + else bodyBlock = factory.createBlock([ + factory.createReturnStatement(arrowFunctionBody) + ]); + const fullModifiers = concatenate(modifiers, getModifierKindFromSource(arrowFunction, 134 /* AsyncKeyword */ )); + const method = factory.createMethodDeclaration(fullModifiers, /*asteriskToken*/ void 0, name, /*questionToken*/ void 0, /*typeParameters*/ void 0, arrowFunction.parameters, /*type*/ void 0, bodyBlock); + copyLeadingComments(assignmentBinaryExpression, method, sourceFile); + members2.push(method); + } + } } - }); - // src/services/codefixes/fixMissingCallParentheses.ts - function doChange21(changes, sourceFile, name) { - changes.replaceNodeWithText(sourceFile, name, `${name.text}()`); - } - function getCallName(sourceFile, start) { - const token = getTokenAtPosition(sourceFile, start); - if (isPropertyAccessExpression(token.parent)) { - let current = token.parent; - while(isPropertyAccessExpression(current.parent))current = current.parent; - return current.name; + function createClassFromVariableDeclaration(node) { + const initializer = node.initializer; + if (!initializer || !isFunctionExpression(initializer) || !isIdentifier(node.name)) return void 0; + const memberElements = createClassElementsFromSymbol(node.symbol); + if (initializer.body) memberElements.unshift(factory.createConstructorDeclaration(/*modifiers*/ void 0, initializer.parameters, initializer.body)); + const modifiers = getModifierKindFromSource(node.parent.parent, 95 /* ExportKeyword */ ); + const cls = factory.createClassDeclaration(modifiers, node.name, /*typeParameters*/ void 0, /*heritageClauses*/ void 0, memberElements); + return cls; } - if (isIdentifier(token)) return token; - return void 0; - } - var fixId34, errorCodes44; - var init_fixMissingCallParentheses = __esm({ - "src/services/codefixes/fixMissingCallParentheses.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId34 = "fixMissingCallParentheses"; - errorCodes44 = [ - Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead.code - ]; - registerCodeFix({ - errorCodes: errorCodes44, - fixIds: [ - fixId34 - ], - getCodeActions (context) { - const { sourceFile: sourceFile , span: span } = context; - const callName = getCallName(sourceFile, span.start); - if (!callName) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange21(t, context.sourceFile, callName)); - return [ - createCodeFixAction(fixId34, changes, Diagnostics.Add_missing_call_parentheses, fixId34, Diagnostics.Add_all_missing_call_parentheses) - ]; - }, - getAllCodeActions: (context)=>codeFixAll(context, errorCodes44, (changes, diag2)=>{ - const callName = getCallName(diag2.file, diag2.start); - if (callName) doChange21(changes, diag2.file, callName); - }) - }); + function createClassFromFunction(node) { + const memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) memberElements.unshift(factory.createConstructorDeclaration(/*modifiers*/ void 0, node.parameters, node.body)); + const modifiers = getModifierKindFromSource(node, 95 /* ExportKeyword */ ); + const cls = factory.createClassDeclaration(modifiers, node.name, /*typeParameters*/ void 0, /*heritageClauses*/ void 0, memberElements); + return cls; } - }); - // src/services/codefixes/fixAwaitInSyncFunction.ts - function getReturnType(expr) { - if (expr.type) return expr.type; - if (isVariableDeclaration(expr.parent) && expr.parent.type && isFunctionTypeNode(expr.parent.type)) return expr.parent.type.type; } - function getNodes3(sourceFile, start) { - const token = getTokenAtPosition(sourceFile, start); - const containingFunction = getContainingFunction(token); - if (!containingFunction) return; - let insertBefore; - switch(containingFunction.kind){ - case 171 /* MethodDeclaration */ : - insertBefore = containingFunction.name; - break; - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - insertBefore = findChildOfKind(containingFunction, 98 /* FunctionKeyword */ , sourceFile); - break; - case 216 /* ArrowFunction */ : - const kind = containingFunction.typeParameters ? 29 /* LessThanToken */ : 20 /* OpenParenToken */ ; - insertBefore = findChildOfKind(containingFunction, kind, sourceFile) || first(containingFunction.parameters); - break; - default: - return; - } - return insertBefore && { - insertBefore: insertBefore, - returnType: getReturnType(containingFunction) - }; + function getModifierKindFromSource(source, kind) { + return canHaveModifiers(source) ? filter(source.modifiers, (modifier)=>modifier.kind === kind) : void 0; } - function doChange22(changes, sourceFile, { insertBefore: insertBefore , returnType: returnType }) { - if (returnType) { - const entityName = getEntityNameFromTypeNode(returnType); - if (!entityName || entityName.kind !== 79 /* Identifier */ || entityName.text !== "Promise") changes.replaceNode(sourceFile, returnType, factory.createTypeReferenceNode("Promise", factory.createNodeArray([ - returnType - ]))); - } - changes.insertModifierBefore(sourceFile, 132 /* AsyncKeyword */ , insertBefore); + function isConstructorAssignment(x) { + if (!x.name) return false; + if (isIdentifier(x.name) && x.name.text === "constructor") return true; + return false; } - var fixId35, errorCodes45; - var init_fixAwaitInSyncFunction = __esm({ - "src/services/codefixes/fixAwaitInSyncFunction.ts" () { + function tryGetPropertyName(node, compilerOptions, quotePreference) { + if (isPropertyAccessExpression(node)) return node.name; + const propName = node.argumentExpression; + if (isNumericLiteral(propName)) return propName; + if (isStringLiteralLike(propName)) return isIdentifierText(propName.text, getEmitScriptTarget(compilerOptions)) ? factory.createIdentifier(propName.text) : isNoSubstitutionTemplateLiteral(propName) ? factory.createStringLiteral(propName.text, quotePreference === 0 /* Single */ ) : propName; + return void 0; + } + var fixId9, errorCodes10; + var init_convertFunctionToEs6Class = __esm({ + "src/services/codefixes/convertFunctionToEs6Class.ts" () { "use strict"; init_ts4(); init_ts_codefix(); - fixId35 = "fixAwaitInSyncFunction"; - errorCodes45 = [ - Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, - Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, - Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function.code + fixId9 = "convertFunctionToEs6Class"; + errorCodes10 = [ + Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code ]; registerCodeFix({ - errorCodes: errorCodes45, + errorCodes: errorCodes10, getCodeActions (context) { - const { sourceFile: sourceFile , span: span } = context; - const nodes = getNodes3(sourceFile, span.start); - if (!nodes) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange22(t, sourceFile, nodes)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange9(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())); return [ - createCodeFixAction(fixId35, changes, Diagnostics.Add_async_modifier_to_containing_function, fixId35, Diagnostics.Add_all_missing_async_modifiers) + createCodeFixAction(fixId9, changes, Diagnostics.Convert_function_to_an_ES2015_class, fixId9, Diagnostics.Convert_all_constructor_functions_to_classes) ]; }, fixIds: [ - fixId35 + fixId9 ], - getAllCodeActions: function getAllCodeActionsToFixAwaitInSyncFunction(context) { - const seen = /* @__PURE__ */ new Map(); - return codeFixAll(context, errorCodes45, (changes, diag2)=>{ - const nodes = getNodes3(diag2.file, diag2.start); - if (!nodes || !addToSeen(seen, getNodeId(nodes.insertBefore))) return; - doChange22(changes, context.sourceFile, nodes); - }); - } + getAllCodeActions: (context)=>codeFixAll(context, errorCodes10, (changes, err)=>doChange9(changes, err.file, err.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())) }); } }); - // src/services/codefixes/fixPropertyOverrideAccessor.ts - function doChange23(file, start, length2, code, context) { - let startPosition; - let endPosition; - if (code === Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property.code) { - startPosition = start; - endPosition = start + length2; - } else if (code === Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor.code) { - const checker = context.program.getTypeChecker(); - const node = getTokenAtPosition(file, start).parent; - Debug.assert(isAccessor(node), "error span of fixPropertyOverrideAccessor should only be on an accessor"); - const containingClass = node.parent; - Debug.assert(isClassLike(containingClass), "erroneous accessors should only be inside classes"); - const base = singleOrUndefined(getAllSupers(containingClass, checker)); - if (!base) return []; - const name = unescapeLeadingUnderscores(getTextOfPropertyName(node.name)); - const baseProp = checker.getPropertyOfType(checker.getTypeAtLocation(base), name); - if (!baseProp || !baseProp.valueDeclaration) return []; - startPosition = baseProp.valueDeclaration.pos; - endPosition = baseProp.valueDeclaration.end; - file = getSourceFileOfNode(baseProp.valueDeclaration); - } else Debug.fail("fixPropertyOverrideAccessor codefix got unexpected error code " + code); - return generateAccessorFromProperty(file, context.program, startPosition, endPosition, context, Diagnostics.Generate_get_and_set_accessors.message); - } - var errorCodes46, fixId36; - var init_fixPropertyOverrideAccessor = __esm({ - "src/services/codefixes/fixPropertyOverrideAccessor.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - errorCodes46 = [ - Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property.code, - Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor.code - ]; - fixId36 = "fixPropertyOverrideAccessor"; - registerCodeFix({ - errorCodes: errorCodes46, - getCodeActions (context) { - const edits = doChange23(context.sourceFile, context.span.start, context.span.length, context.errorCode, context); - if (edits) return [ - createCodeFixAction(fixId36, edits, Diagnostics.Generate_get_and_set_accessors, fixId36, Diagnostics.Generate_get_and_set_accessors_for_all_overriding_properties) - ]; - }, - fixIds: [ - fixId36 - ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes46, (changes, diag2)=>{ - const edits = doChange23(diag2.file, diag2.start, diag2.length, diag2.code, context); - if (edits) for (const edit of edits)changes.pushRaw(context.sourceFile, edit); - }) + // src/services/codefixes/convertToAsyncFunction.ts + function convertToAsyncFunction(changes, sourceFile, position, checker) { + const tokenAtPosition = getTokenAtPosition(sourceFile, position); + let functionToConvert; + if (isIdentifier(tokenAtPosition) && isVariableDeclaration(tokenAtPosition.parent) && tokenAtPosition.parent.initializer && isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) functionToConvert = tokenAtPosition.parent.initializer; + else functionToConvert = tryCast(getContainingFunction(getTokenAtPosition(sourceFile, position)), canBeConvertedToAsync); + if (!functionToConvert) return; + const synthNamesMap = /* @__PURE__ */ new Map(); + const isInJavascript = isInJSFile(functionToConvert); + const setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); + const functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap); + if (!returnsPromise(functionToConvertRenamed, checker)) return; + const returnStatements = functionToConvertRenamed.body && isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body, checker) : emptyArray; + const transformer = { + checker: checker, + synthNamesMap: synthNamesMap, + setOfExpressionsToReturn: setOfExpressionsToReturn, + isInJSFile: isInJavascript + }; + if (!returnStatements.length) return; + const pos = skipTrivia(sourceFile.text, moveRangePastModifiers(functionToConvert).pos); + changes.insertModifierAt(sourceFile, pos, 134 /* AsyncKeyword */ , { + suffix: " " + }); + for (const returnStatement of returnStatements){ + forEachChild(returnStatement, function visit(node) { + if (isCallExpression(node)) { + const newNodes = transformExpression(node, node, transformer, /*hasContinuation*/ false); + if (hasFailed()) return true; + changes.replaceNodeWithNodes(sourceFile, returnStatement, newNodes); + } else if (!isFunctionLike(node)) { + forEachChild(node, visit); + if (hasFailed()) return true; + } }); - } - }); - // src/services/codefixes/inferFromUsage.ts - function getDiagnostic(errorCode, token) { - switch(errorCode){ - case Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - case Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: - return isSetAccessorDeclaration(getContainingFunction(token)) ? Diagnostics.Infer_type_of_0_from_usage : Diagnostics.Infer_parameter_types_from_usage; - case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: - return Diagnostics.Infer_parameter_types_from_usage; - case Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code: - return Diagnostics.Infer_this_type_of_0_from_usage; - default: - return Diagnostics.Infer_type_of_0_from_usage; + if (hasFailed()) return; } } - function mapSuggestionDiagnostic(errorCode) { - switch(errorCode){ - case Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code: - return Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code; - case Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: - return Diagnostics.Variable_0_implicitly_has_an_1_type.code; - case Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: - return Diagnostics.Parameter_0_implicitly_has_an_1_type.code; - case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: - return Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code; - case Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code: - return Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code; - case Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code: - return Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code; - case Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code: - return Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code; - case Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: - return Diagnostics.Member_0_implicitly_has_an_1_type.code; - } - return errorCode; + function getReturnStatementsWithPromiseHandlers(body, checker) { + const res = []; + forEachReturnStatement(body, (ret)=>{ + if (isReturnStatementWithFixablePromiseHandler(ret, checker)) res.push(ret); + }); + return res; } - function doChange24(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, preferences) { - if (!isParameterPropertyModifier(token.kind) && token.kind !== 79 /* Identifier */ && token.kind !== 25 /* DotDotDotToken */ && token.kind !== 108 /* ThisKeyword */ ) return void 0; - const { parent: parent2 } = token; - const importAdder = createImportAdder(sourceFile, program, preferences, host); - errorCode = mapSuggestionDiagnostic(errorCode); - switch(errorCode){ - case Diagnostics.Member_0_implicitly_has_an_1_type.code: - case Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: - if (isVariableDeclaration(parent2) && markSeen(parent2) || isPropertyDeclaration(parent2) || isPropertySignature(parent2)) { - annotateVariableDeclaration(changes, importAdder, sourceFile, parent2, program, host, cancellationToken); - importAdder.writeFixes(changes); - return parent2; - } - if (isPropertyAccessExpression(parent2)) { - const type = inferTypeForVariableFromUsage(parent2.name, program, cancellationToken); - const typeNode = getTypeNodeIfAccessible(type, parent2, program, host); - if (typeNode) { - const typeTag = factory.createJSDocTypeTag(/*tagName*/ void 0, factory.createJSDocTypeExpression(typeNode), /*comment*/ void 0); - changes.addJSDocTags(sourceFile, cast(parent2.parent.parent, isExpressionStatement), [ - typeTag - ]); - } - importAdder.writeFixes(changes); - return parent2; - } - return void 0; - case Diagnostics.Variable_0_implicitly_has_an_1_type.code: - { - const symbol = program.getTypeChecker().getSymbolAtLocation(token); - if (symbol && symbol.valueDeclaration && isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, importAdder, getSourceFileOfNode(symbol.valueDeclaration), symbol.valueDeclaration, program, host, cancellationToken); - importAdder.writeFixes(changes); - return symbol.valueDeclaration; - } - return void 0; - } - } - const containingFunction = getContainingFunction(token); - if (containingFunction === void 0) return void 0; - let declaration; - switch(errorCode){ - case Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - if (isSetAccessorDeclaration(containingFunction)) { - annotateSetAccessor(changes, importAdder, sourceFile, containingFunction, program, host, cancellationToken); - declaration = containingFunction; - break; - } - case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - if (markSeen(containingFunction)) { - const param = cast(parent2, isParameter); - annotateParameters(changes, importAdder, sourceFile, param, containingFunction, program, host, cancellationToken); - declaration = param; - } - break; - case Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: - case Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: - if (isGetAccessorDeclaration(containingFunction) && isIdentifier(containingFunction.name)) { - annotate(changes, importAdder, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); - declaration = containingFunction; - } - break; - case Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - if (isSetAccessorDeclaration(containingFunction)) { - annotateSetAccessor(changes, importAdder, sourceFile, containingFunction, program, host, cancellationToken); - declaration = containingFunction; - } - break; - case Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code: - if (ts_textChanges_exports.isThisTypeAnnotatable(containingFunction) && markSeen(containingFunction)) { - annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken); - declaration = containingFunction; - } - break; - default: - return Debug.fail(String(errorCode)); - } - importAdder.writeFixes(changes); - return declaration; + function getAllPromiseExpressionsToReturn(func, checker) { + if (!func.body) return /* @__PURE__ */ new Set(); + const setOfExpressionsToReturn = /* @__PURE__ */ new Set(); + forEachChild(func.body, function visit(node) { + if (isPromiseReturningCallExpression(node, checker, "then")) { + setOfExpressionsToReturn.add(getNodeId(node)); + forEach(node.arguments, visit); + } else if (isPromiseReturningCallExpression(node, checker, "catch") || isPromiseReturningCallExpression(node, checker, "finally")) { + setOfExpressionsToReturn.add(getNodeId(node)); + forEachChild(node, visit); + } else if (isPromiseTypedExpression(node, checker)) setOfExpressionsToReturn.add(getNodeId(node)); + else forEachChild(node, visit); + }); + return setOfExpressionsToReturn; } - function annotateVariableDeclaration(changes, importAdder, sourceFile, declaration, program, host, cancellationToken) { - if (isIdentifier(declaration.name)) annotate(changes, importAdder, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); + function isPromiseReturningCallExpression(node, checker, name) { + if (!isCallExpression(node)) return false; + const isExpressionOfName = hasPropertyAccessExpressionWithName(node, name); + const nodeType = isExpressionOfName && checker.getTypeAtLocation(node); + return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); } - function annotateParameters(changes, importAdder, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { - if (!isIdentifier(parameterDeclaration.name)) return; - const parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken); - Debug.assert(containingFunction.parameters.length === parameterInferences.length, "Parameter count and inference count should match"); - if (isInJSFile(containingFunction)) annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); - else { - const needParens = isArrowFunction(containingFunction) && !findChildOfKind(containingFunction, 20 /* OpenParenToken */ , sourceFile); - if (needParens) changes.insertNodeBefore(sourceFile, first(containingFunction.parameters), factory.createToken(20 /* OpenParenToken */ )); - for (const { declaration: declaration , type: type } of parameterInferences)if (declaration && !declaration.type && !declaration.initializer) annotate(changes, importAdder, sourceFile, declaration, type, program, host); - if (needParens) changes.insertNodeAfter(sourceFile, last(containingFunction.parameters), factory.createToken(21 /* CloseParenToken */ )); + function isReferenceToType(type, target) { + return (getObjectFlags(type) & 4 /* Reference */ ) !== 0 && type.target === target; + } + function getExplicitPromisedTypeOfPromiseReturningCallExpression(node, callback, checker) { + if (node.expression.name.escapedText === "finally") return void 0; + const promiseType = checker.getTypeAtLocation(node.expression.expression); + if (isReferenceToType(promiseType, checker.getPromiseType()) || isReferenceToType(promiseType, checker.getPromiseLikeType())) { + if (node.expression.name.escapedText === "then") { + if (callback === elementAt(node.arguments, 0)) return elementAt(node.typeArguments, 0); + else if (callback === elementAt(node.arguments, 1)) return elementAt(node.typeArguments, 1); + } else return elementAt(node.typeArguments, 0); } } - function annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken) { - const references = getFunctionReferences(containingFunction, sourceFile, program, cancellationToken); - if (!references || !references.length) return; - const thisInference = inferTypeFromReferences(program, references, cancellationToken).thisParameter(); - const typeNode = getTypeNodeIfAccessible(thisInference, containingFunction, program, host); - if (!typeNode) return; - if (isInJSFile(containingFunction)) annotateJSDocThis(changes, sourceFile, containingFunction, typeNode); - else changes.tryInsertThisTypeAnnotation(sourceFile, containingFunction, typeNode); - } - function annotateJSDocThis(changes, sourceFile, containingFunction, typeNode) { - changes.addJSDocTags(sourceFile, containingFunction, [ - factory.createJSDocThisTag(/*tagName*/ void 0, factory.createJSDocTypeExpression(typeNode)) - ]); + function isPromiseTypedExpression(node, checker) { + if (!isExpression(node)) return false; + return !!checker.getPromisedTypeOfPromise(checker.getTypeAtLocation(node)); } - function annotateSetAccessor(changes, importAdder, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { - const param = firstOrUndefined(setAccessorDeclaration.parameters); - if (param && isIdentifier(setAccessorDeclaration.name) && isIdentifier(param.name)) { - let type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); - if (type === program.getTypeChecker().getAnyType()) type = inferTypeForVariableFromUsage(param.name, program, cancellationToken); - if (isInJSFile(setAccessorDeclaration)) annotateJSDocParameters(changes, sourceFile, [ - { - declaration: param, - type: type + function renameCollidingVarNames(nodeToRename, checker, synthNamesMap) { + const identsToRenameMap = /* @__PURE__ */ new Map(); + const collidingSymbolMap = createMultiMap(); + forEachChild(nodeToRename, function visit(node) { + if (!isIdentifier(node)) { + forEachChild(node, visit); + return; + } + const symbol = checker.getSymbolAtLocation(node); + if (symbol) { + const type = checker.getTypeAtLocation(node); + const lastCallSignature = getLastCallSignature(type, checker); + const symbolIdString = getSymbolId(symbol).toString(); + if (lastCallSignature && !isParameter(node.parent) && !isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + const firstParameter = firstOrUndefined(lastCallSignature.parameters); + const ident = (firstParameter == null ? void 0 : firstParameter.valueDeclaration) && isParameter(firstParameter.valueDeclaration) && tryCast(firstParameter.valueDeclaration.name, isIdentifier) || factory.createUniqueName("result", 16 /* Optimistic */ ); + const synthName = getNewNameIfConflict(ident, collidingSymbolMap); + synthNamesMap.set(symbolIdString, synthName); + collidingSymbolMap.add(ident.text, symbol); + } else if (node.parent && (isParameter(node.parent) || isVariableDeclaration(node.parent) || isBindingElement(node.parent))) { + const originalName = node.text; + const collidingSymbols = collidingSymbolMap.get(originalName); + if (collidingSymbols && collidingSymbols.some((prevSymbol)=>prevSymbol !== symbol)) { + const newName = getNewNameIfConflict(node, collidingSymbolMap); + identsToRenameMap.set(symbolIdString, newName.identifier); + synthNamesMap.set(symbolIdString, newName); + collidingSymbolMap.add(originalName, symbol); + } else { + const identifier = getSynthesizedDeepClone(node); + synthNamesMap.set(symbolIdString, createSynthIdentifier(identifier)); + collidingSymbolMap.add(originalName, symbol); + } } - ], program, host); - else annotate(changes, importAdder, sourceFile, param, type, program, host); - } + } + }); + return getSynthesizedDeepCloneWithReplacements(nodeToRename, /*includeTrivia*/ true, (original)=>{ + if (isBindingElement(original) && isIdentifier(original.name) && isObjectBindingPattern(original.parent)) { + const symbol = checker.getSymbolAtLocation(original.name); + const renameInfo = symbol && identsToRenameMap.get(String(getSymbolId(symbol))); + if (renameInfo && renameInfo.text !== (original.name || original.propertyName).getText()) return factory.createBindingElement(original.dotDotDotToken, original.propertyName || original.name, renameInfo, original.initializer); + } else if (isIdentifier(original)) { + const symbol = checker.getSymbolAtLocation(original); + const renameInfo = symbol && identsToRenameMap.get(String(getSymbolId(symbol))); + if (renameInfo) return factory.createIdentifier(renameInfo.text); + } + }); } - function annotate(changes, importAdder, sourceFile, declaration, type, program, host) { - const typeNode = getTypeNodeIfAccessible(type, declaration, program, host); - if (typeNode) { - if (isInJSFile(sourceFile) && declaration.kind !== 168 /* PropertySignature */ ) { - const parent2 = isVariableDeclaration(declaration) ? tryCast(declaration.parent.parent, isVariableStatement) : declaration; - if (!parent2) return; - const typeExpression = factory.createJSDocTypeExpression(typeNode); - const typeTag = isGetAccessorDeclaration(declaration) ? factory.createJSDocReturnTag(/*tagName*/ void 0, typeExpression, /*comment*/ void 0) : factory.createJSDocTypeTag(/*tagName*/ void 0, typeExpression, /*comment*/ void 0); - changes.addJSDocTags(sourceFile, parent2, [ - typeTag - ]); - } else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, sourceFile, changes, importAdder, getEmitScriptTarget(program.getCompilerOptions()))) changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + function getNewNameIfConflict(name, originalNames) { + const numVarsSameName = (originalNames.get(name.text) || emptyArray).length; + const identifier = numVarsSameName === 0 ? name : factory.createIdentifier(name.text + "_" + numVarsSameName); + return createSynthIdentifier(identifier); + } + function hasFailed() { + return !codeActionSucceeded; + } + function silentFail() { + codeActionSucceeded = false; + return emptyArray; + } + function transformExpression(returnContextNode, node, transformer, hasContinuation, continuationArgName) { + if (isPromiseReturningCallExpression(node, transformer.checker, "then")) return transformThen(node, elementAt(node.arguments, 0), elementAt(node.arguments, 1), transformer, hasContinuation, continuationArgName); + if (isPromiseReturningCallExpression(node, transformer.checker, "catch")) return transformCatch(node, elementAt(node.arguments, 0), transformer, hasContinuation, continuationArgName); + if (isPromiseReturningCallExpression(node, transformer.checker, "finally")) return transformFinally(node, elementAt(node.arguments, 0), transformer, hasContinuation, continuationArgName); + if (isPropertyAccessExpression(node)) return transformExpression(returnContextNode, node.expression, transformer, hasContinuation, continuationArgName); + const nodeType = transformer.checker.getTypeAtLocation(node); + if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { + Debug.assertNode(getOriginalNode(node).parent, isPropertyAccessExpression); + return transformPromiseExpressionOfPropertyAccess(returnContextNode, node, transformer, hasContinuation, continuationArgName); } + return silentFail(); } - function tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, sourceFile, changes, importAdder, scriptTarget) { - const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget); - if (importableReference && changes.tryInsertTypeAnnotation(sourceFile, declaration, importableReference.typeNode)) { - forEach(importableReference.symbols, (s)=>importAdder.addImportFromExportedSymbol(s, /*usageIsTypeOnly*/ true)); - return true; + function isNullOrUndefined2({ checker: checker }, node) { + if (node.kind === 106 /* NullKeyword */ ) return true; + if (isIdentifier(node) && !isGeneratedIdentifier(node) && idText(node) === "undefined") { + const symbol = checker.getSymbolAtLocation(node); + return !symbol || checker.isUndefinedSymbol(symbol); } return false; } - function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { - const signature = parameterInferences.length && parameterInferences[0].declaration.parent; - if (!signature) return; - const inferences = mapDefined(parameterInferences, (inference)=>{ - const param = inference.declaration; - if (param.initializer || getJSDocType(param) || !isIdentifier(param.name)) return; - const typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); - if (typeNode) { - const name = factory.cloneNode(param.name); - setEmitFlags(name, 7168 /* NoNestedComments */ ); - return { - name: factory.cloneNode(param.name), - param: param, - isOptional: !!inference.isOptional, - typeNode: typeNode - }; - } - }); - if (!inferences.length) return; - if (isArrowFunction(signature) || isFunctionExpression(signature)) { - const needParens = isArrowFunction(signature) && !findChildOfKind(signature, 20 /* OpenParenToken */ , sourceFile); - if (needParens) changes.insertNodeBefore(sourceFile, first(signature.parameters), factory.createToken(20 /* OpenParenToken */ )); - forEach(inferences, ({ typeNode: typeNode , param: param })=>{ - const typeTag = factory.createJSDocTypeTag(/*tagName*/ void 0, factory.createJSDocTypeExpression(typeNode)); - const jsDoc = factory.createJSDocComment(/*comment*/ void 0, [ - typeTag - ]); - changes.insertNodeAt(sourceFile, param.getStart(sourceFile), jsDoc, { - suffix: " " + function createUniqueSynthName(prevArgName) { + const renamedPrevArg = factory.createUniqueName(prevArgName.identifier.text, 16 /* Optimistic */ ); + return createSynthIdentifier(renamedPrevArg); + } + function getPossibleNameForVarDecl(node, transformer, continuationArgName) { + let possibleNameForVarDecl; + if (continuationArgName && !shouldReturn(node, transformer)) { + if (isSynthIdentifier(continuationArgName)) { + possibleNameForVarDecl = continuationArgName; + transformer.synthNamesMap.forEach((val, key)=>{ + if (val.identifier.text === continuationArgName.identifier.text) { + const newSynthName = createUniqueSynthName(continuationArgName); + transformer.synthNamesMap.set(key, newSynthName); + } }); - }); - if (needParens) changes.insertNodeAfter(sourceFile, last(signature.parameters), factory.createToken(21 /* CloseParenToken */ )); - } else { - const paramTags = map(inferences, ({ name: name , typeNode: typeNode , isOptional: isOptional })=>factory.createJSDocParameterTag(/*tagName*/ void 0, name, /*isBracketed*/ !!isOptional, factory.createJSDocTypeExpression(typeNode), /* isNameFirst */ false, /*comment*/ void 0)); - changes.addJSDocTags(sourceFile, signature, paramTags); + } else possibleNameForVarDecl = createSynthIdentifier(factory.createUniqueName("result", 16 /* Optimistic */ ), continuationArgName.types); + declareSynthIdentifier(possibleNameForVarDecl); } + return possibleNameForVarDecl; } - function getReferences(token, program, cancellationToken) { - return mapDefined(ts_FindAllReferences_exports.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), (entry)=>entry.kind !== ts_FindAllReferences_exports.EntryKind.Span ? tryCast(entry.node, isIdentifier) : void 0); + function finishCatchOrFinallyTransform(node, transformer, tryStatement, possibleNameForVarDecl, continuationArgName) { + const statements = []; + let varDeclIdentifier; + if (possibleNameForVarDecl && !shouldReturn(node, transformer)) { + varDeclIdentifier = getSynthesizedDeepClone(declareSynthIdentifier(possibleNameForVarDecl)); + const typeArray = possibleNameForVarDecl.types; + const unionType = transformer.checker.getUnionType(typeArray, 2 /* Subtype */ ); + const unionTypeNode = transformer.isInJSFile ? void 0 : transformer.checker.typeToTypeNode(unionType, /*enclosingDeclaration*/ void 0, /*flags*/ void 0); + const varDecl = [ + factory.createVariableDeclaration(varDeclIdentifier, /*exclamationToken*/ void 0, unionTypeNode) + ]; + const varDeclList = factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList(varDecl, 1 /* Let */ )); + statements.push(varDeclList); + } + statements.push(tryStatement); + if (continuationArgName && varDeclIdentifier && isSynthBindingPattern(continuationArgName)) statements.push(factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ + factory.createVariableDeclaration(getSynthesizedDeepClone(declareSynthBindingPattern(continuationArgName)), /*exclamationToken*/ void 0, /*type*/ void 0, varDeclIdentifier) + ], 2 /* Const */ ))); + return statements; } - function inferTypeForVariableFromUsage(token, program, cancellationToken) { - const references = getReferences(token, program, cancellationToken); - return inferTypeFromReferences(program, references, cancellationToken).single(); + function transformFinally(node, onFinally, transformer, hasContinuation, continuationArgName) { + if (!onFinally || isNullOrUndefined2(transformer, onFinally)) return transformExpression(/* returnContextNode */ node, node.expression.expression, transformer, hasContinuation, continuationArgName); + const possibleNameForVarDecl = getPossibleNameForVarDecl(node, transformer, continuationArgName); + const inlinedLeftHandSide = transformExpression(/*returnContextNode*/ node, node.expression.expression, transformer, /*hasContinuation*/ true, possibleNameForVarDecl); + if (hasFailed()) return silentFail(); + const inlinedCallback = transformCallbackArgument(onFinally, hasContinuation, /*continuationArgName*/ void 0, /*inputArgName*/ void 0, node, transformer); + if (hasFailed()) return silentFail(); + const tryBlock = factory.createBlock(inlinedLeftHandSide); + const finallyBlock = factory.createBlock(inlinedCallback); + const tryStatement = factory.createTryStatement(tryBlock, /*catchClause*/ void 0, finallyBlock); + return finishCatchOrFinallyTransform(node, transformer, tryStatement, possibleNameForVarDecl, continuationArgName); } - function inferTypeForParametersFromUsage(func, sourceFile, program, cancellationToken) { - const references = getFunctionReferences(func, sourceFile, program, cancellationToken); - return references && inferTypeFromReferences(program, references, cancellationToken).parameters(func) || func.parameters.map((p)=>({ - declaration: p, - type: isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType() - })); + function transformCatch(node, onRejected, transformer, hasContinuation, continuationArgName) { + if (!onRejected || isNullOrUndefined2(transformer, onRejected)) return transformExpression(/* returnContextNode */ node, node.expression.expression, transformer, hasContinuation, continuationArgName); + const inputArgName = getArgBindingName(onRejected, transformer); + const possibleNameForVarDecl = getPossibleNameForVarDecl(node, transformer, continuationArgName); + const inlinedLeftHandSide = transformExpression(/*returnContextNode*/ node, node.expression.expression, transformer, /*hasContinuation*/ true, possibleNameForVarDecl); + if (hasFailed()) return silentFail(); + const inlinedCallback = transformCallbackArgument(onRejected, hasContinuation, possibleNameForVarDecl, inputArgName, node, transformer); + if (hasFailed()) return silentFail(); + const tryBlock = factory.createBlock(inlinedLeftHandSide); + const catchClause = factory.createCatchClause(inputArgName && getSynthesizedDeepClone(declareSynthBindingName(inputArgName)), factory.createBlock(inlinedCallback)); + const tryStatement = factory.createTryStatement(tryBlock, catchClause, /*finallyBlock*/ void 0); + return finishCatchOrFinallyTransform(node, transformer, tryStatement, possibleNameForVarDecl, continuationArgName); } - function getFunctionReferences(containingFunction, sourceFile, program, cancellationToken) { - let searchToken; - switch(containingFunction.kind){ - case 173 /* Constructor */ : - searchToken = findChildOfKind(containingFunction, 135 /* ConstructorKeyword */ , sourceFile); - break; - case 216 /* ArrowFunction */ : - case 215 /* FunctionExpression */ : - const parent2 = containingFunction.parent; - searchToken = (isVariableDeclaration(parent2) || isPropertyDeclaration(parent2)) && isIdentifier(parent2.name) ? parent2.name : containingFunction.name; - break; - case 259 /* FunctionDeclaration */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - searchToken = containingFunction.name; - break; + function transformThen(node, onFulfilled, onRejected, transformer, hasContinuation, continuationArgName) { + if (!onFulfilled || isNullOrUndefined2(transformer, onFulfilled)) return transformCatch(node, onRejected, transformer, hasContinuation, continuationArgName); + if (onRejected && !isNullOrUndefined2(transformer, onRejected)) return silentFail(); + const inputArgName = getArgBindingName(onFulfilled, transformer); + const inlinedLeftHandSide = transformExpression(node.expression.expression, node.expression.expression, transformer, /*hasContinuation*/ true, inputArgName); + if (hasFailed()) return silentFail(); + const inlinedCallback = transformCallbackArgument(onFulfilled, hasContinuation, continuationArgName, inputArgName, node, transformer); + if (hasFailed()) return silentFail(); + return concatenate(inlinedLeftHandSide, inlinedCallback); + } + function transformPromiseExpressionOfPropertyAccess(returnContextNode, node, transformer, hasContinuation, continuationArgName) { + if (shouldReturn(returnContextNode, transformer)) { + let returnValue = getSynthesizedDeepClone(node); + if (hasContinuation) returnValue = factory.createAwaitExpression(returnValue); + return [ + factory.createReturnStatement(returnValue) + ]; } - if (!searchToken) return void 0; - return getReferences(searchToken, program, cancellationToken); + return createVariableOrAssignmentOrExpressionStatement(continuationArgName, factory.createAwaitExpression(node), /*typeAnnotation*/ void 0); } - function inferTypeFromReferences(program, references, cancellationToken) { - const checker = program.getTypeChecker(); - const builtinConstructors = { - string: ()=>checker.getStringType(), - number: ()=>checker.getNumberType(), - Array: (t)=>checker.createArrayType(t), - Promise: (t)=>checker.createPromiseType(t) - }; - const builtins = [ - checker.getStringType(), - checker.getNumberType(), - checker.createArrayType(checker.getAnyType()), - checker.createPromiseType(checker.getAnyType()) + function createVariableOrAssignmentOrExpressionStatement(variableName, rightHandSide, typeAnnotation) { + if (!variableName || isEmptyBindingName(variableName)) return [ + factory.createExpressionStatement(rightHandSide) ]; - return { - single: single2, - parameters: parameters, - thisParameter: thisParameter - }; - function createEmptyUsage() { - return { - isNumber: void 0, - isString: void 0, - isNumberOrString: void 0, - candidateTypes: void 0, - properties: void 0, - calls: void 0, - constructs: void 0, - numberIndex: void 0, - stringIndex: void 0, - candidateThisTypes: void 0, - inferredTypes: void 0 - }; - } - function combineUsages(usages) { - const combinedProperties = /* @__PURE__ */ new Map(); - for (const u of usages)if (u.properties) u.properties.forEach((p, name)=>{ - if (!combinedProperties.has(name)) combinedProperties.set(name, []); - combinedProperties.get(name).push(p); - }); - const properties = /* @__PURE__ */ new Map(); - combinedProperties.forEach((ps, name)=>{ - properties.set(name, combineUsages(ps)); - }); - return { - isNumber: usages.some((u)=>u.isNumber), - isString: usages.some((u)=>u.isString), - isNumberOrString: usages.some((u)=>u.isNumberOrString), - candidateTypes: flatMap(usages, (u)=>u.candidateTypes), - properties: properties, - calls: flatMap(usages, (u)=>u.calls), - constructs: flatMap(usages, (u)=>u.constructs), - numberIndex: forEach(usages, (u)=>u.numberIndex), - stringIndex: forEach(usages, (u)=>u.stringIndex), - candidateThisTypes: flatMap(usages, (u)=>u.candidateThisTypes), - inferredTypes: void 0 - }; - } - function single2() { - return combineTypes(inferTypesFromReferencesSingle(references)); - } - function parameters(declaration) { - if (references.length === 0 || !declaration.parameters) return void 0; - const usage = createEmptyUsage(); - for (const reference of references){ - cancellationToken.throwIfCancellationRequested(); - calculateUsageOfNode(reference, usage); - } - const calls = [ - ...usage.constructs || [], - ...usage.calls || [] + if (isSynthIdentifier(variableName) && variableName.hasBeenDeclared) return [ + factory.createExpressionStatement(factory.createAssignment(getSynthesizedDeepClone(referenceSynthIdentifier(variableName)), rightHandSide)) + ]; + return [ + factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ + factory.createVariableDeclaration(getSynthesizedDeepClone(declareSynthBindingName(variableName)), /*exclamationToken*/ void 0, typeAnnotation, rightHandSide) + ], 2 /* Const */ )) + ]; + } + function maybeAnnotateAndReturn(expressionToReturn, typeAnnotation) { + if (typeAnnotation && expressionToReturn) { + const name = factory.createUniqueName("result", 16 /* Optimistic */ ); + return [ + ...createVariableOrAssignmentOrExpressionStatement(createSynthIdentifier(name), expressionToReturn, typeAnnotation), + factory.createReturnStatement(name) ]; - return declaration.parameters.map((parameter, parameterIndex)=>{ - const types = []; - const isRest = isRestParameter(parameter); - let isOptional = false; - for (const call of calls){ - if (call.argumentTypes.length <= parameterIndex) { - isOptional = isInJSFile(declaration); - types.push(checker.getUndefinedType()); - } else if (isRest) for(let i = parameterIndex; i < call.argumentTypes.length; i++)types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[i])); - else types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[parameterIndex])); + } + return [ + factory.createReturnStatement(expressionToReturn) + ]; + } + function transformCallbackArgument(func, hasContinuation, continuationArgName, inputArgName, parent2, transformer) { + var _a; + switch(func.kind){ + case 106 /* NullKeyword */ : + break; + case 211 /* PropertyAccessExpression */ : + case 80 /* Identifier */ : + if (!inputArgName) break; + const synthCall = factory.createCallExpression(getSynthesizedDeepClone(func), /*typeArguments*/ void 0, isSynthIdentifier(inputArgName) ? [ + referenceSynthIdentifier(inputArgName) + ] : []); + if (shouldReturn(parent2, transformer)) return maybeAnnotateAndReturn(synthCall, getExplicitPromisedTypeOfPromiseReturningCallExpression(parent2, func, transformer.checker)); + const type = transformer.checker.getTypeAtLocation(func); + const callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */ ); + if (!callSignatures.length) return silentFail(); + const returnType = callSignatures[0].getReturnType(); + const varDeclOrAssignment = createVariableOrAssignmentOrExpressionStatement(continuationArgName, factory.createAwaitExpression(synthCall), getExplicitPromisedTypeOfPromiseReturningCallExpression(parent2, func, transformer.checker)); + if (continuationArgName) continuationArgName.types.push(transformer.checker.getAwaitedType(returnType) || returnType); + return varDeclOrAssignment; + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + { + const funcBody = func.body; + const returnType2 = (_a = getLastCallSignature(transformer.checker.getTypeAtLocation(func), transformer.checker)) == null ? void 0 : _a.getReturnType(); + if (isBlock(funcBody)) { + let refactoredStmts = []; + let seenReturnStatement = false; + for (const statement of funcBody.statements){ + if (isReturnStatement(statement)) { + seenReturnStatement = true; + if (isReturnStatementWithFixablePromiseHandler(statement, transformer.checker)) refactoredStmts = refactoredStmts.concat(transformReturnStatementWithFixablePromiseHandler(transformer, statement, hasContinuation, continuationArgName)); + else { + const possiblyAwaitedRightHandSide = returnType2 && statement.expression ? getPossiblyAwaitedRightHandSide(transformer.checker, returnType2, statement.expression) : statement.expression; + refactoredStmts.push(...maybeAnnotateAndReturn(possiblyAwaitedRightHandSide, getExplicitPromisedTypeOfPromiseReturningCallExpression(parent2, func, transformer.checker))); + } + } else if (hasContinuation && forEachReturnStatement(statement, returnTrue)) return silentFail(); + else refactoredStmts.push(statement); + } + return shouldReturn(parent2, transformer) ? refactoredStmts.map((s)=>getSynthesizedDeepClone(s)) : removeReturns(refactoredStmts, continuationArgName, transformer, seenReturnStatement); + } else { + const inlinedStatements = isFixablePromiseHandler(funcBody, transformer.checker) ? transformReturnStatementWithFixablePromiseHandler(transformer, factory.createReturnStatement(funcBody), hasContinuation, continuationArgName) : emptyArray; + if (inlinedStatements.length > 0) return inlinedStatements; + if (returnType2) { + const possiblyAwaitedRightHandSide = getPossiblyAwaitedRightHandSide(transformer.checker, returnType2, funcBody); + if (!shouldReturn(parent2, transformer)) { + const transformedStatement = createVariableOrAssignmentOrExpressionStatement(continuationArgName, possiblyAwaitedRightHandSide, /*typeAnnotation*/ void 0); + if (continuationArgName) continuationArgName.types.push(transformer.checker.getAwaitedType(returnType2) || returnType2); + return transformedStatement; + } else return maybeAnnotateAndReturn(possiblyAwaitedRightHandSide, getExplicitPromisedTypeOfPromiseReturningCallExpression(parent2, func, transformer.checker)); + } else return silentFail(); + } } - if (isIdentifier(parameter.name)) { - const inferred = inferTypesFromReferencesSingle(getReferences(parameter.name, program, cancellationToken)); - types.push(...isRest ? mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred); + default: + return silentFail(); + } + return emptyArray; + } + function getPossiblyAwaitedRightHandSide(checker, type, expr) { + const rightHandSide = getSynthesizedDeepClone(expr); + return !!checker.getPromisedTypeOfPromise(type) ? factory.createAwaitExpression(rightHandSide) : rightHandSide; + } + function getLastCallSignature(type, checker) { + const callSignatures = checker.getSignaturesOfType(type, 0 /* Call */ ); + return lastOrUndefined(callSignatures); + } + function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) { + const ret = []; + for (const stmt of stmts){ + if (isReturnStatement(stmt)) { + if (stmt.expression) { + const possiblyAwaitedExpression = isPromiseTypedExpression(stmt.expression, transformer.checker) ? factory.createAwaitExpression(stmt.expression) : stmt.expression; + if (prevArgName === void 0) ret.push(factory.createExpressionStatement(possiblyAwaitedExpression)); + else if (isSynthIdentifier(prevArgName) && prevArgName.hasBeenDeclared) ret.push(factory.createExpressionStatement(factory.createAssignment(referenceSynthIdentifier(prevArgName), possiblyAwaitedExpression))); + else ret.push(factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ + factory.createVariableDeclaration(declareSynthBindingName(prevArgName), /*exclamationToken*/ void 0, /*type*/ void 0, possiblyAwaitedExpression) + ], 2 /* Const */ ))); } - const type = combineTypes(types); - return { - type: isRest ? checker.createArrayType(type) : type, - isOptional: isOptional && !isRest, - declaration: parameter - }; - }); + } else ret.push(getSynthesizedDeepClone(stmt)); } - function thisParameter() { - const usage = createEmptyUsage(); - for (const reference of references){ - cancellationToken.throwIfCancellationRequested(); - calculateUsageOfNode(reference, usage); + if (!seenReturnStatement && prevArgName !== void 0) ret.push(factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ + factory.createVariableDeclaration(declareSynthBindingName(prevArgName), /*exclamationToken*/ void 0, /*type*/ void 0, factory.createIdentifier("undefined")) + ], 2 /* Const */ ))); + return ret; + } + function transformReturnStatementWithFixablePromiseHandler(transformer, innerRetStmt, hasContinuation, continuationArgName) { + let innerCbBody = []; + forEachChild(innerRetStmt, function visit(node) { + if (isCallExpression(node)) { + const temp = transformExpression(node, node, transformer, hasContinuation, continuationArgName); + innerCbBody = innerCbBody.concat(temp); + if (innerCbBody.length > 0) return; + } else if (!isFunctionLike(node)) forEachChild(node, visit); + }); + return innerCbBody; + } + function getArgBindingName(funcNode, transformer) { + const types = []; + let name; + if (isFunctionLikeDeclaration(funcNode)) { + if (funcNode.parameters.length > 0) { + const param = funcNode.parameters[0].name; + name = getMappedBindingNameOrDefault(param); } - return combineTypes(usage.candidateThisTypes || emptyArray); + } else if (isIdentifier(funcNode)) name = getMapEntryOrDefault(funcNode); + else if (isPropertyAccessExpression(funcNode) && isIdentifier(funcNode.name)) name = getMapEntryOrDefault(funcNode.name); + if (!name || "identifier" in name && name.identifier.text === "undefined") return void 0; + return name; + function getMappedBindingNameOrDefault(bindingName) { + if (isIdentifier(bindingName)) return getMapEntryOrDefault(bindingName); + const elements = flatMap(bindingName.elements, (element)=>{ + if (isOmittedExpression(element)) return []; + return [ + getMappedBindingNameOrDefault(element.name) + ]; + }); + return createSynthBindingPattern(bindingName, elements); } - function inferTypesFromReferencesSingle(references2) { - const usage = createEmptyUsage(); - for (const reference of references2){ - cancellationToken.throwIfCancellationRequested(); - calculateUsageOfNode(reference, usage); - } - return inferTypes(usage); + function getMapEntryOrDefault(identifier) { + const originalNode = getOriginalNode2(identifier); + const symbol = getSymbol2(originalNode); + if (!symbol) return createSynthIdentifier(identifier, types); + const mapEntry = transformer.synthNamesMap.get(getSymbolId(symbol).toString()); + return mapEntry || createSynthIdentifier(identifier, types); } - function calculateUsageOfNode(node, usage) { - while(isRightSideOfQualifiedNameOrPropertyAccess(node))node = node.parent; - switch(node.parent.kind){ - case 241 /* ExpressionStatement */ : - inferTypeFromExpressionStatement(node, usage); - break; - case 222 /* PostfixUnaryExpression */ : - usage.isNumber = true; - break; - case 221 /* PrefixUnaryExpression */ : - inferTypeFromPrefixUnaryExpression(node.parent, usage); - break; - case 223 /* BinaryExpression */ : - inferTypeFromBinaryExpression(node, node.parent, usage); - break; - case 292 /* CaseClause */ : - case 293 /* DefaultClause */ : - inferTypeFromSwitchStatementLabel(node.parent, usage); - break; - case 210 /* CallExpression */ : - case 211 /* NewExpression */ : - if (node.parent.expression === node) inferTypeFromCallExpression(node.parent, usage); - else inferTypeFromContextualType(node, usage); - break; - case 208 /* PropertyAccessExpression */ : - inferTypeFromPropertyAccessExpression(node.parent, usage); - break; - case 209 /* ElementAccessExpression */ : - inferTypeFromPropertyElementExpression(node.parent, node, usage); - break; - case 299 /* PropertyAssignment */ : - case 300 /* ShorthandPropertyAssignment */ : - inferTypeFromPropertyAssignment(node.parent, usage); - break; - case 169 /* PropertyDeclaration */ : - inferTypeFromPropertyDeclaration(node.parent, usage); - break; - case 257 /* VariableDeclaration */ : - { - const { name: name , initializer: initializer } = node.parent; - if (node === name) { - if (initializer) addCandidateType(usage, checker.getTypeAtLocation(initializer)); - break; - } - } - default: - return inferTypeFromContextualType(node, usage); - } + function getSymbol2(node) { + var _a; + return ((_a = tryCast(node, canHaveSymbol)) == null ? void 0 : _a.symbol) ?? transformer.checker.getSymbolAtLocation(node); } - function inferTypeFromContextualType(node, usage) { - if (isExpressionNode(node)) addCandidateType(usage, checker.getContextualType(node)); + function getOriginalNode2(node) { + return node.original ? node.original : node; } - function inferTypeFromExpressionStatement(node, usage) { - addCandidateType(usage, isCallExpression(node) ? checker.getVoidType() : checker.getAnyType()); - } - function inferTypeFromPrefixUnaryExpression(node, usage) { - switch(node.operator){ - case 45 /* PlusPlusToken */ : - case 46 /* MinusMinusToken */ : - case 40 /* MinusToken */ : - case 54 /* TildeToken */ : - usage.isNumber = true; - break; - case 39 /* PlusToken */ : - usage.isNumberOrString = true; - break; - } + } + function isEmptyBindingName(bindingName) { + if (!bindingName) return true; + if (isSynthIdentifier(bindingName)) return !bindingName.identifier.text; + return every(bindingName.elements, isEmptyBindingName); + } + function createSynthIdentifier(identifier, types = []) { + return { + kind: 0 /* Identifier */ , + identifier: identifier, + types: types, + hasBeenDeclared: false, + hasBeenReferenced: false + }; + } + function createSynthBindingPattern(bindingPattern, elements = emptyArray, types = []) { + return { + kind: 1 /* BindingPattern */ , + bindingPattern: bindingPattern, + elements: elements, + types: types + }; + } + function referenceSynthIdentifier(synthId) { + synthId.hasBeenReferenced = true; + return synthId.identifier; + } + function declareSynthBindingName(synthName) { + return isSynthIdentifier(synthName) ? declareSynthIdentifier(synthName) : declareSynthBindingPattern(synthName); + } + function declareSynthBindingPattern(synthPattern) { + for (const element of synthPattern.elements)declareSynthBindingName(element); + return synthPattern.bindingPattern; + } + function declareSynthIdentifier(synthId) { + synthId.hasBeenDeclared = true; + return synthId.identifier; + } + function isSynthIdentifier(bindingName) { + return bindingName.kind === 0 /* Identifier */ ; + } + function isSynthBindingPattern(bindingName) { + return bindingName.kind === 1 /* BindingPattern */ ; + } + function shouldReturn(expression, transformer) { + return !!expression.original && transformer.setOfExpressionsToReturn.has(getNodeId(expression.original)); + } + var fixId10, errorCodes11, codeActionSucceeded; + var init_convertToAsyncFunction = __esm({ + "src/services/codefixes/convertToAsyncFunction.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId10 = "convertToAsyncFunction"; + errorCodes11 = [ + Diagnostics.This_may_be_converted_to_an_async_function.code + ]; + codeActionSucceeded = true; + registerCodeFix({ + errorCodes: errorCodes11, + getCodeActions (context) { + codeActionSucceeded = true; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker())); + return codeActionSucceeded ? [ + createCodeFixAction(fixId10, changes, Diagnostics.Convert_to_async_function, fixId10, Diagnostics.Convert_all_to_async_functions) + ] : []; + }, + fixIds: [ + fixId10 + ], + getAllCodeActions: (context)=>codeFixAll(context, errorCodes11, (changes, err)=>convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker())) + }); } - function inferTypeFromBinaryExpression(node, parent2, usage) { - switch(parent2.operatorToken.kind){ - case 42 /* AsteriskAsteriskToken */ : - case 41 /* AsteriskToken */ : - case 43 /* SlashToken */ : - case 44 /* PercentToken */ : - case 47 /* LessThanLessThanToken */ : - case 48 /* GreaterThanGreaterThanToken */ : - case 49 /* GreaterThanGreaterThanGreaterThanToken */ : - case 50 /* AmpersandToken */ : - case 51 /* BarToken */ : - case 52 /* CaretToken */ : - case 65 /* MinusEqualsToken */ : - case 67 /* AsteriskAsteriskEqualsToken */ : - case 66 /* AsteriskEqualsToken */ : - case 68 /* SlashEqualsToken */ : - case 69 /* PercentEqualsToken */ : - case 73 /* AmpersandEqualsToken */ : - case 74 /* BarEqualsToken */ : - case 78 /* CaretEqualsToken */ : - case 70 /* LessThanLessThanEqualsToken */ : - case 72 /* GreaterThanGreaterThanGreaterThanEqualsToken */ : - case 71 /* GreaterThanGreaterThanEqualsToken */ : - case 40 /* MinusToken */ : - case 29 /* LessThanToken */ : - case 32 /* LessThanEqualsToken */ : - case 31 /* GreaterThanToken */ : - case 33 /* GreaterThanEqualsToken */ : - const operandType = checker.getTypeAtLocation(parent2.left === node ? parent2.right : parent2.left); - if (operandType.flags & 1056 /* EnumLike */ ) addCandidateType(usage, operandType); - else usage.isNumber = true; - break; - case 64 /* PlusEqualsToken */ : - case 39 /* PlusToken */ : - const otherOperandType = checker.getTypeAtLocation(parent2.left === node ? parent2.right : parent2.left); - if (otherOperandType.flags & 1056 /* EnumLike */ ) addCandidateType(usage, otherOperandType); - else if (otherOperandType.flags & 296 /* NumberLike */ ) usage.isNumber = true; - else if (otherOperandType.flags & 402653316 /* StringLike */ ) usage.isString = true; - else if (otherOperandType.flags & 1 /* Any */ ) ; - else usage.isNumberOrString = true; - break; - case 63 /* EqualsToken */ : - case 34 /* EqualsEqualsToken */ : - case 36 /* EqualsEqualsEqualsToken */ : - case 37 /* ExclamationEqualsEqualsToken */ : - case 35 /* ExclamationEqualsToken */ : - addCandidateType(usage, checker.getTypeAtLocation(parent2.left === node ? parent2.right : parent2.left)); - break; - case 101 /* InKeyword */ : - if (node === parent2.left) usage.isString = true; - break; - case 56 /* BarBarToken */ : - case 60 /* QuestionQuestionToken */ : - if (node === parent2.left && (node.parent.parent.kind === 257 /* VariableDeclaration */ || isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) addCandidateType(usage, checker.getTypeAtLocation(parent2.right)); + }); + // src/services/codefixes/convertToEsModule.ts + function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) { + for (const moduleSpecifier of importingFile.imports){ + const imported = getResolvedModule(importingFile, moduleSpecifier.text, getModeForUsageLocation(importingFile, moduleSpecifier)); + if (!imported || imported.resolvedFileName !== exportingFile.fileName) continue; + const importNode = importFromModuleSpecifier(moduleSpecifier); + switch(importNode.kind){ + case 271 /* ImportEqualsDeclaration */ : + changes.replaceNode(importingFile, importNode, makeImport(importNode.name, /*namedImports*/ void 0, moduleSpecifier, quotePreference)); break; - case 55 /* AmpersandAmpersandToken */ : - case 27 /* CommaToken */ : - case 102 /* InstanceOfKeyword */ : + case 213 /* CallExpression */ : + if (isRequireCall(importNode, /*requireStringLiteralLikeArgument*/ false)) changes.replaceNode(importingFile, importNode, factory.createPropertyAccessExpression(getSynthesizedDeepClone(importNode), "default")); break; } } - function inferTypeFromSwitchStatementLabel(parent2, usage) { - addCandidateType(usage, checker.getTypeAtLocation(parent2.parent.parent.expression)); - } - function inferTypeFromCallExpression(parent2, usage) { - const call = { - argumentTypes: [], - return_: createEmptyUsage() - }; - if (parent2.arguments) for (const argument of parent2.arguments)call.argumentTypes.push(checker.getTypeAtLocation(argument)); - calculateUsageOfNode(parent2, call.return_); - if (parent2.kind === 210 /* CallExpression */ ) (usage.calls || (usage.calls = [])).push(call); - else (usage.constructs || (usage.constructs = [])).push(call); + } + function convertFileToEsModule(sourceFile, checker, changes, target, quotePreference) { + const identifiers = { + original: collectFreeIdentifiers(sourceFile), + additional: /* @__PURE__ */ new Set() + }; + const exports = collectExportRenames(sourceFile, checker, identifiers); + convertExportsAccesses(sourceFile, exports, changes); + let moduleExportsChangedToDefault = false; + let useSitesToUnqualify; + for (const statement of filter(sourceFile.statements, isVariableStatement)){ + const newUseSites = convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); + if (newUseSites) copyEntries(newUseSites, useSitesToUnqualify ?? (useSitesToUnqualify = /* @__PURE__ */ new Map())); } - function inferTypeFromPropertyAccessExpression(parent2, usage) { - const name = escapeLeadingUnderscores(parent2.name.text); - if (!usage.properties) usage.properties = /* @__PURE__ */ new Map(); - const propertyUsage = usage.properties.get(name) || createEmptyUsage(); - calculateUsageOfNode(parent2, propertyUsage); - usage.properties.set(name, propertyUsage); + for (const statement of filter(sourceFile.statements, (s)=>!isVariableStatement(s))){ + const moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, useSitesToUnqualify, quotePreference); + moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; } - function inferTypeFromPropertyElementExpression(parent2, node, usage) { - if (node === parent2.argumentExpression) { - usage.isNumberOrString = true; - return; - } else { - const indexType = checker.getTypeAtLocation(parent2.argumentExpression); - const indexUsage = createEmptyUsage(); - calculateUsageOfNode(parent2, indexUsage); - if (indexType.flags & 296 /* NumberLike */ ) usage.numberIndex = indexUsage; - else usage.stringIndex = indexUsage; + useSitesToUnqualify == null || useSitesToUnqualify.forEach((replacement, original)=>{ + changes.replaceNode(sourceFile, original, replacement); + }); + return moduleExportsChangedToDefault; + } + function collectExportRenames(sourceFile, checker, identifiers) { + const res = /* @__PURE__ */ new Map(); + forEachExportReference(sourceFile, (node)=>{ + const { text: text } = node.name; + if (!res.has(text) && (isIdentifierANonContextualKeyword(node.name) || checker.resolveName(text, node, 111551 /* Value */ , /*excludeGlobals*/ true))) res.set(text, makeUniqueName(`_${text}`, identifiers)); + }); + return res; + } + function convertExportsAccesses(sourceFile, exports, changes) { + forEachExportReference(sourceFile, (node, isAssignmentLhs)=>{ + if (isAssignmentLhs) return; + const { text: text } = node.name; + changes.replaceNode(sourceFile, node, factory.createIdentifier(exports.get(text) || text)); + }); + } + function forEachExportReference(sourceFile, cb) { + sourceFile.forEachChild(function recur(node) { + if (isPropertyAccessExpression(node) && isExportsOrModuleExportsOrAlias(sourceFile, node.expression) && isIdentifier(node.name)) { + const { parent: parent2 } = node; + cb(node, isBinaryExpression(parent2) && parent2.left === node && parent2.operatorToken.kind === 64 /* EqualsToken */ ); } + node.forEachChild(recur); + }); + } + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, useSitesToUnqualify, quotePreference) { + switch(statement.kind){ + case 243 /* VariableStatement */ : + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); + return false; + case 244 /* ExpressionStatement */ : + { + const { expression: expression } = statement; + switch(expression.kind){ + case 213 /* CallExpression */ : + if (isRequireCall(expression, /*requireStringLiteralLikeArgument*/ true)) changes.replaceNode(sourceFile, statement, makeImport(/*defaultImport*/ void 0, /*namedImports*/ void 0, expression.arguments[0], quotePreference)); + return false; + case 226 /* BinaryExpression */ : + { + const { operatorToken: operatorToken } = expression; + return operatorToken.kind === 64 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports, useSitesToUnqualify); + } + } + } + default: + return false; } - function inferTypeFromPropertyAssignment(assignment, usage) { - const nodeWithRealType = isVariableDeclaration(assignment.parent.parent) ? assignment.parent.parent : assignment.parent; - addCandidateThisType(usage, checker.getTypeAtLocation(nodeWithRealType)); - } - function inferTypeFromPropertyDeclaration(declaration, usage) { - addCandidateThisType(usage, checker.getTypeAtLocation(declaration.parent)); - } - function removeLowPriorityInferences(inferences, priorities) { - const toRemove = []; - for (const i of inferences){ - for (const { high: high , low: low } of priorities)if (high(i)) { - Debug.assert(!low(i), "Priority can't have both low and high"); - toRemove.push(low); + } + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference) { + const { declarationList: declarationList } = statement; + let foundImport = false; + const converted = map(declarationList.declarations, (decl)=>{ + const { name: name, initializer: initializer } = decl; + if (initializer) { + if (isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { + foundImport = true; + return convertedImports([]); + } else if (isRequireCall(initializer, /*requireStringLiteralLikeArgument*/ true)) { + foundImport = true; + return convertSingleImport(name, initializer.arguments[0], checker, identifiers, target, quotePreference); + } else if (isPropertyAccessExpression(initializer) && isRequireCall(initializer.expression, /*requireStringLiteralLikeArgument*/ true)) { + foundImport = true; + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, quotePreference); } } - return inferences.filter((i)=>toRemove.every((f)=>!f(i))); - } - function combineFromUsage(usage) { - return combineTypes(inferTypes(usage)); - } - function combineTypes(inferences) { - if (!inferences.length) return checker.getAnyType(); - const stringNumber = checker.getUnionType([ - checker.getStringType(), - checker.getNumberType() + return convertedImports([ + factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ + decl + ], declarationList.flags)) ]); - const priorities = [ - { - high: (t)=>t === checker.getStringType() || t === checker.getNumberType(), - low: (t)=>t === stringNumber - }, - { - high: (t)=>!(t.flags & 16385 /* Void */ ), - low: (t)=>!!(t.flags & 16385 /* Void */ ) - }, + }); + if (foundImport) { + changes.replaceNodeWithNodes(sourceFile, statement, flatMap(converted, (c)=>c.newImports)); + let combinedUseSites; + forEach(converted, (c)=>{ + if (c.useSitesToUnqualify) copyEntries(c.useSitesToUnqualify, combinedUseSites ?? (combinedUseSites = /* @__PURE__ */ new Map())); + }); + return combinedUseSites; + } + } + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { + switch(name.kind){ + case 206 /* ObjectBindingPattern */ : + case 207 /* ArrayBindingPattern */ : { - high: (t)=>!(t.flags & 114689 /* Void */ ) && !(getObjectFlags(t) & 16 /* Anonymous */ ), - low: (t)=>!!(getObjectFlags(t) & 16 /* Anonymous */ ) + const tmp = makeUniqueName(propertyName, identifiers); + return convertedImports([ + makeSingleImport(tmp, propertyName, moduleSpecifier, quotePreference), + makeConst(/*modifiers*/ void 0, name, factory.createIdentifier(tmp)) + ]); } - ]; - let good = removeLowPriorityInferences(inferences, priorities); - const anons = good.filter((i)=>getObjectFlags(i) & 16 /* Anonymous */ ); - if (anons.length) { - good = good.filter((i)=>!(getObjectFlags(i) & 16 /* Anonymous */ )); - good.push(combineAnonymousTypes(anons)); - } - return checker.getWidenedType(checker.getUnionType(good.map(checker.getBaseTypeOfLiteralType), 2 /* Subtype */ )); + case 80 /* Identifier */ : + return convertedImports([ + makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference) + ]); + default: + return Debug.assertNever(name, `Convert to ES module got invalid syntax form ${name.kind}`); } - function combineAnonymousTypes(anons) { - if (anons.length === 1) return anons[0]; - const calls = []; - const constructs = []; - const stringIndices = []; - const numberIndices = []; - let stringIndexReadonly = false; - let numberIndexReadonly = false; - const props = createMultiMap(); - for (const anon2 of anons){ - for (const p of checker.getPropertiesOfType(anon2))props.add(p.name, p.valueDeclaration ? checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration) : checker.getAnyType()); - calls.push(...checker.getSignaturesOfType(anon2, 0 /* Call */ )); - constructs.push(...checker.getSignaturesOfType(anon2, 1 /* Construct */ )); - const stringIndexInfo = checker.getIndexInfoOfType(anon2, 0 /* String */ ); - if (stringIndexInfo) { - stringIndices.push(stringIndexInfo.type); - stringIndexReadonly = stringIndexReadonly || stringIndexInfo.isReadonly; - } - const numberIndexInfo = checker.getIndexInfoOfType(anon2, 1 /* Number */ ); - if (numberIndexInfo) { - numberIndices.push(numberIndexInfo.type); - numberIndexReadonly = numberIndexReadonly || numberIndexInfo.isReadonly; + } + function convertAssignment(sourceFile, checker, assignment, changes, exports, useSitesToUnqualify) { + const { left: left, right: right } = assignment; + if (!isPropertyAccessExpression(left)) return false; + if (isExportsOrModuleExportsOrAlias(sourceFile, left)) { + if (isExportsOrModuleExportsOrAlias(sourceFile, right)) changes.delete(sourceFile, assignment.parent); + else { + const replacement = isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right, useSitesToUnqualify) : isRequireCall(right, /*requireStringLiteralLikeArgument*/ true) ? convertReExportAll(right.arguments[0], checker) : void 0; + if (replacement) { + changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]); + return replacement[1]; + } else { + changes.replaceRangeWithText(sourceFile, createRange(left.getStart(sourceFile), right.pos), "export default"); + return true; } } - const members = mapEntries(props, (name, types)=>{ - const isOptional = types.length < anons.length ? 16777216 /* Optional */ : 0; - const s = checker.createSymbol(4 /* Property */ | isOptional, name); - s.links.type = checker.getUnionType(types); - return [ - name, - s - ]; - }); - const indexInfos = []; - if (stringIndices.length) indexInfos.push(checker.createIndexInfo(checker.getStringType(), checker.getUnionType(stringIndices), stringIndexReadonly)); - if (numberIndices.length) indexInfos.push(checker.createIndexInfo(checker.getNumberType(), checker.getUnionType(numberIndices), numberIndexReadonly)); - return checker.createAnonymousType(anons[0].symbol, members, calls, constructs, indexInfos); - } - function inferTypes(usage) { - var _a2, _b, _c; - const types = []; - if (usage.isNumber) types.push(checker.getNumberType()); - if (usage.isString) types.push(checker.getStringType()); - if (usage.isNumberOrString) types.push(checker.getUnionType([ - checker.getStringType(), - checker.getNumberType() - ])); - if (usage.numberIndex) types.push(checker.createArrayType(combineFromUsage(usage.numberIndex))); - if (((_a2 = usage.properties) == null ? void 0 : _a2.size) || ((_b = usage.constructs) == null ? void 0 : _b.length) || usage.stringIndex) types.push(inferStructuralType(usage)); - const candidateTypes = (usage.candidateTypes || []).map((t)=>checker.getBaseTypeOfLiteralType(t)); - const callsType = ((_c = usage.calls) == null ? void 0 : _c.length) ? inferStructuralType(usage) : void 0; - if (callsType && candidateTypes) types.push(checker.getUnionType([ - callsType, - ...candidateTypes - ], 2 /* Subtype */ )); - else { - if (callsType) types.push(callsType); - if (length(candidateTypes)) types.push(...candidateTypes); + } else if (isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) convertNamedExport(sourceFile, assignment, changes, exports); + return false; + } + function tryChangeModuleExportsObject(object, useSitesToUnqualify) { + const statements = mapAllOrFail(object.properties, (prop)=>{ + switch(prop.kind){ + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 304 /* ShorthandPropertyAssignment */ : + case 305 /* SpreadAssignment */ : + return void 0; + case 303 /* PropertyAssignment */ : + return !isIdentifier(prop.name) ? void 0 : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer, useSitesToUnqualify); + case 174 /* MethodDeclaration */ : + return !isIdentifier(prop.name) ? void 0 : functionExpressionToDeclaration(prop.name.text, [ + factory.createToken(95 /* ExportKeyword */ ) + ], prop, useSitesToUnqualify); + default: + Debug.assertNever(prop, `Convert to ES6 got invalid prop kind ${prop.kind}`); } - types.push(...inferNamedTypesFromProperties(usage)); - return types; - } - function inferStructuralType(usage) { - const members = /* @__PURE__ */ new Map(); - if (usage.properties) usage.properties.forEach((u, name)=>{ - const symbol = checker.createSymbol(4 /* Property */ , name); - symbol.links.type = combineFromUsage(u); - members.set(name, symbol); + }); + return statements && [ + statements, + false + ]; + } + function convertNamedExport(sourceFile, assignment, changes, exports) { + const { text: text } = assignment.left.name; + const rename = exports.get(text); + if (rename !== void 0) { + const newNodes = [ + makeConst(/*modifiers*/ void 0, rename, assignment.right), + makeExportDeclaration([ + factory.createExportSpecifier(/*isTypeOnly*/ false, rename, text) + ]) + ]; + changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes); + } else convertExportsPropertyAssignment(assignment, sourceFile, changes); + } + function convertReExportAll(reExported, checker) { + const moduleSpecifier = reExported.text; + const moduleSymbol = checker.getSymbolAtLocation(reExported); + const exports = moduleSymbol ? moduleSymbol.exports : emptyMap; + return exports.has("export=" /* ExportEquals */ ) ? [ + [ + reExportDefault(moduleSpecifier) + ], + true + ] : !exports.has("default" /* Default */ ) ? [ + [ + reExportStar(moduleSpecifier) + ], + false + ] : // If there's some non-default export, must include both `export *` and `export default`. + exports.size > 1 ? [ + [ + reExportStar(moduleSpecifier), + reExportDefault(moduleSpecifier) + ], + true + ] : [ + [ + reExportDefault(moduleSpecifier) + ], + true + ]; + } + function reExportStar(moduleSpecifier) { + return makeExportDeclaration(/*exportSpecifiers*/ void 0, moduleSpecifier); + } + function reExportDefault(moduleSpecifier) { + return makeExportDeclaration([ + factory.createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ void 0, "default") + ], moduleSpecifier); + } + function convertExportsPropertyAssignment({ left: left, right: right, parent: parent2 }, sourceFile, changes) { + const name = left.name.text; + if ((isFunctionExpression(right) || isArrowFunction(right) || isClassExpression(right)) && (!right.name || right.name.text === name)) { + changes.replaceRange(sourceFile, { + pos: left.getStart(sourceFile), + end: right.getStart(sourceFile) + }, factory.createToken(95 /* ExportKeyword */ ), { + suffix: " " }); - const callSignatures = usage.calls ? [ - getSignatureFromCalls(usage.calls) - ] : []; - const constructSignatures = usage.constructs ? [ - getSignatureFromCalls(usage.constructs) - ] : []; - const indexInfos = usage.stringIndex ? [ - checker.createIndexInfo(checker.getStringType(), combineFromUsage(usage.stringIndex), /*isReadonly*/ false) - ] : []; - return checker.createAnonymousType(/*symbol*/ void 0, members, callSignatures, constructSignatures, indexInfos); - } - function inferNamedTypesFromProperties(usage) { - if (!usage.properties || !usage.properties.size) return []; - const types = builtins.filter((t)=>allPropertiesAreAssignableToUsage(t, usage)); - if (0 < types.length && types.length < 3) return types.map((t)=>inferInstantiationFromUsage(t, usage)); - return []; + if (!right.name) changes.insertName(sourceFile, right, name); + const semi = findChildOfKind(parent2, 27 /* SemicolonToken */ , sourceFile); + if (semi) changes.delete(sourceFile, semi); + } else changes.replaceNodeRangeWithNodes(sourceFile, left.expression, findChildOfKind(left, 25 /* DotToken */ , sourceFile), [ + factory.createToken(95 /* ExportKeyword */ ), + factory.createToken(87 /* ConstKeyword */ ) + ], { + joiner: " ", + suffix: " " + }); + } + function convertExportsDotXEquals_replaceNode(name, exported, useSitesToUnqualify) { + const modifiers = [ + factory.createToken(95 /* ExportKeyword */ ) + ]; + switch(exported.kind){ + case 218 /* FunctionExpression */ : + { + const { name: expressionName } = exported; + if (expressionName && expressionName.text !== name) return exportConst(); + } + case 219 /* ArrowFunction */ : + return functionExpressionToDeclaration(name, modifiers, exported, useSitesToUnqualify); + case 231 /* ClassExpression */ : + return classExpressionToDeclaration(name, modifiers, exported, useSitesToUnqualify); + default: + return exportConst(); } - function allPropertiesAreAssignableToUsage(type, usage) { - if (!usage.properties) return false; - return !forEachEntry(usage.properties, (propUsage, name)=>{ - const source = checker.getTypeOfPropertyOfType(type, name); - if (!source) return true; - if (propUsage.calls) { - const sigs = checker.getSignaturesOfType(source, 0 /* Call */ ); - return !sigs.length || !checker.isTypeAssignableTo(source, getFunctionFromCalls(propUsage.calls)); - } else return !checker.isTypeAssignableTo(source, combineFromUsage(propUsage)); - }); + function exportConst() { + return makeConst(modifiers, factory.createIdentifier(name), replaceImportUseSites(exported, useSitesToUnqualify)); } - function inferInstantiationFromUsage(type, usage) { - if (!(getObjectFlags(type) & 4 /* Reference */ ) || !usage.properties) return type; - const generic = type.target; - const singleTypeParameter = singleOrUndefined(generic.typeParameters); - if (!singleTypeParameter) return type; - const types = []; - usage.properties.forEach((propUsage, name)=>{ - const genericPropertyType = checker.getTypeOfPropertyOfType(generic, name); - Debug.assert(!!genericPropertyType, "generic should have all the properties of its reference."); - types.push(...inferTypeParameters(genericPropertyType, combineFromUsage(propUsage), singleTypeParameter)); - }); - return builtinConstructors[type.symbol.escapedName](combineTypes(types)); + } + function replaceImportUseSites(nodeOrNodes, useSitesToUnqualify) { + if (!useSitesToUnqualify || !some(arrayFrom(useSitesToUnqualify.keys()), (original)=>rangeContainsRange(nodeOrNodes, original))) return nodeOrNodes; + return isArray(nodeOrNodes) ? getSynthesizedDeepClonesWithReplacements(nodeOrNodes, /*includeTrivia*/ true, replaceNode) : getSynthesizedDeepCloneWithReplacements(nodeOrNodes, /*includeTrivia*/ true, replaceNode); + function replaceNode(original) { + if (original.kind === 211 /* PropertyAccessExpression */ ) { + const replacement = useSitesToUnqualify.get(original); + useSitesToUnqualify.delete(original); + return replacement; + } } - function inferTypeParameters(genericType, usageType, typeParameter) { - if (genericType === typeParameter) return [ - usageType - ]; - else if (genericType.flags & 3145728 /* UnionOrIntersection */ ) return flatMap(genericType.types, (t)=>inferTypeParameters(t, usageType, typeParameter)); - else if (getObjectFlags(genericType) & 4 /* Reference */ && getObjectFlags(usageType) & 4 /* Reference */ ) { - const genericArgs = checker.getTypeArguments(genericType); - const usageArgs = checker.getTypeArguments(usageType); - const types = []; - if (genericArgs && usageArgs) { - for(let i = 0; i < genericArgs.length; i++)if (usageArgs[i]) types.push(...inferTypeParameters(genericArgs[i], usageArgs[i], typeParameter)); + } + function convertSingleImport(name, moduleSpecifier, checker, identifiers, target, quotePreference) { + switch(name.kind){ + case 206 /* ObjectBindingPattern */ : + { + const importSpecifiers = mapAllOrFail(name.elements, (e)=>e.dotDotDotToken || e.initializer || e.propertyName && !isIdentifier(e.propertyName) || !isIdentifier(e.name) ? void 0 : makeImportSpecifier2(e.propertyName && e.propertyName.text, e.name.text)); + if (importSpecifiers) return convertedImports([ + makeImport(/*defaultImport*/ void 0, importSpecifiers, moduleSpecifier, quotePreference) + ]); } - return types; - } - const genericSigs = checker.getSignaturesOfType(genericType, 0 /* Call */ ); - const usageSigs = checker.getSignaturesOfType(usageType, 0 /* Call */ ); - if (genericSigs.length === 1 && usageSigs.length === 1) return inferFromSignatures(genericSigs[0], usageSigs[0], typeParameter); - return []; + case 207 /* ArrayBindingPattern */ : + { + const tmp = makeUniqueName(moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); + return convertedImports([ + makeImport(factory.createIdentifier(tmp), /*namedImports*/ void 0, moduleSpecifier, quotePreference), + makeConst(/*modifiers*/ void 0, getSynthesizedDeepClone(name), factory.createIdentifier(tmp)) + ]); + } + case 80 /* Identifier */ : + return convertSingleIdentifierImport(name, moduleSpecifier, checker, identifiers, quotePreference); + default: + return Debug.assertNever(name, `Convert to ES module got invalid name kind ${name.kind}`); } - function inferFromSignatures(genericSig, usageSig, typeParameter) { - var _a2; - const types = []; - for(let i = 0; i < genericSig.parameters.length; i++){ - const genericParam = genericSig.parameters[i]; - const usageParam = usageSig.parameters[i]; - const isRest = genericSig.declaration && isRestParameter(genericSig.declaration.parameters[i]); - if (!usageParam) break; - let genericParamType = genericParam.valueDeclaration ? checker.getTypeOfSymbolAtLocation(genericParam, genericParam.valueDeclaration) : checker.getAnyType(); - const elementType = isRest && checker.getElementTypeOfArrayType(genericParamType); - if (elementType) genericParamType = elementType; - const targetType = ((_a2 = tryCast(usageParam, isTransientSymbol)) == null ? void 0 : _a2.links.type) || (usageParam.valueDeclaration ? checker.getTypeOfSymbolAtLocation(usageParam, usageParam.valueDeclaration) : checker.getAnyType()); - types.push(...inferTypeParameters(genericParamType, targetType, typeParameter)); - } - const genericReturn = checker.getReturnTypeOfSignature(genericSig); - const usageReturn = checker.getReturnTypeOfSignature(usageSig); - types.push(...inferTypeParameters(genericReturn, usageReturn, typeParameter)); - return types; - } - function getFunctionFromCalls(calls) { - return checker.createAnonymousType(/*symbol*/ void 0, createSymbolTable(), [ - getSignatureFromCalls(calls) - ], emptyArray, emptyArray); - } - function getSignatureFromCalls(calls) { - const parameters2 = []; - const length2 = Math.max(...calls.map((c)=>c.argumentTypes.length)); - for(let i = 0; i < length2; i++){ - const symbol = checker.createSymbol(1 /* FunctionScopedVariable */ , escapeLeadingUnderscores(`arg${i}`)); - symbol.links.type = combineTypes(calls.map((call)=>call.argumentTypes[i] || checker.getUndefinedType())); - if (calls.some((call)=>call.argumentTypes[i] === void 0)) symbol.flags |= 16777216 /* Optional */ ; - parameters2.push(symbol); - } - const returnType = combineFromUsage(combineUsages(calls.map((call)=>call.return_))); - return checker.createSignature(/*declaration*/ void 0, /*typeParameters*/ void 0, /*thisParameter*/ void 0, parameters2, returnType, /*typePredicate*/ void 0, length2, 0 /* None */ ); - } - function addCandidateType(usage, type) { - if (type && !(type.flags & 1 /* Any */ ) && !(type.flags & 131072 /* Never */ )) (usage.candidateTypes || (usage.candidateTypes = [])).push(type); + } + function convertSingleIdentifierImport(name, moduleSpecifier, checker, identifiers, quotePreference) { + const nameSymbol = checker.getSymbolAtLocation(name); + const namedBindingsNames = /* @__PURE__ */ new Map(); + let needDefaultImport = false; + let useSitesToUnqualify; + for (const use of identifiers.original.get(name.text)){ + if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) continue; + const { parent: parent2 } = use; + if (isPropertyAccessExpression(parent2)) { + const { name: { text: propertyName } } = parent2; + if (propertyName === "default") { + needDefaultImport = true; + const importDefaultName = use.getText(); + (useSitesToUnqualify ?? (useSitesToUnqualify = /* @__PURE__ */ new Map())).set(parent2, factory.createIdentifier(importDefaultName)); + } else { + Debug.assert(parent2.expression === use, "Didn't expect expression === use"); + let idName = namedBindingsNames.get(propertyName); + if (idName === void 0) { + idName = makeUniqueName(propertyName, identifiers); + namedBindingsNames.set(propertyName, idName); + } + (useSitesToUnqualify ?? (useSitesToUnqualify = /* @__PURE__ */ new Map())).set(parent2, factory.createIdentifier(idName)); + } + } else needDefaultImport = true; } - function addCandidateThisType(usage, type) { - if (type && !(type.flags & 1 /* Any */ ) && !(type.flags & 131072 /* Never */ )) (usage.candidateThisTypes || (usage.candidateThisTypes = [])).push(type); + const namedBindings = namedBindingsNames.size === 0 ? void 0 : arrayFrom(mapIterator(namedBindingsNames.entries(), ([propertyName, idName])=>factory.createImportSpecifier(/*isTypeOnly*/ false, propertyName === idName ? void 0 : factory.createIdentifier(propertyName), factory.createIdentifier(idName)))); + if (!namedBindings) needDefaultImport = true; + return convertedImports([ + makeImport(needDefaultImport ? getSynthesizedDeepClone(name) : void 0, namedBindings, moduleSpecifier, quotePreference) + ], useSitesToUnqualify); + } + function makeUniqueName(name, identifiers) { + while(identifiers.original.has(name) || identifiers.additional.has(name))name = `_${name}`; + identifiers.additional.add(name); + return name; + } + function collectFreeIdentifiers(file) { + const map2 = createMultiMap(); + forEachFreeIdentifier(file, (id)=>map2.add(id.text, id)); + return map2; + } + function forEachFreeIdentifier(node, cb) { + if (isIdentifier(node) && isFreeIdentifier(node)) cb(node); + node.forEachChild((child)=>forEachFreeIdentifier(child, cb)); + } + function isFreeIdentifier(node) { + const { parent: parent2 } = node; + switch(parent2.kind){ + case 211 /* PropertyAccessExpression */ : + return parent2.name !== node; + case 208 /* BindingElement */ : + return parent2.propertyName !== node; + case 276 /* ImportSpecifier */ : + return parent2.propertyName !== node; + default: + return true; } } - var fixId37, errorCodes47; - var init_inferFromUsage = __esm({ - "src/services/codefixes/inferFromUsage.ts" () { + function functionExpressionToDeclaration(name, additionalModifiers, fn, useSitesToUnqualify) { + return factory.createFunctionDeclaration(concatenate(additionalModifiers, getSynthesizedDeepClones(fn.modifiers)), getSynthesizedDeepClone(fn.asteriskToken), name, getSynthesizedDeepClones(fn.typeParameters), getSynthesizedDeepClones(fn.parameters), getSynthesizedDeepClone(fn.type), factory.converters.convertToFunctionBlock(replaceImportUseSites(fn.body, useSitesToUnqualify))); + } + function classExpressionToDeclaration(name, additionalModifiers, cls, useSitesToUnqualify) { + return factory.createClassDeclaration(concatenate(additionalModifiers, getSynthesizedDeepClones(cls.modifiers)), name, getSynthesizedDeepClones(cls.typeParameters), getSynthesizedDeepClones(cls.heritageClauses), replaceImportUseSites(cls.members, useSitesToUnqualify)); + } + function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) { + return propertyName === "default" ? makeImport(factory.createIdentifier(localName), /*namedImports*/ void 0, moduleSpecifier, quotePreference) : makeImport(/*defaultImport*/ void 0, [ + makeImportSpecifier2(propertyName, localName) + ], moduleSpecifier, quotePreference); + } + function makeImportSpecifier2(propertyName, name) { + return factory.createImportSpecifier(/*isTypeOnly*/ false, propertyName !== void 0 && propertyName !== name ? factory.createIdentifier(propertyName) : void 0, factory.createIdentifier(name)); + } + function makeConst(modifiers, name, init) { + return factory.createVariableStatement(modifiers, factory.createVariableDeclarationList([ + factory.createVariableDeclaration(name, /*exclamationToken*/ void 0, /*type*/ void 0, init) + ], 2 /* Const */ )); + } + function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { + return factory.createExportDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, exportSpecifiers && factory.createNamedExports(exportSpecifiers), moduleSpecifier === void 0 ? void 0 : factory.createStringLiteral(moduleSpecifier)); + } + function convertedImports(newImports, useSitesToUnqualify) { + return { + newImports: newImports, + useSitesToUnqualify: useSitesToUnqualify + }; + } + var init_convertToEsModule = __esm({ + "src/services/codefixes/convertToEsModule.ts" () { "use strict"; init_ts4(); init_ts_codefix(); - fixId37 = "inferFromUsage"; - errorCodes47 = [ - // Variable declarations - Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, - // Variable uses - Diagnostics.Variable_0_implicitly_has_an_1_type.code, - // Parameter declarations - Diagnostics.Parameter_0_implicitly_has_an_1_type.code, - Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, - // Get Accessor declarations - Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, - Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, - // Set Accessor declarations - Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, - // Property declarations - Diagnostics.Member_0_implicitly_has_an_1_type.code, - //// Suggestions - // Variable declarations - Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code, - // Variable uses - Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, - // Parameter declarations - Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, - Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code, - // Get Accessor declarations - Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code, - Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code, - // Set Accessor declarations - Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code, - // Property declarations - Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, - // Function expressions and declarations - Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code - ]; registerCodeFix({ - errorCodes: errorCodes47, + errorCodes: [ + Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module.code + ], getCodeActions (context) { - const { sourceFile: sourceFile , program: program , span: { start: start } , errorCode: errorCode , cancellationToken: cancellationToken , host: host , preferences: preferences } = context; - const token = getTokenAtPosition(sourceFile, start); - let declaration; + const { sourceFile: sourceFile, program: program, preferences: preferences } = context; const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2)=>{ - declaration = doChange24(changes2, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ returnTrue, host, preferences); + const moduleExportsChangedToDefault = convertFileToEsModule(sourceFile, program.getTypeChecker(), changes2, getEmitScriptTarget(program.getCompilerOptions()), getQuotePreference(sourceFile, preferences)); + if (moduleExportsChangedToDefault) for (const importingFile of program.getSourceFiles())fixImportOfModuleExports(importingFile, sourceFile, changes2, getQuotePreference(importingFile, preferences)); }); - const name = declaration && getNameOfDeclaration(declaration); - return !name || changes.length === 0 ? void 0 : [ - createCodeFixAction(fixId37, changes, [ - getDiagnostic(errorCode, token), - getTextOfNode(name) - ], fixId37, Diagnostics.Infer_all_types_from_usage) + return [ + createCodeFixActionWithoutFixAll("convertToEsModule", changes, Diagnostics.Convert_to_ES_module) ]; - }, - fixIds: [ - fixId37 - ], - getAllCodeActions (context) { - const { sourceFile: sourceFile , program: program , cancellationToken: cancellationToken , host: host , preferences: preferences } = context; - const markSeen = nodeSeenTracker(); - return codeFixAll(context, errorCodes47, (changes, err)=>{ - doChange24(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, preferences); - }); } }); } }); - // src/services/codefixes/fixReturnTypeInAsyncFunction.ts - function getInfo12(sourceFile, checker, pos) { - if (isInJSFile(sourceFile)) return void 0; - const token = getTokenAtPosition(sourceFile, pos); - const func = findAncestor(token, isFunctionLikeDeclaration); - const returnTypeNode = func == null ? void 0 : func.type; - if (!returnTypeNode) return void 0; - const returnType = checker.getTypeFromTypeNode(returnTypeNode); - const promisedType = checker.getAwaitedType(returnType) || checker.getVoidType(); - const promisedTypeNode = checker.typeToTypeNode(promisedType, /*enclosingDeclaration*/ returnTypeNode, /*flags*/ void 0); - if (promisedTypeNode) return { - returnTypeNode: returnTypeNode, - returnType: returnType, - promisedTypeNode: promisedTypeNode, - promisedType: promisedType - }; + // src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts + function getQualifiedName(sourceFile, pos) { + const qualifiedName = findAncestor(getTokenAtPosition(sourceFile, pos), isQualifiedName); + Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); + return isIdentifier(qualifiedName.left) ? qualifiedName : void 0; } - function doChange25(changes, sourceFile, returnTypeNode, promisedTypeNode) { - changes.replaceNode(sourceFile, returnTypeNode, factory.createTypeReferenceNode("Promise", [ - promisedTypeNode - ])); + function doChange10(changeTracker, sourceFile, qualifiedName) { + const rightText = qualifiedName.right.text; + const replacement = factory.createIndexedAccessTypeNode(factory.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ void 0), factory.createLiteralTypeNode(factory.createStringLiteral(rightText))); + changeTracker.replaceNode(sourceFile, qualifiedName, replacement); } - var fixId38, errorCodes48; - var init_fixReturnTypeInAsyncFunction = __esm({ - "src/services/codefixes/fixReturnTypeInAsyncFunction.ts" () { + var fixId11, errorCodes12; + var init_correctQualifiedNameToIndexedAccessType = __esm({ + "src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts" () { "use strict"; init_ts4(); init_ts_codefix(); - fixId38 = "fixReturnTypeInAsyncFunction"; - errorCodes48 = [ - Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0.code + fixId11 = "correctQualifiedNameToIndexedAccessType"; + errorCodes12 = [ + Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code ]; registerCodeFix({ - errorCodes: errorCodes48, - fixIds: [ - fixId38 - ], - getCodeActions: function getCodeActionsToFixReturnTypeInAsyncFunction(context) { - const { sourceFile: sourceFile , program: program , span: span } = context; - const checker = program.getTypeChecker(); - const info = getInfo12(sourceFile, program.getTypeChecker(), span.start); - if (!info) return void 0; - const { returnTypeNode: returnTypeNode , returnType: returnType , promisedTypeNode: promisedTypeNode , promisedType: promisedType } = info; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange25(t, sourceFile, returnTypeNode, promisedTypeNode)); + errorCodes: errorCodes12, + getCodeActions (context) { + const qualifiedName = getQualifiedName(context.sourceFile, context.span.start); + if (!qualifiedName) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange10(t, context.sourceFile, qualifiedName)); + const newText = `${qualifiedName.left.text}["${qualifiedName.right.text}"]`; return [ - createCodeFixAction(fixId38, changes, [ - Diagnostics.Replace_0_with_Promise_1, - checker.typeToString(returnType), - checker.typeToString(promisedType) - ], fixId38, Diagnostics.Fix_all_incorrect_return_type_of_an_async_functions) + createCodeFixAction(fixId11, changes, [ + Diagnostics.Rewrite_as_the_indexed_access_type_0, + newText + ], fixId11, Diagnostics.Rewrite_all_as_indexed_access_types) ]; }, - getAllCodeActions: (context)=>codeFixAll(context, errorCodes48, (changes, diag2)=>{ - const info = getInfo12(diag2.file, context.program.getTypeChecker(), diag2.start); - if (info) doChange25(changes, diag2.file, info.returnTypeNode, info.promisedTypeNode); + fixIds: [ + fixId11 + ], + getAllCodeActions: (context)=>codeFixAll(context, errorCodes12, (changes, diag2)=>{ + const q = getQualifiedName(diag2.file, diag2.start); + if (q) doChange10(changes, diag2.file, q); }) }); } }); - // src/services/codefixes/disableJsDiagnostics.ts - function makeChange8(changes, sourceFile, position, seenLines) { - const { line: lineNumber } = getLineAndCharacterOfPosition(sourceFile, position); - if (!seenLines || tryAddToSet(seenLines, lineNumber)) changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore"); + // src/services/codefixes/convertToTypeOnlyExport.ts + function getExportSpecifierForDiagnosticSpan(span, sourceFile) { + return tryCast(getTokenAtPosition(sourceFile, span.start).parent, isExportSpecifier); } - var fixName4, fixId39, errorCodes49; - var init_disableJsDiagnostics = __esm({ - "src/services/codefixes/disableJsDiagnostics.ts" () { + function fixSingleExportDeclaration(changes, exportSpecifier, context) { + if (!exportSpecifier) return; + const exportClause = exportSpecifier.parent; + const exportDeclaration = exportClause.parent; + const typeExportSpecifiers = getTypeExportSpecifiers(exportSpecifier, context); + if (typeExportSpecifiers.length === exportClause.elements.length) changes.insertModifierBefore(context.sourceFile, 156 /* TypeKeyword */ , exportClause); + else { + const valueExportDeclaration = factory.updateExportDeclaration(exportDeclaration, exportDeclaration.modifiers, /*isTypeOnly*/ false, factory.updateNamedExports(exportClause, filter(exportClause.elements, (e)=>!contains(typeExportSpecifiers, e))), exportDeclaration.moduleSpecifier, /*assertClause*/ void 0); + const typeExportDeclaration = factory.createExportDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ true, factory.createNamedExports(typeExportSpecifiers), exportDeclaration.moduleSpecifier, /*assertClause*/ void 0); + changes.replaceNode(context.sourceFile, exportDeclaration, valueExportDeclaration, { + leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Exclude + }); + changes.insertNodeAfter(context.sourceFile, exportDeclaration, typeExportDeclaration); + } + } + function getTypeExportSpecifiers(originExportSpecifier, context) { + const exportClause = originExportSpecifier.parent; + if (exportClause.elements.length === 1) return exportClause.elements; + const diagnostics = getDiagnosticsWithinSpan(createTextSpanFromNode(exportClause), context.program.getSemanticDiagnostics(context.sourceFile, context.cancellationToken)); + return filter(exportClause.elements, (element)=>{ + var _a; + return element === originExportSpecifier || ((_a = findDiagnosticForNode(element, diagnostics)) == null ? void 0 : _a.code) === errorCodes13[0]; + }); + } + var errorCodes13, fixId12; + var init_convertToTypeOnlyExport = __esm({ + "src/services/codefixes/convertToTypeOnlyExport.ts" () { "use strict"; init_ts4(); init_ts_codefix(); - fixName4 = "disableJsDiagnostics"; - fixId39 = "disableJsDiagnostics"; - errorCodes49 = mapDefined(Object.keys(Diagnostics), (key)=>{ - const diag2 = Diagnostics[key]; - return diag2.category === 1 /* Error */ ? diag2.code : void 0; - }); + errorCodes13 = [ + Diagnostics.Re_exporting_a_type_when_0_is_enabled_requires_using_export_type.code + ]; + fixId12 = "convertToTypeOnlyExport"; registerCodeFix({ - errorCodes: errorCodes49, - getCodeActions: function getCodeActionsToDisableJsDiagnostics(context) { - const { sourceFile: sourceFile , program: program , span: span , host: host , formatContext: formatContext } = context; - if (!isInJSFile(sourceFile) || !isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) return void 0; - const newLineCharacter = sourceFile.checkJsDirective ? "" : getNewLineOrDefaultFromHost(host, formatContext.options); - const fixes = [ - // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. - createCodeFixActionWithoutFixAll(fixName4, [ - createFileTextChanges(sourceFile.fileName, [ - createTextChange(sourceFile.checkJsDirective ? createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) : createTextSpan(0, 0), `// @ts-nocheck${newLineCharacter}`) - ]) - ], Diagnostics.Disable_checking_for_this_file) + errorCodes: errorCodes13, + getCodeActions: function getCodeActionsToConvertToTypeOnlyExport(context) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>fixSingleExportDeclaration(t, getExportSpecifierForDiagnosticSpan(context.span, context.sourceFile), context)); + if (changes.length) return [ + createCodeFixAction(fixId12, changes, Diagnostics.Convert_to_type_only_export, fixId12, Diagnostics.Convert_all_re_exported_types_to_type_only_exports) ]; - if (ts_textChanges_exports.isValidLocationToAddComment(sourceFile, span.start)) fixes.unshift(createCodeFixAction(fixName4, ts_textChanges_exports.ChangeTracker.with(context, (t)=>makeChange8(t, sourceFile, span.start)), Diagnostics.Ignore_this_error_message, fixId39, Diagnostics.Add_ts_ignore_to_all_error_messages)); - return fixes; }, fixIds: [ - fixId39 + fixId12 ], - getAllCodeActions: (context)=>{ - const seenLines = /* @__PURE__ */ new Set(); - return codeFixAll(context, errorCodes49, (changes, diag2)=>{ - if (ts_textChanges_exports.isValidLocationToAddComment(diag2.file, diag2.start)) makeChange8(changes, diag2.file, diag2.start, seenLines); + getAllCodeActions: function getAllCodeActionsToConvertToTypeOnlyExport(context) { + const fixedExportDeclarations = /* @__PURE__ */ new Map(); + return codeFixAll(context, errorCodes13, (changes, diag2)=>{ + const exportSpecifier = getExportSpecifierForDiagnosticSpan(diag2, context.sourceFile); + if (exportSpecifier && addToSeen(fixedExportDeclarations, getNodeId(exportSpecifier.parent.parent))) fixSingleExportDeclaration(changes, exportSpecifier, context); }); } }); } }); - // src/services/codefixes/helpers.ts - function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, sourceFile, context, preferences, importAdder, addClassElement) { - const classMembers = classDeclaration.symbol.members; - for (const symbol of possiblyMissingSymbols)if (!classMembers.has(symbol.escapedName)) addNewNodeForMemberSymbol(symbol, classDeclaration, sourceFile, context, preferences, importAdder, addClassElement, /* body */ void 0); + // src/services/codefixes/convertToTypeOnlyImport.ts + function getDeclaration2(sourceFile, pos) { + const { parent: parent2 } = getTokenAtPosition(sourceFile, pos); + return isImportSpecifier(parent2) || isImportDeclaration(parent2) && parent2.importClause ? parent2 : void 0; } - function getNoopSymbolTrackerWithResolver(context) { - return { - trackSymbol: ()=>false, - moduleResolverHost: getModuleSpecifierResolverHost(context.program, context.host) - }; + function canConvertImportDeclarationForSpecifier(specifier, sourceFile, program) { + if (specifier.parent.parent.name) return false; + const nonTypeOnlySpecifiers = specifier.parent.elements.filter((e)=>!e.isTypeOnly); + if (nonTypeOnlySpecifiers.length === 1) return true; + const checker = program.getTypeChecker(); + for (const specifier2 of nonTypeOnlySpecifiers){ + const isUsedAsValue = ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(specifier2.name, checker, sourceFile, (usage)=>{ + return !isValidTypeOnlyAliasUseSite(usage); + }); + if (isUsedAsValue) return false; + } + return true; } - function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, context, preferences, importAdder, addClassElement, body, preserveOptional = 3 /* All */ , isAmbient = false) { - var _a2; - const declarations = symbol.getDeclarations(); - const declaration = declarations == null ? void 0 : declarations[0]; - const checker = context.program.getTypeChecker(); - const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions()); - const kind = (_a2 = declaration == null ? void 0 : declaration.kind) != null ? _a2 : 168 /* PropertySignature */ ; - const declarationName = getSynthesizedDeepClone(getNameOfDeclaration(declaration), /*includeTrivia*/ false); - const effectiveModifierFlags = declaration ? getEffectiveModifierFlags(declaration) : 0 /* None */ ; - let modifierFlags = effectiveModifierFlags & 4 /* Public */ ? 4 /* Public */ : effectiveModifierFlags & 16 /* Protected */ ? 16 /* Protected */ : 0 /* None */ ; - if (declaration && isAutoAccessorPropertyDeclaration(declaration)) modifierFlags |= 128 /* Accessor */ ; - const modifiers = createModifiers(); - const type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); - const optional = !!(symbol.flags & 16777216 /* Optional */ ); - const ambient = !!(enclosingDeclaration.flags & 16777216 /* Ambient */ ) || isAmbient; - const quotePreference = getQuotePreference(sourceFile, preferences); - switch(kind){ - case 168 /* PropertySignature */ : - case 169 /* PropertyDeclaration */ : - const flags = quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : void 0; - let typeNode = checker.typeToTypeNode(type, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context)); - if (importAdder) { - const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget); - if (importableReference) { - typeNode = importableReference.typeNode; - importSymbols(importAdder, importableReference.symbols); - } - } - addClassElement(factory.createPropertyDeclaration(modifiers, declaration ? createName(declarationName) : symbol.getName(), optional && preserveOptional & 2 /* Property */ ? factory.createToken(57 /* QuestionToken */ ) : void 0, typeNode, /*initializer*/ void 0)); - break; - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - { - Debug.assertIsDefined(declarations); - let typeNode2 = checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ void 0, getNoopSymbolTrackerWithResolver(context)); - const allAccessors = getAllAccessorDeclarations(declarations, declaration); - const orderedAccessors = allAccessors.secondAccessor ? [ - allAccessors.firstAccessor, - allAccessors.secondAccessor - ] : [ - allAccessors.firstAccessor - ]; - if (importAdder) { - const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode2, scriptTarget); - if (importableReference) { - typeNode2 = importableReference.typeNode; - importSymbols(importAdder, importableReference.symbols); - } - } - for (const accessor of orderedAccessors)if (isGetAccessorDeclaration(accessor)) addClassElement(factory.createGetAccessorDeclaration(modifiers, createName(declarationName), emptyArray, createTypeNode(typeNode2), createBody(body, quotePreference, ambient))); - else { - Debug.assertNode(accessor, isSetAccessorDeclaration, "The counterpart to a getter should be a setter"); - const parameter = getSetAccessorValueParameter(accessor); - const parameterName = parameter && isIdentifier(parameter.name) ? idText(parameter.name) : void 0; - addClassElement(factory.createSetAccessorDeclaration(modifiers, createName(declarationName), createDummyParameters(1, [ - parameterName - ], [ - createTypeNode(typeNode2) - ], 1, /*inJs*/ false), createBody(body, quotePreference, ambient))); - } - break; - } - case 170 /* MethodSignature */ : - case 171 /* MethodDeclaration */ : - Debug.assertIsDefined(declarations); - const signatures = type.isUnion() ? flatMap(type.types, (t)=>t.getCallSignatures()) : type.getCallSignatures(); - if (!some(signatures)) break; - if (declarations.length === 1) { - Debug.assert(signatures.length === 1, "One declaration implies one signature"); - const signature = signatures[0]; - outputMethod(quotePreference, signature, modifiers, createName(declarationName), createBody(body, quotePreference, ambient)); - break; - } - for (const signature of signatures)outputMethod(quotePreference, signature, modifiers, createName(declarationName)); - if (!ambient) { - if (declarations.length > signatures.length) { - const signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]); - outputMethod(quotePreference, signature, modifiers, createName(declarationName), createBody(body, quotePreference)); - } else { - Debug.assert(declarations.length === signatures.length, "Declarations and signatures should match count"); - addClassElement(createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, createName(declarationName), optional && !!(preserveOptional & 1 /* Method */ ), modifiers, quotePreference, body)); + function doChange11(changes, sourceFile, declaration) { + var _a; + if (isImportSpecifier(declaration)) changes.replaceNode(sourceFile, declaration, factory.updateImportSpecifier(declaration, /*isTypeOnly*/ true, declaration.propertyName, declaration.name)); + else { + const importClause = declaration.importClause; + if (importClause.name && importClause.namedBindings) changes.replaceNodeWithNodes(sourceFile, declaration, [ + factory.createImportDeclaration(getSynthesizedDeepClones(declaration.modifiers, /*includeTrivia*/ true), factory.createImportClause(/*isTypeOnly*/ true, getSynthesizedDeepClone(importClause.name, /*includeTrivia*/ true), /*namedBindings*/ void 0), getSynthesizedDeepClone(declaration.moduleSpecifier, /*includeTrivia*/ true), getSynthesizedDeepClone(declaration.assertClause, /*includeTrivia*/ true)), + factory.createImportDeclaration(getSynthesizedDeepClones(declaration.modifiers, /*includeTrivia*/ true), factory.createImportClause(/*isTypeOnly*/ true, /*name*/ void 0, getSynthesizedDeepClone(importClause.namedBindings, /*includeTrivia*/ true)), getSynthesizedDeepClone(declaration.moduleSpecifier, /*includeTrivia*/ true), getSynthesizedDeepClone(declaration.assertClause, /*includeTrivia*/ true)) + ]); + else { + const newNamedBindings = ((_a = importClause.namedBindings) == null ? void 0 : _a.kind) === 275 /* NamedImports */ ? factory.updateNamedImports(importClause.namedBindings, sameMap(importClause.namedBindings.elements, (e)=>factory.updateImportSpecifier(e, /*isTypeOnly*/ false, e.propertyName, e.name))) : importClause.namedBindings; + const importDeclaration = factory.updateImportDeclaration(declaration, declaration.modifiers, factory.updateImportClause(importClause, /*isTypeOnly*/ true, importClause.name, newNamedBindings), declaration.moduleSpecifier, declaration.assertClause); + changes.replaceNode(sourceFile, declaration, importDeclaration); + } + } + } + var errorCodes14, fixId13; + var init_convertToTypeOnlyImport = __esm({ + "src/services/codefixes/convertToTypeOnlyImport.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + errorCodes14 = [ + Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set_to_error.code, + Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled.code + ]; + fixId13 = "convertToTypeOnlyImport"; + registerCodeFix({ + errorCodes: errorCodes14, + getCodeActions: function getCodeActionsToConvertToTypeOnlyImport(context) { + var _a; + const declaration = getDeclaration2(context.sourceFile, context.span.start); + if (declaration) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange11(t, context.sourceFile, declaration)); + const importDeclarationChanges = declaration.kind === 276 /* ImportSpecifier */ && canConvertImportDeclarationForSpecifier(declaration, context.sourceFile, context.program) ? ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange11(t, context.sourceFile, declaration.parent.parent.parent)) : void 0; + const mainAction = createCodeFixAction(fixId13, changes, declaration.kind === 276 /* ImportSpecifier */ ? [ + Diagnostics.Use_type_0, + ((_a = declaration.propertyName) == null ? void 0 : _a.text) ?? declaration.name.text + ] : Diagnostics.Use_import_type, fixId13, Diagnostics.Fix_all_with_type_only_imports); + if (some(importDeclarationChanges)) return [ + createCodeFixActionWithoutFixAll(fixId13, importDeclarationChanges, Diagnostics.Use_import_type), + mainAction + ]; + return [ + mainAction + ]; } + return void 0; + }, + fixIds: [ + fixId13 + ], + getAllCodeActions: function getAllCodeActionsToConvertToTypeOnlyImport(context) { + const fixedImportDeclarations = /* @__PURE__ */ new Set(); + return codeFixAll(context, errorCodes14, (changes, diag2)=>{ + const errorDeclaration = getDeclaration2(diag2.file, diag2.start); + if ((errorDeclaration == null ? void 0 : errorDeclaration.kind) === 272 /* ImportDeclaration */ && !fixedImportDeclarations.has(errorDeclaration)) { + doChange11(changes, diag2.file, errorDeclaration); + fixedImportDeclarations.add(errorDeclaration); + } else if ((errorDeclaration == null ? void 0 : errorDeclaration.kind) === 276 /* ImportSpecifier */ && !fixedImportDeclarations.has(errorDeclaration.parent.parent.parent) && canConvertImportDeclarationForSpecifier(errorDeclaration, diag2.file, context.program)) { + doChange11(changes, diag2.file, errorDeclaration.parent.parent.parent); + fixedImportDeclarations.add(errorDeclaration.parent.parent.parent); + } else if ((errorDeclaration == null ? void 0 : errorDeclaration.kind) === 276 /* ImportSpecifier */ ) doChange11(changes, diag2.file, errorDeclaration); + }); } - break; - } - function outputMethod(quotePreference2, signature, modifiers2, name, body2) { - const method = createSignatureDeclarationFromSignature(171 /* MethodDeclaration */ , context, quotePreference2, signature, body2, name, modifiers2, optional && !!(preserveOptional & 1 /* Method */ ), enclosingDeclaration, importAdder); - if (method) addClassElement(method); - } - function createModifiers() { - let modifiers2; - if (modifierFlags) modifiers2 = combine(modifiers2, factory.createModifiersFromModifierFlags(modifierFlags)); - if (shouldAddOverrideKeyword()) modifiers2 = append(modifiers2, factory.createToken(161 /* OverrideKeyword */ )); - return modifiers2 && factory.createNodeArray(modifiers2); - } - function shouldAddOverrideKeyword() { - return !!(context.program.getCompilerOptions().noImplicitOverride && declaration && hasAbstractModifier(declaration)); + }); } - function createName(node) { - if (isIdentifier(node) && node.escapedText === "constructor") return factory.createComputedPropertyName(factory.createStringLiteral(idText(node), quotePreference === 0 /* Single */ )); - return getSynthesizedDeepClone(node, /*includeTrivia*/ false); + }); + // src/services/codefixes/convertTypedefToType.ts + function doChange12(changes, node, sourceFile, newLine, fixAll = false) { + if (!isJSDocTypedefTag(node)) return; + const declaration = createDeclaration(node); + if (!declaration) return; + const commentNode = node.parent; + const { leftSibling: leftSibling, rightSibling: rightSibling } = getLeftAndRightSiblings(node); + let pos = commentNode.getStart(); + let prefix = ""; + if (!leftSibling && commentNode.comment) { + pos = findEndOfTextBetween(commentNode, commentNode.getStart(), node.getStart()); + prefix = `${newLine} */${newLine}`; + } + if (leftSibling) { + if (fixAll && isJSDocTypedefTag(leftSibling)) { + pos = node.getStart(); + prefix = ""; + } else { + pos = findEndOfTextBetween(commentNode, leftSibling.getStart(), node.getStart()); + prefix = `${newLine} */${newLine}`; + } } - function createBody(block, quotePreference2, ambient2) { - return ambient2 ? void 0 : getSynthesizedDeepClone(block, /*includeTrivia*/ false) || createStubbedMethodBody(quotePreference2); + let end = commentNode.getEnd(); + let suffix = ""; + if (rightSibling) { + if (fixAll && isJSDocTypedefTag(rightSibling)) { + end = rightSibling.getStart(); + suffix = `${newLine}${newLine}`; + } else { + end = rightSibling.getStart(); + suffix = `${newLine}/**${newLine} * `; + } } - function createTypeNode(typeNode) { - return getSynthesizedDeepClone(typeNode, /*includeTrivia*/ false); + changes.replaceRange(sourceFile, { + pos: pos, + end: end + }, declaration, { + prefix: prefix, + suffix: suffix + }); + } + function getLeftAndRightSiblings(typedefNode) { + const commentNode = typedefNode.parent; + const maxChildIndex = commentNode.getChildCount() - 1; + const currentNodeIndex = commentNode.getChildren().findIndex((n)=>n.getStart() === typedefNode.getStart() && n.getEnd() === typedefNode.getEnd()); + const leftSibling = currentNodeIndex > 0 ? commentNode.getChildAt(currentNodeIndex - 1) : void 0; + const rightSibling = currentNodeIndex < maxChildIndex ? commentNode.getChildAt(currentNodeIndex + 1) : void 0; + return { + leftSibling: leftSibling, + rightSibling: rightSibling + }; + } + function findEndOfTextBetween(jsDocComment, from, to) { + const comment = jsDocComment.getText().substring(from - jsDocComment.getStart(), to - jsDocComment.getStart()); + for(let i = comment.length; i > 0; i--){ + if (!/[*/\s]/g.test(comment.substring(i - 1, i))) return from + i; } + return to; } - function createSignatureDeclarationFromSignature(kind, context, quotePreference, signature, body, name, modifiers, optional, enclosingDeclaration, importAdder) { - const program = context.program; - const checker = program.getTypeChecker(); - const scriptTarget = getEmitScriptTarget(program.getCompilerOptions()); - const isJs = isInJSFile(enclosingDeclaration); - const flags = 524545 /* AllowEmptyTuple */ | (quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : 0 /* None */ ); - const signatureDeclaration = checker.signatureToSignatureDeclaration(signature, kind, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context)); - if (!signatureDeclaration) return void 0; - let typeParameters = isJs ? void 0 : signatureDeclaration.typeParameters; - let parameters = signatureDeclaration.parameters; - let type = isJs ? void 0 : signatureDeclaration.type; - if (importAdder) { - if (typeParameters) { - const newTypeParameters = sameMap(typeParameters, (typeParameterDecl)=>{ - let constraint = typeParameterDecl.constraint; - let defaultType = typeParameterDecl.default; - if (constraint) { - const importableReference = tryGetAutoImportableReferenceFromTypeNode(constraint, scriptTarget); - if (importableReference) { - constraint = importableReference.typeNode; - importSymbols(importAdder, importableReference.symbols); - } - } - if (defaultType) { - const importableReference = tryGetAutoImportableReferenceFromTypeNode(defaultType, scriptTarget); - if (importableReference) { - defaultType = importableReference.typeNode; - importSymbols(importAdder, importableReference.symbols); - } - } - return factory.updateTypeParameterDeclaration(typeParameterDecl, typeParameterDecl.modifiers, typeParameterDecl.name, constraint, defaultType); - }); - if (typeParameters !== newTypeParameters) typeParameters = setTextRange(factory.createNodeArray(newTypeParameters, typeParameters.hasTrailingComma), typeParameters); - } - const newParameters = sameMap(parameters, (parameterDecl)=>{ - let type2 = isJs ? void 0 : parameterDecl.type; - if (type2) { - const importableReference = tryGetAutoImportableReferenceFromTypeNode(type2, scriptTarget); - if (importableReference) { - type2 = importableReference.typeNode; - importSymbols(importAdder, importableReference.symbols); - } - } - return factory.updateParameterDeclaration(parameterDecl, parameterDecl.modifiers, parameterDecl.dotDotDotToken, parameterDecl.name, isJs ? void 0 : parameterDecl.questionToken, type2, parameterDecl.initializer); - }); - if (parameters !== newParameters) parameters = setTextRange(factory.createNodeArray(newParameters, parameters.hasTrailingComma), parameters); - if (type) { - const importableReference = tryGetAutoImportableReferenceFromTypeNode(type, scriptTarget); - if (importableReference) { - type = importableReference.typeNode; - importSymbols(importAdder, importableReference.symbols); - } + function createDeclaration(tag) { + var _a; + const { typeExpression: typeExpression } = tag; + if (!typeExpression) return; + const typeName = (_a = tag.name) == null ? void 0 : _a.getText(); + if (!typeName) return; + if (typeExpression.kind === 329 /* JSDocTypeLiteral */ ) return createInterfaceForTypeLiteral(typeName, typeExpression); + if (typeExpression.kind === 316 /* JSDocTypeExpression */ ) return createTypeAliasForTypeExpression(typeName, typeExpression); + } + function createInterfaceForTypeLiteral(typeName, typeLiteral) { + const propertySignatures = createSignatureFromTypeLiteral(typeLiteral); + if (!some(propertySignatures)) return; + return factory.createInterfaceDeclaration(/*modifiers*/ void 0, typeName, /*typeParameters*/ void 0, /*heritageClauses*/ void 0, propertySignatures); + } + function createTypeAliasForTypeExpression(typeName, typeExpression) { + const typeReference = getSynthesizedDeepClone(typeExpression.type); + if (!typeReference) return; + return factory.createTypeAliasDeclaration(/*modifiers*/ void 0, factory.createIdentifier(typeName), /*typeParameters*/ void 0, typeReference); + } + function createSignatureFromTypeLiteral(typeLiteral) { + const propertyTags = typeLiteral.jsDocPropertyTags; + if (!some(propertyTags)) return; + const getSignature = (tag)=>{ + var _a; + const name = getPropertyName(tag); + const type = (_a = tag.typeExpression) == null ? void 0 : _a.type; + const isOptional = tag.isBracketed; + let typeReference; + if (type && isJSDocTypeLiteral(type)) { + const signatures = createSignatureFromTypeLiteral(type); + typeReference = factory.createTypeLiteralNode(signatures); + } else if (type) typeReference = getSynthesizedDeepClone(type); + if (typeReference && name) { + const questionToken = isOptional ? factory.createToken(58 /* QuestionToken */ ) : void 0; + return factory.createPropertySignature(/*modifiers*/ void 0, name, questionToken, typeReference); } - } - const questionToken = optional ? factory.createToken(57 /* QuestionToken */ ) : void 0; - const asteriskToken = signatureDeclaration.asteriskToken; - if (isFunctionExpression(signatureDeclaration)) return factory.updateFunctionExpression(signatureDeclaration, modifiers, signatureDeclaration.asteriskToken, tryCast(name, isIdentifier), typeParameters, parameters, type, body != null ? body : signatureDeclaration.body); - if (isArrowFunction(signatureDeclaration)) return factory.updateArrowFunction(signatureDeclaration, modifiers, typeParameters, parameters, type, signatureDeclaration.equalsGreaterThanToken, body != null ? body : signatureDeclaration.body); - if (isMethodDeclaration(signatureDeclaration)) return factory.updateMethodDeclaration(signatureDeclaration, modifiers, asteriskToken, name != null ? name : factory.createIdentifier(""), questionToken, typeParameters, parameters, type, body); - if (isFunctionDeclaration(signatureDeclaration)) return factory.updateFunctionDeclaration(signatureDeclaration, modifiers, signatureDeclaration.asteriskToken, tryCast(name, isIdentifier), typeParameters, parameters, type, body != null ? body : signatureDeclaration.body); - return void 0; + }; + return mapDefined(propertyTags, getSignature); } - function createSignatureDeclarationFromCallExpression(kind, context, importAdder, call, name, modifierFlags, contextNode) { - const quotePreference = getQuotePreference(context.sourceFile, context.preferences); - const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions()); - const tracker = getNoopSymbolTrackerWithResolver(context); - const checker = context.program.getTypeChecker(); - const isJs = isInJSFile(contextNode); - const { typeArguments: typeArguments , arguments: args , parent: parent2 } = call; - const contextualType = isJs ? void 0 : checker.getContextualType(call); - const names = map(args, (arg)=>isIdentifier(arg) ? arg.text : isPropertyAccessExpression(arg) && isIdentifier(arg.name) ? arg.name.text : void 0); - const instanceTypes = isJs ? [] : map(args, (arg)=>checker.getTypeAtLocation(arg)); - const { argumentTypeNodes: argumentTypeNodes , argumentTypeParameters: argumentTypeParameters } = getArgumentTypesAndTypeParameters(checker, importAdder, instanceTypes, contextNode, scriptTarget, /*flags*/ void 0, tracker); - const modifiers = modifierFlags ? factory.createNodeArray(factory.createModifiersFromModifierFlags(modifierFlags)) : void 0; - const asteriskToken = isYieldExpression(parent2) ? factory.createToken(41 /* AsteriskToken */ ) : void 0; - const typeParameters = isJs ? void 0 : createTypeParametersForArguments(checker, argumentTypeParameters, typeArguments); - const parameters = createDummyParameters(args.length, names, argumentTypeNodes, /*minArgumentCount*/ void 0, isJs); - const type = isJs || contextualType === void 0 ? void 0 : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ void 0, tracker); - switch(kind){ - case 171 /* MethodDeclaration */ : - return factory.createMethodDeclaration(modifiers, asteriskToken, name, /*questionToken*/ void 0, typeParameters, parameters, type, createStubbedMethodBody(quotePreference)); - case 170 /* MethodSignature */ : - return factory.createMethodSignature(modifiers, name, /*questionToken*/ void 0, typeParameters, parameters, type === void 0 ? factory.createKeywordTypeNode(157 /* UnknownKeyword */ ) : type); - case 259 /* FunctionDeclaration */ : - return factory.createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, createStubbedBody(Diagnostics.Function_not_implemented.message, quotePreference)); - default: - Debug.fail("Unexpected kind"); - } + function getPropertyName(tag) { + return tag.name.kind === 80 /* Identifier */ ? tag.name.text : tag.name.right.text; } - function createTypeParametersForArguments(checker, argumentTypeParameters, typeArguments) { - const usedNames = new Set(argumentTypeParameters.map((pair)=>pair[0])); - const constraintsByName = new Map(argumentTypeParameters); - if (typeArguments) { - const typeArgumentsWithNewTypes = typeArguments.filter((typeArgument)=>!argumentTypeParameters.some((pair)=>{ - var _a2; - return checker.getTypeAtLocation(typeArgument) === ((_a2 = pair[1]) == null ? void 0 : _a2.argumentType); - })); - const targetSize = usedNames.size + typeArgumentsWithNewTypes.length; - for(let i = 0; usedNames.size < targetSize; i += 1)usedNames.add(createTypeParameterName(i)); - } - return arrayFrom(usedNames.values(), (usedName)=>{ - var _a2; - return factory.createTypeParameterDeclaration(/*modifiers*/ void 0, usedName, (_a2 = constraintsByName.get(usedName)) == null ? void 0 : _a2.constraint); + function getJSDocTypedefNodes(node) { + if (hasJSDocNodes(node)) return flatMap(node.jsDoc, (doc)=>{ + var _a; + return (_a = doc.tags) == null ? void 0 : _a.filter((tag)=>isJSDocTypedefTag(tag)); }); + return []; } - function createTypeParameterName(index) { - return 84 /* T */ + index <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + index) : `T${index}`; - } - function typeToAutoImportableTypeNode(checker, importAdder, type, contextNode, scriptTarget, flags, tracker) { - let typeNode = checker.typeToTypeNode(type, contextNode, flags, tracker); - if (typeNode && isImportTypeNode(typeNode)) { - const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget); - if (importableReference) { - importSymbols(importAdder, importableReference.symbols); - typeNode = importableReference.typeNode; - } + var fixId14, errorCodes15; + var init_convertTypedefToType = __esm({ + "src/services/codefixes/convertTypedefToType.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId14 = "convertTypedefToType"; + errorCodes15 = [ + Diagnostics.JSDoc_typedef_may_be_converted_to_TypeScript_type.code + ]; + registerCodeFix({ + fixIds: [ + fixId14 + ], + errorCodes: errorCodes15, + getCodeActions (context) { + const newLineCharacter = getNewLineOrDefaultFromHost(context.host, context.formatContext.options); + const node = getTokenAtPosition(context.sourceFile, context.span.start); + if (!node) return; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange12(t, node, context.sourceFile, newLineCharacter)); + if (changes.length > 0) return [ + createCodeFixAction(fixId14, changes, Diagnostics.Convert_typedef_to_TypeScript_type, fixId14, Diagnostics.Convert_all_typedef_to_TypeScript_types) + ]; + }, + getAllCodeActions: (context)=>codeFixAll(context, errorCodes15, (changes, diag2)=>{ + const newLineCharacter = getNewLineOrDefaultFromHost(context.host, context.formatContext.options); + const node = getTokenAtPosition(diag2.file, diag2.start); + const fixAll = true; + if (node) doChange12(changes, node, diag2.file, newLineCharacter, fixAll); + }) + }); } - return getSynthesizedDeepClone(typeNode); + }); + // src/services/codefixes/convertLiteralTypeToMappedType.ts + function getInfo5(sourceFile, pos) { + const token = getTokenAtPosition(sourceFile, pos); + if (isIdentifier(token)) { + const propertySignature = cast(token.parent.parent, isPropertySignature); + const propertyName = token.getText(sourceFile); + return { + container: cast(propertySignature.parent, isTypeLiteralNode), + typeNode: propertySignature.type, + constraint: propertyName, + name: propertyName === "K" ? "P" : "K" + }; + } + return void 0; } - function typeContainsTypeParameter(type) { - if (type.isUnionOrIntersection()) return type.types.some(typeContainsTypeParameter); - return type.flags & 262144 /* TypeParameter */ ; + function doChange13(changes, sourceFile, { container: container, typeNode: typeNode, constraint: constraint, name: name }) { + changes.replaceNode(sourceFile, container, factory.createMappedTypeNode(/*readonlyToken*/ void 0, factory.createTypeParameterDeclaration(/*modifiers*/ void 0, name, factory.createTypeReferenceNode(constraint)), /*nameType*/ void 0, /*questionToken*/ void 0, typeNode, /*members*/ void 0)); } - function getArgumentTypesAndTypeParameters(checker, importAdder, instanceTypes, contextNode, scriptTarget, flags, tracker) { - const argumentTypeNodes = []; - const argumentTypeParameters = /* @__PURE__ */ new Map(); - for(let i = 0; i < instanceTypes.length; i += 1){ - const instanceType = instanceTypes[i]; - if (instanceType.isUnionOrIntersection() && instanceType.types.some(typeContainsTypeParameter)) { - const synthesizedTypeParameterName = createTypeParameterName(i); - argumentTypeNodes.push(factory.createTypeReferenceNode(synthesizedTypeParameterName)); - argumentTypeParameters.set(synthesizedTypeParameterName, void 0); - continue; - } - const widenedInstanceType = checker.getBaseTypeOfLiteralType(instanceType); - const argumentTypeNode = typeToAutoImportableTypeNode(checker, importAdder, widenedInstanceType, contextNode, scriptTarget, flags, tracker); - if (!argumentTypeNode) continue; - argumentTypeNodes.push(argumentTypeNode); - const argumentTypeParameter = getFirstTypeParameterName(instanceType); - const instanceTypeConstraint = instanceType.isTypeParameter() && instanceType.constraint && !isAnonymousObjectConstraintType(instanceType.constraint) ? typeToAutoImportableTypeNode(checker, importAdder, instanceType.constraint, contextNode, scriptTarget, flags, tracker) : void 0; - if (argumentTypeParameter) argumentTypeParameters.set(argumentTypeParameter, { - argumentType: instanceType, - constraint: instanceTypeConstraint + var fixId15, errorCodes16; + var init_convertLiteralTypeToMappedType = __esm({ + "src/services/codefixes/convertLiteralTypeToMappedType.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId15 = "convertLiteralTypeToMappedType"; + errorCodes16 = [ + Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0.code + ]; + registerCodeFix({ + errorCodes: errorCodes16, + getCodeActions: function getCodeActionsToConvertLiteralTypeToMappedType(context) { + const { sourceFile: sourceFile, span: span } = context; + const info = getInfo5(sourceFile, span.start); + if (!info) return void 0; + const { name: name, constraint: constraint } = info; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange13(t, sourceFile, info)); + return [ + createCodeFixAction(fixId15, changes, [ + Diagnostics.Convert_0_to_1_in_0, + constraint, + name + ], fixId15, Diagnostics.Convert_all_type_literals_to_mapped_type) + ]; + }, + fixIds: [ + fixId15 + ], + getAllCodeActions: (context)=>codeFixAll(context, errorCodes16, (changes, diag2)=>{ + const info = getInfo5(diag2.file, diag2.start); + if (info) doChange13(changes, diag2.file, info); + }) }); } - return { - argumentTypeNodes: argumentTypeNodes, - argumentTypeParameters: arrayFrom(argumentTypeParameters.entries()) - }; + }); + // src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts + function getClass(sourceFile, pos) { + return Debug.checkDefined(getContainingClass(getTokenAtPosition(sourceFile, pos)), "There should be a containing class"); } - function isAnonymousObjectConstraintType(type) { - return type.flags & 524288 /* Object */ && type.objectFlags === 16 /* Anonymous */ ; + function symbolPointsToNonPrivateMember(symbol) { + return !symbol.valueDeclaration || !(getEffectiveModifierFlags(symbol.valueDeclaration) & 8 /* Private */ ); } - function getFirstTypeParameterName(type) { - var _a2; - if (type.flags & 3145728 /* Intersection */ ) for (const subType of type.types){ - const subTypeName = getFirstTypeParameterName(subType); - if (subTypeName) return subTypeName; + function addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) { + const checker = context.program.getTypeChecker(); + const maybeHeritageClauseSymbol = getHeritageClauseSymbolTable(classDeclaration, checker); + const implementedType = checker.getTypeAtLocation(implementedTypeNode); + const implementedTypeSymbols = checker.getPropertiesOfType(implementedType); + const nonPrivateAndNotExistedInHeritageClauseMembers = implementedTypeSymbols.filter(and(symbolPointsToNonPrivateMember, (symbol)=>!maybeHeritageClauseSymbol.has(symbol.escapedName))); + const classType = checker.getTypeAtLocation(classDeclaration); + const constructor = find(classDeclaration.members, (m)=>isConstructorDeclaration(m)); + if (!classType.getNumberIndexType()) createMissingIndexSignatureDeclaration(implementedType, 1 /* Number */ ); + if (!classType.getStringIndexType()) createMissingIndexSignatureDeclaration(implementedType, 0 /* String */ ); + const importAdder = createImportAdder(sourceFile, context.program, preferences, context.host); + createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, sourceFile, context, preferences, importAdder, (member)=>insertInterfaceMemberNode(sourceFile, classDeclaration, member)); + importAdder.writeFixes(changeTracker); + function createMissingIndexSignatureDeclaration(type, kind) { + const indexInfoOfKind = checker.getIndexInfoOfType(type, kind); + if (indexInfoOfKind) insertInterfaceMemberNode(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, classDeclaration, /*flags*/ void 0, getNoopSymbolTrackerWithResolver(context))); + } + function insertInterfaceMemberNode(sourceFile2, cls, newElement) { + if (constructor) changeTracker.insertNodeAfter(sourceFile2, constructor, newElement); + else changeTracker.insertMemberAtStart(sourceFile2, cls, newElement); } - return type.flags & 262144 /* TypeParameter */ ? (_a2 = type.getSymbol()) == null ? void 0 : _a2.getName() : void 0; } - function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { - const parameters = []; - const parameterNameCounts = /* @__PURE__ */ new Map(); - for(let i = 0; i < argCount; i++){ - const parameterName = (names == null ? void 0 : names[i]) || `arg${i}`; - const parameterNameCount = parameterNameCounts.get(parameterName); - parameterNameCounts.set(parameterName, (parameterNameCount || 0) + 1); - const newParameter = factory.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, /*name*/ parameterName + (parameterNameCount || ""), /*questionToken*/ minArgumentCount !== void 0 && i >= minArgumentCount ? factory.createToken(57 /* QuestionToken */ ) : void 0, /*type*/ inJs ? void 0 : (types == null ? void 0 : types[i]) || factory.createKeywordTypeNode(157 /* UnknownKeyword */ ), /*initializer*/ void 0); - parameters.push(newParameter); + function getHeritageClauseSymbolTable(classDeclaration, checker) { + const heritageClauseNode = getEffectiveBaseTypeNode(classDeclaration); + if (!heritageClauseNode) return createSymbolTable(); + const heritageClauseType = checker.getTypeAtLocation(heritageClauseNode); + const heritageClauseTypeSymbols = checker.getPropertiesOfType(heritageClauseType); + return createSymbolTable(heritageClauseTypeSymbols.filter(symbolPointsToNonPrivateMember)); + } + var errorCodes17, fixId16; + var init_fixClassIncorrectlyImplementsInterface = __esm({ + "src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + errorCodes17 = [ + Diagnostics.Class_0_incorrectly_implements_interface_1.code, + Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code + ]; + fixId16 = "fixClassIncorrectlyImplementsInterface"; + registerCodeFix({ + errorCodes: errorCodes17, + getCodeActions (context) { + const { sourceFile: sourceFile, span: span } = context; + const classDeclaration = getClass(sourceFile, span.start); + return mapDefined(getEffectiveImplementsTypeNodes(classDeclaration), (implementedTypeNode)=>{ + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences)); + return changes.length === 0 ? void 0 : createCodeFixAction(fixId16, changes, [ + Diagnostics.Implement_interface_0, + implementedTypeNode.getText(sourceFile) + ], fixId16, Diagnostics.Implement_all_unimplemented_interfaces); + }); + }, + fixIds: [ + fixId16 + ], + getAllCodeActions (context) { + const seenClassDeclarations = /* @__PURE__ */ new Map(); + return codeFixAll(context, errorCodes17, (changes, diag2)=>{ + const classDeclaration = getClass(diag2.file, diag2.start); + if (addToSeen(seenClassDeclarations, getNodeId(classDeclaration))) for (const implementedTypeNode of getEffectiveImplementsTypeNodes(classDeclaration))addMissingDeclarations(context, implementedTypeNode, diag2.file, classDeclaration, changes, context.preferences); + }); + } + }); } - return parameters; + }); + // src/services/codefixes/importFixes.ts + function createImportAdder(sourceFile, program, preferences, host, cancellationToken) { + return createImportAdderWorker(sourceFile, program, /*useAutoImportProvider*/ false, preferences, host, cancellationToken); } - function createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference, body) { - let maxArgsSignature = signatures[0]; - let minArgumentCount = signatures[0].minArgumentCount; - let someSigHasRestParameter = false; - for (const sig of signatures){ - minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); - if (signatureHasRestParameter(sig)) someSigHasRestParameter = true; - if (sig.parameters.length >= maxArgsSignature.parameters.length && (!signatureHasRestParameter(sig) || signatureHasRestParameter(maxArgsSignature))) maxArgsSignature = sig; + function createImportAdderWorker(sourceFile, program, useAutoImportProvider, preferences, host, cancellationToken) { + const compilerOptions = program.getCompilerOptions(); + const addToNamespace = []; + const importType = []; + const addToExisting = /* @__PURE__ */ new Map(); + const newImports = /* @__PURE__ */ new Map(); + return { + addImportFromDiagnostic: addImportFromDiagnostic, + addImportFromExportedSymbol: addImportFromExportedSymbol, + writeFixes: writeFixes, + hasFixes: hasFixes + }; + function addImportFromDiagnostic(diagnostic, context) { + const info = getFixInfos(context, diagnostic.code, diagnostic.start, useAutoImportProvider); + if (!info || !info.length) return; + addImport(first(info)); } - const maxNonRestArgs = maxArgsSignature.parameters.length - (signatureHasRestParameter(maxArgsSignature) ? 1 : 0); - const maxArgsParameterSymbolNames = maxArgsSignature.parameters.map((symbol)=>symbol.name); - const parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ void 0, minArgumentCount, /*inJs*/ false); - if (someSigHasRestParameter) { - const restParameter = factory.createParameterDeclaration(/*modifiers*/ void 0, factory.createToken(25 /* DotDotDotToken */ ), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", /*questionToken*/ maxNonRestArgs >= minArgumentCount ? factory.createToken(57 /* QuestionToken */ ) : void 0, factory.createArrayTypeNode(factory.createKeywordTypeNode(157 /* UnknownKeyword */ )), /*initializer*/ void 0); - parameters.push(restParameter); + function addImportFromExportedSymbol(exportedSymbol, isValidTypeOnlyUseSite) { + const moduleSymbol = Debug.checkDefined(exportedSymbol.parent); + const symbolName2 = getNameForExportedSymbol(exportedSymbol, getEmitScriptTarget(compilerOptions)); + const checker = program.getTypeChecker(); + const symbol = checker.getMergedSymbol(skipAlias(exportedSymbol, checker)); + const exportInfo = getAllExportInfoForSymbol(sourceFile, symbol, symbolName2, moduleSymbol, /*preferCapitalized*/ false, program, host, preferences, cancellationToken); + const useRequire = shouldUseRequire(sourceFile, program); + const fix = getImportFixForSymbol(sourceFile, Debug.checkDefined(exportInfo), program, /*position*/ void 0, !!isValidTypeOnlyUseSite, useRequire, host, preferences); + if (fix) addImport({ + fix: fix, + symbolName: symbolName2, + errorIdentifierText: void 0 + }); } - return createStubbedMethod(modifiers, name, optional, /*typeParameters*/ void 0, parameters, getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration), quotePreference, body); - } - function getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration) { - if (length(signatures)) { - const type = checker.getUnionType(map(signatures, checker.getReturnTypeOfSignature)); - return checker.typeToTypeNode(type, enclosingDeclaration, 1 /* NoTruncation */ , getNoopSymbolTrackerWithResolver(context)); + function addImport(info) { + var _a, _b; + const { fix: fix, symbolName: symbolName2 } = info; + switch(fix.kind){ + case 0 /* UseNamespace */ : + addToNamespace.push(fix); + break; + case 1 /* JsdocTypeImport */ : + importType.push(fix); + break; + case 2 /* AddToExisting */ : + { + const { importClauseOrBindingPattern: importClauseOrBindingPattern, importKind: importKind, addAsTypeOnly: addAsTypeOnly } = fix; + const key = String(getNodeId(importClauseOrBindingPattern)); + let entry = addToExisting.get(key); + if (!entry) addToExisting.set(key, entry = { + importClauseOrBindingPattern: importClauseOrBindingPattern, + defaultImport: void 0, + namedImports: /* @__PURE__ */ new Map() + }); + if (importKind === 0 /* Named */ ) { + const prevValue = entry == null ? void 0 : entry.namedImports.get(symbolName2); + entry.namedImports.set(symbolName2, reduceAddAsTypeOnlyValues(prevValue, addAsTypeOnly)); + } else { + Debug.assert(entry.defaultImport === void 0 || entry.defaultImport.name === symbolName2, "(Add to Existing) Default import should be missing or match symbolName"); + entry.defaultImport = { + name: symbolName2, + addAsTypeOnly: reduceAddAsTypeOnlyValues((_a = entry.defaultImport) == null ? void 0 : _a.addAsTypeOnly, addAsTypeOnly) + }; + } + break; + } + case 3 /* AddNew */ : + { + const { moduleSpecifier: moduleSpecifier, importKind: importKind, useRequire: useRequire, addAsTypeOnly: addAsTypeOnly } = fix; + const entry = getNewImportEntry(moduleSpecifier, importKind, useRequire, addAsTypeOnly); + Debug.assert(entry.useRequire === useRequire, "(Add new) Tried to add an `import` and a `require` for the same module"); + switch(importKind){ + case 1 /* Default */ : + Debug.assert(entry.defaultImport === void 0 || entry.defaultImport.name === symbolName2, "(Add new) Default import should be missing or match symbolName"); + entry.defaultImport = { + name: symbolName2, + addAsTypeOnly: reduceAddAsTypeOnlyValues((_b = entry.defaultImport) == null ? void 0 : _b.addAsTypeOnly, addAsTypeOnly) + }; + break; + case 0 /* Named */ : + const prevValue = (entry.namedImports || (entry.namedImports = /* @__PURE__ */ new Map())).get(symbolName2); + entry.namedImports.set(symbolName2, reduceAddAsTypeOnlyValues(prevValue, addAsTypeOnly)); + break; + case 3 /* CommonJS */ : + case 2 /* Namespace */ : + Debug.assert(entry.namespaceLikeImport === void 0 || entry.namespaceLikeImport.name === symbolName2, "Namespacelike import shoudl be missing or match symbolName"); + entry.namespaceLikeImport = { + importKind: importKind, + name: symbolName2, + addAsTypeOnly: addAsTypeOnly + }; + break; + } + break; + } + case 4 /* PromoteTypeOnly */ : + break; + default: + Debug.assertNever(fix, `fix wasn't never - got kind ${fix.kind}`); + } + function reduceAddAsTypeOnlyValues(prevValue, newValue) { + return Math.max(prevValue ?? 0, newValue); + } + function getNewImportEntry(moduleSpecifier, importKind, useRequire, addAsTypeOnly) { + const typeOnlyKey = newImportsKey(moduleSpecifier, /*topLevelTypeOnly*/ true); + const nonTypeOnlyKey = newImportsKey(moduleSpecifier, /*topLevelTypeOnly*/ false); + const typeOnlyEntry = newImports.get(typeOnlyKey); + const nonTypeOnlyEntry = newImports.get(nonTypeOnlyKey); + const newEntry = { + defaultImport: void 0, + namedImports: void 0, + namespaceLikeImport: void 0, + useRequire: useRequire + }; + if (importKind === 1 /* Default */ && addAsTypeOnly === 2 /* Required */ ) { + if (typeOnlyEntry) return typeOnlyEntry; + newImports.set(typeOnlyKey, newEntry); + return newEntry; + } + if (addAsTypeOnly === 1 /* Allowed */ && (typeOnlyEntry || nonTypeOnlyEntry)) return typeOnlyEntry || nonTypeOnlyEntry; + if (nonTypeOnlyEntry) return nonTypeOnlyEntry; + newImports.set(nonTypeOnlyKey, newEntry); + return newEntry; + } + function newImportsKey(moduleSpecifier, topLevelTypeOnly) { + return `${topLevelTypeOnly ? 1 : 0}|${moduleSpecifier}`; + } } - } - function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference, body) { - return factory.createMethodDeclaration(modifiers, /*asteriskToken*/ void 0, name, optional ? factory.createToken(57 /* QuestionToken */ ) : void 0, typeParameters, parameters, returnType, body || createStubbedMethodBody(quotePreference)); - } - function createStubbedMethodBody(quotePreference) { - return createStubbedBody(Diagnostics.Method_not_implemented.message, quotePreference); - } - function createStubbedBody(text, quotePreference) { - return factory.createBlock([ - factory.createThrowStatement(factory.createNewExpression(factory.createIdentifier("Error"), /*typeArguments*/ void 0, // TODO Handle auto quote preference. - [ - factory.createStringLiteral(text, /*isSingleQuote*/ quotePreference === 0 /* Single */ ) - ])) - ], /*multiline*/ true); - } - function setJsonCompilerOptionValues(changeTracker, configFile, options) { - const tsconfigObjectLiteral = getTsConfigObjectLiteralExpression(configFile); - if (!tsconfigObjectLiteral) return void 0; - const compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions"); - if (compilerOptionsProperty === void 0) { - changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", factory.createObjectLiteralExpression(options.map(([optionName, optionValue])=>createJsonPropertyAssignment(optionName, optionValue)), /*multiLine*/ true))); - return; + function writeFixes(changeTracker, oldFileQuotePreference) { + let quotePreference; + if (sourceFile.imports.length === 0 && oldFileQuotePreference !== void 0) quotePreference = oldFileQuotePreference; + else quotePreference = getQuotePreference(sourceFile, preferences); + for (const fix of addToNamespace)addNamespaceQualifier(changeTracker, sourceFile, fix); + for (const fix of importType)addImportType(changeTracker, sourceFile, fix, quotePreference); + addToExisting.forEach(({ importClauseOrBindingPattern: importClauseOrBindingPattern, defaultImport: defaultImport, namedImports: namedImports })=>{ + doAddExistingFix(changeTracker, sourceFile, importClauseOrBindingPattern, defaultImport, arrayFrom(namedImports.entries(), ([name, addAsTypeOnly])=>({ + addAsTypeOnly: addAsTypeOnly, + name: name + })), preferences); + }); + let newDeclarations; + newImports.forEach(({ useRequire: useRequire, defaultImport: defaultImport, namedImports: namedImports, namespaceLikeImport: namespaceLikeImport }, key)=>{ + const moduleSpecifier = key.slice(2); + const getDeclarations = useRequire ? getNewRequires : getNewImports; + const declarations = getDeclarations(moduleSpecifier, quotePreference, defaultImport, namedImports && arrayFrom(namedImports.entries(), ([name, addAsTypeOnly])=>({ + addAsTypeOnly: addAsTypeOnly, + name: name + })), namespaceLikeImport, compilerOptions); + newDeclarations = combine(newDeclarations, declarations); + }); + if (newDeclarations) insertImports(changeTracker, sourceFile, newDeclarations, /*blankLineBetween*/ true, preferences); } - const compilerOptions = compilerOptionsProperty.initializer; - if (!isObjectLiteralExpression(compilerOptions)) return; - for (const [optionName, optionValue] of options){ - const optionProperty = findJsonProperty(compilerOptions, optionName); - if (optionProperty === void 0) changeTracker.insertNodeAtObjectStart(configFile, compilerOptions, createJsonPropertyAssignment(optionName, optionValue)); - else changeTracker.replaceNode(configFile, optionProperty.initializer, optionValue); + function hasFixes() { + return addToNamespace.length > 0 || importType.length > 0 || addToExisting.size > 0 || newImports.size > 0; } } - function setJsonCompilerOptionValue(changeTracker, configFile, optionName, optionValue) { - setJsonCompilerOptionValues(changeTracker, configFile, [ - [ - optionName, - optionValue - ] - ]); + function createImportSpecifierResolver(importingFile, program, host, preferences) { + const packageJsonImportFilter = createPackageJsonImportFilter(importingFile, preferences, host); + const importMap = createExistingImportMap(program.getTypeChecker(), importingFile, program.getCompilerOptions()); + return { + getModuleSpecifierForBestExportInfo: getModuleSpecifierForBestExportInfo + }; + function getModuleSpecifierForBestExportInfo(exportInfo, position, isValidTypeOnlyUseSite, fromCacheOnly) { + const { fixes: fixes, computedWithoutCacheCount: computedWithoutCacheCount } = getImportFixes(exportInfo, position, isValidTypeOnlyUseSite, /*useRequire*/ false, program, importingFile, host, preferences, importMap, fromCacheOnly); + const result = getBestFix(fixes, importingFile, program, packageJsonImportFilter, host); + return result && { + ...result, + computedWithoutCacheCount: computedWithoutCacheCount + }; + } } - function createJsonPropertyAssignment(name, initializer) { - return factory.createPropertyAssignment(factory.createStringLiteral(name), initializer); + function getImportCompletionAction(targetSymbol, moduleSymbol, exportMapKey, sourceFile, symbolName2, isJsxTagName, host, program, formatContext, position, preferences, cancellationToken) { + const compilerOptions = program.getCompilerOptions(); + let exportInfos; + if (exportMapKey) { + exportInfos = getExportInfoMap(sourceFile, host, program, preferences, cancellationToken).get(sourceFile.path, exportMapKey); + Debug.assertIsDefined(exportInfos, "Some exportInfo should match the specified exportMapKey"); + } else { + exportInfos = pathIsBareSpecifier(stripQuotes(moduleSymbol.name)) ? [ + getSingleExportInfoForSymbol(targetSymbol, symbolName2, moduleSymbol, program, host) + ] : getAllExportInfoForSymbol(sourceFile, targetSymbol, symbolName2, moduleSymbol, isJsxTagName, program, host, preferences, cancellationToken); + Debug.assertIsDefined(exportInfos, "Some exportInfo should match the specified symbol / moduleSymbol"); + } + const useRequire = shouldUseRequire(sourceFile, program); + const isValidTypeOnlyUseSite = isValidTypeOnlyAliasUseSite(getTokenAtPosition(sourceFile, position)); + const fix = Debug.checkDefined(getImportFixForSymbol(sourceFile, exportInfos, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences)); + return { + moduleSpecifier: fix.moduleSpecifier, + codeAction: codeFixActionToCodeAction(codeActionForFix({ + host: host, + formatContext: formatContext, + preferences: preferences + }, sourceFile, symbolName2, fix, /*includeSymbolNameInDescription*/ false, compilerOptions, preferences)) + }; } - function findJsonProperty(obj, name) { - return find(obj.properties, (p)=>isPropertyAssignment(p) && !!p.name && isStringLiteral(p.name) && p.name.text === name); + function getPromoteTypeOnlyCompletionAction(sourceFile, symbolToken, program, host, formatContext, preferences) { + const compilerOptions = program.getCompilerOptions(); + const symbolName2 = single(getSymbolNamesToImport(sourceFile, program.getTypeChecker(), symbolToken, compilerOptions)); + const fix = getTypeOnlyPromotionFix(sourceFile, symbolToken, symbolName2, program); + const includeSymbolNameInDescription = symbolName2 !== symbolToken.text; + return fix && codeFixActionToCodeAction(codeActionForFix({ + host: host, + formatContext: formatContext, + preferences: preferences + }, sourceFile, symbolName2, fix, includeSymbolNameInDescription, compilerOptions, preferences)); } - function tryGetAutoImportableReferenceFromTypeNode(importTypeNode, scriptTarget) { - let symbols; - const typeNode = visitNode(importTypeNode, visit, isTypeNode); - if (symbols && typeNode) return { - typeNode: typeNode, - symbols: symbols - }; - function visit(node) { - if (isLiteralImportTypeNode(node) && node.qualifier) { - const firstIdentifier = getFirstIdentifier(node.qualifier); - const name = getNameForExportedSymbol(firstIdentifier.symbol, scriptTarget); - const qualifier = name !== firstIdentifier.text ? replaceFirstIdentifierOfEntityName(node.qualifier, factory.createIdentifier(name)) : node.qualifier; - symbols = append(symbols, firstIdentifier.symbol); - const typeArguments = visitNodes2(node.typeArguments, visit, isTypeNode); - return factory.createTypeReferenceNode(qualifier, typeArguments); - } - return visitEachChild(node, visit, nullTransformationContext); - } + function getImportFixForSymbol(sourceFile, exportInfos, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences) { + const packageJsonImportFilter = createPackageJsonImportFilter(sourceFile, preferences, host); + return getBestFix(getImportFixes(exportInfos, position, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences).fixes, sourceFile, program, packageJsonImportFilter, host); } - function replaceFirstIdentifierOfEntityName(name, newIdentifier) { - if (name.kind === 79 /* Identifier */ ) return newIdentifier; - return factory.createQualifiedName(replaceFirstIdentifierOfEntityName(name.left, newIdentifier), name.right); + function codeFixActionToCodeAction({ description: description3, changes: changes, commands: commands }) { + return { + description: description3, + changes: changes, + commands: commands + }; } - function importSymbols(importAdder, symbols) { - symbols.forEach((s)=>importAdder.addImportFromExportedSymbol(s, /*isValidTypeOnlyUseSite*/ true)); + function getAllExportInfoForSymbol(importingFile, symbol, symbolName2, moduleSymbol, preferCapitalized, program, host, preferences, cancellationToken) { + const getChecker = createGetChecker(program, host); + return getExportInfoMap(importingFile, host, program, preferences, cancellationToken).search(importingFile.path, preferCapitalized, (name)=>name === symbolName2, (info)=>{ + if (skipAlias(info[0].symbol, getChecker(info[0].isFromPackageJson)) === symbol && info.some((i)=>i.moduleSymbol === moduleSymbol || i.symbol.parent === moduleSymbol)) return info; + }); } - function findAncestorMatchingSpan(sourceFile, span) { - const end = textSpanEnd(span); - let token = getTokenAtPosition(sourceFile, span.start); - while(token.end < end)token = token.parent; - return token; + function getSingleExportInfoForSymbol(symbol, symbolName2, moduleSymbol, program, host) { + var _a, _b; + const compilerOptions = program.getCompilerOptions(); + const mainProgramInfo = getInfoWithChecker(program.getTypeChecker(), /*isFromPackageJson*/ false); + if (mainProgramInfo) return mainProgramInfo; + const autoImportProvider = (_b = (_a = host.getPackageJsonAutoImportProvider) == null ? void 0 : _a.call(host)) == null ? void 0 : _b.getTypeChecker(); + return Debug.checkDefined(autoImportProvider && getInfoWithChecker(autoImportProvider, /*isFromPackageJson*/ true), `Could not find symbol in specified module for code actions`); + function getInfoWithChecker(checker, isFromPackageJson) { + const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && skipAlias(defaultInfo.symbol, checker) === symbol) return { + symbol: defaultInfo.symbol, + moduleSymbol: moduleSymbol, + moduleFileName: void 0, + exportKind: defaultInfo.exportKind, + targetFlags: skipAlias(symbol, checker).flags, + isFromPackageJson: isFromPackageJson + }; + const named = checker.tryGetMemberInModuleExportsAndProperties(symbolName2, moduleSymbol); + if (named && skipAlias(named, checker) === symbol) return { + symbol: named, + moduleSymbol: moduleSymbol, + moduleFileName: void 0, + exportKind: 0 /* Named */ , + targetFlags: skipAlias(symbol, checker).flags, + isFromPackageJson: isFromPackageJson + }; + } } - var PreserveOptionalFlags; - var init_helpers = __esm({ - "src/services/codefixes/helpers.ts" () { - "use strict"; - init_ts4(); - PreserveOptionalFlags = /* @__PURE__ */ ((PreserveOptionalFlags2)=>{ - PreserveOptionalFlags2[PreserveOptionalFlags2["Method"] = 1] = "Method"; - PreserveOptionalFlags2[PreserveOptionalFlags2["Property"] = 2] = "Property"; - PreserveOptionalFlags2[PreserveOptionalFlags2["All"] = 3] = "All"; - return PreserveOptionalFlags2; - })(PreserveOptionalFlags || {}); - } - }); - // src/services/codefixes/generateAccessors.ts - function generateAccessorFromProperty(file, program, start, end, context, _actionName) { - const fieldInfo = getAccessorConvertiblePropertyAtPosition(file, program, start, end); - if (!fieldInfo || ts_refactor_exports.isRefactorErrorInfo(fieldInfo)) return void 0; - const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context); - const { isStatic: isStatic2 , isReadonly: isReadonly , fieldName: fieldName , accessorName: accessorName , originalName: originalName , type: type , container: container , declaration: declaration } = fieldInfo; - suppressLeadingAndTrailingTrivia(fieldName); - suppressLeadingAndTrailingTrivia(accessorName); - suppressLeadingAndTrailingTrivia(declaration); - suppressLeadingAndTrailingTrivia(container); - let accessorModifiers; - let fieldModifiers; - if (isClassLike(container)) { - const modifierFlags = getEffectiveModifierFlags(declaration); - if (isSourceFileJS(file)) { - const modifiers = factory.createModifiersFromModifierFlags(modifierFlags); - accessorModifiers = modifiers; - fieldModifiers = modifiers; - } else { - accessorModifiers = factory.createModifiersFromModifierFlags(prepareModifierFlagsForAccessor(modifierFlags)); - fieldModifiers = factory.createModifiersFromModifierFlags(prepareModifierFlagsForField(modifierFlags)); - } - if (canHaveDecorators(declaration)) fieldModifiers = concatenate(getDecorators(declaration), fieldModifiers); - } - updateFieldDeclaration(changeTracker, file, declaration, type, fieldName, fieldModifiers); - const getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic2, container); - suppressLeadingAndTrailingTrivia(getAccessor); - insertAccessor(changeTracker, file, getAccessor, declaration, container); - if (isReadonly) { - const constructor = getFirstConstructorWithBody(container); - if (constructor) updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName.text, originalName); - } else { - const setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic2, container); - suppressLeadingAndTrailingTrivia(setAccessor); - insertAccessor(changeTracker, file, setAccessor, declaration, container); - } - return changeTracker.getChanges(); + function getImportFixes(exportInfos, usagePosition, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences, importMap = createExistingImportMap(program.getTypeChecker(), sourceFile, program.getCompilerOptions()), fromCacheOnly) { + const checker = program.getTypeChecker(); + const existingImports = flatMap(exportInfos, importMap.getImportsForExportInfo); + const useNamespace = usagePosition !== void 0 && tryUseExistingNamespaceImport(existingImports, usagePosition); + const addToExisting = tryAddToExistingImport(existingImports, isValidTypeOnlyUseSite, checker, program.getCompilerOptions()); + if (addToExisting) return { + computedWithoutCacheCount: 0, + fixes: [ + ...useNamespace ? [ + useNamespace + ] : emptyArray, + addToExisting + ] + }; + const { fixes: fixes, computedWithoutCacheCount: computedWithoutCacheCount = 0 } = getFixesForAddImport(exportInfos, existingImports, program, sourceFile, usagePosition, isValidTypeOnlyUseSite, useRequire, host, preferences, fromCacheOnly); + return { + computedWithoutCacheCount: computedWithoutCacheCount, + fixes: [ + ...useNamespace ? [ + useNamespace + ] : emptyArray, + ...fixes + ] + }; } - function isConvertibleName(name) { - return isIdentifier(name) || isStringLiteral(name); + function tryUseExistingNamespaceImport(existingImports, position) { + return firstDefined(existingImports, ({ declaration: declaration, importKind: importKind })=>{ + var _a; + if (importKind !== 0 /* Named */ ) return void 0; + const namespacePrefix = getNamespaceLikeImportText(declaration); + const moduleSpecifier = namespacePrefix && ((_a = tryGetModuleSpecifierFromDeclaration(declaration)) == null ? void 0 : _a.text); + if (moduleSpecifier) return { + kind: 0 /* UseNamespace */ , + namespacePrefix: namespacePrefix, + usagePosition: position, + moduleSpecifier: moduleSpecifier + }; + }); } - function isAcceptedDeclaration(node) { - return isParameterPropertyDeclaration(node, node.parent) || isPropertyDeclaration(node) || isPropertyAssignment(node); + function getNamespaceLikeImportText(declaration) { + var _a, _b, _c; + switch(declaration.kind){ + case 260 /* VariableDeclaration */ : + return (_a = tryCast(declaration.name, isIdentifier)) == null ? void 0 : _a.text; + case 271 /* ImportEqualsDeclaration */ : + return declaration.name.text; + case 272 /* ImportDeclaration */ : + return (_c = tryCast((_b = declaration.importClause) == null ? void 0 : _b.namedBindings, isNamespaceImport)) == null ? void 0 : _c.name.text; + default: + return Debug.assertNever(declaration); + } } - function createPropertyName(name, originalName) { - return isIdentifier(originalName) ? factory.createIdentifier(name) : factory.createStringLiteral(name); + function getAddAsTypeOnly(isValidTypeOnlyUseSite, isForNewImportDeclaration, symbol, targetFlags, checker, compilerOptions) { + if (!isValidTypeOnlyUseSite) return 4 /* NotAllowed */ ; + if (isForNewImportDeclaration && compilerOptions.importsNotUsedAsValues === 2 /* Error */ ) return 2 /* Required */ ; + if (importNameElisionDisabled(compilerOptions) && (!(targetFlags & 111551 /* Value */ ) || !!checker.getTypeOnlyAliasDeclaration(symbol))) return 2 /* Required */ ; + return 1 /* Allowed */ ; } - function createAccessorAccessExpression(fieldName, isStatic2, container) { - const leftHead = isStatic2 ? container.name : factory.createThis(); - return isIdentifier(fieldName) ? factory.createPropertyAccessExpression(leftHead, fieldName) : factory.createElementAccessExpression(leftHead, factory.createStringLiteralFromNode(fieldName)); + function tryAddToExistingImport(existingImports, isValidTypeOnlyUseSite, checker, compilerOptions) { + let best; + for (const existingImport of existingImports){ + const fix = getAddToExistingImportFix(existingImport); + if (!fix) continue; + const isTypeOnly = isTypeOnlyImportDeclaration(fix.importClauseOrBindingPattern); + if (fix.addAsTypeOnly !== 4 /* NotAllowed */ && isTypeOnly || fix.addAsTypeOnly === 4 /* NotAllowed */ && !isTypeOnly) return fix; + best ?? (best = fix); + } + return best; + function getAddToExistingImportFix({ declaration: declaration, importKind: importKind, symbol: symbol, targetFlags: targetFlags }) { + if (importKind === 3 /* CommonJS */ || importKind === 2 /* Namespace */ || declaration.kind === 271 /* ImportEqualsDeclaration */ ) return void 0; + if (declaration.kind === 260 /* VariableDeclaration */ ) return (importKind === 0 /* Named */ || importKind === 1 /* Default */ ) && declaration.name.kind === 206 /* ObjectBindingPattern */ ? { + kind: 2 /* AddToExisting */ , + importClauseOrBindingPattern: declaration.name, + importKind: importKind, + moduleSpecifier: declaration.initializer.arguments[0].text, + addAsTypeOnly: 4 /* NotAllowed */ + } : void 0; + const { importClause: importClause } = declaration; + if (!importClause || !isStringLiteralLike(declaration.moduleSpecifier)) return void 0; + const { name: name, namedBindings: namedBindings } = importClause; + if (importClause.isTypeOnly && !(importKind === 0 /* Named */ && namedBindings)) return void 0; + const addAsTypeOnly = getAddAsTypeOnly(isValidTypeOnlyUseSite, /*isForNewImportDeclaration*/ false, symbol, targetFlags, checker, compilerOptions); + if (importKind === 1 /* Default */ && (name || // Cannot add a default import to a declaration that already has one + addAsTypeOnly === 2 /* Required */ && namedBindings)) return void 0; + if (importKind === 0 /* Named */ && (namedBindings == null ? void 0 : namedBindings.kind) === 274 /* NamespaceImport */ ) return void 0; + return { + kind: 2 /* AddToExisting */ , + importClauseOrBindingPattern: importClause, + importKind: importKind, + moduleSpecifier: declaration.moduleSpecifier.text, + addAsTypeOnly: addAsTypeOnly + }; + } } - function prepareModifierFlagsForAccessor(modifierFlags) { - modifierFlags &= -65 /* Readonly */ ; - modifierFlags &= -9 /* Private */ ; - if (!(modifierFlags & 16 /* Protected */ )) modifierFlags |= 4 /* Public */ ; - return modifierFlags; + function createExistingImportMap(checker, importingFile, compilerOptions) { + let importMap; + for (const moduleSpecifier of importingFile.imports){ + const i = importFromModuleSpecifier(moduleSpecifier); + if (isVariableDeclarationInitializedToRequire(i.parent)) { + const moduleSymbol = checker.resolveExternalModuleName(moduleSpecifier); + if (moduleSymbol) (importMap || (importMap = createMultiMap())).add(getSymbolId(moduleSymbol), i.parent); + } else if (i.kind === 272 /* ImportDeclaration */ || i.kind === 271 /* ImportEqualsDeclaration */ ) { + const moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol) (importMap || (importMap = createMultiMap())).add(getSymbolId(moduleSymbol), i); + } + } + return { + getImportsForExportInfo: ({ moduleSymbol: moduleSymbol, exportKind: exportKind, targetFlags: targetFlags, symbol: symbol })=>{ + if (!(targetFlags & 111551 /* Value */ ) && isSourceFileJS(importingFile)) return emptyArray; + const matchingDeclarations = importMap == null ? void 0 : importMap.get(getSymbolId(moduleSymbol)); + if (!matchingDeclarations) return emptyArray; + const importKind = getImportKind(importingFile, exportKind, compilerOptions); + return matchingDeclarations.map((declaration)=>({ + declaration: declaration, + importKind: importKind, + symbol: symbol, + targetFlags: targetFlags + })); + } + }; } - function prepareModifierFlagsForField(modifierFlags) { - modifierFlags &= -5 /* Public */ ; - modifierFlags &= -17 /* Protected */ ; - modifierFlags |= 8 /* Private */ ; - return modifierFlags; + function shouldUseRequire(sourceFile, program) { + if (!isSourceFileJS(sourceFile)) return false; + if (sourceFile.commonJsModuleIndicator && !sourceFile.externalModuleIndicator) return true; + if (sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) return false; + const compilerOptions = program.getCompilerOptions(); + if (compilerOptions.configFile) return getEmitModuleKind(compilerOptions) < 5 /* ES2015 */ ; + if (sourceFile.impliedNodeFormat === 1 /* CommonJS */ ) return true; + if (sourceFile.impliedNodeFormat === 99 /* ESNext */ ) return false; + for (const otherFile of program.getSourceFiles()){ + if (otherFile === sourceFile || !isSourceFileJS(otherFile) || program.isSourceFileFromExternalLibrary(otherFile)) continue; + if (otherFile.commonJsModuleIndicator && !otherFile.externalModuleIndicator) return true; + if (otherFile.externalModuleIndicator && !otherFile.commonJsModuleIndicator) return false; + } + return true; } - function getAccessorConvertiblePropertyAtPosition(file, program, start, end, considerEmptySpans = true) { - const node = getTokenAtPosition(file, start); - const cursorRequest = start === end && considerEmptySpans; - const declaration = findAncestor(node.parent, isAcceptedDeclaration); - const meaning = 124 /* Readonly */ ; - if (!declaration || !(nodeOverlapsWithStartEnd(declaration.name, file, start, end) || cursorRequest)) return { - error: getLocaleSpecificMessage(Diagnostics.Could_not_find_property_for_which_to_generate_accessor) - }; - if (!isConvertibleName(declaration.name)) return { - error: getLocaleSpecificMessage(Diagnostics.Name_is_not_valid) - }; - if ((getEffectiveModifierFlags(declaration) & 126975 /* Modifier */ | meaning) !== meaning) return { - error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_property_with_modifier) - }; - const name = declaration.name.text; - const startWithUnderscore = startsWithUnderscore(name); - const fieldName = createPropertyName(startWithUnderscore ? name : getUniqueName(`_${name}`, file), declaration.name); - const accessorName = createPropertyName(startWithUnderscore ? getUniqueName(name.substring(1), file) : name, declaration.name); + function createGetChecker(program, host) { + return memoizeOne((isFromPackageJson)=>isFromPackageJson ? host.getPackageJsonAutoImportProvider().getTypeChecker() : program.getTypeChecker()); + } + function getNewImportFixes(program, sourceFile, usagePosition, isValidTypeOnlyUseSite, useRequire, exportInfo, host, preferences, fromCacheOnly) { + const isJs = isSourceFileJS(sourceFile); + const compilerOptions = program.getCompilerOptions(); + const moduleSpecifierResolutionHost = createModuleSpecifierResolutionHost(program, host); + const getChecker = createGetChecker(program, host); + const moduleResolution = getEmitModuleResolutionKind(compilerOptions); + const rejectNodeModulesRelativePaths = moduleResolutionUsesNodeModules(moduleResolution); + const getModuleSpecifiers2 = fromCacheOnly ? (moduleSymbol)=>({ + moduleSpecifiers: ts_moduleSpecifiers_exports.tryGetModuleSpecifiersFromCache(moduleSymbol, sourceFile, moduleSpecifierResolutionHost, preferences), + computedWithoutCache: false + }) : (moduleSymbol, checker)=>ts_moduleSpecifiers_exports.getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, sourceFile, moduleSpecifierResolutionHost, preferences); + let computedWithoutCacheCount = 0; + const fixes = flatMap(exportInfo, (exportInfo2, i)=>{ + const checker = getChecker(exportInfo2.isFromPackageJson); + const { computedWithoutCache: computedWithoutCache, moduleSpecifiers: moduleSpecifiers } = getModuleSpecifiers2(exportInfo2.moduleSymbol, checker); + const importedSymbolHasValueMeaning = !!(exportInfo2.targetFlags & 111551 /* Value */ ); + const addAsTypeOnly = getAddAsTypeOnly(isValidTypeOnlyUseSite, /*isForNewImportDeclaration*/ true, exportInfo2.symbol, exportInfo2.targetFlags, checker, compilerOptions); + computedWithoutCacheCount += computedWithoutCache ? 1 : 0; + return mapDefined(moduleSpecifiers, (moduleSpecifier)=>{ + var _a; + if (rejectNodeModulesRelativePaths && pathContainsNodeModules(moduleSpecifier)) return void 0; + if (!importedSymbolHasValueMeaning && isJs && usagePosition !== void 0) return { + kind: 1 /* JsdocTypeImport */ , + moduleSpecifier: moduleSpecifier, + usagePosition: usagePosition, + exportInfo: exportInfo2, + isReExport: i > 0 + }; + const importKind = getImportKind(sourceFile, exportInfo2.exportKind, compilerOptions); + let qualification; + if (usagePosition !== void 0 && importKind === 3 /* CommonJS */ && exportInfo2.exportKind === 0 /* Named */ ) { + const exportEquals = checker.resolveExternalModuleSymbol(exportInfo2.moduleSymbol); + let namespacePrefix; + if (exportEquals !== exportInfo2.moduleSymbol) namespacePrefix = (_a = getDefaultExportInfoWorker(exportEquals, checker, compilerOptions)) == null ? void 0 : _a.name; + namespacePrefix || (namespacePrefix = moduleSymbolToValidIdentifier(exportInfo2.moduleSymbol, getEmitScriptTarget(compilerOptions), /*forceCapitalize*/ false)); + qualification = { + namespacePrefix: namespacePrefix, + usagePosition: usagePosition + }; + } + return { + kind: 3 /* AddNew */ , + moduleSpecifier: moduleSpecifier, + importKind: importKind, + useRequire: useRequire, + addAsTypeOnly: addAsTypeOnly, + exportInfo: exportInfo2, + isReExport: i > 0, + qualification: qualification + }; + }); + }); return { - isStatic: hasStaticModifier(declaration), - isReadonly: hasEffectiveReadonlyModifier(declaration), - type: getDeclarationType(declaration, program), - container: declaration.kind === 166 /* Parameter */ ? declaration.parent.parent : declaration.parent, - originalName: declaration.name.text, - declaration: declaration, - fieldName: fieldName, - accessorName: accessorName, - renameAccessor: startWithUnderscore + computedWithoutCacheCount: computedWithoutCacheCount, + fixes: fixes }; } - function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic2, container) { - return factory.createGetAccessorDeclaration(modifiers, accessorName, [], type, factory.createBlock([ - factory.createReturnStatement(createAccessorAccessExpression(fieldName, isStatic2, container)) - ], /*multiLine*/ true)); + function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, usagePosition, isValidTypeOnlyUseSite, useRequire, host, preferences, fromCacheOnly) { + const existingDeclaration = firstDefined(existingImports, (info)=>newImportInfoFromExistingSpecifier(info, isValidTypeOnlyUseSite, useRequire, program.getTypeChecker(), program.getCompilerOptions())); + return existingDeclaration ? { + fixes: [ + existingDeclaration + ] + } : getNewImportFixes(program, sourceFile, usagePosition, isValidTypeOnlyUseSite, useRequire, exportInfos, host, preferences, fromCacheOnly); } - function generateSetAccessor(fieldName, accessorName, type, modifiers, isStatic2, container) { - return factory.createSetAccessorDeclaration(modifiers, accessorName, [ - factory.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, factory.createIdentifier("value"), /*questionToken*/ void 0, type) - ], factory.createBlock([ - factory.createExpressionStatement(factory.createAssignment(createAccessorAccessExpression(fieldName, isStatic2, container), factory.createIdentifier("value"))) - ], /*multiLine*/ true)); + function newImportInfoFromExistingSpecifier({ declaration: declaration, importKind: importKind, symbol: symbol, targetFlags: targetFlags }, isValidTypeOnlyUseSite, useRequire, checker, compilerOptions) { + var _a; + const moduleSpecifier = (_a = tryGetModuleSpecifierFromDeclaration(declaration)) == null ? void 0 : _a.text; + if (moduleSpecifier) { + const addAsTypeOnly = useRequire ? 4 /* NotAllowed */ : getAddAsTypeOnly(isValidTypeOnlyUseSite, /*isForNewImportDeclaration*/ true, symbol, targetFlags, checker, compilerOptions); + return { + kind: 3 /* AddNew */ , + moduleSpecifier: moduleSpecifier, + importKind: importKind, + addAsTypeOnly: addAsTypeOnly, + useRequire: useRequire + }; + } } - function updatePropertyDeclaration(changeTracker, file, declaration, type, fieldName, modifiers) { - const property = factory.updatePropertyDeclaration(declaration, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, type, declaration.initializer); - changeTracker.replaceNode(file, declaration, property); + function getFixInfos(context, errorCode, pos, useAutoImportProvider) { + const symbolToken = getTokenAtPosition(context.sourceFile, pos); + let info; + if (errorCode === Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) info = getFixesInfoForUMDImport(context, symbolToken); + else if (!isIdentifier(symbolToken)) return void 0; + else if (errorCode === Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type.code) { + const symbolName2 = single(getSymbolNamesToImport(context.sourceFile, context.program.getTypeChecker(), symbolToken, context.program.getCompilerOptions())); + const fix = getTypeOnlyPromotionFix(context.sourceFile, symbolToken, symbolName2, context.program); + return fix && [ + { + fix: fix, + symbolName: symbolName2, + errorIdentifierText: symbolToken.text + } + ]; + } else info = getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider); + const packageJsonImportFilter = createPackageJsonImportFilter(context.sourceFile, context.preferences, context.host); + return info && sortFixInfo(info, context.sourceFile, context.program, packageJsonImportFilter, context.host); } - function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) { - let assignment = factory.updatePropertyAssignment(declaration, fieldName, declaration.initializer); - if (assignment.modifiers || assignment.questionToken || assignment.exclamationToken) { - if (assignment === declaration) assignment = factory.cloneNode(assignment); - assignment.modifiers = void 0; - assignment.questionToken = void 0; - assignment.exclamationToken = void 0; + function sortFixInfo(fixes, sourceFile, program, packageJsonImportFilter, host) { + const _toPath = (fileName)=>toPath(fileName, host.getCurrentDirectory(), hostGetCanonicalFileName(host)); + return sort(fixes, (a, b)=>compareBooleans(!!a.isJsxNamespaceFix, !!b.isJsxNamespaceFix) || compareValues(a.fix.kind, b.fix.kind) || compareModuleSpecifiers(a.fix, b.fix, sourceFile, program, packageJsonImportFilter.allowsImportingSpecifier, _toPath)); + } + function getBestFix(fixes, sourceFile, program, packageJsonImportFilter, host) { + if (!some(fixes)) return; + if (fixes[0].kind === 0 /* UseNamespace */ || fixes[0].kind === 2 /* AddToExisting */ ) return fixes[0]; + return fixes.reduce((best, fix)=>// Takes true branch of conditional if `fix` is better than `best` + compareModuleSpecifiers(fix, best, sourceFile, program, packageJsonImportFilter.allowsImportingSpecifier, (fileName)=>toPath(fileName, host.getCurrentDirectory(), hostGetCanonicalFileName(host))) === -1 /* LessThan */ ? fix : best); + } + function compareModuleSpecifiers(a, b, importingFile, program, allowsImportingSpecifier, toPath3) { + if (a.kind !== 0 /* UseNamespace */ && b.kind !== 0 /* UseNamespace */ ) return compareBooleans(allowsImportingSpecifier(b.moduleSpecifier), allowsImportingSpecifier(a.moduleSpecifier)) || compareNodeCoreModuleSpecifiers(a.moduleSpecifier, b.moduleSpecifier, importingFile, program) || compareBooleans(isFixPossiblyReExportingImportingFile(a, importingFile, program.getCompilerOptions(), toPath3), isFixPossiblyReExportingImportingFile(b, importingFile, program.getCompilerOptions(), toPath3)) || compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier); + return 0 /* EqualTo */ ; + } + function isFixPossiblyReExportingImportingFile(fix, importingFile, compilerOptions, toPath3) { + var _a; + if (fix.isReExport && ((_a = fix.exportInfo) == null ? void 0 : _a.moduleFileName) && getEmitModuleResolutionKind(compilerOptions) === 2 /* Node10 */ && isIndexFileName(fix.exportInfo.moduleFileName)) { + const reExportDir = toPath3(getDirectoryPath(fix.exportInfo.moduleFileName)); + return startsWith(importingFile.path, reExportDir); } - changeTracker.replacePropertyAssignment(file, declaration, assignment); + return false; } - function updateFieldDeclaration(changeTracker, file, declaration, type, fieldName, modifiers) { - if (isPropertyDeclaration(declaration)) updatePropertyDeclaration(changeTracker, file, declaration, type, fieldName, modifiers); - else if (isPropertyAssignment(declaration)) updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName); - else changeTracker.replaceNode(file, declaration, factory.updateParameterDeclaration(declaration, modifiers, declaration.dotDotDotToken, cast(fieldName, isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); + function isIndexFileName(fileName) { + return getBaseFileName(fileName, [ + ".js", + ".jsx", + ".d.ts", + ".ts", + ".tsx" + ], /*ignoreCase*/ true) === "index"; } - function insertAccessor(changeTracker, file, accessor, declaration, container) { - isParameterPropertyDeclaration(declaration, declaration.parent) ? changeTracker.insertMemberAtStart(file, container, accessor) : isPropertyAssignment(declaration) ? changeTracker.insertNodeAfterComma(file, declaration, accessor) : changeTracker.insertNodeAfter(file, declaration, accessor); + function compareNodeCoreModuleSpecifiers(a, b, importingFile, program) { + if (startsWith(a, "node:") && !startsWith(b, "node:")) return shouldUseUriStyleNodeCoreModules(importingFile, program) ? -1 /* LessThan */ : 1 /* GreaterThan */ ; + if (startsWith(b, "node:") && !startsWith(a, "node:")) return shouldUseUriStyleNodeCoreModules(importingFile, program) ? 1 /* GreaterThan */ : -1 /* LessThan */ ; + return 0 /* EqualTo */ ; } - function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName, originalName) { - if (!constructor.body) return; - constructor.body.forEachChild(function recur(node) { - if (isElementAccessExpression(node) && node.expression.kind === 108 /* ThisKeyword */ && isStringLiteral(node.argumentExpression) && node.argumentExpression.text === originalName && isWriteAccess(node)) changeTracker.replaceNode(file, node.argumentExpression, factory.createStringLiteral(fieldName)); - if (isPropertyAccessExpression(node) && node.expression.kind === 108 /* ThisKeyword */ && node.name.text === originalName && isWriteAccess(node)) changeTracker.replaceNode(file, node.name, factory.createIdentifier(fieldName)); - if (!isFunctionLike(node) && !isClassLike(node)) node.forEachChild(recur); + function getFixesInfoForUMDImport({ sourceFile: sourceFile, program: program, host: host, preferences: preferences }, token) { + const checker = program.getTypeChecker(); + const umdSymbol = getUmdSymbol(token, checker); + if (!umdSymbol) return void 0; + const symbol = checker.getAliasedSymbol(umdSymbol); + const symbolName2 = umdSymbol.name; + const exportInfo = [ + { + symbol: umdSymbol, + moduleSymbol: symbol, + moduleFileName: void 0, + exportKind: 3 /* UMD */ , + targetFlags: symbol.flags, + isFromPackageJson: false + } + ]; + const useRequire = shouldUseRequire(sourceFile, program); + const fixes = getImportFixes(exportInfo, /*usagePosition*/ void 0, /*isValidTypeOnlyUseSite*/ false, useRequire, program, sourceFile, host, preferences).fixes; + return fixes.map((fix)=>{ + var _a; + return { + fix: fix, + symbolName: symbolName2, + errorIdentifierText: (_a = tryCast(token, isIdentifier)) == null ? void 0 : _a.text + }; }); } - function getDeclarationType(declaration, program) { - const typeNode = getTypeAnnotationNode(declaration); - if (isPropertyDeclaration(declaration) && typeNode && declaration.questionToken) { - const typeChecker = program.getTypeChecker(); - const type = typeChecker.getTypeFromTypeNode(typeNode); - if (!typeChecker.isTypeAssignableTo(typeChecker.getUndefinedType(), type)) { - const types = isUnionTypeNode(typeNode) ? typeNode.types : [ - typeNode - ]; - return factory.createUnionTypeNode([ - ...types, - factory.createKeywordTypeNode(155 /* UndefinedKeyword */ ) - ]); - } + function getUmdSymbol(token, checker) { + const umdSymbol = isIdentifier(token) ? checker.getSymbolAtLocation(token) : void 0; + if (isUMDExportSymbol(umdSymbol)) return umdSymbol; + const { parent: parent2 } = token; + if (isJsxOpeningLikeElement(parent2) && parent2.tagName === token || isJsxOpeningFragment(parent2)) { + const parentSymbol = checker.resolveName(checker.getJsxNamespace(parent2), isJsxOpeningLikeElement(parent2) ? token : parent2, 111551 /* Value */ , /*excludeGlobals*/ false); + if (isUMDExportSymbol(parentSymbol)) return parentSymbol; } - return typeNode; + return void 0; } - function getAllSupers(decl, checker) { - const res = []; - while(decl){ - const superElement = getClassExtendsHeritageElement(decl); - const superSymbol = superElement && checker.getSymbolAtLocation(superElement.expression); - if (!superSymbol) break; - const symbol = superSymbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(superSymbol) : superSymbol; - const superDecl = symbol.declarations && find(symbol.declarations, isClassLike); - if (!superDecl) break; - res.push(superDecl); - decl = superDecl; + function getImportKind(importingFile, exportKind, compilerOptions, forceImportKeyword) { + if (compilerOptions.verbatimModuleSyntax && (getEmitModuleKind(compilerOptions) === 1 /* CommonJS */ || importingFile.impliedNodeFormat === 1 /* CommonJS */ )) return 3 /* CommonJS */ ; + switch(exportKind){ + case 0 /* Named */ : + return 0 /* Named */ ; + case 1 /* Default */ : + return 1 /* Default */ ; + case 2 /* ExportEquals */ : + return getExportEqualsImportKind(importingFile, compilerOptions, !!forceImportKeyword); + case 3 /* UMD */ : + return getUmdImportKind(importingFile, compilerOptions, !!forceImportKeyword); + default: + return Debug.assertNever(exportKind); } - return res; } - var init_generateAccessors = __esm({ - "src/services/codefixes/generateAccessors.ts" () { - "use strict"; - init_ts4(); + function getUmdImportKind(importingFile, compilerOptions, forceImportKeyword) { + if (getAllowSyntheticDefaultImports(compilerOptions)) return 1 /* Default */ ; + const moduleKind = getEmitModuleKind(compilerOptions); + switch(moduleKind){ + case 2 /* AMD */ : + case 1 /* CommonJS */ : + case 3 /* UMD */ : + if (isInJSFile(importingFile)) return isExternalModule(importingFile) || forceImportKeyword ? 2 /* Namespace */ : 3 /* CommonJS */ ; + return 3 /* CommonJS */ ; + case 4 /* System */ : + case 5 /* ES2015 */ : + case 6 /* ES2020 */ : + case 7 /* ES2022 */ : + case 99 /* ESNext */ : + case 0 /* None */ : + return 2 /* Namespace */ ; + case 100 /* Node16 */ : + case 199 /* NodeNext */ : + return importingFile.impliedNodeFormat === 99 /* ESNext */ ? 2 /* Namespace */ : 3 /* CommonJS */ ; + default: + return Debug.assertNever(moduleKind, `Unexpected moduleKind ${moduleKind}`); } - }); - // src/services/codefixes/fixInvalidImportSyntax.ts - function getCodeFixesForImportDeclaration(context, node) { - const sourceFile = getSourceFileOfNode(node); - const namespace = getNamespaceDeclarationNode(node); - const opts = context.program.getCompilerOptions(); - const variations = []; - variations.push(createAction(context, sourceFile, node, makeImport(namespace.name, /*namedImports*/ void 0, node.moduleSpecifier, getQuotePreference(sourceFile, context.preferences)))); - if (getEmitModuleKind(opts) === 1 /* CommonJS */ ) variations.push(createAction(context, sourceFile, node, factory.createImportEqualsDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, namespace.name, factory.createExternalModuleReference(node.moduleSpecifier)))); - return variations; - } - function createAction(context, sourceFile, node, replacement) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>t.replaceNode(sourceFile, node, replacement)); - return createCodeFixActionWithoutFixAll(fixName5, changes, [ - Diagnostics.Replace_import_with_0, - changes[0].textChanges[0].newText - ]); } - function getActionsForUsageOfInvalidImport(context) { - const sourceFile = context.sourceFile; - const targetKind = Diagnostics.This_expression_is_not_callable.code === context.errorCode ? 210 /* CallExpression */ : 211 /* NewExpression */ ; - const node = findAncestor(getTokenAtPosition(sourceFile, context.span.start), (a)=>a.kind === targetKind); - if (!node) return []; - const expr = node.expression; - return getImportCodeFixesForExpression(context, expr); + function getFixesInfoForNonUMDImport({ sourceFile: sourceFile, program: program, cancellationToken: cancellationToken, host: host, preferences: preferences }, symbolToken, useAutoImportProvider) { + const checker = program.getTypeChecker(); + const compilerOptions = program.getCompilerOptions(); + return flatMap(getSymbolNamesToImport(sourceFile, checker, symbolToken, compilerOptions), (symbolName2)=>{ + if (symbolName2 === "default" /* Default */ ) return void 0; + const isValidTypeOnlyUseSite = isValidTypeOnlyAliasUseSite(symbolToken); + const useRequire = shouldUseRequire(sourceFile, program); + const exportInfo = getExportInfos(symbolName2, isJSXTagName(symbolToken), getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, program, useAutoImportProvider, host, preferences); + return arrayFrom(flatMapIterator(exportInfo.values(), (exportInfos)=>getImportFixes(exportInfos, symbolToken.getStart(sourceFile), isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences).fixes), (fix)=>({ + fix: fix, + symbolName: symbolName2, + errorIdentifierText: symbolToken.text, + isJsxNamespaceFix: symbolName2 !== symbolToken.text + })); + }); } - function getActionsForInvalidImportLocation(context) { - const sourceFile = context.sourceFile; - const node = findAncestor(getTokenAtPosition(sourceFile, context.span.start), (a)=>a.getStart() === context.span.start && a.getEnd() === context.span.start + context.span.length); - if (!node) return []; - return getImportCodeFixesForExpression(context, node); + function getTypeOnlyPromotionFix(sourceFile, symbolToken, symbolName2, program) { + const checker = program.getTypeChecker(); + const symbol = checker.resolveName(symbolName2, symbolToken, 111551 /* Value */ , /*excludeGlobals*/ true); + if (!symbol) return void 0; + const typeOnlyAliasDeclaration = checker.getTypeOnlyAliasDeclaration(symbol); + if (!typeOnlyAliasDeclaration || getSourceFileOfNode(typeOnlyAliasDeclaration) !== sourceFile) return void 0; + return { + kind: 4 /* PromoteTypeOnly */ , + typeOnlyAliasDeclaration: typeOnlyAliasDeclaration + }; } - function getImportCodeFixesForExpression(context, expr) { - const type = context.program.getTypeChecker().getTypeAtLocation(expr); - if (!(type.symbol && isTransientSymbol(type.symbol) && type.symbol.links.originatingImport)) return []; - const fixes = []; - const relatedImport = type.symbol.links.originatingImport; - if (!isImportCall(relatedImport)) addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); - if (isExpression(expr) && !(isNamedDeclaration(expr.parent) && expr.parent.name === expr)) { - const sourceFile = context.sourceFile; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>t.replaceNode(sourceFile, expr, factory.createPropertyAccessExpression(expr, "default"), {})); - fixes.push(createCodeFixActionWithoutFixAll(fixName5, changes, Diagnostics.Use_synthetic_default_member)); + function getSymbolNamesToImport(sourceFile, checker, symbolToken, compilerOptions) { + const parent2 = symbolToken.parent; + if ((isJsxOpeningLikeElement(parent2) || isJsxClosingElement(parent2)) && parent2.tagName === symbolToken && jsxModeNeedsExplicitImport(compilerOptions.jsx)) { + const jsxNamespace = checker.getJsxNamespace(sourceFile); + if (needsJsxNamespaceFix(jsxNamespace, symbolToken, checker)) { + const needsComponentNameFix = !isIntrinsicJsxName(symbolToken.text) && !checker.resolveName(symbolToken.text, symbolToken, 111551 /* Value */ , /*excludeGlobals*/ false); + return needsComponentNameFix ? [ + symbolToken.text, + jsxNamespace + ] : [ + jsxNamespace + ]; + } } - return fixes; + return [ + symbolToken.text + ]; } - var fixName5; - var init_fixInvalidImportSyntax = __esm({ - "src/services/codefixes/fixInvalidImportSyntax.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixName5 = "invalidImportSyntax"; - registerCodeFix({ - errorCodes: [ - Diagnostics.This_expression_is_not_callable.code, - Diagnostics.This_expression_is_not_constructable.code - ], - getCodeActions: getActionsForUsageOfInvalidImport - }); - registerCodeFix({ - errorCodes: [ - // The following error codes cover pretty much all assignability errors that could involve an expression - Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, - Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code, - Diagnostics.Type_0_is_not_assignable_to_type_1.code, - Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code, - Diagnostics.Type_predicate_0_is_not_assignable_to_1.code, - Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3.code, - Diagnostics._0_index_type_1_is_not_assignable_to_2_index_type_3.code, - Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2.code, - Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code, - Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property.code, - Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1.code - ], - getCodeActions: getActionsForInvalidImportLocation - }); + function needsJsxNamespaceFix(jsxNamespace, symbolToken, checker) { + if (isIntrinsicJsxName(symbolToken.text)) return true; + const namespaceSymbol = checker.resolveName(jsxNamespace, symbolToken, 111551 /* Value */ , /*excludeGlobals*/ true); + return !namespaceSymbol || some(namespaceSymbol.declarations, isTypeOnlyImportOrExportDeclaration) && !(namespaceSymbol.flags & 111551 /* Value */ ); + } + function getExportInfos(symbolName2, isJsxTagName, currentTokenMeaning, cancellationToken, fromFile, program, useAutoImportProvider, host, preferences) { + var _a; + const originalSymbolToExportInfos = createMultiMap(); + const packageJsonFilter = createPackageJsonImportFilter(fromFile, preferences, host); + const moduleSpecifierCache = (_a = host.getModuleSpecifierCache) == null ? void 0 : _a.call(host); + const getModuleSpecifierResolutionHost = memoizeOne((isFromPackageJson)=>{ + return createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); + }); + function addSymbol(moduleSymbol, toFile, exportedSymbol, exportKind, program2, isFromPackageJson) { + const moduleSpecifierResolutionHost = getModuleSpecifierResolutionHost(isFromPackageJson); + if (toFile && isImportableFile(program2, fromFile, toFile, preferences, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) || !toFile && packageJsonFilter.allowsImportingAmbientModule(moduleSymbol, moduleSpecifierResolutionHost)) { + const checker = program2.getTypeChecker(); + originalSymbolToExportInfos.add(getUniqueSymbolId(exportedSymbol, checker).toString(), { + symbol: exportedSymbol, + moduleSymbol: moduleSymbol, + moduleFileName: toFile == null ? void 0 : toFile.fileName, + exportKind: exportKind, + targetFlags: skipAlias(exportedSymbol, checker).flags, + isFromPackageJson: isFromPackageJson + }); + } } - }); - // src/services/codefixes/fixStrictClassInitialization.ts - function getInfo13(sourceFile, pos) { - const token = getTokenAtPosition(sourceFile, pos); - if (isIdentifier(token) && isPropertyDeclaration(token.parent)) { - const type = getEffectiveTypeAnnotationNode(token.parent); - if (type) return { - type: type, - prop: token.parent, - isJs: isInJSFile(token.parent) - }; + forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, (moduleSymbol, sourceFile, program2, isFromPackageJson)=>{ + const checker = program2.getTypeChecker(); + cancellationToken.throwIfCancellationRequested(); + const compilerOptions = program2.getCompilerOptions(); + const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && (defaultInfo.name === symbolName2 || moduleSymbolToValidIdentifier(moduleSymbol, getEmitScriptTarget(compilerOptions), isJsxTagName) === symbolName2) && symbolHasMeaning(defaultInfo.resolvedSymbol, currentTokenMeaning)) addSymbol(moduleSymbol, sourceFile, defaultInfo.symbol, defaultInfo.exportKind, program2, isFromPackageJson); + const exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName2, moduleSymbol); + if (exportSymbolWithIdenticalName && symbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) addSymbol(moduleSymbol, sourceFile, exportSymbolWithIdenticalName, 0 /* Named */ , program2, isFromPackageJson); + }); + return originalSymbolToExportInfos; + } + function getExportEqualsImportKind(importingFile, compilerOptions, forceImportKeyword) { + const allowSyntheticDefaults = getAllowSyntheticDefaultImports(compilerOptions); + const isJS = isInJSFile(importingFile); + if (!isJS && getEmitModuleKind(compilerOptions) >= 5 /* ES2015 */ ) return allowSyntheticDefaults ? 1 /* Default */ : 2 /* Namespace */ ; + if (isJS) return isExternalModule(importingFile) || forceImportKeyword ? allowSyntheticDefaults ? 1 /* Default */ : 2 /* Namespace */ : 3 /* CommonJS */ ; + for (const statement of importingFile.statements){ + if (isImportEqualsDeclaration(statement) && !nodeIsMissing(statement.moduleReference)) return 3 /* CommonJS */ ; } - return void 0; + return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */ ; } - function getActionForAddMissingDefiniteAssignmentAssertion(context, info) { - if (info.isJs) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addDefiniteAssignmentAssertion(t, context.sourceFile, info.prop)); - return createCodeFixAction(fixName6, changes, [ - Diagnostics.Add_definite_assignment_assertion_to_property_0, - info.prop.getText() - ], fixIdAddDefiniteAssignmentAssertions, Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); + function codeActionForFix(context, sourceFile, symbolName2, fix, includeSymbolNameInDescription, compilerOptions, preferences) { + let diag2; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (tracker)=>{ + diag2 = codeActionForFixWorker(tracker, sourceFile, symbolName2, fix, includeSymbolNameInDescription, compilerOptions, preferences); + }); + return createCodeFixAction(importFixName, changes, diag2, importFixId, Diagnostics.Add_all_missing_imports); } - function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { - suppressLeadingAndTrailingTrivia(propertyDeclaration); - const property = factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.modifiers, propertyDeclaration.name, factory.createToken(53 /* ExclamationToken */ ), propertyDeclaration.type, propertyDeclaration.initializer); - changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); + function codeActionForFixWorker(changes, sourceFile, symbolName2, fix, includeSymbolNameInDescription, compilerOptions, preferences) { + const quotePreference = getQuotePreference(sourceFile, preferences); + switch(fix.kind){ + case 0 /* UseNamespace */ : + addNamespaceQualifier(changes, sourceFile, fix); + return [ + Diagnostics.Change_0_to_1, + symbolName2, + `${fix.namespacePrefix}.${symbolName2}` + ]; + case 1 /* JsdocTypeImport */ : + addImportType(changes, sourceFile, fix, quotePreference); + return [ + Diagnostics.Change_0_to_1, + symbolName2, + getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName2 + ]; + case 2 /* AddToExisting */ : + { + const { importClauseOrBindingPattern: importClauseOrBindingPattern, importKind: importKind, addAsTypeOnly: addAsTypeOnly, moduleSpecifier: moduleSpecifier } = fix; + doAddExistingFix(changes, sourceFile, importClauseOrBindingPattern, importKind === 1 /* Default */ ? { + name: symbolName2, + addAsTypeOnly: addAsTypeOnly + } : void 0, importKind === 0 /* Named */ ? [ + { + name: symbolName2, + addAsTypeOnly: addAsTypeOnly + } + ] : emptyArray, preferences); + const moduleSpecifierWithoutQuotes = stripQuotes(moduleSpecifier); + return includeSymbolNameInDescription ? [ + Diagnostics.Import_0_from_1, + symbolName2, + moduleSpecifierWithoutQuotes + ] : [ + Diagnostics.Update_import_from_0, + moduleSpecifierWithoutQuotes + ]; + } + case 3 /* AddNew */ : + { + const { importKind: importKind, moduleSpecifier: moduleSpecifier, addAsTypeOnly: addAsTypeOnly, useRequire: useRequire, qualification: qualification } = fix; + const getDeclarations = useRequire ? getNewRequires : getNewImports; + const defaultImport = importKind === 1 /* Default */ ? { + name: symbolName2, + addAsTypeOnly: addAsTypeOnly + } : void 0; + const namedImports = importKind === 0 /* Named */ ? [ + { + name: symbolName2, + addAsTypeOnly: addAsTypeOnly + } + ] : void 0; + const namespaceLikeImport = importKind === 2 /* Namespace */ || importKind === 3 /* CommonJS */ ? { + importKind: importKind, + name: (qualification == null ? void 0 : qualification.namespacePrefix) || symbolName2, + addAsTypeOnly: addAsTypeOnly + } : void 0; + insertImports(changes, sourceFile, getDeclarations(moduleSpecifier, quotePreference, defaultImport, namedImports, namespaceLikeImport, compilerOptions), /*blankLineBetween*/ true, preferences); + if (qualification) addNamespaceQualifier(changes, sourceFile, qualification); + return includeSymbolNameInDescription ? [ + Diagnostics.Import_0_from_1, + symbolName2, + moduleSpecifier + ] : [ + Diagnostics.Add_import_from_0, + moduleSpecifier + ]; + } + case 4 /* PromoteTypeOnly */ : + { + const { typeOnlyAliasDeclaration: typeOnlyAliasDeclaration } = fix; + const promotedDeclaration = promoteFromTypeOnly(changes, typeOnlyAliasDeclaration, compilerOptions, sourceFile, preferences); + return promotedDeclaration.kind === 276 /* ImportSpecifier */ ? [ + Diagnostics.Remove_type_from_import_of_0_from_1, + symbolName2, + getModuleSpecifierText(promotedDeclaration.parent.parent) + ] : [ + Diagnostics.Remove_type_from_import_declaration_from_0, + getModuleSpecifierText(promotedDeclaration) + ]; + } + default: + return Debug.assertNever(fix, `Unexpected fix kind ${fix.kind}`); + } } - function getActionForAddMissingUndefinedType(context, info) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addUndefinedType(t, context.sourceFile, info)); - return createCodeFixAction(fixName6, changes, [ - Diagnostics.Add_undefined_type_to_property_0, - info.prop.name.getText() - ], fixIdAddUndefinedType, Diagnostics.Add_undefined_type_to_all_uninitialized_properties); + function getModuleSpecifierText(promotedDeclaration) { + var _a, _b; + return promotedDeclaration.kind === 271 /* ImportEqualsDeclaration */ ? ((_b = tryCast((_a = tryCast(promotedDeclaration.moduleReference, isExternalModuleReference)) == null ? void 0 : _a.expression, isStringLiteralLike)) == null ? void 0 : _b.text) || promotedDeclaration.moduleReference.getText() : cast(promotedDeclaration.parent.moduleSpecifier, isStringLiteral).text; } - function addUndefinedType(changeTracker, sourceFile, info) { - const undefinedTypeNode = factory.createKeywordTypeNode(155 /* UndefinedKeyword */ ); - const types = isUnionTypeNode(info.type) ? info.type.types.concat(undefinedTypeNode) : [ - info.type, - undefinedTypeNode - ]; - const unionTypeNode = factory.createUnionTypeNode(types); - if (info.isJs) changeTracker.addJSDocTags(sourceFile, info.prop, [ - factory.createJSDocTypeTag(/*tagName*/ void 0, factory.createJSDocTypeExpression(unionTypeNode)) - ]); - else changeTracker.replaceNode(sourceFile, info.type, unionTypeNode); + function promoteFromTypeOnly(changes, aliasDeclaration, compilerOptions, sourceFile, preferences) { + const convertExistingToTypeOnly = importNameElisionDisabled(compilerOptions); + switch(aliasDeclaration.kind){ + case 276 /* ImportSpecifier */ : + if (aliasDeclaration.isTypeOnly) { + const sortKind = ts_OrganizeImports_exports.detectImportSpecifierSorting(aliasDeclaration.parent.elements, preferences); + if (aliasDeclaration.parent.elements.length > 1 && sortKind) { + changes.delete(sourceFile, aliasDeclaration); + const newSpecifier = factory.updateImportSpecifier(aliasDeclaration, /*isTypeOnly*/ false, aliasDeclaration.propertyName, aliasDeclaration.name); + const comparer = ts_OrganizeImports_exports.getOrganizeImportsComparer(preferences, sortKind === 2 /* CaseInsensitive */ ); + const insertionIndex = ts_OrganizeImports_exports.getImportSpecifierInsertionIndex(aliasDeclaration.parent.elements, newSpecifier, comparer); + changes.insertImportSpecifierAtIndex(sourceFile, newSpecifier, aliasDeclaration.parent, insertionIndex); + } else changes.deleteRange(sourceFile, aliasDeclaration.getFirstToken()); + return aliasDeclaration; + } else { + Debug.assert(aliasDeclaration.parent.parent.isTypeOnly); + promoteImportClause(aliasDeclaration.parent.parent); + return aliasDeclaration.parent.parent; + } + case 273 /* ImportClause */ : + promoteImportClause(aliasDeclaration); + return aliasDeclaration; + case 274 /* NamespaceImport */ : + promoteImportClause(aliasDeclaration.parent); + return aliasDeclaration.parent; + case 271 /* ImportEqualsDeclaration */ : + changes.deleteRange(sourceFile, aliasDeclaration.getChildAt(1)); + return aliasDeclaration; + default: + Debug.failBadSyntaxKind(aliasDeclaration); + } + function promoteImportClause(importClause) { + changes.delete(sourceFile, getTypeKeywordOfTypeOnlyImport(importClause, sourceFile)); + if (!compilerOptions.allowImportingTsExtensions) { + const moduleSpecifier = tryGetModuleSpecifierFromDeclaration(importClause.parent); + const resolvedModule = moduleSpecifier && getResolvedModule(sourceFile, moduleSpecifier.text, getModeForUsageLocation(sourceFile, moduleSpecifier)); + if (resolvedModule == null ? void 0 : resolvedModule.resolvedUsingTsExtension) { + const changedExtension = changeAnyExtension(moduleSpecifier.text, getOutputExtension(moduleSpecifier.text, compilerOptions)); + changes.replaceNode(sourceFile, moduleSpecifier, factory.createStringLiteral(changedExtension)); + } + } + if (convertExistingToTypeOnly) { + const namedImports = tryCast(importClause.namedBindings, isNamedImports); + if (namedImports && namedImports.elements.length > 1) { + if (ts_OrganizeImports_exports.detectImportSpecifierSorting(namedImports.elements, preferences) && aliasDeclaration.kind === 276 /* ImportSpecifier */ && namedImports.elements.indexOf(aliasDeclaration) !== 0) { + changes.delete(sourceFile, aliasDeclaration); + changes.insertImportSpecifierAtIndex(sourceFile, aliasDeclaration, namedImports, 0); + } + for (const element of namedImports.elements)if (element !== aliasDeclaration && !element.isTypeOnly) changes.insertModifierBefore(sourceFile, 156 /* TypeKeyword */ , element); + } + } + } } - function getActionForAddMissingInitializer(context, info) { - if (info.isJs) return void 0; - const checker = context.program.getTypeChecker(); - const initializer = getInitializer(checker, info.prop); - if (!initializer) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addInitializer(t, context.sourceFile, info.prop, initializer)); - return createCodeFixAction(fixName6, changes, [ - Diagnostics.Add_initializer_to_property_0, - info.prop.name.getText() - ], fixIdAddInitializer, Diagnostics.Add_initializers_to_all_uninitialized_properties); + function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports, preferences) { + var _a; + if (clause.kind === 206 /* ObjectBindingPattern */ ) { + if (defaultImport) addElementToBindingPattern(clause, defaultImport.name, "default"); + for (const specifier of namedImports)addElementToBindingPattern(clause, specifier.name, /*propertyName*/ void 0); + return; + } + const promoteFromTypeOnly2 = clause.isTypeOnly && some([ + defaultImport, + ...namedImports + ], (i)=>(i == null ? void 0 : i.addAsTypeOnly) === 4 /* NotAllowed */ ); + const existingSpecifiers = clause.namedBindings && ((_a = tryCast(clause.namedBindings, isNamedImports)) == null ? void 0 : _a.elements); + if (defaultImport) { + Debug.assert(!clause.name, "Cannot add a default import to an import clause that already has one"); + changes.insertNodeAt(sourceFile, clause.getStart(sourceFile), factory.createIdentifier(defaultImport.name), { + suffix: ", " + }); + } + if (namedImports.length) { + let ignoreCaseForSorting; + if (typeof preferences.organizeImportsIgnoreCase === "boolean") ignoreCaseForSorting = preferences.organizeImportsIgnoreCase; + else if (existingSpecifiers) { + const targetImportSorting = ts_OrganizeImports_exports.detectImportSpecifierSorting(existingSpecifiers, preferences); + if (targetImportSorting !== 3 /* Both */ ) ignoreCaseForSorting = targetImportSorting === 2 /* CaseInsensitive */ ; + } + if (ignoreCaseForSorting === void 0) ignoreCaseForSorting = ts_OrganizeImports_exports.detectSorting(sourceFile, preferences) === 2 /* CaseInsensitive */ ; + const comparer = ts_OrganizeImports_exports.getOrganizeImportsComparer(preferences, ignoreCaseForSorting); + const newSpecifiers = stableSort(namedImports.map((namedImport)=>factory.createImportSpecifier((!clause.isTypeOnly || promoteFromTypeOnly2) && needsTypeOnly(namedImport), /*propertyName*/ void 0, factory.createIdentifier(namedImport.name))), (s1, s2)=>ts_OrganizeImports_exports.compareImportOrExportSpecifiers(s1, s2, comparer)); + const specifierSort = (existingSpecifiers == null ? void 0 : existingSpecifiers.length) && ts_OrganizeImports_exports.detectImportSpecifierSorting(existingSpecifiers, preferences); + if (specifierSort && !(ignoreCaseForSorting && specifierSort === 1 /* CaseSensitive */ )) for (const spec of newSpecifiers){ + const insertionIndex = promoteFromTypeOnly2 && !spec.isTypeOnly ? 0 : ts_OrganizeImports_exports.getImportSpecifierInsertionIndex(existingSpecifiers, spec, comparer); + changes.insertImportSpecifierAtIndex(sourceFile, spec, clause.namedBindings, insertionIndex); + } + else if (existingSpecifiers == null ? void 0 : existingSpecifiers.length) for (const spec of newSpecifiers)changes.insertNodeInListAfter(sourceFile, last(existingSpecifiers), spec, existingSpecifiers); + else if (newSpecifiers.length) { + const namedImports2 = factory.createNamedImports(newSpecifiers); + if (clause.namedBindings) changes.replaceNode(sourceFile, clause.namedBindings, namedImports2); + else changes.insertNodeAfter(sourceFile, Debug.checkDefined(clause.name, "Import clause must have either named imports or a default import"), namedImports2); + } + } + if (promoteFromTypeOnly2) { + changes.delete(sourceFile, getTypeKeywordOfTypeOnlyImport(clause, sourceFile)); + if (existingSpecifiers) for (const specifier of existingSpecifiers)changes.insertModifierBefore(sourceFile, 156 /* TypeKeyword */ , specifier); + } + function addElementToBindingPattern(bindingPattern, name, propertyName) { + const element = factory.createBindingElement(/*dotDotDotToken*/ void 0, propertyName, name); + if (bindingPattern.elements.length) changes.insertNodeInListAfter(sourceFile, last(bindingPattern.elements), element); + else changes.replaceNode(sourceFile, bindingPattern, factory.createObjectBindingPattern([ + element + ])); + } } - function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) { - suppressLeadingAndTrailingTrivia(propertyDeclaration); - const property = factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); - changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); + function addNamespaceQualifier(changes, sourceFile, { namespacePrefix: namespacePrefix, usagePosition: usagePosition }) { + changes.insertText(sourceFile, usagePosition, namespacePrefix + "."); } - function getInitializer(checker, propertyDeclaration) { - return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); + function addImportType(changes, sourceFile, { moduleSpecifier: moduleSpecifier, usagePosition: position }, quotePreference) { + changes.insertText(sourceFile, position, getImportTypePrefix(moduleSpecifier, quotePreference)); } - function getDefaultValueFromType(checker, type) { - if (type.flags & 512 /* BooleanLiteral */ ) return type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true) ? factory.createFalse() : factory.createTrue(); - else if (type.isStringLiteral()) return factory.createStringLiteral(type.value); - else if (type.isNumberLiteral()) return factory.createNumericLiteral(type.value); - else if (type.flags & 2048 /* BigIntLiteral */ ) return factory.createBigIntLiteral(type.value); - else if (type.isUnion()) return firstDefined(type.types, (t)=>getDefaultValueFromType(checker, t)); - else if (type.isClass()) { - const classDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); - if (!classDeclaration || hasSyntacticModifier(classDeclaration, 256 /* Abstract */ )) return void 0; - const constructorDeclaration = getFirstConstructorWithBody(classDeclaration); - if (constructorDeclaration && constructorDeclaration.parameters.length) return void 0; - return factory.createNewExpression(factory.createIdentifier(type.symbol.name), /*typeArguments*/ void 0, /*argumentsArray*/ void 0); - } else if (checker.isArrayLikeType(type)) return factory.createArrayLiteralExpression(); - return void 0; + function getImportTypePrefix(moduleSpecifier, quotePreference) { + const quote2 = getQuoteFromPreference(quotePreference); + return `import(${quote2}${moduleSpecifier}${quote2}).`; } - var fixName6, fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer, errorCodes50; - var init_fixStrictClassInitialization = __esm({ - "src/services/codefixes/fixStrictClassInitialization.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixName6 = "strictClassInitialization"; - fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions"; - fixIdAddUndefinedType = "addMissingPropertyUndefinedType"; - fixIdAddInitializer = "addMissingPropertyInitializer"; - errorCodes50 = [ - Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code - ]; - registerCodeFix({ - errorCodes: errorCodes50, - getCodeActions: function getCodeActionsForStrictClassInitializationErrors(context) { - const info = getInfo13(context.sourceFile, context.span.start); - if (!info) return; - const result = []; - append(result, getActionForAddMissingUndefinedType(context, info)); - append(result, getActionForAddMissingDefiniteAssignmentAssertion(context, info)); - append(result, getActionForAddMissingInitializer(context, info)); - return result; - }, - fixIds: [ - fixIdAddDefiniteAssignmentAssertions, - fixIdAddUndefinedType, - fixIdAddInitializer - ], - getAllCodeActions: (context)=>{ - return codeFixAll(context, errorCodes50, (changes, diag2)=>{ - const info = getInfo13(diag2.file, diag2.start); - if (!info) return; - switch(context.fixId){ - case fixIdAddDefiniteAssignmentAssertions: - addDefiniteAssignmentAssertion(changes, diag2.file, info.prop); - break; - case fixIdAddUndefinedType: - addUndefinedType(changes, diag2.file, info); - break; - case fixIdAddInitializer: - const checker = context.program.getTypeChecker(); - const initializer = getInitializer(checker, info.prop); - if (!initializer) return; - addInitializer(changes, diag2.file, info.prop, initializer); - break; - default: - Debug.fail(JSON.stringify(context.fixId)); - } - }); - } - }); + function needsTypeOnly({ addAsTypeOnly: addAsTypeOnly }) { + return addAsTypeOnly === 2 /* Required */ ; + } + function getNewImports(moduleSpecifier, quotePreference, defaultImport, namedImports, namespaceLikeImport, compilerOptions) { + const quotedModuleSpecifier = makeStringLiteral(moduleSpecifier, quotePreference); + let statements; + if (defaultImport !== void 0 || (namedImports == null ? void 0 : namedImports.length)) { + const topLevelTypeOnly = (!defaultImport || needsTypeOnly(defaultImport)) && every(namedImports, needsTypeOnly) || compilerOptions.verbatimModuleSyntax && (defaultImport == null ? void 0 : defaultImport.addAsTypeOnly) !== 4 /* NotAllowed */ && !some(namedImports, (i)=>i.addAsTypeOnly === 4 /* NotAllowed */ ); + statements = combine(statements, makeImport(defaultImport && factory.createIdentifier(defaultImport.name), namedImports == null ? void 0 : namedImports.map(({ addAsTypeOnly: addAsTypeOnly, name: name })=>factory.createImportSpecifier(!topLevelTypeOnly && addAsTypeOnly === 2 /* Required */ , /*propertyName*/ void 0, factory.createIdentifier(name))), moduleSpecifier, quotePreference, topLevelTypeOnly)); } - }); - // src/services/codefixes/requireInTs.ts - function doChange26(changes, sourceFile, info) { - const { allowSyntheticDefaults: allowSyntheticDefaults , defaultImportName: defaultImportName , namedImports: namedImports , statement: statement , required: required } = info; - changes.replaceNode(sourceFile, statement, defaultImportName && !allowSyntheticDefaults ? factory.createImportEqualsDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, defaultImportName, factory.createExternalModuleReference(required)) : factory.createImportDeclaration(/*modifiers*/ void 0, factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, namedImports), required, /*assertClause*/ void 0)); + if (namespaceLikeImport) { + const declaration = namespaceLikeImport.importKind === 3 /* CommonJS */ ? factory.createImportEqualsDeclaration(/*modifiers*/ void 0, needsTypeOnly(namespaceLikeImport), factory.createIdentifier(namespaceLikeImport.name), factory.createExternalModuleReference(quotedModuleSpecifier)) : factory.createImportDeclaration(/*modifiers*/ void 0, factory.createImportClause(needsTypeOnly(namespaceLikeImport), /*name*/ void 0, factory.createNamespaceImport(factory.createIdentifier(namespaceLikeImport.name))), quotedModuleSpecifier, /*assertClause*/ void 0); + statements = combine(statements, declaration); + } + return Debug.checkDefined(statements); } - function getInfo14(sourceFile, program, pos) { - const { parent: parent2 } = getTokenAtPosition(sourceFile, pos); - if (!isRequireCall(parent2, /*checkArgumentIsStringLiteralLike*/ true)) throw Debug.failBadSyntaxKind(parent2); - const decl = cast(parent2.parent, isVariableDeclaration); - const defaultImportName = tryCast(decl.name, isIdentifier); - const namedImports = isObjectBindingPattern(decl.name) ? tryCreateNamedImportsFromObjectBindingPattern(decl.name) : void 0; - if (defaultImportName || namedImports) return { - allowSyntheticDefaults: getAllowSyntheticDefaultImports(program.getCompilerOptions()), - defaultImportName: defaultImportName, - namedImports: namedImports, - statement: cast(decl.parent.parent, isVariableStatement), - required: first(parent2.arguments) - }; + function getNewRequires(moduleSpecifier, quotePreference, defaultImport, namedImports, namespaceLikeImport) { + const quotedModuleSpecifier = makeStringLiteral(moduleSpecifier, quotePreference); + let statements; + if (defaultImport || (namedImports == null ? void 0 : namedImports.length)) { + const bindingElements = (namedImports == null ? void 0 : namedImports.map(({ name: name })=>factory.createBindingElement(/*dotDotDotToken*/ void 0, /*propertyName*/ void 0, name))) || []; + if (defaultImport) bindingElements.unshift(factory.createBindingElement(/*dotDotDotToken*/ void 0, "default", defaultImport.name)); + const declaration = createConstEqualsRequireDeclaration(factory.createObjectBindingPattern(bindingElements), quotedModuleSpecifier); + statements = combine(statements, declaration); + } + if (namespaceLikeImport) { + const declaration = createConstEqualsRequireDeclaration(namespaceLikeImport.name, quotedModuleSpecifier); + statements = combine(statements, declaration); + } + return Debug.checkDefined(statements); } - function tryCreateNamedImportsFromObjectBindingPattern(node) { - const importSpecifiers = []; - for (const element of node.elements){ - if (!isIdentifier(element.name) || element.initializer) return void 0; - importSpecifiers.push(factory.createImportSpecifier(/*isTypeOnly*/ false, tryCast(element.propertyName, isIdentifier), element.name)); + function createConstEqualsRequireDeclaration(name, quotedModuleSpecifier) { + return factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ + factory.createVariableDeclaration(typeof name === "string" ? factory.createIdentifier(name) : name, /*exclamationToken*/ void 0, /*type*/ void 0, factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ void 0, [ + quotedModuleSpecifier + ])) + ], 2 /* Const */ )); + } + function symbolHasMeaning({ declarations: declarations }, meaning) { + return some(declarations, (decl)=>!!(getMeaningFromDeclaration(decl) & meaning)); + } + function moduleSymbolToValidIdentifier(moduleSymbol, target, forceCapitalize) { + return moduleSpecifierToValidIdentifier(removeFileExtension(stripQuotes(moduleSymbol.name)), target, forceCapitalize); + } + function moduleSpecifierToValidIdentifier(moduleSpecifier, target, forceCapitalize) { + const baseName = getBaseFileName(removeSuffix(moduleSpecifier, "/index")); + let res = ""; + let lastCharWasValid = true; + const firstCharCode = baseName.charCodeAt(0); + if (isIdentifierStart(firstCharCode, target)) { + res += String.fromCharCode(firstCharCode); + if (forceCapitalize) res = res.toUpperCase(); + } else lastCharWasValid = false; + for(let i = 1; i < baseName.length; i++){ + const ch = baseName.charCodeAt(i); + const isValid = isIdentifierPart(ch, target); + if (isValid) { + let char = String.fromCharCode(ch); + if (!lastCharWasValid) char = char.toUpperCase(); + res += char; + } + lastCharWasValid = isValid; } - if (importSpecifiers.length) return factory.createNamedImports(importSpecifiers); + return !isStringANonContextualKeyword(res) ? res || "_" : `_${res}`; } - var fixId40, errorCodes51; - var init_requireInTs = __esm({ - "src/services/codefixes/requireInTs.ts" () { + var importFixName, importFixId, errorCodes18; + var init_importFixes = __esm({ + "src/services/codefixes/importFixes.ts" () { "use strict"; init_ts4(); init_ts_codefix(); - fixId40 = "requireInTs"; - errorCodes51 = [ - Diagnostics.require_call_may_be_converted_to_an_import.code + importFixName = "import"; + importFixId = "fixMissingImport"; + errorCodes18 = [ + Diagnostics.Cannot_find_name_0.code, + Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, + Diagnostics.Cannot_find_namespace_0.code, + Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code, + Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code, + Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer.code, + Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type.code ]; registerCodeFix({ - errorCodes: errorCodes51, + errorCodes: errorCodes18, getCodeActions (context) { - const info = getInfo14(context.sourceFile, context.program, context.span.start); + const { errorCode: errorCode, preferences: preferences, sourceFile: sourceFile, span: span, program: program } = context; + const info = getFixInfos(context, errorCode, span.start, /*useAutoImportProvider*/ true); if (!info) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange26(t, context.sourceFile, info)); - return [ - createCodeFixAction(fixId40, changes, Diagnostics.Convert_require_to_import, fixId40, Diagnostics.Convert_all_require_to_import) - ]; + return info.map(({ fix: fix, symbolName: symbolName2, errorIdentifierText: errorIdentifierText })=>codeActionForFix(context, sourceFile, symbolName2, fix, /*includeSymbolNameInDescription*/ symbolName2 !== errorIdentifierText, program.getCompilerOptions(), preferences)); }, fixIds: [ - fixId40 + importFixId ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes51, (changes, diag2)=>{ - const info = getInfo14(diag2.file, context.program, diag2.start); - if (info) doChange26(changes, context.sourceFile, info); - }) + getAllCodeActions: (context)=>{ + const { sourceFile: sourceFile, program: program, preferences: preferences, host: host, cancellationToken: cancellationToken } = context; + const importAdder = createImportAdderWorker(sourceFile, program, /*useAutoImportProvider*/ true, preferences, host, cancellationToken); + eachDiagnostic(context, errorCodes18, (diag2)=>importAdder.addImportFromDiagnostic(diag2, context)); + return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, importAdder.writeFixes)); + } }); } }); - // src/services/codefixes/useDefaultImport.ts - function getInfo15(sourceFile, pos) { - const name = getTokenAtPosition(sourceFile, pos); - if (!isIdentifier(name)) return void 0; - const { parent: parent2 } = name; - if (isImportEqualsDeclaration(parent2) && isExternalModuleReference(parent2.moduleReference)) return { - importNode: parent2, - name: name, - moduleSpecifier: parent2.moduleReference.expression - }; - else if (isNamespaceImport(parent2)) { - const importNode = parent2.parent.parent; + // src/services/codefixes/fixAddMissingConstraint.ts + function getInfo6(program, sourceFile, span) { + const diag2 = find(program.getSemanticDiagnostics(sourceFile), (diag3)=>diag3.start === span.start && diag3.length === span.length); + if (diag2 === void 0 || diag2.relatedInformation === void 0) return; + const related = find(diag2.relatedInformation, (related2)=>related2.code === Diagnostics.This_type_parameter_might_need_an_extends_0_constraint.code); + if (related === void 0 || related.file === void 0 || related.start === void 0 || related.length === void 0) return; + let declaration = findAncestorMatchingSpan(related.file, createTextSpan(related.start, related.length)); + if (declaration === void 0) return; + if (isIdentifier(declaration) && isTypeParameterDeclaration(declaration.parent)) declaration = declaration.parent; + if (isTypeParameterDeclaration(declaration)) { + if (isMappedTypeNode(declaration.parent)) return; + const token = getTokenAtPosition(sourceFile, span.start); + const checker = program.getTypeChecker(); + const constraint = tryGetConstraintType(checker, token) || tryGetConstraintFromDiagnosticMessage(related.messageText); return { - importNode: importNode, - name: name, - moduleSpecifier: importNode.moduleSpecifier + constraint: constraint, + declaration: declaration, + token: token }; } + return void 0; } - function doChange27(changes, sourceFile, info, preferences) { - changes.replaceNode(sourceFile, info.importNode, makeImport(info.name, /*namedImports*/ void 0, info.moduleSpecifier, getQuotePreference(sourceFile, preferences))); - } - var fixId41, errorCodes52; - var init_useDefaultImport = __esm({ - "src/services/codefixes/useDefaultImport.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId41 = "useDefaultImport"; - errorCodes52 = [ - Diagnostics.Import_may_be_converted_to_a_default_import.code - ]; - registerCodeFix({ - errorCodes: errorCodes52, - getCodeActions (context) { - const { sourceFile: sourceFile , span: { start: start } } = context; - const info = getInfo15(sourceFile, start); - if (!info) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange27(t, sourceFile, info, context.preferences)); - return [ - createCodeFixAction(fixId41, changes, Diagnostics.Convert_to_default_import, fixId41, Diagnostics.Convert_all_to_default_imports) - ]; - }, - fixIds: [ - fixId41 - ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes52, (changes, diag2)=>{ - const info = getInfo15(diag2.file, diag2.start); - if (info) doChange27(changes, diag2.file, info, context.preferences); - }) + function addMissingConstraint(changes, program, preferences, host, sourceFile, info) { + const { declaration: declaration, constraint: constraint } = info; + const checker = program.getTypeChecker(); + if (isString(constraint)) changes.insertText(sourceFile, declaration.name.end, ` extends ${constraint}`); + else { + const scriptTarget = getEmitScriptTarget(program.getCompilerOptions()); + const tracker = getNoopSymbolTrackerWithResolver({ + program: program, + host: host }); + const importAdder = createImportAdder(sourceFile, program, preferences, host); + const typeNode = typeToAutoImportableTypeNode(checker, importAdder, constraint, /*contextNode*/ void 0, scriptTarget, /*flags*/ void 0, tracker); + if (typeNode) { + changes.replaceNode(sourceFile, declaration, factory.updateTypeParameterDeclaration(declaration, /*modifiers*/ void 0, declaration.name, typeNode, declaration.default)); + importAdder.writeFixes(changes); + } } - }); - // src/services/codefixes/useBigintLiteral.ts - function makeChange9(changeTracker, sourceFile, span) { - const numericLiteral = tryCast(getTokenAtPosition(sourceFile, span.start), isNumericLiteral); - if (!numericLiteral) return; - const newText = numericLiteral.getText(sourceFile) + "n"; - changeTracker.replaceNode(sourceFile, numericLiteral, factory.createBigIntLiteral(newText)); } - var fixId42, errorCodes53; - var init_useBigintLiteral = __esm({ - "src/services/codefixes/useBigintLiteral.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId42 = "useBigintLiteral"; - errorCodes53 = [ - Diagnostics.Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers.code - ]; - registerCodeFix({ - errorCodes: errorCodes53, - getCodeActions: function getCodeActionsToUseBigintLiteral(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>makeChange9(t, context.sourceFile, context.span)); - if (changes.length > 0) return [ - createCodeFixAction(fixId42, changes, Diagnostics.Convert_to_a_bigint_numeric_literal, fixId42, Diagnostics.Convert_all_to_bigint_numeric_literals) - ]; - }, - fixIds: [ - fixId42 - ], - getAllCodeActions: (context)=>{ - return codeFixAll(context, errorCodes53, (changes, diag2)=>makeChange9(changes, diag2.file, diag2)); - } - }); - } - }); - // src/services/codefixes/fixAddModuleReferTypeMissingTypeof.ts - function getImportTypeNode(sourceFile, pos) { - const token = getTokenAtPosition(sourceFile, pos); - Debug.assert(token.kind === 100 /* ImportKeyword */ , "This token should be an ImportKeyword"); - Debug.assert(token.parent.kind === 202 /* ImportType */ , "Token parent should be an ImportType"); - return token.parent; + function tryGetConstraintFromDiagnosticMessage(messageText) { + const [_, constraint] = flattenDiagnosticMessageText(messageText, "\n", 0).match(/`extends (.*)`/) || []; + return constraint; } - function doChange28(changes, sourceFile, importType) { - const newTypeNode = factory.updateImportTypeNode(importType, importType.argument, importType.assertions, importType.qualifier, importType.typeArguments, /* isTypeOf */ true); - changes.replaceNode(sourceFile, importType, newTypeNode); + function tryGetConstraintType(checker, node) { + if (isTypeNode(node.parent)) return checker.getTypeArgumentConstraint(node.parent); + const contextualType = isExpression(node) ? checker.getContextualType(node) : void 0; + return contextualType || checker.getTypeAtLocation(node); } - var fixIdAddMissingTypeof, fixId43, errorCodes54; - var init_fixAddModuleReferTypeMissingTypeof = __esm({ - "src/services/codefixes/fixAddModuleReferTypeMissingTypeof.ts" () { + var fixId17, errorCodes19; + var init_fixAddMissingConstraint = __esm({ + "src/services/codefixes/fixAddMissingConstraint.ts" () { "use strict"; init_ts4(); init_ts_codefix(); - fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof"; - fixId43 = fixIdAddMissingTypeof; - errorCodes54 = [ - Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0.code + fixId17 = "addMissingConstraint"; + errorCodes19 = [ + // We want errors this could be attached to: + // Diagnostics.This_type_parameter_probably_needs_an_extends_0_constraint + Diagnostics.Type_0_is_not_comparable_to_type_1.code, + Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code, + Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, + Diagnostics.Type_0_is_not_assignable_to_type_1.code, + Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, + Diagnostics.Property_0_is_incompatible_with_index_signature.code, + Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code, + Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code ]; registerCodeFix({ - errorCodes: errorCodes54, - getCodeActions: function getCodeActionsToAddMissingTypeof(context) { - const { sourceFile: sourceFile , span: span } = context; - const importType = getImportTypeNode(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange28(t, sourceFile, importType)); + errorCodes: errorCodes19, + getCodeActions (context) { + const { sourceFile: sourceFile, span: span, program: program, preferences: preferences, host: host } = context; + const info = getInfo6(program, sourceFile, span); + if (info === void 0) return; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addMissingConstraint(t, program, preferences, host, sourceFile, info)); return [ - createCodeFixAction(fixId43, changes, Diagnostics.Add_missing_typeof, fixId43, Diagnostics.Add_missing_typeof) + createCodeFixAction(fixId17, changes, Diagnostics.Add_extends_constraint, fixId17, Diagnostics.Add_extends_constraint_to_all_type_parameters) ]; }, fixIds: [ - fixId43 + fixId17 ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes54, (changes, diag2)=>doChange28(changes, context.sourceFile, getImportTypeNode(diag2.file, diag2.start))) + getAllCodeActions: (context)=>{ + const { program: program, preferences: preferences, host: host } = context; + const seen = /* @__PURE__ */ new Map(); + return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes)=>{ + eachDiagnostic(context, errorCodes19, (diag2)=>{ + const info = getInfo6(program, diag2.file, createTextSpan(diag2.start, diag2.length)); + if (info) { + if (addToSeen(seen, getNodeId(info.declaration))) return addMissingConstraint(changes, program, preferences, host, diag2.file, info); + } + return void 0; + }); + })); + } }); } }); - // src/services/codefixes/wrapJsxInFragment.ts - function findNodeToFix(sourceFile, pos) { - const lessThanToken = getTokenAtPosition(sourceFile, pos); - const firstJsxElementOrOpenElement = lessThanToken.parent; - let binaryExpr = firstJsxElementOrOpenElement.parent; - if (!isBinaryExpression(binaryExpr)) { - binaryExpr = binaryExpr.parent; - if (!isBinaryExpression(binaryExpr)) return void 0; + // src/services/codefixes/fixOverrideModifier.ts + function dispatchChanges(changeTracker, context, errorCode, pos) { + switch(errorCode){ + case Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code: + case Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code: + case Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code: + case Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code: + case Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code: + return doAddOverrideModifierChange(changeTracker, context.sourceFile, pos); + case Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code: + case Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code: + case Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code: + case Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code: + return doRemoveOverrideModifierChange(changeTracker, context.sourceFile, pos); + default: + Debug.fail("Unexpected error code: " + errorCode); } - if (!nodeIsMissing(binaryExpr.operatorToken)) return void 0; - return binaryExpr; } - function doChange29(changeTracker, sf, node) { - const jsx = flattenInvalidBinaryExpr(node); - if (jsx) changeTracker.replaceNode(sf, node, factory.createJsxFragment(factory.createJsxOpeningFragment(), jsx, factory.createJsxJsxClosingFragment())); + function doAddOverrideModifierChange(changeTracker, sourceFile, pos) { + const classElement = findContainerClassElementLike(sourceFile, pos); + if (isSourceFileJS(sourceFile)) { + changeTracker.addJSDocTags(sourceFile, classElement, [ + factory.createJSDocOverrideTag(factory.createIdentifier("override")) + ]); + return; + } + const modifiers = classElement.modifiers || emptyArray; + const staticModifier = find(modifiers, isStaticModifier); + const abstractModifier = find(modifiers, isAbstractModifier); + const accessibilityModifier = find(modifiers, (m)=>isAccessibilityModifier(m.kind)); + const lastDecorator = findLast(modifiers, isDecorator); + const modifierPos = abstractModifier ? abstractModifier.end : staticModifier ? staticModifier.end : accessibilityModifier ? accessibilityModifier.end : lastDecorator ? skipTrivia(sourceFile.text, lastDecorator.end) : classElement.getStart(sourceFile); + const options = accessibilityModifier || staticModifier || abstractModifier ? { + prefix: " " + } : { + suffix: " " + }; + changeTracker.insertModifierAt(sourceFile, modifierPos, 164 /* OverrideKeyword */ , options); } - function flattenInvalidBinaryExpr(node) { - const children = []; - let current = node; - while(true){ - if (isBinaryExpression(current) && nodeIsMissing(current.operatorToken) && current.operatorToken.kind === 27 /* CommaToken */ ) { - children.push(current.left); - if (isJsxChild(current.right)) { - children.push(current.right); - return children; - } else if (isBinaryExpression(current.right)) { - current = current.right; - continue; - } else return void 0; - } else return void 0; + function doRemoveOverrideModifierChange(changeTracker, sourceFile, pos) { + const classElement = findContainerClassElementLike(sourceFile, pos); + if (isSourceFileJS(sourceFile)) { + changeTracker.filterJSDocTags(sourceFile, classElement, not(isJSDocOverrideTag)); + return; } + const overrideModifier = find(classElement.modifiers, isOverrideModifier); + Debug.assertIsDefined(overrideModifier); + changeTracker.deleteModifier(sourceFile, overrideModifier); } - var fixID2, errorCodes55; - var init_wrapJsxInFragment = __esm({ - "src/services/codefixes/wrapJsxInFragment.ts" () { + function isClassElementLikeHasJSDoc(node) { + switch(node.kind){ + case 176 /* Constructor */ : + case 172 /* PropertyDeclaration */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + return true; + case 169 /* Parameter */ : + return isParameterPropertyDeclaration(node, node.parent); + default: + return false; + } + } + function findContainerClassElementLike(sourceFile, pos) { + const token = getTokenAtPosition(sourceFile, pos); + const classElement = findAncestor(token, (node)=>{ + if (isClassLike(node)) return "quit"; + return isClassElementLikeHasJSDoc(node); + }); + Debug.assert(classElement && isClassElementLikeHasJSDoc(classElement)); + return classElement; + } + var fixName, fixAddOverrideId, fixRemoveOverrideId, errorCodes20, errorCodeFixIdMap; + var init_fixOverrideModifier = __esm({ + "src/services/codefixes/fixOverrideModifier.ts" () { "use strict"; init_ts4(); init_ts_codefix(); - fixID2 = "wrapJsxInFragment"; - errorCodes55 = [ - Diagnostics.JSX_expressions_must_have_one_parent_element.code + fixName = "fixOverrideModifier"; + fixAddOverrideId = "fixAddOverrideModifier"; + fixRemoveOverrideId = "fixRemoveOverrideModifier"; + errorCodes20 = [ + Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code, + Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code, + Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code, + Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code, + Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code, + Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code, + Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code, + Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code, + Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code ]; + errorCodeFixIdMap = { + // case #1: + [Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code]: { + descriptions: Diagnostics.Add_override_modifier, + fixId: fixAddOverrideId, + fixAllDescriptions: Diagnostics.Add_all_missing_override_modifiers + }, + [Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code]: { + descriptions: Diagnostics.Add_override_modifier, + fixId: fixAddOverrideId, + fixAllDescriptions: Diagnostics.Add_all_missing_override_modifiers + }, + // case #2: + [Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code]: { + descriptions: Diagnostics.Remove_override_modifier, + fixId: fixRemoveOverrideId, + fixAllDescriptions: Diagnostics.Remove_all_unnecessary_override_modifiers + }, + [Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code]: { + descriptions: Diagnostics.Remove_override_modifier, + fixId: fixRemoveOverrideId, + fixAllDescriptions: Diagnostics.Remove_override_modifier + }, + // case #3: + [Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code]: { + descriptions: Diagnostics.Add_override_modifier, + fixId: fixAddOverrideId, + fixAllDescriptions: Diagnostics.Add_all_missing_override_modifiers + }, + [Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code]: { + descriptions: Diagnostics.Add_override_modifier, + fixId: fixAddOverrideId, + fixAllDescriptions: Diagnostics.Add_all_missing_override_modifiers + }, + // case #4: + [Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code]: { + descriptions: Diagnostics.Add_override_modifier, + fixId: fixAddOverrideId, + fixAllDescriptions: Diagnostics.Remove_all_unnecessary_override_modifiers + }, + // case #5: + [Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code]: { + descriptions: Diagnostics.Remove_override_modifier, + fixId: fixRemoveOverrideId, + fixAllDescriptions: Diagnostics.Remove_all_unnecessary_override_modifiers + }, + [Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code]: { + descriptions: Diagnostics.Remove_override_modifier, + fixId: fixRemoveOverrideId, + fixAllDescriptions: Diagnostics.Remove_all_unnecessary_override_modifiers + } + }; registerCodeFix({ - errorCodes: errorCodes55, - getCodeActions: function getCodeActionsToWrapJsxInFragment(context) { - const { sourceFile: sourceFile , span: span } = context; - const node = findNodeToFix(sourceFile, span.start); - if (!node) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange29(t, sourceFile, node)); + errorCodes: errorCodes20, + getCodeActions: function getCodeActionsToFixOverrideModifierIssues(context) { + const { errorCode: errorCode, span: span } = context; + const info = errorCodeFixIdMap[errorCode]; + if (!info) return emptyArray; + const { descriptions: descriptions, fixId: fixId52, fixAllDescriptions: fixAllDescriptions } = info; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2)=>dispatchChanges(changes2, context, errorCode, span.start)); return [ - createCodeFixAction(fixID2, changes, Diagnostics.Wrap_in_JSX_fragment, fixID2, Diagnostics.Wrap_all_unparented_JSX_in_JSX_fragment) + createCodeFixActionMaybeFixAll(fixName, changes, descriptions, fixId52, fixAllDescriptions) ]; }, fixIds: [ - fixID2 + fixName, + fixAddOverrideId, + fixRemoveOverrideId ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes55, (changes, diag2)=>{ - const node = findNodeToFix(context.sourceFile, diag2.start); - if (!node) return void 0; - doChange29(changes, context.sourceFile, node); + getAllCodeActions: (context)=>codeFixAll(context, errorCodes20, (changes, diag2)=>{ + const { code: code, start: start } = diag2; + const info = errorCodeFixIdMap[code]; + if (!info || info.fixId !== context.fixId) return; + dispatchChanges(changes, context, code, start); }) }); } }); - // src/services/codefixes/convertToMappedObjectType.ts - function getInfo16(sourceFile, pos) { - const token = getTokenAtPosition(sourceFile, pos); - const indexSignature = tryCast(token.parent.parent, isIndexSignatureDeclaration); - if (!indexSignature) return void 0; - const container = isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : tryCast(indexSignature.parent.parent, isTypeAliasDeclaration); - if (!container) return void 0; - return { - indexSignature: indexSignature, - container: container - }; - } - function createTypeAliasFromInterface(declaration, type) { - return factory.createTypeAliasDeclaration(declaration.modifiers, declaration.name, declaration.typeParameters, type); + // src/services/codefixes/fixNoPropertyAccessFromIndexSignature.ts + function doChange14(changes, sourceFile, node, preferences) { + const quotePreference = getQuotePreference(sourceFile, preferences); + const argumentsExpression = factory.createStringLiteral(node.name.text, quotePreference === 0 /* Single */ ); + changes.replaceNode(sourceFile, node, isPropertyAccessChain(node) ? factory.createElementAccessChain(node.expression, node.questionDotToken, argumentsExpression) : factory.createElementAccessExpression(node.expression, argumentsExpression)); } - function doChange30(changes, sourceFile, { indexSignature: indexSignature , container: container }) { - const members = isInterfaceDeclaration(container) ? container.members : container.type.members; - const otherMembers = members.filter((member)=>!isIndexSignatureDeclaration(member)); - const parameter = first(indexSignature.parameters); - const mappedTypeParameter = factory.createTypeParameterDeclaration(/*modifiers*/ void 0, cast(parameter.name, isIdentifier), parameter.type); - const mappedIntersectionType = factory.createMappedTypeNode(hasEffectiveReadonlyModifier(indexSignature) ? factory.createModifier(146 /* ReadonlyKeyword */ ) : void 0, mappedTypeParameter, /*nameType*/ void 0, indexSignature.questionToken, indexSignature.type, /*members*/ void 0); - const intersectionType = factory.createIntersectionTypeNode([ - ...getAllSuperTypeNodes(container), - mappedIntersectionType, - ...otherMembers.length ? [ - factory.createTypeLiteralNode(otherMembers) - ] : emptyArray - ]); - changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType)); + function getPropertyAccessExpression(sourceFile, pos) { + return cast(getTokenAtPosition(sourceFile, pos).parent, isPropertyAccessExpression); } - var fixId44, errorCodes56; - var init_convertToMappedObjectType = __esm({ - "src/services/codefixes/convertToMappedObjectType.ts" () { + var fixId18, errorCodes21; + var init_fixNoPropertyAccessFromIndexSignature = __esm({ + "src/services/codefixes/fixNoPropertyAccessFromIndexSignature.ts" () { "use strict"; init_ts4(); init_ts_codefix(); - fixId44 = "fixConvertToMappedObjectType"; - errorCodes56 = [ - Diagnostics.An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_object_type_instead.code + fixId18 = "fixNoPropertyAccessFromIndexSignature"; + errorCodes21 = [ + Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0.code ]; registerCodeFix({ - errorCodes: errorCodes56, - getCodeActions: function getCodeActionsToConvertToMappedTypeObject(context) { - const { sourceFile: sourceFile , span: span } = context; - const info = getInfo16(sourceFile, span.start); - if (!info) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange30(t, sourceFile, info)); - const name = idText(info.container.name); - return [ - createCodeFixAction(fixId44, changes, [ - Diagnostics.Convert_0_to_mapped_object_type, - name - ], fixId44, [ - Diagnostics.Convert_0_to_mapped_object_type, - name - ]) - ]; - }, + errorCodes: errorCodes21, fixIds: [ - fixId44 + fixId18 ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes56, (changes, diag2)=>{ - const info = getInfo16(diag2.file, diag2.start); - if (info) doChange30(changes, diag2.file, info); - }) - }); - } - }); - // src/services/codefixes/removeAccidentalCallParentheses.ts - var fixId45, errorCodes57; - var init_removeAccidentalCallParentheses = __esm({ - "src/services/codefixes/removeAccidentalCallParentheses.ts" () { - "use strict"; - init_ts4(); - init_ts_codefix(); - fixId45 = "removeAccidentalCallParentheses"; - errorCodes57 = [ - Diagnostics.This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without.code - ]; - registerCodeFix({ - errorCodes: errorCodes57, getCodeActions (context) { - const callExpression = findAncestor(getTokenAtPosition(context.sourceFile, context.span.start), isCallExpression); - if (!callExpression) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>{ - t.deleteRange(context.sourceFile, { - pos: callExpression.expression.end, - end: callExpression.end - }); - }); + const { sourceFile: sourceFile, span: span, preferences: preferences } = context; + const property = getPropertyAccessExpression(sourceFile, span.start); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange14(t, context.sourceFile, property, preferences)); return [ - createCodeFixActionWithoutFixAll(fixId45, changes, Diagnostics.Remove_parentheses) + createCodeFixAction(fixId18, changes, [ + Diagnostics.Use_element_access_for_0, + property.name.text + ], fixId18, Diagnostics.Use_element_access_for_all_undeclared_properties) ]; }, - fixIds: [ - fixId45 - ] + getAllCodeActions: (context)=>codeFixAll(context, errorCodes21, (changes, diag2)=>doChange14(changes, diag2.file, getPropertyAccessExpression(diag2.file, diag2.start), context.preferences)) }); } }); - // src/services/codefixes/removeUnnecessaryAwait.ts - function makeChange10(changeTracker, sourceFile, span) { - const awaitKeyword = tryCast(getTokenAtPosition(sourceFile, span.start), (node)=>node.kind === 133 /* AwaitKeyword */ ); - const awaitExpression = awaitKeyword && tryCast(awaitKeyword.parent, isAwaitExpression); - if (!awaitExpression) return; - let expressionToReplace = awaitExpression; - const hasSurroundingParens = isParenthesizedExpression(awaitExpression.parent); - if (hasSurroundingParens) { - const leftMostExpression = getLeftmostExpression(awaitExpression.expression, /*stopAtCallExpressions*/ false); - if (isIdentifier(leftMostExpression)) { - const precedingToken = findPrecedingToken(awaitExpression.parent.pos, sourceFile); - if (precedingToken && precedingToken.kind !== 103 /* NewKeyword */ ) expressionToReplace = awaitExpression.parent; + // src/services/codefixes/fixImplicitThis.ts + function doChange15(changes, sourceFile, pos, checker) { + const token = getTokenAtPosition(sourceFile, pos); + if (!isThis(token)) return void 0; + const fn = getThisContainer(token, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false); + if (!isFunctionDeclaration(fn) && !isFunctionExpression(fn)) return void 0; + if (!isSourceFile(getThisContainer(fn, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false))) { + const fnKeyword = Debug.checkDefined(findChildOfKind(fn, 100 /* FunctionKeyword */ , sourceFile)); + const { name: name } = fn; + const body = Debug.checkDefined(fn.body); + if (isFunctionExpression(fn)) { + if (name && ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(name, checker, sourceFile, body)) return void 0; + changes.delete(sourceFile, fnKeyword); + if (name) changes.delete(sourceFile, name); + changes.insertText(sourceFile, body.pos, " =>"); + return [ + Diagnostics.Convert_function_expression_0_to_arrow_function, + name ? name.text : ANONYMOUS + ]; + } else { + changes.replaceNode(sourceFile, fnKeyword, factory.createToken(87 /* ConstKeyword */ )); + changes.insertText(sourceFile, name.end, " = "); + changes.insertText(sourceFile, body.pos, " =>"); + return [ + Diagnostics.Convert_function_declaration_0_to_arrow_function, + name.text + ]; } } - changeTracker.replaceNode(sourceFile, expressionToReplace, awaitExpression.expression); } - var fixId46, errorCodes58; - var init_removeUnnecessaryAwait = __esm({ - "src/services/codefixes/removeUnnecessaryAwait.ts" () { + var fixId19, errorCodes22; + var init_fixImplicitThis = __esm({ + "src/services/codefixes/fixImplicitThis.ts" () { "use strict"; init_ts4(); init_ts_codefix(); - fixId46 = "removeUnnecessaryAwait"; - errorCodes58 = [ - Diagnostics.await_has_no_effect_on_the_type_of_this_expression.code + fixId19 = "fixImplicitThis"; + errorCodes22 = [ + Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code ]; registerCodeFix({ - errorCodes: errorCodes58, - getCodeActions: function getCodeActionsToRemoveUnnecessaryAwait(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>makeChange10(t, context.sourceFile, context.span)); - if (changes.length > 0) return [ - createCodeFixAction(fixId46, changes, Diagnostics.Remove_unnecessary_await, fixId46, Diagnostics.Remove_all_unnecessary_uses_of_await) - ]; + errorCodes: errorCodes22, + getCodeActions: function getCodeActionsToFixImplicitThis(context) { + const { sourceFile: sourceFile, program: program, span: span } = context; + let diagnostic; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>{ + diagnostic = doChange15(t, sourceFile, span.start, program.getTypeChecker()); + }); + return diagnostic ? [ + createCodeFixAction(fixId19, changes, diagnostic, fixId19, Diagnostics.Fix_all_implicit_this_errors) + ] : emptyArray; }, fixIds: [ - fixId46 + fixId19 ], - getAllCodeActions: (context)=>{ - return codeFixAll(context, errorCodes58, (changes, diag2)=>makeChange10(changes, diag2.file, diag2)); - } + getAllCodeActions: (context)=>codeFixAll(context, errorCodes22, (changes, diag2)=>{ + doChange15(changes, diag2.file, diag2.start, context.program.getTypeChecker()); + }) }); } }); - // src/services/codefixes/splitTypeOnlyImport.ts - function getImportDeclaration2(sourceFile, span) { - return findAncestor(getTokenAtPosition(sourceFile, span.start), isImportDeclaration); + // src/services/codefixes/fixImportNonExportedMember.ts + function getInfo7(sourceFile, pos, program) { + var _a; + const token = getTokenAtPosition(sourceFile, pos); + if (isIdentifier(token)) { + const importDeclaration = findAncestor(token, isImportDeclaration); + if (importDeclaration === void 0) return void 0; + const moduleSpecifier = isStringLiteral(importDeclaration.moduleSpecifier) ? importDeclaration.moduleSpecifier.text : void 0; + if (moduleSpecifier === void 0) return void 0; + const resolvedModule = getResolvedModule(sourceFile, moduleSpecifier, /*mode*/ void 0); + if (resolvedModule === void 0) return void 0; + const moduleSourceFile = program.getSourceFile(resolvedModule.resolvedFileName); + if (moduleSourceFile === void 0 || isSourceFileFromLibrary(program, moduleSourceFile)) return void 0; + const moduleSymbol = moduleSourceFile.symbol; + const locals = (_a = tryCast(moduleSymbol.valueDeclaration, canHaveLocals)) == null ? void 0 : _a.locals; + if (locals === void 0) return void 0; + const localSymbol = locals.get(token.escapedText); + if (localSymbol === void 0) return void 0; + const node = getNodeOfSymbol(localSymbol); + if (node === void 0) return void 0; + const exportName = { + node: token, + isTypeOnly: isTypeDeclaration(node) + }; + return { + exportName: exportName, + node: node, + moduleSourceFile: moduleSourceFile, + moduleSpecifier: moduleSpecifier + }; + } + return void 0; } - function splitTypeOnlyImport(changes, importDeclaration, context) { - if (!importDeclaration) return; - const importClause = Debug.checkDefined(importDeclaration.importClause); - changes.replaceNode(context.sourceFile, importDeclaration, factory.updateImportDeclaration(importDeclaration, importDeclaration.modifiers, factory.updateImportClause(importClause, importClause.isTypeOnly, importClause.name, /*namedBindings*/ void 0), importDeclaration.moduleSpecifier, importDeclaration.assertClause)); - changes.insertNodeAfter(context.sourceFile, importDeclaration, factory.createImportDeclaration(/*modifiers*/ void 0, factory.updateImportClause(importClause, importClause.isTypeOnly, /*name*/ void 0, importClause.namedBindings), importDeclaration.moduleSpecifier, importDeclaration.assertClause)); + function doChange16(changes, program, { exportName: exportName, node: node, moduleSourceFile: moduleSourceFile }) { + const exportDeclaration = tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly); + if (exportDeclaration) updateExport(changes, program, moduleSourceFile, exportDeclaration, [ + exportName + ]); + else if (canHaveExportModifier(node)) changes.insertExportModifier(moduleSourceFile, node); + else createExport(changes, program, moduleSourceFile, [ + exportName + ]); } - var errorCodes59, fixId47; - var init_splitTypeOnlyImport = __esm({ - "src/services/codefixes/splitTypeOnlyImport.ts" () { + function doChanges(changes, program, sourceFile, moduleExports, node) { + if (length(moduleExports)) { + if (node) updateExport(changes, program, sourceFile, node, moduleExports); + else createExport(changes, program, sourceFile, moduleExports); + } + } + function tryGetExportDeclaration(sourceFile, isTypeOnly) { + const predicate = (node)=>isExportDeclaration(node) && (isTypeOnly && node.isTypeOnly || !node.isTypeOnly); + return findLast(sourceFile.statements, predicate); + } + function updateExport(changes, program, sourceFile, node, names) { + const namedExports = node.exportClause && isNamedExports(node.exportClause) ? node.exportClause.elements : factory.createNodeArray([]); + const allowTypeModifier = !node.isTypeOnly && !!(getIsolatedModules(program.getCompilerOptions()) || find(namedExports, (e)=>e.isTypeOnly)); + changes.replaceNode(sourceFile, node, factory.updateExportDeclaration(node, node.modifiers, node.isTypeOnly, factory.createNamedExports(factory.createNodeArray([ + ...namedExports, + ...createExportSpecifiers(names, allowTypeModifier) + ], /*hasTrailingComma*/ namedExports.hasTrailingComma)), node.moduleSpecifier, node.assertClause)); + } + function createExport(changes, program, sourceFile, names) { + changes.insertNodeAtEndOfScope(sourceFile, sourceFile, factory.createExportDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, factory.createNamedExports(createExportSpecifiers(names, /*allowTypeModifier*/ getIsolatedModules(program.getCompilerOptions()))), /*moduleSpecifier*/ void 0, /*assertClause*/ void 0)); + } + function createExportSpecifiers(names, allowTypeModifier) { + return factory.createNodeArray(map(names, (n)=>factory.createExportSpecifier(allowTypeModifier && n.isTypeOnly, /*propertyName*/ void 0, n.node))); + } + function getNodeOfSymbol(symbol) { + if (symbol.valueDeclaration === void 0) return firstOrUndefined(symbol.declarations); + const declaration = symbol.valueDeclaration; + const variableStatement = isVariableDeclaration(declaration) ? tryCast(declaration.parent.parent, isVariableStatement) : void 0; + return variableStatement && length(variableStatement.declarationList.declarations) === 1 ? variableStatement : declaration; + } + var fixId20, errorCodes23; + var init_fixImportNonExportedMember = __esm({ + "src/services/codefixes/fixImportNonExportedMember.ts" () { "use strict"; init_ts4(); init_ts_codefix(); - errorCodes59 = [ - Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both.code + fixId20 = "fixImportNonExportedMember"; + errorCodes23 = [ + Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported.code ]; - fixId47 = "splitTypeOnlyImport"; registerCodeFix({ - errorCodes: errorCodes59, + errorCodes: errorCodes23, fixIds: [ - fixId47 + fixId20 ], - getCodeActions: function getCodeActionsToSplitTypeOnlyImport(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>{ - return splitTypeOnlyImport(t, getImportDeclaration2(context.sourceFile, context.span), context); - }); - if (changes.length) return [ - createCodeFixAction(fixId47, changes, Diagnostics.Split_into_two_separate_import_declarations, fixId47, Diagnostics.Split_all_invalid_type_only_imports) + getCodeActions (context) { + const { sourceFile: sourceFile, span: span, program: program } = context; + const info = getInfo7(sourceFile, span.start, program); + if (info === void 0) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange16(t, program, info)); + return [ + createCodeFixAction(fixId20, changes, [ + Diagnostics.Export_0_from_module_1, + info.exportName.node.text, + info.moduleSpecifier + ], fixId20, Diagnostics.Export_all_referenced_locals) ]; }, - getAllCodeActions: (context)=>codeFixAll(context, errorCodes59, (changes, error)=>{ - splitTypeOnlyImport(changes, getImportDeclaration2(context.sourceFile, error), context); - }) + getAllCodeActions (context) { + const { program: program } = context; + return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes)=>{ + const exports = /* @__PURE__ */ new Map(); + eachDiagnostic(context, errorCodes23, (diag2)=>{ + const info = getInfo7(diag2.file, diag2.start, program); + if (info === void 0) return void 0; + const { exportName: exportName, node: node, moduleSourceFile: moduleSourceFile } = info; + if (tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly) === void 0 && canHaveExportModifier(node)) changes.insertExportModifier(moduleSourceFile, node); + else { + const moduleExports = exports.get(moduleSourceFile) || { + typeOnlyExports: [], + exports: [] + }; + if (exportName.isTypeOnly) moduleExports.typeOnlyExports.push(exportName); + else moduleExports.exports.push(exportName); + exports.set(moduleSourceFile, moduleExports); + } + }); + exports.forEach((moduleExports, moduleSourceFile)=>{ + const exportDeclaration = tryGetExportDeclaration(moduleSourceFile, /*isTypeOnly*/ true); + if (exportDeclaration && exportDeclaration.isTypeOnly) { + doChanges(changes, program, moduleSourceFile, moduleExports.typeOnlyExports, exportDeclaration); + doChanges(changes, program, moduleSourceFile, moduleExports.exports, tryGetExportDeclaration(moduleSourceFile, /*isTypeOnly*/ false)); + } else doChanges(changes, program, moduleSourceFile, [ + ...moduleExports.exports, + ...moduleExports.typeOnlyExports + ], exportDeclaration); + }); + })); + } }); } }); - // src/services/codefixes/convertConstToLet.ts - function getInfo17(sourceFile, pos, program) { - var _a2; - const checker = program.getTypeChecker(); - const symbol = checker.getSymbolAtLocation(getTokenAtPosition(sourceFile, pos)); - if (symbol === void 0) return; - const declaration = tryCast((_a2 = symbol == null ? void 0 : symbol.valueDeclaration) == null ? void 0 : _a2.parent, isVariableDeclarationList); - if (declaration === void 0) return; - const constToken = findChildOfKind(declaration, 85 /* ConstKeyword */ , sourceFile); - if (constToken === void 0) return; - return { - symbol: symbol, - token: constToken - }; + // src/services/codefixes/fixIncorrectNamedTupleSyntax.ts + function getNamedTupleMember(sourceFile, pos) { + const token = getTokenAtPosition(sourceFile, pos); + return findAncestor(token, (t)=>t.kind === 202 /* NamedTupleMember */ ); } - function doChange31(changes, sourceFile, token) { - changes.replaceNode(sourceFile, token, factory.createToken(119 /* LetKeyword */ )); + function doChange17(changes, sourceFile, namedTupleMember) { + if (!namedTupleMember) return; + let unwrappedType = namedTupleMember.type; + let sawOptional = false; + let sawRest = false; + while(unwrappedType.kind === 190 /* OptionalType */ || unwrappedType.kind === 191 /* RestType */ || unwrappedType.kind === 196 /* ParenthesizedType */ ){ + if (unwrappedType.kind === 190 /* OptionalType */ ) sawOptional = true; + else if (unwrappedType.kind === 191 /* RestType */ ) sawRest = true; + unwrappedType = unwrappedType.type; + } + const updated = factory.updateNamedTupleMember(namedTupleMember, namedTupleMember.dotDotDotToken || (sawRest ? factory.createToken(26 /* DotDotDotToken */ ) : void 0), namedTupleMember.name, namedTupleMember.questionToken || (sawOptional ? factory.createToken(58 /* QuestionToken */ ) : void 0), unwrappedType); + if (updated === namedTupleMember) return; + changes.replaceNode(sourceFile, namedTupleMember, updated); } - var fixId48, errorCodes60; - var init_convertConstToLet = __esm({ - "src/services/codefixes/convertConstToLet.ts" () { + var fixId21, errorCodes24; + var init_fixIncorrectNamedTupleSyntax = __esm({ + "src/services/codefixes/fixIncorrectNamedTupleSyntax.ts" () { "use strict"; init_ts4(); init_ts_codefix(); - fixId48 = "fixConvertConstToLet"; - errorCodes60 = [ - Diagnostics.Cannot_assign_to_0_because_it_is_a_constant.code + fixId21 = "fixIncorrectNamedTupleSyntax"; + errorCodes24 = [ + Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type.code, + Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type.code ]; registerCodeFix({ - errorCodes: errorCodes60, - getCodeActions: function getCodeActionsToConvertConstToLet(context) { - const { sourceFile: sourceFile , span: span , program: program } = context; - const info = getInfo17(sourceFile, span.start, program); - if (info === void 0) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange31(t, sourceFile, info.token)); + errorCodes: errorCodes24, + getCodeActions: function getCodeActionsToFixIncorrectNamedTupleSyntax(context) { + const { sourceFile: sourceFile, span: span } = context; + const namedTupleMember = getNamedTupleMember(sourceFile, span.start); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange17(t, sourceFile, namedTupleMember)); return [ - createCodeFixActionMaybeFixAll(fixId48, changes, Diagnostics.Convert_const_to_let, fixId48, Diagnostics.Convert_all_const_to_let) + createCodeFixAction(fixId21, changes, Diagnostics.Move_labeled_tuple_element_modifiers_to_labels, fixId21, Diagnostics.Move_labeled_tuple_element_modifiers_to_labels) ]; }, - getAllCodeActions: (context)=>{ - const { program: program } = context; - const seen = /* @__PURE__ */ new Map(); - return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes)=>{ - eachDiagnostic(context, errorCodes60, (diag2)=>{ - const info = getInfo17(diag2.file, diag2.start, program); - if (info) { - if (addToSeen(seen, getSymbolId(info.symbol))) return doChange31(changes, diag2.file, info.token); - } - return void 0; - }); - })); - }, fixIds: [ - fixId48 + fixId21 ] }); } }); - // src/services/codefixes/fixExpectedComma.ts - function getInfo18(sourceFile, pos, _) { + // src/services/codefixes/fixSpelling.ts + function getInfo8(sourceFile, pos, context, errorCode) { const node = getTokenAtPosition(sourceFile, pos); - return node.kind === 26 /* SemicolonToken */ && node.parent && (isObjectLiteralExpression(node.parent) || isArrayLiteralExpression(node.parent)) ? { - node: node - } : void 0; + const parent2 = node.parent; + if ((errorCode === Diagnostics.No_overload_matches_this_call.code || errorCode === Diagnostics.Type_0_is_not_assignable_to_type_1.code) && !isJsxAttribute(parent2)) return void 0; + const checker = context.program.getTypeChecker(); + let suggestedSymbol; + if (isPropertyAccessExpression(parent2) && parent2.name === node) { + Debug.assert(isMemberName(node), "Expected an identifier for spelling (property access)"); + let containingType = checker.getTypeAtLocation(parent2.expression); + if (parent2.flags & 64 /* OptionalChain */ ) containingType = checker.getNonNullableType(containingType); + suggestedSymbol = checker.getSuggestedSymbolForNonexistentProperty(node, containingType); + } else if (isBinaryExpression(parent2) && parent2.operatorToken.kind === 103 /* InKeyword */ && parent2.left === node && isPrivateIdentifier(node)) { + const receiverType = checker.getTypeAtLocation(parent2.right); + suggestedSymbol = checker.getSuggestedSymbolForNonexistentProperty(node, receiverType); + } else if (isQualifiedName(parent2) && parent2.right === node) { + const symbol = checker.getSymbolAtLocation(parent2.left); + if (symbol && symbol.flags & 1536 /* Module */ ) suggestedSymbol = checker.getSuggestedSymbolForNonexistentModule(parent2.right, symbol); + } else if (isImportSpecifier(parent2) && parent2.name === node) { + Debug.assertNode(node, isIdentifier, "Expected an identifier for spelling (import)"); + const importDeclaration = findAncestor(node, isImportDeclaration); + const resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration); + if (resolvedSourceFile && resolvedSourceFile.symbol) suggestedSymbol = checker.getSuggestedSymbolForNonexistentModule(node, resolvedSourceFile.symbol); + } else if (isJsxAttribute(parent2) && parent2.name === node) { + Debug.assertNode(node, isIdentifier, "Expected an identifier for JSX attribute"); + const tag = findAncestor(node, isJsxOpeningLikeElement); + const props = checker.getContextualTypeForArgumentAtIndex(tag, 0); + suggestedSymbol = checker.getSuggestedSymbolForNonexistentJSXAttribute(node, props); + } else if (hasSyntacticModifier(parent2, 16384 /* Override */ ) && isClassElement(parent2) && parent2.name === node) { + const baseDeclaration = findAncestor(node, isClassLike); + const baseTypeNode = baseDeclaration ? getEffectiveBaseTypeNode(baseDeclaration) : void 0; + const baseType = baseTypeNode ? checker.getTypeAtLocation(baseTypeNode) : void 0; + if (baseType) suggestedSymbol = checker.getSuggestedSymbolForNonexistentClassMember(getTextOfNode(node), baseType); + } else { + const meaning = getMeaningFromLocation(node); + const name = getTextOfNode(node); + Debug.assert(name !== void 0, "name should be defined"); + suggestedSymbol = checker.getSuggestedSymbolForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); + } + return suggestedSymbol === void 0 ? void 0 : { + node: node, + suggestedSymbol: suggestedSymbol + }; } - function doChange32(changes, sourceFile, { node: node }) { - const newNode = factory.createToken(27 /* CommaToken */ ); - changes.replaceNode(sourceFile, node, newNode); + function doChange18(changes, sourceFile, node, suggestedSymbol, target) { + const suggestion = symbolName(suggestedSymbol); + if (!isIdentifierText(suggestion, target) && isPropertyAccessExpression(node.parent)) { + const valDecl = suggestedSymbol.valueDeclaration; + if (valDecl && isNamedDeclaration(valDecl) && isPrivateIdentifier(valDecl.name)) changes.replaceNode(sourceFile, node, factory.createIdentifier(suggestion)); + else changes.replaceNode(sourceFile, node.parent, factory.createElementAccessExpression(node.parent.expression, factory.createStringLiteral(suggestion))); + } else changes.replaceNode(sourceFile, node, factory.createIdentifier(suggestion)); } - var fixId49, expectedErrorCode, errorCodes61; - var init_fixExpectedComma = __esm({ - "src/services/codefixes/fixExpectedComma.ts" () { + function convertSemanticMeaningToSymbolFlags(meaning) { + let flags = 0; + if (meaning & 4 /* Namespace */ ) flags |= 1920 /* Namespace */ ; + if (meaning & 2 /* Type */ ) flags |= 788968 /* Type */ ; + if (meaning & 1 /* Value */ ) flags |= 111551 /* Value */ ; + return flags; + } + function getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration) { + if (!importDeclaration || !isStringLiteralLike(importDeclaration.moduleSpecifier)) return void 0; + const resolvedModule = getResolvedModule(sourceFile, importDeclaration.moduleSpecifier.text, getModeForUsageLocation(sourceFile, importDeclaration.moduleSpecifier)); + if (!resolvedModule) return void 0; + return context.program.getSourceFile(resolvedModule.resolvedFileName); + } + var fixId22, errorCodes25; + var init_fixSpelling = __esm({ + "src/services/codefixes/fixSpelling.ts" () { "use strict"; init_ts4(); init_ts_codefix(); - fixId49 = "fixExpectedComma"; - expectedErrorCode = Diagnostics._0_expected.code; - errorCodes61 = [ - expectedErrorCode + fixId22 = "fixSpelling"; + errorCodes25 = [ + Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code, + Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + Diagnostics.Could_not_find_name_0_Did_you_mean_1.code, + Diagnostics.Cannot_find_namespace_0_Did_you_mean_1.code, + Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, + Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2.code, + Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1.code, + Diagnostics.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.code, + // for JSX class components + Diagnostics.No_overload_matches_this_call.code, + // for JSX FC + Diagnostics.Type_0_is_not_assignable_to_type_1.code ]; registerCodeFix({ - errorCodes: errorCodes61, + errorCodes: errorCodes25, getCodeActions (context) { - const { sourceFile: sourceFile } = context; - const info = getInfo18(sourceFile, context.span.start, context.errorCode); + const { sourceFile: sourceFile, errorCode: errorCode } = context; + const info = getInfo8(sourceFile, context.span.start, context, errorCode); if (!info) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange32(t, sourceFile, info)); + const { node: node, suggestedSymbol: suggestedSymbol } = info; + const target = getEmitScriptTarget(context.host.getCompilationSettings()); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange18(t, sourceFile, node, suggestedSymbol, target)); return [ - createCodeFixAction(fixId49, changes, [ - Diagnostics.Change_0_to_1, - ";", - "," - ], fixId49, [ - Diagnostics.Change_0_to_1, - ";", - "," - ]) + createCodeFixAction("spelling", changes, [ + Diagnostics.Change_spelling_to_0, + symbolName(suggestedSymbol) + ], fixId22, Diagnostics.Fix_all_detected_spelling_errors) ]; }, fixIds: [ - fixId49 + fixId22 ], - getAllCodeActions: (context)=>codeFixAll(context, errorCodes61, (changes, diag2)=>{ - const info = getInfo18(diag2.file, diag2.start, diag2.code); - if (info) doChange32(changes, context.sourceFile, info); + getAllCodeActions: (context)=>codeFixAll(context, errorCodes25, (changes, diag2)=>{ + const info = getInfo8(diag2.file, diag2.start, context, diag2.code); + const target = getEmitScriptTarget(context.host.getCompilationSettings()); + if (info) doChange18(changes, context.sourceFile, info.node, info.suggestedSymbol, target); }) }); } }); - // src/services/codefixes/fixAddVoidToPromise.ts - function makeChange11(changes, sourceFile, span, program, seen) { - const node = getTokenAtPosition(sourceFile, span.start); - if (!isIdentifier(node) || !isCallExpression(node.parent) || node.parent.expression !== node || node.parent.arguments.length !== 0) return; - const checker = program.getTypeChecker(); - const symbol = checker.getSymbolAtLocation(node); - const decl = symbol == null ? void 0 : symbol.valueDeclaration; - if (!decl || !isParameter(decl) || !isNewExpression(decl.parent.parent)) return; - if (seen == null ? void 0 : seen.has(decl)) return; - seen == null || seen.add(decl); - const typeArguments = getEffectiveTypeArguments(decl.parent.parent); - if (some(typeArguments)) { - const typeArgument = typeArguments[0]; - const needsParens = !isUnionTypeNode(typeArgument) && !isParenthesizedTypeNode(typeArgument) && isParenthesizedTypeNode(factory.createUnionTypeNode([ - typeArgument, - factory.createKeywordTypeNode(114 /* VoidKeyword */ ) - ]).types[0]); - if (needsParens) changes.insertText(sourceFile, typeArgument.pos, "("); - changes.insertText(sourceFile, typeArgument.end, needsParens ? ") | void" : " | void"); - } else { - const signature = checker.getResolvedSignature(node.parent); - const parameter = signature == null ? void 0 : signature.parameters[0]; - const parameterType = parameter && checker.getTypeOfSymbolAtLocation(parameter, decl.parent.parent); - if (isInJSFile(decl)) { - if (!parameterType || parameterType.flags & 3 /* AnyOrUnknown */ ) { - changes.insertText(sourceFile, decl.parent.parent.end, `)`); - changes.insertText(sourceFile, skipTrivia(sourceFile.text, decl.parent.parent.pos), `/** @type {Promise} */(`); - } - } else if (!parameterType || parameterType.flags & 2 /* Unknown */ ) changes.insertText(sourceFile, decl.parent.parent.expression.end, ""); - } + // src/services/codefixes/returnValueCorrect.ts + function createObjectTypeFromLabeledExpression(checker, label, expression) { + const member = checker.createSymbol(4 /* Property */ , label.escapedText); + member.links.type = checker.getTypeAtLocation(expression); + const members = createSymbolTable([ + member + ]); + return checker.createAnonymousType(/*symbol*/ void 0, members, [], [], []); } - function getEffectiveTypeArguments(node) { - var _a2; - if (isInJSFile(node)) { - if (isParenthesizedExpression(node.parent)) { - const jsDocType = (_a2 = getJSDocTypeTag(node.parent)) == null ? void 0 : _a2.typeExpression.type; - if (jsDocType && isTypeReferenceNode(jsDocType) && isIdentifier(jsDocType.typeName) && idText(jsDocType.typeName) === "Promise") return jsDocType.typeArguments; + function getFixInfo(checker, declaration, expectType, isFunctionType) { + if (!declaration.body || !isBlock(declaration.body) || length(declaration.body.statements) !== 1) return void 0; + const firstStatement = first(declaration.body.statements); + if (isExpressionStatement(firstStatement) && checkFixedAssignableTo(checker, declaration, checker.getTypeAtLocation(firstStatement.expression), expectType, isFunctionType)) return { + declaration: declaration, + kind: 0 /* MissingReturnStatement */ , + expression: firstStatement.expression, + statement: firstStatement, + commentSource: firstStatement.expression + }; + else if (isLabeledStatement(firstStatement) && isExpressionStatement(firstStatement.statement)) { + const node = factory.createObjectLiteralExpression([ + factory.createPropertyAssignment(firstStatement.label, firstStatement.statement.expression) + ]); + const nodeType = createObjectTypeFromLabeledExpression(checker, firstStatement.label, firstStatement.statement.expression); + if (checkFixedAssignableTo(checker, declaration, nodeType, expectType, isFunctionType)) return isArrowFunction(declaration) ? { + declaration: declaration, + kind: 1 /* MissingParentheses */ , + expression: node, + statement: firstStatement, + commentSource: firstStatement.statement.expression + } : { + declaration: declaration, + kind: 0 /* MissingReturnStatement */ , + expression: node, + statement: firstStatement, + commentSource: firstStatement.statement.expression + }; + } else if (isBlock(firstStatement) && length(firstStatement.statements) === 1) { + const firstBlockStatement = first(firstStatement.statements); + if (isLabeledStatement(firstBlockStatement) && isExpressionStatement(firstBlockStatement.statement)) { + const node = factory.createObjectLiteralExpression([ + factory.createPropertyAssignment(firstBlockStatement.label, firstBlockStatement.statement.expression) + ]); + const nodeType = createObjectTypeFromLabeledExpression(checker, firstBlockStatement.label, firstBlockStatement.statement.expression); + if (checkFixedAssignableTo(checker, declaration, nodeType, expectType, isFunctionType)) return { + declaration: declaration, + kind: 0 /* MissingReturnStatement */ , + expression: node, + statement: firstStatement, + commentSource: firstBlockStatement + }; } - } else return node.typeArguments; + } + return void 0; } - var fixName7, fixId50, errorCodes62; - var init_fixAddVoidToPromise = __esm({ - "src/services/codefixes/fixAddVoidToPromise.ts" () { + function checkFixedAssignableTo(checker, declaration, exprType, type, isFunctionType) { + if (isFunctionType) { + const sig = checker.getSignatureFromDeclaration(declaration); + if (sig) { + if (hasSyntacticModifier(declaration, 512 /* Async */ )) exprType = checker.createPromiseType(exprType); + const newSig = checker.createSignature(declaration, sig.typeParameters, sig.thisParameter, sig.parameters, exprType, /*typePredicate*/ void 0, sig.minArgumentCount, sig.flags); + exprType = checker.createAnonymousType(/*symbol*/ void 0, createSymbolTable(), [ + newSig + ], [], []); + } else exprType = checker.getAnyType(); + } + return checker.isTypeAssignableTo(exprType, type); + } + function getInfo9(checker, sourceFile, position, errorCode) { + const node = getTokenAtPosition(sourceFile, position); + if (!node.parent) return void 0; + const declaration = findAncestor(node.parent, isFunctionLikeDeclaration); + switch(errorCode){ + case Diagnostics.A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value.code: + if (!declaration || !declaration.body || !declaration.type || !rangeContainsRange(declaration.type, node)) return void 0; + return getFixInfo(checker, declaration, checker.getTypeFromTypeNode(declaration.type), /*isFunctionType*/ false); + case Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code: + if (!declaration || !isCallExpression(declaration.parent) || !declaration.body) return void 0; + const pos = declaration.parent.arguments.indexOf(declaration); + if (pos === -1) return void 0; + const type = checker.getContextualTypeForArgumentAtIndex(declaration.parent, pos); + if (!type) return void 0; + return getFixInfo(checker, declaration, type, /*isFunctionType*/ true); + case Diagnostics.Type_0_is_not_assignable_to_type_1.code: + if (!isDeclarationName(node) || !isVariableLike(node.parent) && !isJsxAttribute(node.parent)) return void 0; + const initializer = getVariableLikeInitializer(node.parent); + if (!initializer || !isFunctionLikeDeclaration(initializer) || !initializer.body) return void 0; + return getFixInfo(checker, initializer, checker.getTypeAtLocation(node.parent), /*isFunctionType*/ true); + } + return void 0; + } + function getVariableLikeInitializer(declaration) { + switch(declaration.kind){ + case 260 /* VariableDeclaration */ : + case 169 /* Parameter */ : + case 208 /* BindingElement */ : + case 172 /* PropertyDeclaration */ : + case 303 /* PropertyAssignment */ : + return declaration.initializer; + case 291 /* JsxAttribute */ : + return declaration.initializer && (isJsxExpression(declaration.initializer) ? declaration.initializer.expression : void 0); + case 304 /* ShorthandPropertyAssignment */ : + case 171 /* PropertySignature */ : + case 306 /* EnumMember */ : + case 355 /* JSDocPropertyTag */ : + case 348 /* JSDocParameterTag */ : + return void 0; + } + } + function addReturnStatement(changes, sourceFile, expression, statement) { + suppressLeadingAndTrailingTrivia(expression); + const probablyNeedSemi = probablyUsesSemicolons(sourceFile); + changes.replaceNode(sourceFile, statement, factory.createReturnStatement(expression), { + leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, + trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Exclude, + suffix: probablyNeedSemi ? ";" : void 0 + }); + } + function removeBlockBodyBrace(changes, sourceFile, declaration, expression, commentSource, withParen) { + const newBody = withParen || needsParentheses(expression) ? factory.createParenthesizedExpression(expression) : expression; + suppressLeadingAndTrailingTrivia(commentSource); + copyComments(commentSource, newBody); + changes.replaceNode(sourceFile, declaration.body, newBody); + } + function wrapBlockWithParen(changes, sourceFile, declaration, expression) { + changes.replaceNode(sourceFile, declaration.body, factory.createParenthesizedExpression(expression)); + } + function getActionForfixAddReturnStatement(context, expression, statement) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addReturnStatement(t, context.sourceFile, expression, statement)); + return createCodeFixAction(fixId23, changes, Diagnostics.Add_a_return_statement, fixIdAddReturnStatement, Diagnostics.Add_all_missing_return_statement); + } + function getActionForFixRemoveBracesFromArrowFunctionBody(context, declaration, expression, commentSource) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>removeBlockBodyBrace(t, context.sourceFile, declaration, expression, commentSource, /*withParen*/ false)); + return createCodeFixAction(fixId23, changes, Diagnostics.Remove_braces_from_arrow_function_body, fixRemoveBracesFromArrowFunctionBody, Diagnostics.Remove_braces_from_all_arrow_function_bodies_with_relevant_issues); + } + function getActionForfixWrapTheBlockWithParen(context, declaration, expression) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>wrapBlockWithParen(t, context.sourceFile, declaration, expression)); + return createCodeFixAction(fixId23, changes, Diagnostics.Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal, fixIdWrapTheBlockWithParen, Diagnostics.Wrap_all_object_literal_with_parentheses); + } + var fixId23, fixIdAddReturnStatement, fixRemoveBracesFromArrowFunctionBody, fixIdWrapTheBlockWithParen, errorCodes26; + var init_returnValueCorrect = __esm({ + "src/services/codefixes/returnValueCorrect.ts" () { "use strict"; init_ts4(); init_ts_codefix(); - fixName7 = "addVoidToPromise"; - fixId50 = "addVoidToPromise"; - errorCodes62 = [ - Diagnostics.Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_without_arguments.code, - Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise.code + fixId23 = "returnValueCorrect"; + fixIdAddReturnStatement = "fixAddReturnStatement"; + fixRemoveBracesFromArrowFunctionBody = "fixRemoveBracesFromArrowFunctionBody"; + fixIdWrapTheBlockWithParen = "fixWrapTheBlockWithParen"; + errorCodes26 = [ + Diagnostics.A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value.code, + Diagnostics.Type_0_is_not_assignable_to_type_1.code, + Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code ]; registerCodeFix({ - errorCodes: errorCodes62, + errorCodes: errorCodes26, fixIds: [ - fixId50 + fixIdAddReturnStatement, + fixRemoveBracesFromArrowFunctionBody, + fixIdWrapTheBlockWithParen ], - getCodeActions (context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>makeChange11(t, context.sourceFile, context.span, context.program)); - if (changes.length > 0) return [ - createCodeFixAction(fixName7, changes, Diagnostics.Add_void_to_Promise_resolved_without_a_value, fixId50, Diagnostics.Add_void_to_all_Promises_resolved_without_a_value) + getCodeActions: function getCodeActionsToCorrectReturnValue(context) { + const { program: program, sourceFile: sourceFile, span: { start: start }, errorCode: errorCode } = context; + const info = getInfo9(program.getTypeChecker(), sourceFile, start, errorCode); + if (!info) return void 0; + if (info.kind === 0 /* MissingReturnStatement */ ) return append([ + getActionForfixAddReturnStatement(context, info.expression, info.statement) + ], isArrowFunction(info.declaration) ? getActionForFixRemoveBracesFromArrowFunctionBody(context, info.declaration, info.expression, info.commentSource) : void 0); + else return [ + getActionForfixWrapTheBlockWithParen(context, info.declaration, info.expression) ]; }, - getAllCodeActions (context) { - return codeFixAll(context, errorCodes62, (changes, diag2)=>makeChange11(changes, diag2.file, diag2, context.program, /* @__PURE__ */ new Set())); - } + getAllCodeActions: (context)=>codeFixAll(context, errorCodes26, (changes, diag2)=>{ + const info = getInfo9(context.program.getTypeChecker(), diag2.file, diag2.start, diag2.code); + if (!info) return void 0; + switch(context.fixId){ + case fixIdAddReturnStatement: + addReturnStatement(changes, diag2.file, info.expression, info.statement); + break; + case fixRemoveBracesFromArrowFunctionBody: + if (!isArrowFunction(info.declaration)) return void 0; + removeBlockBodyBrace(changes, diag2.file, info.declaration, info.expression, info.commentSource, /*withParen*/ false); + break; + case fixIdWrapTheBlockWithParen: + if (!isArrowFunction(info.declaration)) return void 0; + wrapBlockWithParen(changes, diag2.file, info.declaration, info.expression); + break; + default: + Debug.fail(JSON.stringify(context.fixId)); + } + }) }); } }); - // src/services/_namespaces/ts.codefix.ts - var ts_codefix_exports = {}; - __export(ts_codefix_exports, { - PreserveOptionalFlags: ()=>PreserveOptionalFlags, - addNewNodeForMemberSymbol: ()=>addNewNodeForMemberSymbol, - codeFixAll: ()=>codeFixAll, - createCodeFixAction: ()=>createCodeFixAction, - createCodeFixActionMaybeFixAll: ()=>createCodeFixActionMaybeFixAll, - createCodeFixActionWithoutFixAll: ()=>createCodeFixActionWithoutFixAll, - createCombinedCodeActions: ()=>createCombinedCodeActions, - createFileTextChanges: ()=>createFileTextChanges, - createImportAdder: ()=>createImportAdder, - createImportSpecifierResolver: ()=>createImportSpecifierResolver, - createJsonPropertyAssignment: ()=>createJsonPropertyAssignment, - createMissingMemberNodes: ()=>createMissingMemberNodes, - createSignatureDeclarationFromCallExpression: ()=>createSignatureDeclarationFromCallExpression, - createSignatureDeclarationFromSignature: ()=>createSignatureDeclarationFromSignature, - createStubbedBody: ()=>createStubbedBody, - eachDiagnostic: ()=>eachDiagnostic, - findAncestorMatchingSpan: ()=>findAncestorMatchingSpan, - findJsonProperty: ()=>findJsonProperty, - generateAccessorFromProperty: ()=>generateAccessorFromProperty, - getAccessorConvertiblePropertyAtPosition: ()=>getAccessorConvertiblePropertyAtPosition, - getAllFixes: ()=>getAllFixes, - getAllSupers: ()=>getAllSupers, - getArgumentTypesAndTypeParameters: ()=>getArgumentTypesAndTypeParameters, - getFixes: ()=>getFixes, - getImportCompletionAction: ()=>getImportCompletionAction, - getImportKind: ()=>getImportKind, - getNoopSymbolTrackerWithResolver: ()=>getNoopSymbolTrackerWithResolver, - getPromoteTypeOnlyCompletionAction: ()=>getPromoteTypeOnlyCompletionAction, - getSupportedErrorCodes: ()=>getSupportedErrorCodes, - importFixName: ()=>importFixName, - importSymbols: ()=>importSymbols, - moduleSpecifierToValidIdentifier: ()=>moduleSpecifierToValidIdentifier, - moduleSymbolToValidIdentifier: ()=>moduleSymbolToValidIdentifier, - parameterShouldGetTypeFromJSDoc: ()=>parameterShouldGetTypeFromJSDoc, - registerCodeFix: ()=>registerCodeFix, - setJsonCompilerOptionValue: ()=>setJsonCompilerOptionValue, - setJsonCompilerOptionValues: ()=>setJsonCompilerOptionValues, - tryGetAutoImportableReferenceFromTypeNode: ()=>tryGetAutoImportableReferenceFromTypeNode, - typeToAutoImportableTypeNode: ()=>typeToAutoImportableTypeNode - }); - var init_ts_codefix = __esm({ - "src/services/_namespaces/ts.codefix.ts" () { - "use strict"; - init_codeFixProvider(); - init_addConvertToUnknownForNonOverlappingTypes(); - init_addEmptyExportDeclaration(); - init_addMissingAsync(); - init_addMissingAwait(); - init_addMissingConst(); - init_addMissingDeclareProperty(); - init_addMissingInvocationForDecorator(); - init_addNameToNamelessParameter(); - init_addOptionalPropertyUndefined(); - init_annotateWithTypeFromJSDoc(); - init_convertFunctionToEs6Class(); - init_convertToAsyncFunction(); - init_convertToEsModule(); - init_correctQualifiedNameToIndexedAccessType(); - init_convertToTypeOnlyExport(); - init_convertToTypeOnlyImport(); - init_convertLiteralTypeToMappedType(); - init_fixClassIncorrectlyImplementsInterface(); - init_importFixes(); - init_fixAddMissingConstraint(); - init_fixOverrideModifier(); - init_fixNoPropertyAccessFromIndexSignature(); - init_fixImplicitThis(); - init_fixImportNonExportedMember(); - init_fixIncorrectNamedTupleSyntax(); - init_fixSpelling(); - init_returnValueCorrect(); - init_fixAddMissingMember(); - init_fixAddMissingNewOperator(); - init_fixCannotFindModule(); - init_fixClassDoesntImplementInheritedAbstractMember(); - init_fixClassSuperMustPrecedeThisAccess(); - init_fixConstructorForDerivedNeedSuperCall(); - init_fixEnableJsxFlag(); - init_fixNaNEquality(); - init_fixModuleAndTargetOptions(); - init_fixPropertyAssignment(); - init_fixExtendsInterfaceBecomesImplements(); - init_fixForgottenThisPropertyAccess(); - init_fixInvalidJsxCharacters(); - init_fixUnmatchedParameter(); - init_fixUnreferenceableDecoratorMetadata(); - init_fixUnusedIdentifier(); - init_fixUnreachableCode(); - init_fixUnusedLabel(); - init_fixJSDocTypes(); - init_fixMissingCallParentheses(); - init_fixAwaitInSyncFunction(); - init_fixPropertyOverrideAccessor(); - init_inferFromUsage(); - init_fixReturnTypeInAsyncFunction(); - init_disableJsDiagnostics(); - init_helpers(); - init_generateAccessors(); - init_fixInvalidImportSyntax(); - init_fixStrictClassInitialization(); - init_requireInTs(); - init_useDefaultImport(); - init_useBigintLiteral(); - init_fixAddModuleReferTypeMissingTypeof(); - init_wrapJsxInFragment(); - init_convertToMappedObjectType(); - init_removeAccidentalCallParentheses(); - init_removeUnnecessaryAwait(); - init_splitTypeOnlyImport(); - init_convertConstToLet(); - init_fixExpectedComma(); - init_fixAddVoidToPromise(); - } - }); - // src/services/completions.ts - function originIsThisType(origin) { - return !!(origin.kind & 1 /* ThisType */ ); - } - function originIsSymbolMember(origin) { - return !!(origin.kind & 2 /* SymbolMember */ ); - } - function originIsExport(origin) { - return !!(origin && origin.kind & 4 /* Export */ ); - } - function originIsResolvedExport(origin) { - return !!(origin && origin.kind === 32 /* ResolvedExport */ ); - } - function originIncludesSymbolName(origin) { - return originIsExport(origin) || originIsResolvedExport(origin) || originIsComputedPropertyName(origin); + // src/services/codefixes/fixAddMissingMember.ts + function getInfo10(sourceFile, tokenPos, errorCode, checker, program) { + var _a; + const token = getTokenAtPosition(sourceFile, tokenPos); + const parent2 = token.parent; + if (errorCode === Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code) { + if (!(token.kind === 19 /* OpenBraceToken */ && isObjectLiteralExpression(parent2) && isCallExpression(parent2.parent))) return void 0; + const argIndex = findIndex(parent2.parent.arguments, (arg)=>arg === parent2); + if (argIndex < 0) return void 0; + const signature = checker.getResolvedSignature(parent2.parent); + if (!(signature && signature.declaration && signature.parameters[argIndex])) return void 0; + const param = signature.parameters[argIndex].valueDeclaration; + if (!(param && isParameter(param) && isIdentifier(param.name))) return void 0; + const properties = arrayFrom(checker.getUnmatchedProperties(checker.getTypeAtLocation(parent2), checker.getParameterType(signature, argIndex), /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ false)); + if (!length(properties)) return void 0; + return { + kind: 3 /* ObjectLiteral */ , + token: param.name, + properties: properties, + parentDeclaration: parent2 + }; + } + if (!isMemberName(token)) return void 0; + if (isIdentifier(token) && hasInitializer(parent2) && parent2.initializer && isObjectLiteralExpression(parent2.initializer)) { + const targetType = checker.getContextualType(token) || checker.getTypeAtLocation(token); + const properties = arrayFrom(checker.getUnmatchedProperties(checker.getTypeAtLocation(parent2.initializer), targetType, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ false)); + if (!length(properties)) return void 0; + return { + kind: 3 /* ObjectLiteral */ , + token: token, + properties: properties, + parentDeclaration: parent2.initializer + }; + } + if (isIdentifier(token) && isJsxOpeningLikeElement(token.parent)) { + const target = getEmitScriptTarget(program.getCompilerOptions()); + const attributes = getUnmatchedAttributes(checker, target, token.parent); + if (!length(attributes)) return void 0; + return { + kind: 4 /* JsxAttributes */ , + token: token, + attributes: attributes, + parentDeclaration: token.parent + }; + } + if (isIdentifier(token)) { + const type = (_a = checker.getContextualType(token)) == null ? void 0 : _a.getNonNullableType(); + if (type && getObjectFlags(type) & 16 /* Anonymous */ ) { + const signature = firstOrUndefined(checker.getSignaturesOfType(type, 0 /* Call */ )); + if (signature === void 0) return void 0; + return { + kind: 5 /* Signature */ , + token: token, + signature: signature, + sourceFile: sourceFile, + parentDeclaration: findScope(token) + }; + } + if (isCallExpression(parent2) && parent2.expression === token) return { + kind: 2 /* Function */ , + token: token, + call: parent2, + sourceFile: sourceFile, + modifierFlags: 0 /* None */ , + parentDeclaration: findScope(token) + }; + } + if (!isPropertyAccessExpression(parent2)) return void 0; + const leftExpressionType = skipConstraint(checker.getTypeAtLocation(parent2.expression)); + const symbol = leftExpressionType.symbol; + if (!symbol || !symbol.declarations) return void 0; + if (isIdentifier(token) && isCallExpression(parent2.parent)) { + const moduleDeclaration = find(symbol.declarations, isModuleDeclaration); + const moduleDeclarationSourceFile = moduleDeclaration == null ? void 0 : moduleDeclaration.getSourceFile(); + if (moduleDeclaration && moduleDeclarationSourceFile && !isSourceFileFromLibrary(program, moduleDeclarationSourceFile)) return { + kind: 2 /* Function */ , + token: token, + call: parent2.parent, + sourceFile: sourceFile, + modifierFlags: 1 /* Export */ , + parentDeclaration: moduleDeclaration + }; + const moduleSourceFile = find(symbol.declarations, isSourceFile); + if (sourceFile.commonJsModuleIndicator) return void 0; + if (moduleSourceFile && !isSourceFileFromLibrary(program, moduleSourceFile)) return { + kind: 2 /* Function */ , + token: token, + call: parent2.parent, + sourceFile: moduleSourceFile, + modifierFlags: 1 /* Export */ , + parentDeclaration: moduleSourceFile + }; + } + const classDeclaration = find(symbol.declarations, isClassLike); + if (!classDeclaration && isPrivateIdentifier(token)) return void 0; + const declaration = classDeclaration || find(symbol.declarations, (d)=>isInterfaceDeclaration(d) || isTypeLiteralNode(d)); + if (declaration && !isSourceFileFromLibrary(program, declaration.getSourceFile())) { + const makeStatic = !isTypeLiteralNode(declaration) && (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); + if (makeStatic && (isPrivateIdentifier(token) || isInterfaceDeclaration(declaration))) return void 0; + const declSourceFile = declaration.getSourceFile(); + const modifierFlags = isTypeLiteralNode(declaration) ? 0 /* None */ : (makeStatic ? 32 /* Static */ : 0 /* None */ ) | (startsWithUnderscore(token.text) ? 8 /* Private */ : 0 /* None */ ); + const isJSFile = isSourceFileJS(declSourceFile); + const call = tryCast(parent2.parent, isCallExpression); + return { + kind: 0 /* TypeLikeDeclaration */ , + token: token, + call: call, + modifierFlags: modifierFlags, + parentDeclaration: declaration, + declSourceFile: declSourceFile, + isJSFile: isJSFile + }; + } + const enumDeclaration = find(symbol.declarations, isEnumDeclaration); + if (enumDeclaration && !(leftExpressionType.flags & 1056 /* EnumLike */ ) && !isPrivateIdentifier(token) && !isSourceFileFromLibrary(program, enumDeclaration.getSourceFile())) return { + kind: 1 /* Enum */ , + token: token, + parentDeclaration: enumDeclaration + }; + return void 0; } - function originIsPackageJsonImport(origin) { - return (originIsExport(origin) || originIsResolvedExport(origin)) && !!origin.isFromPackageJson; + function getActionsForMissingMemberDeclaration(context, info) { + return info.isJSFile ? singleElementArray(createActionForAddMissingMemberInJavascriptFile(context, info)) : createActionsForAddMissingMemberInTypeScriptFile(context, info); } - function originIsPromise(origin) { - return !!(origin.kind & 8 /* Promise */ ); + function createActionForAddMissingMemberInJavascriptFile(context, { parentDeclaration: parentDeclaration, declSourceFile: declSourceFile, modifierFlags: modifierFlags, token: token }) { + if (isInterfaceDeclaration(parentDeclaration) || isTypeLiteralNode(parentDeclaration)) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addMissingMemberInJs(t, declSourceFile, parentDeclaration, token, !!(modifierFlags & 32 /* Static */ ))); + if (changes.length === 0) return void 0; + const diagnostic = modifierFlags & 32 /* Static */ ? Diagnostics.Initialize_static_property_0 : isPrivateIdentifier(token) ? Diagnostics.Declare_a_private_field_named_0 : Diagnostics.Initialize_property_0_in_the_constructor; + return createCodeFixAction(fixMissingMember, changes, [ + diagnostic, + token.text + ], fixMissingMember, Diagnostics.Add_all_missing_members); } - function originIsNullableMember(origin) { - return !!(origin.kind & 16 /* Nullable */ ); + function addMissingMemberInJs(changeTracker, sourceFile, classDeclaration, token, makeStatic) { + const tokenName = token.text; + if (makeStatic) { + if (classDeclaration.kind === 231 /* ClassExpression */ ) return; + const className = classDeclaration.name.getText(); + const staticInitialization = initializePropertyToUndefined(factory.createIdentifier(className), tokenName); + changeTracker.insertNodeAfter(sourceFile, classDeclaration, staticInitialization); + } else if (isPrivateIdentifier(token)) { + const property = factory.createPropertyDeclaration(/*modifiers*/ void 0, tokenName, /*questionOrExclamationToken*/ void 0, /*type*/ void 0, /*initializer*/ void 0); + const lastProp = getNodeToInsertPropertyAfter(classDeclaration); + if (lastProp) changeTracker.insertNodeAfter(sourceFile, lastProp, property); + else changeTracker.insertMemberAtStart(sourceFile, classDeclaration, property); + } else { + const classConstructor = getFirstConstructorWithBody(classDeclaration); + if (!classConstructor) return; + const propertyInitialization = initializePropertyToUndefined(factory.createThis(), tokenName); + changeTracker.insertNodeAtConstructorEnd(sourceFile, classConstructor, propertyInitialization); + } } - function originIsTypeOnlyAlias(origin) { - return !!(origin && origin.kind & 64 /* TypeOnlyAlias */ ); + function initializePropertyToUndefined(obj, propertyName) { + return factory.createExpressionStatement(factory.createAssignment(factory.createPropertyAccessExpression(obj, propertyName), createUndefined())); } - function originIsObjectLiteralMethod(origin) { - return !!(origin && origin.kind & 128 /* ObjectLiteralMethod */ ); + function createActionsForAddMissingMemberInTypeScriptFile(context, { parentDeclaration: parentDeclaration, declSourceFile: declSourceFile, modifierFlags: modifierFlags, token: token }) { + const memberName = token.text; + const isStatic2 = modifierFlags & 32 /* Static */ ; + const typeNode = getTypeNode2(context.program.getTypeChecker(), parentDeclaration, token); + const addPropertyDeclarationChanges = (modifierFlags2)=>ts_textChanges_exports.ChangeTracker.with(context, (t)=>addPropertyDeclaration(t, declSourceFile, parentDeclaration, memberName, typeNode, modifierFlags2)); + const actions2 = [ + createCodeFixAction(fixMissingMember, addPropertyDeclarationChanges(modifierFlags & 32 /* Static */ ), [ + isStatic2 ? Diagnostics.Declare_static_property_0 : Diagnostics.Declare_property_0, + memberName + ], fixMissingMember, Diagnostics.Add_all_missing_members) + ]; + if (isStatic2 || isPrivateIdentifier(token)) return actions2; + if (modifierFlags & 8 /* Private */ ) actions2.unshift(createCodeFixActionWithoutFixAll(fixMissingMember, addPropertyDeclarationChanges(8 /* Private */ ), [ + Diagnostics.Declare_private_property_0, + memberName + ])); + actions2.push(createAddIndexSignatureAction(context, declSourceFile, parentDeclaration, token.text, typeNode)); + return actions2; } - function originIsIgnore(origin) { - return !!(origin && origin.kind & 256 /* Ignore */ ); + function getTypeNode2(checker, node, token) { + let typeNode; + if (token.parent.parent.kind === 226 /* BinaryExpression */ ) { + const binaryExpression = token.parent.parent; + const otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; + const widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); + typeNode = checker.typeToTypeNode(widenedType, node, 1 /* NoTruncation */ ); + } else { + const contextualType = checker.getContextualType(token.parent); + typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ void 0, 1 /* NoTruncation */ ) : void 0; + } + return typeNode || factory.createKeywordTypeNode(133 /* AnyKeyword */ ); } - function originIsComputedPropertyName(origin) { - return !!(origin && origin.kind & 512 /* ComputedPropertyName */ ); + function addPropertyDeclaration(changeTracker, sourceFile, node, tokenName, typeNode, modifierFlags) { + const modifiers = modifierFlags ? factory.createNodeArray(factory.createModifiersFromModifierFlags(modifierFlags)) : void 0; + const property = isClassLike(node) ? factory.createPropertyDeclaration(modifiers, tokenName, /*questionOrExclamationToken*/ void 0, typeNode, /*initializer*/ void 0) : factory.createPropertySignature(/*modifiers*/ void 0, tokenName, /*questionToken*/ void 0, typeNode); + const lastProp = getNodeToInsertPropertyAfter(node); + if (lastProp) changeTracker.insertNodeAfter(sourceFile, lastProp, property); + else changeTracker.insertMemberAtStart(sourceFile, node, property); } - function resolvingModuleSpecifiers(logPrefix, host, resolver, program, position, preferences, isForImportStatementCompletion, isValidTypeOnlyUseSite, cb) { - var _a2, _b, _c; - const start = timestamp(); - const needsFullResolution = isForImportStatementCompletion || moduleResolutionSupportsPackageJsonExportsAndImports(getEmitModuleResolutionKind(program.getCompilerOptions())); - let skippedAny = false; - let ambientCount = 0; - let resolvedCount = 0; - let resolvedFromCacheCount = 0; - let cacheAttemptCount = 0; - const result = cb({ - tryResolve: tryResolve, - skippedAny: ()=>skippedAny, - resolvedAny: ()=>resolvedCount > 0, - resolvedBeyondLimit: ()=>resolvedCount > moduleSpecifierResolutionLimit - }); - const hitRateMessage = cacheAttemptCount ? ` (${(resolvedFromCacheCount / cacheAttemptCount * 100).toFixed(1)}% hit rate)` : ""; - (_a2 = host.log) == null || _a2.call(host, `${logPrefix}: resolved ${resolvedCount} module specifiers, plus ${ambientCount} ambient and ${resolvedFromCacheCount} from cache${hitRateMessage}`); - (_b = host.log) == null || _b.call(host, `${logPrefix}: response is ${skippedAny ? "incomplete" : "complete"}`); - (_c = host.log) == null || _c.call(host, `${logPrefix}: ${timestamp() - start}`); - return result; - function tryResolve(exportInfo, isFromAmbientModule) { - if (isFromAmbientModule) { - const result3 = resolver.getModuleSpecifierForBestExportInfo(exportInfo, position, isValidTypeOnlyUseSite); - if (result3) ambientCount++; - return result3 || "failed"; - } - const shouldResolveModuleSpecifier = needsFullResolution || preferences.allowIncompleteCompletions && resolvedCount < moduleSpecifierResolutionLimit; - const shouldGetModuleSpecifierFromCache = !shouldResolveModuleSpecifier && preferences.allowIncompleteCompletions && cacheAttemptCount < moduleSpecifierResolutionCacheAttemptLimit; - const result2 = shouldResolveModuleSpecifier || shouldGetModuleSpecifierFromCache ? resolver.getModuleSpecifierForBestExportInfo(exportInfo, position, isValidTypeOnlyUseSite, shouldGetModuleSpecifierFromCache) : void 0; - if (!shouldResolveModuleSpecifier && !shouldGetModuleSpecifierFromCache || shouldGetModuleSpecifierFromCache && !result2) skippedAny = true; - resolvedCount += (result2 == null ? void 0 : result2.computedWithoutCacheCount) || 0; - resolvedFromCacheCount += exportInfo.length - ((result2 == null ? void 0 : result2.computedWithoutCacheCount) || 0); - if (shouldGetModuleSpecifierFromCache) cacheAttemptCount++; - return result2 || (needsFullResolution ? "failed" : "skipped"); + function getNodeToInsertPropertyAfter(node) { + let res; + for (const member of node.members){ + if (!isPropertyDeclaration(member)) break; + res = member; } + return res; } - function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter, completionKind, cancellationToken, formatContext, includeSymbol = false) { - var _a2; - const { previousToken: previousToken } = getRelevantTokens(position, sourceFile); - if (triggerCharacter && !isInString(sourceFile, position, previousToken) && !isValidTrigger(sourceFile, triggerCharacter, previousToken, position)) return void 0; - if (triggerCharacter === " ") { - if (preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) return { - isGlobalCompletion: true, - isMemberCompletion: false, - isNewIdentifierLocation: true, - isIncomplete: true, - entries: [] - }; - return void 0; - } - const compilerOptions = program.getCompilerOptions(); - const incompleteCompletionsCache = preferences.allowIncompleteCompletions ? (_a2 = host.getIncompleteCompletionsCache) == null ? void 0 : _a2.call(host) : void 0; - if (incompleteCompletionsCache && completionKind === 3 /* TriggerForIncompleteCompletions */ && previousToken && isIdentifier(previousToken)) { - const incompleteContinuation = continuePreviousIncompleteResponse(incompleteCompletionsCache, sourceFile, previousToken, program, host, preferences, cancellationToken, position); - if (incompleteContinuation) return incompleteContinuation; - } else incompleteCompletionsCache == null || incompleteCompletionsCache.clear(); - const stringCompletions = ts_Completions_StringCompletions_exports.getStringLiteralCompletions(sourceFile, position, previousToken, compilerOptions, host, program, log, preferences, includeSymbol); - if (stringCompletions) return stringCompletions; - if (previousToken && isBreakOrContinueStatement(previousToken.parent) && (previousToken.kind === 81 /* BreakKeyword */ || previousToken.kind === 86 /* ContinueKeyword */ || previousToken.kind === 79 /* Identifier */ )) return getLabelCompletionAtPosition(previousToken.parent); - const completionData = getCompletionData(program, log, sourceFile, compilerOptions, position, preferences, /*detailsEntryId*/ void 0, host, formatContext, cancellationToken); - if (!completionData) return void 0; - switch(completionData.kind){ - case 0 /* Data */ : - const response = completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences, formatContext, position, includeSymbol); - if (response == null ? void 0 : response.isIncomplete) incompleteCompletionsCache == null || incompleteCompletionsCache.set(response); - return response; - case 1 /* JsDocTagName */ : - return jsdocCompletionInfo(ts_JsDoc_exports.getJSDocTagNameCompletions()); - case 2 /* JsDocTag */ : - return jsdocCompletionInfo(ts_JsDoc_exports.getJSDocTagCompletions()); - case 3 /* JsDocParameterName */ : - return jsdocCompletionInfo(ts_JsDoc_exports.getJSDocParameterNameCompletions(completionData.tag)); - case 4 /* Keywords */ : - return specificKeywordCompletionInfo(completionData.keywordCompletions, completionData.isNewIdentifierLocation); - default: - return Debug.assertNever(completionData); - } + function createAddIndexSignatureAction(context, sourceFile, node, tokenName, typeNode) { + const stringTypeNode = factory.createKeywordTypeNode(154 /* StringKeyword */ ); + const indexingParameter = factory.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, "x", /*questionToken*/ void 0, stringTypeNode, /*initializer*/ void 0); + const indexSignature = factory.createIndexSignature(/*modifiers*/ void 0, [ + indexingParameter + ], typeNode); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>t.insertMemberAtStart(sourceFile, node, indexSignature)); + return createCodeFixActionWithoutFixAll(fixMissingMember, changes, [ + Diagnostics.Add_index_signature_for_property_0, + tokenName + ]); } - function compareCompletionEntries(entryInArray, entryToInsert) { - var _a2, _b; - let result = compareStringsCaseSensitiveUI(entryInArray.sortText, entryToInsert.sortText); - if (result === 0 /* EqualTo */ ) result = compareStringsCaseSensitiveUI(entryInArray.name, entryToInsert.name); - if (result === 0 /* EqualTo */ && ((_a2 = entryInArray.data) == null ? void 0 : _a2.moduleSpecifier) && ((_b = entryToInsert.data) == null ? void 0 : _b.moduleSpecifier)) result = compareNumberOfDirectorySeparators(entryInArray.data.moduleSpecifier, entryToInsert.data.moduleSpecifier); - if (result === 0 /* EqualTo */ ) return -1 /* LessThan */ ; - return result; + function getActionsForMissingMethodDeclaration(context, info) { + const { parentDeclaration: parentDeclaration, declSourceFile: declSourceFile, modifierFlags: modifierFlags, token: token, call: call } = info; + if (call === void 0) return void 0; + const methodName = token.text; + const addMethodDeclarationChanges = (modifierFlags2)=>ts_textChanges_exports.ChangeTracker.with(context, (t)=>addMethodDeclaration(context, t, call, token, modifierFlags2, parentDeclaration, declSourceFile)); + const actions2 = [ + createCodeFixAction(fixMissingMember, addMethodDeclarationChanges(modifierFlags & 32 /* Static */ ), [ + modifierFlags & 32 /* Static */ ? Diagnostics.Declare_static_method_0 : Diagnostics.Declare_method_0, + methodName + ], fixMissingMember, Diagnostics.Add_all_missing_members) + ]; + if (modifierFlags & 8 /* Private */ ) actions2.unshift(createCodeFixActionWithoutFixAll(fixMissingMember, addMethodDeclarationChanges(8 /* Private */ ), [ + Diagnostics.Declare_private_method_0, + methodName + ])); + return actions2; } - function completionEntryDataIsResolved(data) { - return !!(data == null ? void 0 : data.moduleSpecifier); + function addMethodDeclaration(context, changes, callExpression, name, modifierFlags, parentDeclaration, sourceFile) { + const importAdder = createImportAdder(sourceFile, context.program, context.preferences, context.host); + const kind = isClassLike(parentDeclaration) ? 174 /* MethodDeclaration */ : 173 /* MethodSignature */ ; + const signatureDeclaration = createSignatureDeclarationFromCallExpression(kind, context, importAdder, callExpression, name, modifierFlags, parentDeclaration); + const containingMethodDeclaration = tryGetContainingMethodDeclaration(parentDeclaration, callExpression); + if (containingMethodDeclaration) changes.insertNodeAfter(sourceFile, containingMethodDeclaration, signatureDeclaration); + else changes.insertMemberAtStart(sourceFile, parentDeclaration, signatureDeclaration); + importAdder.writeFixes(changes); } - function continuePreviousIncompleteResponse(cache, file, location, program, host, preferences, cancellationToken, position) { - const previousResponse = cache.get(); - if (!previousResponse) return void 0; - const touchNode = getTouchingPropertyName(file, position); - const lowerCaseTokenText = location.text.toLowerCase(); - const exportMap = getExportInfoMap(file, host, program, preferences, cancellationToken); - const newEntries = resolvingModuleSpecifiers("continuePreviousIncompleteResponse", host, ts_codefix_exports.createImportSpecifierResolver(file, program, host, preferences), program, location.getStart(), preferences, /*isForImportStatementCompletion*/ false, isValidTypeOnlyAliasUseSite(location), (context)=>{ - const entries = mapDefined(previousResponse.entries, (entry)=>{ - var _a2; - if (!entry.hasAction || !entry.source || !entry.data || completionEntryDataIsResolved(entry.data)) return entry; - if (!charactersFuzzyMatchInString(entry.name, lowerCaseTokenText)) return void 0; - const { origin: origin } = Debug.checkDefined(getAutoImportSymbolFromCompletionEntryData(entry.name, entry.data, program, host)); - const info = exportMap.get(file.path, entry.data.exportMapKey); - const result = info && context.tryResolve(info, !isExternalModuleNameRelative(stripQuotes(origin.moduleSymbol.name))); - if (result === "skipped") return entry; - if (!result || result === "failed") { - (_a2 = host.log) == null || _a2.call(host, `Unexpected failure resolving auto import for '${entry.name}' from '${entry.source}'`); - return void 0; - } - const newOrigin = { - ...origin, - kind: 32 /* ResolvedExport */ , - moduleSpecifier: result.moduleSpecifier - }; - entry.data = originToCompletionEntryData(newOrigin); - entry.source = getSourceFromOrigin(newOrigin); - entry.sourceDisplay = [ - textPart(newOrigin.moduleSpecifier) - ]; - return entry; - }); - if (!context.skippedAny()) previousResponse.isIncomplete = void 0; - return entries; + function addEnumMemberDeclaration(changes, checker, { token: token, parentDeclaration: parentDeclaration }) { + const hasStringInitializer = some(parentDeclaration.members, (member)=>{ + const type = checker.getTypeAtLocation(member); + return !!(type && type.flags & 402653316 /* StringLike */ ); + }); + const enumMember = factory.createEnumMember(token, hasStringInitializer ? factory.createStringLiteral(token.text) : void 0); + changes.replaceNode(parentDeclaration.getSourceFile(), parentDeclaration, factory.updateEnumDeclaration(parentDeclaration, parentDeclaration.modifiers, parentDeclaration.name, concatenate(parentDeclaration.members, singleElementArray(enumMember))), { + leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Exclude }); - previousResponse.entries = newEntries; - previousResponse.flags = (previousResponse.flags || 0) | 4 /* IsContinuation */ ; - previousResponse.optionalReplacementSpan = getOptionalReplacementSpan(touchNode); - return previousResponse; - } - function jsdocCompletionInfo(entries) { - return { - isGlobalCompletion: false, - isMemberCompletion: false, - isNewIdentifierLocation: false, - entries: entries - }; } - function keywordToCompletionEntry(keyword) { - return { - name: tokenToString(keyword), - kind: "keyword" /* keyword */ , - kindModifiers: "" /* none */ , - sortText: SortText.GlobalsOrKeywords - }; + function addFunctionDeclaration(changes, context, info) { + const quotePreference = getQuotePreference(context.sourceFile, context.preferences); + const importAdder = createImportAdder(context.sourceFile, context.program, context.preferences, context.host); + const functionDeclaration = info.kind === 2 /* Function */ ? createSignatureDeclarationFromCallExpression(262 /* FunctionDeclaration */ , context, importAdder, info.call, idText(info.token), info.modifierFlags, info.parentDeclaration) : createSignatureDeclarationFromSignature(262 /* FunctionDeclaration */ , context, quotePreference, info.signature, createStubbedBody(Diagnostics.Function_not_implemented.message, quotePreference), info.token, /*modifiers*/ void 0, /*optional*/ void 0, /*enclosingDeclaration*/ void 0, importAdder); + if (functionDeclaration === void 0) Debug.fail("fixMissingFunctionDeclaration codefix got unexpected error."); + isReturnStatement(info.parentDeclaration) ? changes.insertNodeBefore(info.sourceFile, info.parentDeclaration, functionDeclaration, /*blankLineBetween*/ true) : changes.insertNodeAtEndOfScope(info.sourceFile, info.parentDeclaration, functionDeclaration); + importAdder.writeFixes(changes); } - function specificKeywordCompletionInfo(entries, isNewIdentifierLocation) { - return { - isGlobalCompletion: false, - isMemberCompletion: false, - isNewIdentifierLocation: isNewIdentifierLocation, - entries: entries.slice() + function addJsxAttributes(changes, context, info) { + const importAdder = createImportAdder(context.sourceFile, context.program, context.preferences, context.host); + const quotePreference = getQuotePreference(context.sourceFile, context.preferences); + const checker = context.program.getTypeChecker(); + const jsxAttributesNode = info.parentDeclaration.attributes; + const hasSpreadAttribute = some(jsxAttributesNode.properties, isJsxSpreadAttribute); + const attrs = map(info.attributes, (attr)=>{ + const value1 = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(attr), info.parentDeclaration); + const name = factory.createIdentifier(attr.name); + const jsxAttribute = factory.createJsxAttribute(name, factory.createJsxExpression(/*dotDotDotToken*/ void 0, value1)); + setParent(name, jsxAttribute); + return jsxAttribute; + }); + const jsxAttributes = factory.createJsxAttributes(hasSpreadAttribute ? [ + ...attrs, + ...jsxAttributesNode.properties + ] : [ + ...jsxAttributesNode.properties, + ...attrs + ]); + const options = { + prefix: jsxAttributesNode.pos === jsxAttributesNode.end ? " " : void 0 }; + changes.replaceNode(context.sourceFile, jsxAttributesNode, jsxAttributes, options); + importAdder.writeFixes(changes); } - function keywordCompletionData(keywordFilters, filterOutTsOnlyKeywords, isNewIdentifierLocation) { - return { - kind: 4 /* Keywords */ , - keywordCompletions: getKeywordCompletions(keywordFilters, filterOutTsOnlyKeywords), - isNewIdentifierLocation: isNewIdentifierLocation + function addObjectLiteralProperties(changes, context, info) { + const importAdder = createImportAdder(context.sourceFile, context.program, context.preferences, context.host); + const quotePreference = getQuotePreference(context.sourceFile, context.preferences); + const target = getEmitScriptTarget(context.program.getCompilerOptions()); + const checker = context.program.getTypeChecker(); + const props = map(info.properties, (prop)=>{ + const initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop), info.parentDeclaration); + return factory.createPropertyAssignment(createPropertyNameFromSymbol(prop, target, quotePreference, checker), initializer); + }); + const options = { + leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, + trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Exclude, + indentation: info.indentation }; + changes.replaceNode(context.sourceFile, info.parentDeclaration, factory.createObjectLiteralExpression([ + ...info.parentDeclaration.properties, + ...props + ], /*multiLine*/ true), options); + importAdder.writeFixes(changes); } - function keywordFiltersFromSyntaxKind(keywordCompletion) { - switch(keywordCompletion){ - case 154 /* TypeKeyword */ : - return 8 /* TypeKeyword */ ; - default: - Debug.fail("Unknown mapping from SyntaxKind to KeywordCompletionFilters"); + function tryGetValueFromType(context, checker, importAdder, quotePreference, type, enclosingDeclaration) { + if (type.flags & 3 /* AnyOrUnknown */ ) return createUndefined(); + if (type.flags & 134217732 /* TemplateLiteral */ ) return factory.createStringLiteral("", /* isSingleQuote */ quotePreference === 0 /* Single */ ); + if (type.flags & 8 /* Number */ ) return factory.createNumericLiteral(0); + if (type.flags & 64 /* BigInt */ ) return factory.createBigIntLiteral("0n"); + if (type.flags & 16 /* Boolean */ ) return factory.createFalse(); + if (type.flags & 1056 /* EnumLike */ ) { + const enumMember = type.symbol.exports ? firstOrUndefinedIterator(type.symbol.exports.values()) : type.symbol; + const name = checker.symbolToExpression(type.symbol.parent ? type.symbol.parent : type.symbol, 111551 /* Value */ , /*enclosingDeclaration*/ void 0, /*flags*/ void 0); + return enumMember === void 0 || name === void 0 ? factory.createNumericLiteral(0) : factory.createPropertyAccessExpression(name, checker.symbolToString(enumMember)); } - } - function getOptionalReplacementSpan(location) { - return (location == null ? void 0 : location.kind) === 79 /* Identifier */ ? createTextSpanFromNode(location) : void 0; - } - function completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences, formatContext, position, includeSymbol) { - const { symbols: symbols , contextToken: contextToken , completionKind: completionKind , isInSnippetScope: isInSnippetScope , isNewIdentifierLocation: isNewIdentifierLocation , location: location , propertyAccessToConvert: propertyAccessToConvert , keywordFilters: keywordFilters , symbolToOriginInfoMap: symbolToOriginInfoMap , recommendedCompletion: recommendedCompletion , isJsxInitializer: isJsxInitializer , isTypeOnlyLocation: isTypeOnlyLocation , isJsxIdentifierExpected: isJsxIdentifierExpected , isRightOfOpenTag: isRightOfOpenTag , isRightOfDotOrQuestionDot: isRightOfDotOrQuestionDot , importStatementCompletion: importStatementCompletion , insideJsDocTagTypeExpression: insideJsDocTagTypeExpression , symbolToSortTextMap: symbolToSortTextMap , hasUnresolvedAutoImports: hasUnresolvedAutoImports } = completionData; - let literals = completionData.literals; - const checker = program.getTypeChecker(); - if (getLanguageVariant(sourceFile.scriptKind) === 1 /* JSX */ ) { - const completionInfo = getJsxClosingTagCompletion(location, sourceFile); - if (completionInfo) return completionInfo; + if (type.flags & 256 /* NumberLiteral */ ) return factory.createNumericLiteral(type.value); + if (type.flags & 2048 /* BigIntLiteral */ ) return factory.createBigIntLiteral(type.value); + if (type.flags & 128 /* StringLiteral */ ) return factory.createStringLiteral(type.value, /* isSingleQuote */ quotePreference === 0 /* Single */ ); + if (type.flags & 512 /* BooleanLiteral */ ) return type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true) ? factory.createFalse() : factory.createTrue(); + if (type.flags & 65536 /* Null */ ) return factory.createNull(); + if (type.flags & 1048576 /* Union */ ) { + const expression = firstDefined(type.types, (t)=>tryGetValueFromType(context, checker, importAdder, quotePreference, t, enclosingDeclaration)); + return expression ?? createUndefined(); } - const caseClause = findAncestor(contextToken, isCaseClause); - if (caseClause && (isCaseKeyword(contextToken) || isNodeDescendantOf(contextToken, caseClause.expression))) { - const tracker = newCaseClauseTracker(checker, caseClause.parent.clauses); - literals = literals.filter((literal)=>!tracker.hasValue(literal)); - symbols.forEach((symbol, i)=>{ - if (symbol.valueDeclaration && isEnumMember(symbol.valueDeclaration)) { - const value1 = checker.getConstantValue(symbol.valueDeclaration); - if (value1 !== void 0 && tracker.hasValue(value1)) symbolToOriginInfoMap[i] = { - kind: 256 /* Ignore */ - }; - } + if (checker.isArrayLikeType(type)) return factory.createArrayLiteralExpression(); + if (isObjectLiteralType(type)) { + const props = map(checker.getPropertiesOfType(type), (prop)=>{ + const initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop), enclosingDeclaration); + return factory.createPropertyAssignment(prop.name, initializer); }); + return factory.createObjectLiteralExpression(props, /*multiLine*/ true); } - const entries = createSortedArray(); - const isChecked = isCheckedFile(sourceFile, compilerOptions); - if (isChecked && !isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* None */ ) return void 0; - const uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, /*replacementToken*/ void 0, contextToken, location, position, sourceFile, host, program, getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importStatementCompletion, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag, includeSymbol); - if (keywordFilters !== 0 /* None */ ) { - for (const keywordEntry of getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && isSourceFileJS(sourceFile)))if (isTypeOnlyLocation && isTypeKeyword(stringToToken(keywordEntry.name)) || !uniqueNames.has(keywordEntry.name)) { - uniqueNames.add(keywordEntry.name); - insertSorted(entries, keywordEntry, compareCompletionEntries, /*allowDuplicates*/ true); - } - } - for (const keywordEntry of getContextualKeywords(contextToken, position))if (!uniqueNames.has(keywordEntry.name)) { - uniqueNames.add(keywordEntry.name); - insertSorted(entries, keywordEntry, compareCompletionEntries, /*allowDuplicates*/ true); - } - for (const literal of literals){ - const literalEntry = createCompletionEntryForLiteral(sourceFile, preferences, literal); - uniqueNames.add(literalEntry.name); - insertSorted(entries, literalEntry, compareCompletionEntries, /*allowDuplicates*/ true); + if (getObjectFlags(type) & 16 /* Anonymous */ ) { + const decl = find(type.symbol.declarations || emptyArray, or(isFunctionTypeNode, isMethodSignature, isMethodDeclaration)); + if (decl === void 0) return createUndefined(); + const signature = checker.getSignaturesOfType(type, 0 /* Call */ ); + if (signature === void 0) return createUndefined(); + const func = createSignatureDeclarationFromSignature(218 /* FunctionExpression */ , context, quotePreference, signature[0], createStubbedBody(Diagnostics.Function_not_implemented.message, quotePreference), /*name*/ void 0, /*modifiers*/ void 0, /*optional*/ void 0, /*enclosingDeclaration*/ enclosingDeclaration, importAdder); + return func ?? createUndefined(); } - if (!isChecked) getJSCompletionEntries(sourceFile, location.pos, uniqueNames, getEmitScriptTarget(compilerOptions), entries); - let caseBlock; - if (preferences.includeCompletionsWithInsertText && contextToken && !isRightOfOpenTag && !isRightOfDotOrQuestionDot && (caseBlock = findAncestor(contextToken, isCaseBlock))) { - const cases = getExhaustiveCaseSnippets(caseBlock, sourceFile, preferences, compilerOptions, host, program, formatContext); - if (cases) entries.push(cases.entry); + if (getObjectFlags(type) & 1 /* Class */ ) { + const classDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); + if (classDeclaration === void 0 || hasAbstractModifier(classDeclaration)) return createUndefined(); + const constructorDeclaration = getFirstConstructorWithBody(classDeclaration); + if (constructorDeclaration && length(constructorDeclaration.parameters)) return createUndefined(); + return factory.createNewExpression(factory.createIdentifier(type.symbol.name), /*typeArguments*/ void 0, /*argumentsArray*/ void 0); } - return { - flags: completionData.flags, - isGlobalCompletion: isInSnippetScope, - isIncomplete: preferences.allowIncompleteCompletions && hasUnresolvedAutoImports ? true : void 0, - isMemberCompletion: isMemberCompletionKind(completionKind), - isNewIdentifierLocation: isNewIdentifierLocation, - optionalReplacementSpan: getOptionalReplacementSpan(location), - entries: entries - }; + return createUndefined(); } - function isCheckedFile(sourceFile, compilerOptions) { - return !isSourceFileJS(sourceFile) || !!isCheckJsEnabledForFile(sourceFile, compilerOptions); + function createUndefined() { + return factory.createIdentifier("undefined"); } - function getExhaustiveCaseSnippets(caseBlock, sourceFile, preferences, options, host, program, formatContext) { - const clauses = caseBlock.clauses; - const checker = program.getTypeChecker(); - const switchType = checker.getTypeAtLocation(caseBlock.parent.expression); - if (switchType && switchType.isUnion() && every(switchType.types, (type)=>type.isLiteral())) { - const tracker = newCaseClauseTracker(checker, clauses); - const target = getEmitScriptTarget(options); - const quotePreference = getQuotePreference(sourceFile, preferences); - const importAdder = ts_codefix_exports.createImportAdder(sourceFile, program, preferences, host); - const elements = []; - for (const type of switchType.types){ - if (type.flags & 1024 /* EnumLiteral */ ) { - Debug.assert(type.symbol, "An enum member type should have a symbol"); - Debug.assert(type.symbol.parent, "An enum member type should have a parent symbol (the enum symbol)"); - const enumValue = type.symbol.valueDeclaration && checker.getConstantValue(type.symbol.valueDeclaration); - if (enumValue !== void 0) { - if (tracker.hasValue(enumValue)) continue; - tracker.addValue(enumValue); - } - const typeNode = ts_codefix_exports.typeToAutoImportableTypeNode(checker, importAdder, type, caseBlock, target); - if (!typeNode) return void 0; - const expr = typeNodeToExpression(typeNode, target, quotePreference); - if (!expr) return void 0; - elements.push(expr); - } else if (!tracker.hasValue(type.value)) switch(typeof type.value){ - case "object": - elements.push(type.value.negative ? factory.createPrefixUnaryExpression(40 /* MinusToken */ , factory.createBigIntLiteral({ - negative: false, - base10Value: type.value.base10Value - })) : factory.createBigIntLiteral(type.value)); - break; - case "number": - elements.push(type.value < 0 ? factory.createPrefixUnaryExpression(40 /* MinusToken */ , factory.createNumericLiteral(-type.value)) : factory.createNumericLiteral(type.value)); - break; - case "string": - elements.push(factory.createStringLiteral(type.value, quotePreference === 0 /* Single */ )); - break; - } - } - if (elements.length === 0) return void 0; - const newClauses = map(elements, (element)=>factory.createCaseClause(element, [])); - const newLineChar = getNewLineOrDefaultFromHost(host, formatContext == null ? void 0 : formatContext.options); - const printer = createSnippetPrinter({ - removeComments: true, - module: options.module, - target: options.target, - newLine: getNewLineKind(newLineChar) - }); - const printNode = formatContext ? (node)=>printer.printAndFormatNode(4 /* Unspecified */ , node, sourceFile, formatContext) : (node)=>printer.printNode(4 /* Unspecified */ , node, sourceFile); - const insertText = map(newClauses, (clause, i)=>{ - if (preferences.includeCompletionsWithSnippetText) return `${printNode(clause)}$${i + 1}`; - return `${printNode(clause)}`; - }).join(newLineChar); - const firstClause = printer.printNode(4 /* Unspecified */ , newClauses[0], sourceFile); - return { - entry: { - name: `${firstClause} ...`, - kind: "" /* unknown */ , - sortText: SortText.GlobalsOrKeywords, - insertText: insertText, - hasAction: importAdder.hasFixes() || void 0, - source: "SwitchCases/" /* SwitchCases */ , - isSnippet: preferences.includeCompletionsWithSnippetText ? true : void 0 - }, - importAdder: importAdder - }; - } - return void 0; + function isObjectLiteralType(type) { + return type.flags & 524288 /* Object */ && (getObjectFlags(type) & 128 /* ObjectLiteral */ || type.symbol && tryCast(singleOrUndefined(type.symbol.declarations), isTypeLiteralNode)); } - function typeNodeToExpression(typeNode, languageVersion, quotePreference) { - switch(typeNode.kind){ - case 180 /* TypeReference */ : - const typeName = typeNode.typeName; - return entityNameToExpression(typeName, languageVersion, quotePreference); - case 196 /* IndexedAccessType */ : - const objectExpression = typeNodeToExpression(typeNode.objectType, languageVersion, quotePreference); - const indexExpression = typeNodeToExpression(typeNode.indexType, languageVersion, quotePreference); - return objectExpression && indexExpression && factory.createElementAccessExpression(objectExpression, indexExpression); - case 198 /* LiteralType */ : - const literal = typeNode.literal; - switch(literal.kind){ - case 10 /* StringLiteral */ : - return factory.createStringLiteral(literal.text, quotePreference === 0 /* Single */ ); - case 8 /* NumericLiteral */ : - return factory.createNumericLiteral(literal.text, literal.numericLiteralFlags); - } - return void 0; - case 193 /* ParenthesizedType */ : - const exp = typeNodeToExpression(typeNode.type, languageVersion, quotePreference); - return exp && (isIdentifier(exp) ? exp : factory.createParenthesizedExpression(exp)); - case 183 /* TypeQuery */ : - return entityNameToExpression(typeNode.exprName, languageVersion, quotePreference); - case 202 /* ImportType */ : - Debug.fail(`We should not get an import type after calling 'codefix.typeToAutoImportableTypeNode'.`); + function getUnmatchedAttributes(checker, target, source) { + const attrsType = checker.getContextualType(source.attributes); + if (attrsType === void 0) return emptyArray; + const targetProps = attrsType.getProperties(); + if (!length(targetProps)) return emptyArray; + const seenNames = /* @__PURE__ */ new Set(); + for (const sourceProp of source.attributes.properties){ + if (isJsxAttribute(sourceProp)) seenNames.add(getEscapedTextOfJsxAttributeName(sourceProp.name)); + if (isJsxSpreadAttribute(sourceProp)) { + const type = checker.getTypeAtLocation(sourceProp.expression); + for (const prop of type.getProperties())seenNames.add(prop.escapedName); + } } - return void 0; + return filter(targetProps, (targetProp)=>isIdentifierText(targetProp.name, target, 1 /* JSX */ ) && !(targetProp.flags & 16777216 /* Optional */ || getCheckFlags(targetProp) & 48 /* Partial */ || seenNames.has(targetProp.escapedName))); } - function entityNameToExpression(entityName, languageVersion, quotePreference) { - if (isIdentifier(entityName)) return entityName; - const unescapedName = unescapeLeadingUnderscores(entityName.right.escapedText); - if (canUsePropertyAccess(unescapedName, languageVersion)) return factory.createPropertyAccessExpression(entityNameToExpression(entityName.left, languageVersion, quotePreference), unescapedName); - else return factory.createElementAccessExpression(entityNameToExpression(entityName.left, languageVersion, quotePreference), factory.createStringLiteral(unescapedName, quotePreference === 0 /* Single */ )); + function tryGetContainingMethodDeclaration(node, callExpression) { + if (isTypeLiteralNode(node)) return void 0; + const declaration = findAncestor(callExpression, (n)=>isMethodDeclaration(n) || isConstructorDeclaration(n)); + return declaration && declaration.parent === node ? declaration : void 0; } - function isMemberCompletionKind(kind) { - switch(kind){ - case 0 /* ObjectPropertyDeclaration */ : - case 3 /* MemberLike */ : - case 2 /* PropertyAccess */ : - return true; - default: - return false; + function createPropertyNameFromSymbol(symbol, target, quotePreference, checker) { + if (isTransientSymbol(symbol)) { + const prop = checker.symbolToNode(symbol, 111551 /* Value */ , /*enclosingDeclaration*/ void 0, 1073741824 /* WriteComputedProps */ ); + if (prop && isComputedPropertyName(prop)) return prop; } + return createPropertyNameNodeForIdentifierOrLiteral(symbol.name, target, quotePreference === 0 /* Single */ ); } - function getJsxClosingTagCompletion(location, sourceFile) { - const jsxClosingElement = findAncestor(location, (node)=>{ - switch(node.kind){ - case 284 /* JsxClosingElement */ : - return true; - case 43 /* SlashToken */ : - case 31 /* GreaterThanToken */ : - case 79 /* Identifier */ : - case 208 /* PropertyAccessExpression */ : - return false; - default: - return "quit"; - } - }); - if (jsxClosingElement) { - const hasClosingAngleBracket = !!findChildOfKind(jsxClosingElement, 31 /* GreaterThanToken */ , sourceFile); - const tagName = jsxClosingElement.parent.openingElement.tagName; - const closingTag = tagName.getText(sourceFile); - const fullClosingTag = closingTag + (hasClosingAngleBracket ? "" : ">"); - const replacementSpan = createTextSpanFromNode(jsxClosingElement.tagName); - const entry = { - name: fullClosingTag, - kind: "class" /* classElement */ , - kindModifiers: void 0, - sortText: SortText.LocationPriority - }; - return { - isGlobalCompletion: false, - isMemberCompletion: true, - isNewIdentifierLocation: false, - optionalReplacementSpan: replacementSpan, - entries: [ - entry - ] - }; + function findScope(node) { + if (findAncestor(node, isJsxExpression)) { + const returnStatement = findAncestor(node.parent, isReturnStatement); + if (returnStatement) return returnStatement; } - return; - } - function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { - getNameTable(sourceFile).forEach((pos, name)=>{ - if (pos === position) return; - const realName = unescapeLeadingUnderscores(name); - if (!uniqueNames.has(realName) && isIdentifierText(realName, target)) { - uniqueNames.add(realName); - insertSorted(entries, { - name: realName, - kind: "warning" /* warning */ , - kindModifiers: "", - sortText: SortText.JavascriptIdentifiers, - isFromUncheckedFile: true - }, compareCompletionEntries); - } - }); - } - function completionNameForLiteral(sourceFile, preferences, literal) { - return typeof literal === "object" ? pseudoBigIntToString(literal) + "n" : isString(literal) ? quote(sourceFile, preferences, literal) : JSON.stringify(literal); - } - function createCompletionEntryForLiteral(sourceFile, preferences, literal) { - return { - name: completionNameForLiteral(sourceFile, preferences, literal), - kind: "string" /* string */ , - kindModifiers: "" /* none */ , - sortText: SortText.LocationPriority - }; + return getSourceFileOfNode(node); } - function createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, position, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importStatementCompletion, useSemicolons, options, preferences, completionKind, formatContext, isJsxIdentifierExpected, isRightOfOpenTag, includeSymbol) { - let insertText; - let replacementSpan = getReplacementSpanForContextToken(replacementToken); - let data; - let isSnippet; - let source = getSourceFromOrigin(origin); - let sourceDisplay; - let hasAction; - let labelDetails; - const typeChecker = program.getTypeChecker(); - const insertQuestionDot = origin && originIsNullableMember(origin); - const useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess; - if (origin && originIsThisType(origin)) insertText = needsConvertPropertyAccess ? `this${insertQuestionDot ? "?." : ""}[${quotePropertyName(sourceFile, preferences, name)}]` : `this${insertQuestionDot ? "?." : "."}${name}`; - else if ((useBraces || insertQuestionDot) && propertyAccessToConvert) { - insertText = useBraces ? needsConvertPropertyAccess ? `[${quotePropertyName(sourceFile, preferences, name)}]` : `[${name}]` : name; - if (insertQuestionDot || propertyAccessToConvert.questionDotToken) insertText = `?.${insertText}`; - const dot = findChildOfKind(propertyAccessToConvert, 24 /* DotToken */ , sourceFile) || findChildOfKind(propertyAccessToConvert, 28 /* QuestionDotToken */ , sourceFile); - if (!dot) return void 0; - const end = startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end; - replacementSpan = createTextSpanFromBounds(dot.getStart(sourceFile), end); - } - if (isJsxInitializer) { - if (insertText === void 0) insertText = name; - insertText = `{${insertText}}`; - if (typeof isJsxInitializer !== "boolean") replacementSpan = createTextSpanFromNode(isJsxInitializer, sourceFile); - } - if (origin && originIsPromise(origin) && propertyAccessToConvert) { - if (insertText === void 0) insertText = name; - const precedingToken = findPrecedingToken(propertyAccessToConvert.pos, sourceFile); - let awaitText = ""; - if (precedingToken && positionIsASICandidate(precedingToken.end, precedingToken.parent, sourceFile)) awaitText = ";"; - awaitText += `(await ${propertyAccessToConvert.expression.getText()})`; - insertText = needsConvertPropertyAccess ? `${awaitText}${insertText}` : `${awaitText}${insertQuestionDot ? "?." : "."}${insertText}`; - const isInAwaitExpression = tryCast(propertyAccessToConvert.parent, isAwaitExpression); - const wrapNode = isInAwaitExpression ? propertyAccessToConvert.parent : propertyAccessToConvert.expression; - replacementSpan = createTextSpanFromBounds(wrapNode.getStart(sourceFile), propertyAccessToConvert.end); - } - if (originIsResolvedExport(origin)) { - sourceDisplay = [ - textPart(origin.moduleSpecifier) + var fixMissingMember, fixMissingProperties, fixMissingAttributes, fixMissingFunctionDeclaration, errorCodes27; + var init_fixAddMissingMember = __esm({ + "src/services/codefixes/fixAddMissingMember.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixMissingMember = "fixMissingMember"; + fixMissingProperties = "fixMissingProperties"; + fixMissingAttributes = "fixMissingAttributes"; + fixMissingFunctionDeclaration = "fixMissingFunctionDeclaration"; + errorCodes27 = [ + Diagnostics.Property_0_does_not_exist_on_type_1.code, + Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2.code, + Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2.code, + Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code, + Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, + Diagnostics.Cannot_find_name_0.code ]; - if (importStatementCompletion) { - ({ insertText: insertText , replacementSpan: replacementSpan } = getInsertTextAndReplacementSpanForImportCompletion(name, importStatementCompletion, origin, useSemicolons, sourceFile, options, preferences)); - isSnippet = preferences.includeCompletionsWithSnippetText ? true : void 0; - } - } - if ((origin == null ? void 0 : origin.kind) === 64 /* TypeOnlyAlias */ ) hasAction = true; - if (preferences.includeCompletionsWithClassMemberSnippets && preferences.includeCompletionsWithInsertText && completionKind === 3 /* MemberLike */ && isClassLikeMemberCompletion(symbol, location, sourceFile)) { - let importAdder; - ({ insertText: insertText , isSnippet: isSnippet , importAdder: importAdder , replacementSpan: replacementSpan } = getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, position, contextToken, formatContext)); - sortText = SortText.ClassMemberSnippets; - if (importAdder == null ? void 0 : importAdder.hasFixes()) { - hasAction = true; - source = "ClassMemberSnippet/" /* ClassMemberSnippet */ ; - } - } - if (origin && originIsObjectLiteralMethod(origin)) { - ({ insertText: insertText , isSnippet: isSnippet , labelDetails: labelDetails } = origin); - if (!preferences.useLabelDetailsInCompletionEntries) { - name = name + labelDetails.detail; - labelDetails = void 0; - } - source = "ObjectLiteralMethodSnippet/" /* ObjectLiteralMethodSnippet */ ; - sortText = SortText.SortBelow(sortText); - } - if (isJsxIdentifierExpected && !isRightOfOpenTag && preferences.includeCompletionsWithSnippetText && preferences.jsxAttributeCompletionStyle && preferences.jsxAttributeCompletionStyle !== "none" && !(isJsxAttribute(location.parent) && location.parent.initializer)) { - let useBraces2 = preferences.jsxAttributeCompletionStyle === "braces"; - const type = typeChecker.getTypeOfSymbolAtLocation(symbol, location); - if (preferences.jsxAttributeCompletionStyle === "auto" && !(type.flags & 528 /* BooleanLike */ ) && !(type.flags & 1048576 /* Union */ && find(type.types, (type2)=>!!(type2.flags & 528 /* BooleanLike */ )))) { - if (type.flags & 402653316 /* StringLike */ || type.flags & 1048576 /* Union */ && every(type.types, (type2)=>!!(type2.flags & 402686084 /* Undefined */ || isStringAndEmptyAnonymousObjectIntersection(type2)))) { - insertText = `${escapeSnippetText(name)}=${quote(sourceFile, preferences, "$1")}`; - isSnippet = true; - } else useBraces2 = true; - } - if (useBraces2) { - insertText = `${escapeSnippetText(name)}={$1}`; - isSnippet = true; - } - } - if (insertText !== void 0 && !preferences.includeCompletionsWithInsertText) return void 0; - if (originIsExport(origin) || originIsResolvedExport(origin)) { - data = originToCompletionEntryData(origin); - hasAction = !importStatementCompletion; + registerCodeFix({ + errorCodes: errorCodes27, + getCodeActions (context) { + const typeChecker = context.program.getTypeChecker(); + const info = getInfo10(context.sourceFile, context.span.start, context.errorCode, typeChecker, context.program); + if (!info) return void 0; + if (info.kind === 3 /* ObjectLiteral */ ) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addObjectLiteralProperties(t, context, info)); + return [ + createCodeFixAction(fixMissingProperties, changes, Diagnostics.Add_missing_properties, fixMissingProperties, Diagnostics.Add_all_missing_properties) + ]; + } + if (info.kind === 4 /* JsxAttributes */ ) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addJsxAttributes(t, context, info)); + return [ + createCodeFixAction(fixMissingAttributes, changes, Diagnostics.Add_missing_attributes, fixMissingAttributes, Diagnostics.Add_all_missing_attributes) + ]; + } + if (info.kind === 2 /* Function */ || info.kind === 5 /* Signature */ ) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addFunctionDeclaration(t, context, info)); + return [ + createCodeFixAction(fixMissingFunctionDeclaration, changes, [ + Diagnostics.Add_missing_function_declaration_0, + info.token.text + ], fixMissingFunctionDeclaration, Diagnostics.Add_all_missing_function_declarations) + ]; + } + if (info.kind === 1 /* Enum */ ) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addEnumMemberDeclaration(t, context.program.getTypeChecker(), info)); + return [ + createCodeFixAction(fixMissingMember, changes, [ + Diagnostics.Add_missing_enum_member_0, + info.token.text + ], fixMissingMember, Diagnostics.Add_all_missing_members) + ]; + } + return concatenate(getActionsForMissingMethodDeclaration(context, info), getActionsForMissingMemberDeclaration(context, info)); + }, + fixIds: [ + fixMissingMember, + fixMissingFunctionDeclaration, + fixMissingProperties, + fixMissingAttributes + ], + getAllCodeActions: (context)=>{ + const { program: program, fixId: fixId52 } = context; + const checker = program.getTypeChecker(); + const seen = /* @__PURE__ */ new Map(); + const typeDeclToMembers = /* @__PURE__ */ new Map(); + return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes)=>{ + eachDiagnostic(context, errorCodes27, (diag2)=>{ + const info = getInfo10(diag2.file, diag2.start, diag2.code, checker, context.program); + if (!info || !addToSeen(seen, getNodeId(info.parentDeclaration) + "#" + info.token.text)) return; + if (fixId52 === fixMissingFunctionDeclaration && (info.kind === 2 /* Function */ || info.kind === 5 /* Signature */ )) addFunctionDeclaration(changes, context, info); + else if (fixId52 === fixMissingProperties && info.kind === 3 /* ObjectLiteral */ ) addObjectLiteralProperties(changes, context, info); + else if (fixId52 === fixMissingAttributes && info.kind === 4 /* JsxAttributes */ ) addJsxAttributes(changes, context, info); + else { + if (info.kind === 1 /* Enum */ ) addEnumMemberDeclaration(changes, checker, info); + if (info.kind === 0 /* TypeLikeDeclaration */ ) { + const { parentDeclaration: parentDeclaration, token: token } = info; + const infos = getOrUpdate(typeDeclToMembers, parentDeclaration, ()=>[]); + if (!infos.some((i)=>i.token.text === token.text)) infos.push(info); + } + } + }); + typeDeclToMembers.forEach((infos, declaration)=>{ + const supers = isTypeLiteralNode(declaration) ? void 0 : getAllSupers(declaration, checker); + for (const info of infos){ + if (supers == null ? void 0 : supers.some((superClassOrInterface)=>{ + const superInfos = typeDeclToMembers.get(superClassOrInterface); + return !!superInfos && superInfos.some(({ token: token2 })=>token2.text === info.token.text); + })) continue; + const { parentDeclaration: parentDeclaration, declSourceFile: declSourceFile, modifierFlags: modifierFlags, token: token, call: call, isJSFile: isJSFile } = info; + if (call && !isPrivateIdentifier(token)) addMethodDeclaration(context, changes, call, token, modifierFlags & 32 /* Static */ , parentDeclaration, declSourceFile); + else if (isJSFile && !isInterfaceDeclaration(parentDeclaration) && !isTypeLiteralNode(parentDeclaration)) addMissingMemberInJs(changes, declSourceFile, parentDeclaration, token, !!(modifierFlags & 32 /* Static */ )); + else { + const typeNode = getTypeNode2(checker, parentDeclaration, token); + addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, modifierFlags & 32 /* Static */ ); + } + } + }); + })); + } + }); } - return { - name: name, - kind: ts_SymbolDisplay_exports.getSymbolKind(typeChecker, symbol, location), - kindModifiers: ts_SymbolDisplay_exports.getSymbolModifiers(typeChecker, symbol), - sortText: sortText, - source: source, - hasAction: hasAction ? true : void 0, - isRecommended: isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker) || void 0, - insertText: insertText, - replacementSpan: replacementSpan, - sourceDisplay: sourceDisplay, - labelDetails: labelDetails, - isSnippet: isSnippet, - isPackageJsonImport: originIsPackageJsonImport(origin) || void 0, - isImportStatementCompletion: !!importStatementCompletion || void 0, - data: data, - ...includeSymbol ? { - symbol: symbol - } : void 0 - }; + }); + // src/services/codefixes/fixAddMissingNewOperator.ts + function addMissingNewOperator(changes, sourceFile, span) { + const call = cast(findAncestorMatchingSpan2(sourceFile, span), isCallExpression); + const newExpression = factory.createNewExpression(call.expression, call.typeArguments, call.arguments); + changes.replaceNode(sourceFile, call, newExpression); } - function isClassLikeMemberCompletion(symbol, location, sourceFile) { - if (isInJSFile(location)) return false; - const memberFlags = 106500 /* EnumMemberExcludes */ ; - return !!(symbol.flags & memberFlags) && (isClassLike(location) || location.parent && location.parent.parent && isClassElement(location.parent) && location === location.parent.name && location.parent.getLastToken(sourceFile) === location.parent.name && isClassLike(location.parent.parent) || location.parent && isSyntaxList(location) && isClassLike(location.parent)); + function findAncestorMatchingSpan2(sourceFile, span) { + let token = getTokenAtPosition(sourceFile, span.start); + const end = textSpanEnd(span); + while(token.end < end)token = token.parent; + return token; } - function getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, position, contextToken, formatContext) { - const classLikeDeclaration = findAncestor(location, isClassLike); - if (!classLikeDeclaration) return { - insertText: name - }; - let isSnippet; - let replacementSpan; - let insertText = name; - const checker = program.getTypeChecker(); - const sourceFile = location.getSourceFile(); - const printer = createSnippetPrinter({ - removeComments: true, - module: options.module, - target: options.target, - omitTrailingSemicolon: false, - newLine: getNewLineKind(getNewLineOrDefaultFromHost(host, formatContext == null ? void 0 : formatContext.options)) - }); - const importAdder = ts_codefix_exports.createImportAdder(sourceFile, program, preferences, host); - let body; - if (preferences.includeCompletionsWithSnippetText) { - isSnippet = true; - const emptyStmt = factory.createEmptyStatement(); - body = factory.createBlock([ - emptyStmt - ], /* multiline */ true); - setSnippetElement(emptyStmt, { - kind: 0 /* TabStop */ , - order: 0 + var fixId24, errorCodes28; + var init_fixAddMissingNewOperator = __esm({ + "src/services/codefixes/fixAddMissingNewOperator.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId24 = "addMissingNewOperator"; + errorCodes28 = [ + Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new.code + ]; + registerCodeFix({ + errorCodes: errorCodes28, + getCodeActions (context) { + const { sourceFile: sourceFile, span: span } = context; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addMissingNewOperator(t, sourceFile, span)); + return [ + createCodeFixAction(fixId24, changes, Diagnostics.Add_missing_new_operator_to_call, fixId24, Diagnostics.Add_missing_new_operator_to_all_calls) + ]; + }, + fixIds: [ + fixId24 + ], + getAllCodeActions: (context)=>codeFixAll(context, errorCodes28, (changes, diag2)=>addMissingNewOperator(changes, context.sourceFile, diag2)) }); - } else body = factory.createBlock([], /* multiline */ true); - let modifiers = 0 /* None */ ; - const { modifiers: presentModifiers , span: modifiersSpan } = getPresentModifiers(contextToken, sourceFile, position); - const isAbstract = !!(presentModifiers & 256 /* Abstract */ ); - const completionNodes = []; - ts_codefix_exports.addNewNodeForMemberSymbol(symbol, classLikeDeclaration, sourceFile, { - program: program, - host: host - }, preferences, importAdder, // `addNewNodeForMemberSymbol` calls this callback function for each new member node - // it adds for the given member symbol. - // We store these member nodes in the `completionNodes` array. - // Note: there might be: - // - No nodes if `addNewNodeForMemberSymbol` cannot figure out a node for the member; - // - One node; - // - More than one node if the member is overloaded (e.g. a method with overload signatures). - (node)=>{ - let requiredModifiers = 0 /* None */ ; - if (isAbstract) requiredModifiers |= 256 /* Abstract */ ; - if (isClassElement(node) && checker.getMemberOverrideModifierStatus(classLikeDeclaration, node, symbol) === 1 /* NeedsOverride */ ) requiredModifiers |= 16384 /* Override */ ; - if (!completionNodes.length) modifiers = node.modifierFlagsCache | requiredModifiers | presentModifiers; - node = factory.updateModifiers(node, modifiers); - completionNodes.push(node); - }, body, ts_codefix_exports.PreserveOptionalFlags.Property, isAbstract); - if (completionNodes.length) { - const format = 131073 /* NoTrailingNewLine */ ; - replacementSpan = modifiersSpan; - if (formatContext) insertText = printer.printAndFormatSnippetList(format, factory.createNodeArray(completionNodes), sourceFile, formatContext); - else insertText = printer.printSnippetList(format, factory.createNodeArray(completionNodes), sourceFile); } + }); + // src/services/codefixes/fixCannotFindModule.ts + function getInstallCommand(fileName, packageName) { return { - insertText: insertText, - isSnippet: isSnippet, - importAdder: importAdder, - replacementSpan: replacementSpan + type: "install package", + file: fileName, + packageName: packageName }; } - function getPresentModifiers(contextToken, sourceFile, position) { - if (!contextToken || getLineAndCharacterOfPosition(sourceFile, position).line > getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line) return { - modifiers: 0 /* None */ - }; - let modifiers = 0 /* None */ ; - let span; - let contextMod; - if (contextMod = isModifierLike2(contextToken)) { - modifiers |= modifierToFlag(contextMod); - span = createTextSpanFromNode(contextToken); - } - if (isPropertyDeclaration(contextToken.parent)) { - modifiers |= modifiersToFlags(contextToken.parent.modifiers) & 126975 /* Modifier */ ; - span = createTextSpanFromNode(contextToken.parent); - } - return { - modifiers: modifiers, - span: span - }; + function tryGetImportedPackageName(sourceFile, pos) { + const moduleSpecifierText = tryCast(getTokenAtPosition(sourceFile, pos), isStringLiteral); + if (!moduleSpecifierText) return void 0; + const moduleName = moduleSpecifierText.text; + const { packageName: packageName } = parsePackageName(moduleName); + return isExternalModuleNameRelative(packageName) ? void 0 : packageName; } - function isModifierLike2(node) { - if (isModifier(node)) return node.kind; - if (isIdentifier(node)) { - const originalKeywordKind = identifierToKeywordKind(node); - if (originalKeywordKind && isModifierKind(originalKeywordKind)) return originalKeywordKind; - } - return void 0; + function getTypesPackageNameToInstall(packageName, host, diagCode) { + var _a; + return diagCode === errorCodeCannotFindModule ? ts_JsTyping_exports.nodeCoreModules.has(packageName) ? "@types/node" : void 0 : ((_a = host.isKnownTypesPackageName) == null ? void 0 : _a.call(host, packageName)) ? getTypesPackageName(packageName) : void 0; } - function getEntryForObjectLiteralMethodCompletion(symbol, name, enclosingDeclaration, program, host, options, preferences, formatContext) { - const isSnippet = preferences.includeCompletionsWithSnippetText || void 0; - let insertText = name; - const sourceFile = enclosingDeclaration.getSourceFile(); - const method = createObjectLiteralMethod(symbol, enclosingDeclaration, sourceFile, program, host, preferences); - if (!method) return void 0; - const printer = createSnippetPrinter({ - removeComments: true, - module: options.module, - target: options.target, - omitTrailingSemicolon: false, - newLine: getNewLineKind(getNewLineOrDefaultFromHost(host, formatContext == null ? void 0 : formatContext.options)) - }); - if (formatContext) insertText = printer.printAndFormatSnippetList(80 /* AllowTrailingComma */ , factory.createNodeArray([ - method - ], /*hasTrailingComma*/ true), sourceFile, formatContext); - else insertText = printer.printSnippetList(80 /* AllowTrailingComma */ , factory.createNodeArray([ - method - ], /*hasTrailingComma*/ true), sourceFile); - const signaturePrinter = createPrinter({ - removeComments: true, - module: options.module, - target: options.target, - omitTrailingSemicolon: true - }); - const methodSignature = factory.createMethodSignature(/*modifiers*/ void 0, /*name*/ "", method.questionToken, method.typeParameters, method.parameters, method.type); - const labelDetails = { - detail: signaturePrinter.printNode(4 /* Unspecified */ , methodSignature, sourceFile) - }; - return { - isSnippet: isSnippet, - insertText: insertText, - labelDetails: labelDetails - }; - } - function createObjectLiteralMethod(symbol, enclosingDeclaration, sourceFile, program, host, preferences) { - const declarations = symbol.getDeclarations(); - if (!(declarations && declarations.length)) return void 0; - const checker = program.getTypeChecker(); - const declaration = declarations[0]; - const name = getSynthesizedDeepClone(getNameOfDeclaration(declaration), /*includeTrivia*/ false); - const type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); - const quotePreference = getQuotePreference(sourceFile, preferences); - const builderFlags = 33554432 /* OmitThisParameter */ | (quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : 0 /* None */ ); - switch(declaration.kind){ - case 168 /* PropertySignature */ : - case 169 /* PropertyDeclaration */ : - case 170 /* MethodSignature */ : - case 171 /* MethodDeclaration */ : - { - let effectiveType = type.flags & 1048576 /* Union */ && type.types.length < 10 ? checker.getUnionType(type.types, 2 /* Subtype */ ) : type; - if (effectiveType.flags & 1048576 /* Union */ ) { - const functionTypes = filter(effectiveType.types, (type2)=>checker.getSignaturesOfType(type2, 0 /* Call */ ).length > 0); - if (functionTypes.length === 1) effectiveType = functionTypes[0]; - else return void 0; - } - const signatures = checker.getSignaturesOfType(effectiveType, 0 /* Call */ ); - if (signatures.length !== 1) return void 0; - const typeNode = checker.typeToTypeNode(effectiveType, enclosingDeclaration, builderFlags, ts_codefix_exports.getNoopSymbolTrackerWithResolver({ - program: program, - host: host - })); - if (!typeNode || !isFunctionTypeNode(typeNode)) return void 0; - let body; - if (preferences.includeCompletionsWithSnippetText) { - const emptyStmt = factory.createEmptyStatement(); - body = factory.createBlock([ - emptyStmt - ], /* multiline */ true); - setSnippetElement(emptyStmt, { - kind: 0 /* TabStop */ , - order: 0 - }); - } else body = factory.createBlock([], /* multiline */ true); - const parameters = typeNode.parameters.map((typedParam)=>factory.createParameterDeclaration(/*modifiers*/ void 0, typedParam.dotDotDotToken, typedParam.name, /*questionToken*/ void 0, /*type*/ void 0, typedParam.initializer)); - return factory.createMethodDeclaration(/*modifiers*/ void 0, /*asteriskToken*/ void 0, name, /*questionToken*/ void 0, /*typeParameters*/ void 0, parameters, /*type*/ void 0, body); - } - default: - return void 0; - } - } - function createSnippetPrinter(printerOptions) { - let escapes; - const baseWriter = ts_textChanges_exports.createWriter(getNewLineCharacter(printerOptions)); - const printer = createPrinter(printerOptions, baseWriter); - const writer = { - ...baseWriter, - write: (s)=>escapingWrite(s, ()=>baseWriter.write(s)), - nonEscapingWrite: baseWriter.write, - writeLiteral: (s)=>escapingWrite(s, ()=>baseWriter.writeLiteral(s)), - writeStringLiteral: (s)=>escapingWrite(s, ()=>baseWriter.writeStringLiteral(s)), - writeSymbol: (s, symbol)=>escapingWrite(s, ()=>baseWriter.writeSymbol(s, symbol)), - writeParameter: (s)=>escapingWrite(s, ()=>baseWriter.writeParameter(s)), - writeComment: (s)=>escapingWrite(s, ()=>baseWriter.writeComment(s)), - writeProperty: (s)=>escapingWrite(s, ()=>baseWriter.writeProperty(s)) - }; - return { - printSnippetList: printSnippetList, - printAndFormatSnippetList: printAndFormatSnippetList, - printNode: printNode, - printAndFormatNode: printAndFormatNode - }; - function escapingWrite(s, write) { - const escaped = escapeSnippetText(s); - if (escaped !== s) { - const start = baseWriter.getTextPos(); - write(); - const end = baseWriter.getTextPos(); - escapes = append(escapes || (escapes = []), { - newText: escaped, - span: { - start: start, - length: end - start - } - }); - } else write(); - } - function printSnippetList(format, list, sourceFile) { - const unescaped = printUnescapedSnippetList(format, list, sourceFile); - return escapes ? ts_textChanges_exports.applyChanges(unescaped, escapes) : unescaped; - } - function printUnescapedSnippetList(format, list, sourceFile) { - escapes = void 0; - writer.clear(); - printer.writeList(format, list, sourceFile, writer); - return writer.getText(); - } - function printAndFormatSnippetList(format, list, sourceFile, formatContext) { - const syntheticFile = { - text: printUnescapedSnippetList(format, list, sourceFile), - getLineAndCharacterOfPosition (pos) { - return getLineAndCharacterOfPosition(this, pos); + var fixName2, fixIdInstallTypesPackage, errorCodeCannotFindModule, errorCodes29; + var init_fixCannotFindModule = __esm({ + "src/services/codefixes/fixCannotFindModule.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixName2 = "fixCannotFindModule"; + fixIdInstallTypesPackage = "installTypesPackage"; + errorCodeCannotFindModule = Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations.code; + errorCodes29 = [ + errorCodeCannotFindModule, + Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code + ]; + registerCodeFix({ + errorCodes: errorCodes29, + getCodeActions: function getCodeActionsToFixNotFoundModule(context) { + const { host: host, sourceFile: sourceFile, span: { start: start } } = context; + const packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === void 0) return void 0; + const typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === void 0 ? [] : [ + createCodeFixAction(fixName2, /*changes*/ [], [ + Diagnostics.Install_0, + typesPackageName + ], fixIdInstallTypesPackage, Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName)) + ]; + }, + fixIds: [ + fixIdInstallTypesPackage + ], + getAllCodeActions: (context)=>{ + return codeFixAll(context, errorCodes29, (_changes, diag2, commands)=>{ + const packageName = tryGetImportedPackageName(diag2.file, diag2.start); + if (packageName === void 0) return void 0; + switch(context.fixId){ + case fixIdInstallTypesPackage: + { + const pkg = getTypesPackageNameToInstall(packageName, context.host, diag2.code); + if (pkg) commands.push(getInstallCommand(diag2.file.fileName, pkg)); + break; + } + default: + Debug.fail(`Bad fixId: ${context.fixId}`); + } + }); } - }; - const formatOptions = getFormatCodeSettingsForWriting(formatContext, sourceFile); - const changes = flatMap(list, (node)=>{ - const nodeWithPos = ts_textChanges_exports.assignPositionsToNode(node); - return ts_formatting_exports.formatNodeGivenIndentation(nodeWithPos, syntheticFile, sourceFile.languageVariant, /* indentation */ 0, /* delta */ 0, { - ...formatContext, - options: formatOptions - }); }); - const allChanges = escapes ? stableSort(concatenate(changes, escapes), (a, b)=>compareTextSpans(a.span, b.span)) : changes; - return ts_textChanges_exports.applyChanges(syntheticFile.text, allChanges); - } - function printNode(hint, node, sourceFile) { - const unescaped = printUnescapedNode(hint, node, sourceFile); - return escapes ? ts_textChanges_exports.applyChanges(unescaped, escapes) : unescaped; } - function printUnescapedNode(hint, node, sourceFile) { - escapes = void 0; - writer.clear(); - printer.writeNode(hint, node, sourceFile, writer); - return writer.getText(); - } - function printAndFormatNode(hint, node, sourceFile, formatContext) { - const syntheticFile = { - text: printUnescapedNode(hint, node, sourceFile), - getLineAndCharacterOfPosition (pos) { - return getLineAndCharacterOfPosition(this, pos); + }); + // src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts + function getClass2(sourceFile, pos) { + const token = getTokenAtPosition(sourceFile, pos); + return cast(token.parent, isClassLike); + } + function addMissingMembers(classDeclaration, sourceFile, context, changeTracker, preferences) { + const extendsNode = getEffectiveBaseTypeNode(classDeclaration); + const checker = context.program.getTypeChecker(); + const instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); + const abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); + const importAdder = createImportAdder(sourceFile, context.program, preferences, context.host); + createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, sourceFile, context, preferences, importAdder, (member)=>changeTracker.insertMemberAtStart(sourceFile, classDeclaration, member)); + importAdder.writeFixes(changeTracker); + } + function symbolPointsToNonPrivateAndAbstractMember(symbol) { + const flags = getSyntacticModifierFlags(first(symbol.getDeclarations())); + return !(flags & 8 /* Private */ ) && !!(flags & 256 /* Abstract */ ); + } + var errorCodes30, fixId25; + var init_fixClassDoesntImplementInheritedAbstractMember = __esm({ + "src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + errorCodes30 = [ + Diagnostics.Non_abstract_class_0_does_not_implement_all_abstract_members_of_1.code + ]; + fixId25 = "fixClassDoesntImplementInheritedAbstractMember"; + registerCodeFix({ + errorCodes: errorCodes30, + getCodeActions: function getCodeActionsToFixClassNotImplementingInheritedMembers(context) { + const { sourceFile: sourceFile, span: span } = context; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addMissingMembers(getClass2(sourceFile, span.start), sourceFile, context, t, context.preferences)); + return changes.length === 0 ? void 0 : [ + createCodeFixAction(fixId25, changes, Diagnostics.Implement_inherited_abstract_class, fixId25, Diagnostics.Implement_all_inherited_abstract_classes) + ]; + }, + fixIds: [ + fixId25 + ], + getAllCodeActions: function getAllCodeActionsToFixClassDoesntImplementInheritedAbstractMember(context) { + const seenClassDeclarations = /* @__PURE__ */ new Map(); + return codeFixAll(context, errorCodes30, (changes, diag2)=>{ + const classDeclaration = getClass2(diag2.file, diag2.start); + if (addToSeen(seenClassDeclarations, getNodeId(classDeclaration))) addMissingMembers(classDeclaration, context.sourceFile, context, changes, context.preferences); + }); } - }; - const formatOptions = getFormatCodeSettingsForWriting(formatContext, sourceFile); - const nodeWithPos = ts_textChanges_exports.assignPositionsToNode(node); - const changes = ts_formatting_exports.formatNodeGivenIndentation(nodeWithPos, syntheticFile, sourceFile.languageVariant, /* indentation */ 0, /* delta */ 0, { - ...formatContext, - options: formatOptions }); - const allChanges = escapes ? stableSort(concatenate(changes, escapes), (a, b)=>compareTextSpans(a.span, b.span)) : changes; - return ts_textChanges_exports.applyChanges(syntheticFile.text, allChanges); } + }); + // src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts + function doChange19(changes, sourceFile, constructor, superCall) { + changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall); + changes.delete(sourceFile, superCall); } - function originToCompletionEntryData(origin) { - const ambientModuleName = origin.fileName ? void 0 : stripQuotes(origin.moduleSymbol.name); - const isPackageJsonImport = origin.isFromPackageJson ? true : void 0; - if (originIsResolvedExport(origin)) { - const resolvedData = { - exportName: origin.exportName, - exportMapKey: origin.exportMapKey, - moduleSpecifier: origin.moduleSpecifier, - ambientModuleName: ambientModuleName, - fileName: origin.fileName, - isPackageJsonImport: isPackageJsonImport - }; - return resolvedData; - } - const unresolvedData = { - exportName: origin.exportName, - exportMapKey: origin.exportMapKey, - fileName: origin.fileName, - ambientModuleName: origin.fileName ? void 0 : stripQuotes(origin.moduleSymbol.name), - isPackageJsonImport: origin.isFromPackageJson ? true : void 0 - }; - return unresolvedData; + function getNodes(sourceFile, pos) { + const token = getTokenAtPosition(sourceFile, pos); + if (token.kind !== 110 /* ThisKeyword */ ) return void 0; + const constructor = getContainingFunction(token); + const superCall = findSuperCall(constructor.body); + return superCall && !superCall.expression.arguments.some((arg)=>isPropertyAccessExpression(arg) && arg.expression === token) ? { + constructor: constructor, + superCall: superCall + } : void 0; } - function completionEntryDataToSymbolOriginInfo(data, completionName, moduleSymbol) { - const isDefaultExport = data.exportName === "default" /* Default */ ; - const isFromPackageJson = !!data.isPackageJsonImport; - if (completionEntryDataIsResolved(data)) { - const resolvedOrigin = { - kind: 32 /* ResolvedExport */ , - exportName: data.exportName, - exportMapKey: data.exportMapKey, - moduleSpecifier: data.moduleSpecifier, - symbolName: completionName, - fileName: data.fileName, - moduleSymbol: moduleSymbol, - isDefaultExport: isDefaultExport, - isFromPackageJson: isFromPackageJson - }; - return resolvedOrigin; - } - const unresolvedOrigin = { - kind: 4 /* Export */ , - exportName: data.exportName, - exportMapKey: data.exportMapKey, - symbolName: completionName, - fileName: data.fileName, - moduleSymbol: moduleSymbol, - isDefaultExport: isDefaultExport, - isFromPackageJson: isFromPackageJson - }; - return unresolvedOrigin; + function findSuperCall(n) { + return isExpressionStatement(n) && isSuperCall(n.expression) ? n : isFunctionLike(n) ? void 0 : forEachChild(n, findSuperCall); } - function getInsertTextAndReplacementSpanForImportCompletion(name, importStatementCompletion, origin, useSemicolons, sourceFile, options, preferences) { - const replacementSpan = importStatementCompletion.replacementSpan; - const quotedModuleSpecifier = quote(sourceFile, preferences, escapeSnippetText(origin.moduleSpecifier)); - const exportKind = origin.isDefaultExport ? 1 /* Default */ : origin.exportName === "export=" /* ExportEquals */ ? 2 /* ExportEquals */ : 0 /* Named */ ; - const tabStop = preferences.includeCompletionsWithSnippetText ? "$1" : ""; - const importKind = ts_codefix_exports.getImportKind(sourceFile, exportKind, options, /*forceImportKeyword*/ true); - const isImportSpecifierTypeOnly = importStatementCompletion.couldBeTypeOnlyImportSpecifier; - const topLevelTypeOnlyText = importStatementCompletion.isTopLevelTypeOnly ? ` ${tokenToString(154 /* TypeKeyword */ )} ` : " "; - const importSpecifierTypeOnlyText = isImportSpecifierTypeOnly ? `${tokenToString(154 /* TypeKeyword */ )} ` : ""; - const suffix = useSemicolons ? ";" : ""; - switch(importKind){ - case 3 /* CommonJS */ : - return { - replacementSpan: replacementSpan, - insertText: `import${topLevelTypeOnlyText}${escapeSnippetText(name)}${tabStop} = require(${quotedModuleSpecifier})${suffix}` - }; - case 1 /* Default */ : - return { - replacementSpan: replacementSpan, - insertText: `import${topLevelTypeOnlyText}${escapeSnippetText(name)}${tabStop} from ${quotedModuleSpecifier}${suffix}` - }; - case 2 /* Namespace */ : - return { - replacementSpan: replacementSpan, - insertText: `import${topLevelTypeOnlyText}* as ${escapeSnippetText(name)} from ${quotedModuleSpecifier}${suffix}` - }; - case 0 /* Named */ : - return { - replacementSpan: replacementSpan, - insertText: `import${topLevelTypeOnlyText}{ ${importSpecifierTypeOnlyText}${escapeSnippetText(name)}${tabStop} } from ${quotedModuleSpecifier}${suffix}` - }; + var fixId26, errorCodes31; + var init_fixClassSuperMustPrecedeThisAccess = __esm({ + "src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId26 = "classSuperMustPrecedeThisAccess"; + errorCodes31 = [ + Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code + ]; + registerCodeFix({ + errorCodes: errorCodes31, + getCodeActions (context) { + const { sourceFile: sourceFile, span: span } = context; + const nodes = getNodes(sourceFile, span.start); + if (!nodes) return void 0; + const { constructor: constructor, superCall: superCall } = nodes; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange19(t, sourceFile, constructor, superCall)); + return [ + createCodeFixAction(fixId26, changes, Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId26, Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor) + ]; + }, + fixIds: [ + fixId26 + ], + getAllCodeActions (context) { + const { sourceFile: sourceFile } = context; + const seenClasses = /* @__PURE__ */ new Map(); + return codeFixAll(context, errorCodes31, (changes, diag2)=>{ + const nodes = getNodes(diag2.file, diag2.start); + if (!nodes) return; + const { constructor: constructor, superCall: superCall } = nodes; + if (addToSeen(seenClasses, getNodeId(constructor.parent))) doChange19(changes, sourceFile, constructor, superCall); + }); + } + }); } + }); + // src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts + function getNode(sourceFile, pos) { + const token = getTokenAtPosition(sourceFile, pos); + Debug.assert(isConstructorDeclaration(token.parent), "token should be at the constructor declaration"); + return token.parent; } - function quotePropertyName(sourceFile, preferences, name) { - if (/^\d+$/.test(name)) return name; - return quote(sourceFile, preferences, name); - } - function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { - return localSymbol === recommendedCompletion || !!(localSymbol.flags & 1048576 /* ExportValue */ ) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion; + function doChange20(changes, sourceFile, ctr) { + const superCall = factory.createExpressionStatement(factory.createCallExpression(factory.createSuper(), /*typeArguments*/ void 0, /*argumentsArray*/ emptyArray)); + changes.insertNodeAtConstructorStart(sourceFile, ctr, superCall); } - function getSourceFromOrigin(origin) { - if (originIsExport(origin)) return stripQuotes(origin.moduleSymbol.name); - if (originIsResolvedExport(origin)) return origin.moduleSpecifier; - if ((origin == null ? void 0 : origin.kind) === 1 /* ThisType */ ) return "ThisProperty/" /* ThisProperty */ ; - if ((origin == null ? void 0 : origin.kind) === 64 /* TypeOnlyAlias */ ) return "TypeOnlyAlias/" /* TypeOnlyAlias */ ; + var fixId27, errorCodes32; + var init_fixConstructorForDerivedNeedSuperCall = __esm({ + "src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId27 = "constructorForDerivedNeedSuperCall"; + errorCodes32 = [ + Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code + ]; + registerCodeFix({ + errorCodes: errorCodes32, + getCodeActions (context) { + const { sourceFile: sourceFile, span: span } = context; + const ctr = getNode(sourceFile, span.start); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange20(t, sourceFile, ctr)); + return [ + createCodeFixAction(fixId27, changes, Diagnostics.Add_missing_super_call, fixId27, Diagnostics.Add_all_missing_super_calls) + ]; + }, + fixIds: [ + fixId27 + ], + getAllCodeActions: (context)=>codeFixAll(context, errorCodes32, (changes, diag2)=>doChange20(changes, context.sourceFile, getNode(diag2.file, diag2.start))) + }); + } + }); + // src/services/codefixes/fixEnableJsxFlag.ts + function doChange21(changeTracker, configFile) { + setJsonCompilerOptionValue(changeTracker, configFile, "jsx", factory.createStringLiteral("react")); } - function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, contextToken, location, position, sourceFile, host, program, target, log, kind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importStatementCompletion, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag, includeSymbol = false) { - var _a2; - const start = timestamp(); - const variableDeclaration = getVariableDeclaration(location); - const useSemicolons = probablyUsesSemicolons(sourceFile); - const typeChecker = program.getTypeChecker(); - const uniques = /* @__PURE__ */ new Map(); - for(let i = 0; i < symbols.length; i++){ - const symbol = symbols[i]; - const origin = symbolToOriginInfoMap == null ? void 0 : symbolToOriginInfoMap[i]; - const info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, !!jsxIdentifierExpected); - if (!info || uniques.get(info.name) && (!origin || !originIsObjectLiteralMethod(origin)) || kind === 1 /* Global */ && symbolToSortTextMap && !shouldIncludeSymbol(symbol, symbolToSortTextMap)) continue; - const { name: name , needsConvertPropertyAccess: needsConvertPropertyAccess } = info; - const originalSortText = (_a2 = symbolToSortTextMap == null ? void 0 : symbolToSortTextMap[getSymbolId(symbol)]) != null ? _a2 : SortText.LocationPriority; - const sortText = isDeprecated(symbol, typeChecker) ? SortText.Deprecated(originalSortText) : originalSortText; - const entry = createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, position, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importStatementCompletion, useSemicolons, compilerOptions, preferences, kind, formatContext, isJsxIdentifierExpected, isRightOfOpenTag, includeSymbol); - if (!entry) continue; - const shouldShadowLaterSymbols = (!origin || originIsTypeOnlyAlias(origin)) && !(symbol.parent === void 0 && !some(symbol.declarations, (d)=>d.getSourceFile() === location.getSourceFile())); - uniques.set(name, shouldShadowLaterSymbols); - insertSorted(entries, entry, compareCompletionEntries, /*allowDuplicates*/ true); + var fixID, errorCodes33; + var init_fixEnableJsxFlag = __esm({ + "src/services/codefixes/fixEnableJsxFlag.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixID = "fixEnableJsxFlag"; + errorCodes33 = [ + Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided.code + ]; + registerCodeFix({ + errorCodes: errorCodes33, + getCodeActions: function getCodeActionsToFixEnableJsxFlag(context) { + const { configFile: configFile } = context.program.getCompilerOptions(); + if (configFile === void 0) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (changeTracker)=>doChange21(changeTracker, configFile)); + return [ + createCodeFixActionWithoutFixAll(fixID, changes, Diagnostics.Enable_the_jsx_flag_in_your_configuration_file) + ]; + }, + fixIds: [ + fixID + ], + getAllCodeActions: (context)=>codeFixAll(context, errorCodes33, (changes)=>{ + const { configFile: configFile } = context.program.getCompilerOptions(); + if (configFile === void 0) return void 0; + doChange21(changes, configFile); + }) + }); } - log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (timestamp() - start)); - return { - has: (name)=>uniques.has(name), - add: (name)=>uniques.set(name, true) + }); + // src/services/codefixes/fixNaNEquality.ts + function getInfo11(program, sourceFile, span) { + const diag2 = find(program.getSemanticDiagnostics(sourceFile), (diag3)=>diag3.start === span.start && diag3.length === span.length); + if (diag2 === void 0 || diag2.relatedInformation === void 0) return; + const related = find(diag2.relatedInformation, (related2)=>related2.code === Diagnostics.Did_you_mean_0.code); + if (related === void 0 || related.file === void 0 || related.start === void 0 || related.length === void 0) return; + const token = findAncestorMatchingSpan(related.file, createTextSpan(related.start, related.length)); + if (token === void 0) return; + if (isExpression(token) && isBinaryExpression(token.parent)) return { + suggestion: getSuggestion(related.messageText), + expression: token.parent, + arg: token }; - function shouldIncludeSymbol(symbol, symbolToSortTextMap2) { - let allFlags = symbol.flags; - if (!isSourceFile(location)) { - if (isExportAssignment(location.parent)) return true; - if (variableDeclaration && symbol.valueDeclaration === variableDeclaration) return false; - const symbolOrigin = skipAlias(symbol, typeChecker); - if (!!sourceFile.externalModuleIndicator && !compilerOptions.allowUmdGlobalAccess && symbolToSortTextMap2[getSymbolId(symbol)] === SortText.GlobalsOrKeywords && (symbolToSortTextMap2[getSymbolId(symbolOrigin)] === SortText.AutoImportSuggestions || symbolToSortTextMap2[getSymbolId(symbolOrigin)] === SortText.LocationPriority)) return false; - allFlags |= getCombinedLocalAndExportSymbolFlags(symbolOrigin); - if (isInRightSideOfInternalImportEqualsDeclaration(location)) return !!(allFlags & 1920 /* Namespace */ ); - if (isTypeOnlyLocation) return symbolCanBeReferencedAtTypeLocation(symbol, typeChecker); - } - return !!(allFlags & 111551 /* Value */ ); - } + return void 0; } - function getLabelCompletionAtPosition(node) { - const entries = getLabelStatementCompletions(node); - if (entries.length) return { - isGlobalCompletion: false, - isMemberCompletion: false, - isNewIdentifierLocation: false, - entries: entries - }; + function doChange22(changes, sourceFile, arg, expression) { + const callExpression = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Number"), factory.createIdentifier("isNaN")), /*typeArguments*/ void 0, [ + arg + ]); + const operator = expression.operatorToken.kind; + changes.replaceNode(sourceFile, expression, operator === 38 /* ExclamationEqualsEqualsToken */ || operator === 36 /* ExclamationEqualsToken */ ? factory.createPrefixUnaryExpression(54 /* ExclamationToken */ , callExpression) : callExpression); } - function getLabelStatementCompletions(node) { - const entries = []; - const uniques = /* @__PURE__ */ new Map(); - let current = node; - while(current){ - if (isFunctionLike(current)) break; - if (isLabeledStatement(current)) { - const name = current.label.text; - if (!uniques.has(name)) { - uniques.set(name, true); - entries.push({ - name: name, - kindModifiers: "" /* none */ , - kind: "label" /* label */ , - sortText: SortText.LocationPriority + function getSuggestion(messageText) { + const [_, suggestion] = flattenDiagnosticMessageText(messageText, "\n", 0).match(/'(.*)'/) || []; + return suggestion; + } + var fixId28, errorCodes34; + var init_fixNaNEquality = __esm({ + "src/services/codefixes/fixNaNEquality.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId28 = "fixNaNEquality"; + errorCodes34 = [ + Diagnostics.This_condition_will_always_return_0.code + ]; + registerCodeFix({ + errorCodes: errorCodes34, + getCodeActions (context) { + const { sourceFile: sourceFile, span: span, program: program } = context; + const info = getInfo11(program, sourceFile, span); + if (info === void 0) return; + const { suggestion: suggestion, expression: expression, arg: arg } = info; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange22(t, sourceFile, arg, expression)); + return [ + createCodeFixAction(fixId28, changes, [ + Diagnostics.Use_0, + suggestion + ], fixId28, Diagnostics.Use_Number_isNaN_in_all_conditions) + ]; + }, + fixIds: [ + fixId28 + ], + getAllCodeActions: (context)=>{ + return codeFixAll(context, errorCodes34, (changes, diag2)=>{ + const info = getInfo11(context.program, diag2.file, createTextSpan(diag2.start, diag2.length)); + if (info) doChange22(changes, diag2.file, info.arg, info.expression); }); } - } - current = current.parent; + }); } - return entries; - } - function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences) { - if (entryId.source === "SwitchCases/" /* SwitchCases */ ) return { - type: "cases" - }; - if (entryId.data) { - const autoImport = getAutoImportSymbolFromCompletionEntryData(entryId.name, entryId.data, program, host); - if (autoImport) { - const { contextToken: contextToken2 , previousToken: previousToken2 } = getRelevantTokens(position, sourceFile); - return { - type: "symbol", - symbol: autoImport.symbol, - location: getTouchingPropertyName(sourceFile, position), - previousToken: previousToken2, - contextToken: contextToken2, - isJsxInitializer: false, - isTypeOnlyLocation: false, - origin: autoImport.origin - }; - } - } - const compilerOptions = program.getCompilerOptions(); - const completionData = getCompletionData(program, log, sourceFile, compilerOptions, position, { - includeCompletionsForModuleExports: true, - includeCompletionsWithInsertText: true - }, entryId, host, /*formatContext*/ void 0); - if (!completionData) return { - type: "none" - }; - if (completionData.kind !== 0 /* Data */ ) return { - type: "request", - request: completionData - }; - const { symbols: symbols , literals: literals , location: location , completionKind: completionKind , symbolToOriginInfoMap: symbolToOriginInfoMap , contextToken: contextToken , previousToken: previousToken , isJsxInitializer: isJsxInitializer , isTypeOnlyLocation: isTypeOnlyLocation } = completionData; - const literal = find(literals, (l)=>completionNameForLiteral(sourceFile, preferences, l) === entryId.name); - if (literal !== void 0) return { - type: "literal", - literal: literal - }; - return firstDefined(symbols, (symbol, index)=>{ - const origin = symbolToOriginInfoMap[index]; - const info = getCompletionEntryDisplayNameForSymbol(symbol, getEmitScriptTarget(compilerOptions), origin, completionKind, completionData.isJsxIdentifierExpected); - return info && info.name === entryId.name && (entryId.source === "ClassMemberSnippet/" /* ClassMemberSnippet */ && symbol.flags & 106500 /* ClassMember */ || entryId.source === "ObjectLiteralMethodSnippet/" /* ObjectLiteralMethodSnippet */ && symbol.flags & 8196 /* Method */ || getSourceFromOrigin(origin) === entryId.source) ? { - type: "symbol", - symbol: symbol, - location: location, - origin: origin, - contextToken: contextToken, - previousToken: previousToken, - isJsxInitializer: isJsxInitializer, - isTypeOnlyLocation: isTypeOnlyLocation - } : void 0; - }) || { - type: "none" - }; - } - function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, preferences, cancellationToken) { - const typeChecker = program.getTypeChecker(); - const compilerOptions = program.getCompilerOptions(); - const { name: name , source: source , data: data } = entryId; - const { previousToken: previousToken , contextToken: contextToken } = getRelevantTokens(position, sourceFile); - if (isInString(sourceFile, position, previousToken)) return ts_Completions_StringCompletions_exports.getStringLiteralCompletionDetails(name, sourceFile, position, previousToken, typeChecker, compilerOptions, host, cancellationToken, preferences); - const symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences); - switch(symbolCompletion.type){ - case "request": - { - const { request: request } = symbolCompletion; - switch(request.kind){ - case 1 /* JsDocTagName */ : - return ts_JsDoc_exports.getJSDocTagNameCompletionDetails(name); - case 2 /* JsDocTag */ : - return ts_JsDoc_exports.getJSDocTagCompletionDetails(name); - case 3 /* JsDocParameterName */ : - return ts_JsDoc_exports.getJSDocParameterNameCompletionDetails(name); - case 4 /* Keywords */ : - return some(request.keywordCompletions, (c)=>c.name === name) ? createSimpleDetails(name, "keyword" /* keyword */ , 5 /* keyword */ ) : void 0; - default: - return Debug.assertNever(request); + }); + // src/services/codefixes/fixModuleAndTargetOptions.ts + var init_fixModuleAndTargetOptions = __esm({ + "src/services/codefixes/fixModuleAndTargetOptions.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + registerCodeFix({ + errorCodes: [ + Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code, + Diagnostics.Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code, + Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code + ], + getCodeActions: function getCodeActionsToFixModuleAndTarget(context) { + const compilerOptions = context.program.getCompilerOptions(); + const { configFile: configFile } = compilerOptions; + if (configFile === void 0) return void 0; + const codeFixes = []; + const moduleKind = getEmitModuleKind(compilerOptions); + const moduleOutOfRange = moduleKind >= 5 /* ES2015 */ && moduleKind < 99 /* ESNext */ ; + if (moduleOutOfRange) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2)=>{ + setJsonCompilerOptionValue(changes2, configFile, "module", factory.createStringLiteral("esnext")); + }); + codeFixes.push(createCodeFixActionWithoutFixAll("fixModuleOption", changes, [ + Diagnostics.Set_the_module_option_in_your_configuration_file_to_0, + "esnext" + ])); } - } - case "symbol": - { - const { symbol: symbol , location: location , contextToken: contextToken2 , origin: origin , previousToken: previousToken2 } = symbolCompletion; - const { codeActions: codeActions , sourceDisplay: sourceDisplay } = getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken2, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken2, formatContext, preferences, data, source, cancellationToken); - const symbolName2 = originIsComputedPropertyName(origin) ? origin.symbolName : symbol.name; - return createCompletionDetailsForSymbol(symbol, symbolName2, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); - } - case "literal": - { - const { literal: literal } = symbolCompletion; - return createSimpleDetails(completionNameForLiteral(sourceFile, preferences, literal), "string" /* string */ , typeof literal === "string" ? 8 /* stringLiteral */ : 7 /* numericLiteral */ ); - } - case "cases": - { - const { entry: entry , importAdder: importAdder } = getExhaustiveCaseSnippets(contextToken.parent, sourceFile, preferences, program.getCompilerOptions(), host, program, /*formatContext*/ void 0); - if (importAdder.hasFixes()) { - const changes = ts_textChanges_exports.ChangeTracker.with({ - host: host, - formatContext: formatContext, - preferences: preferences - }, importAdder.writeFixes); - return { - name: entry.name, - kind: "" /* unknown */ , - kindModifiers: "", - displayParts: [], - sourceDisplay: void 0, - codeActions: [ - { - changes: changes, - description: diagnosticToString([ - Diagnostics.Includes_imports_of_types_referenced_by_0, - name - ]) - } - ] - }; + const target = getEmitScriptTarget(compilerOptions); + const targetOutOfRange = target < 4 /* ES2017 */ || target > 99 /* ESNext */ ; + if (targetOutOfRange) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (tracker)=>{ + const configObject = getTsConfigObjectLiteralExpression(configFile); + if (!configObject) return; + const options = [ + [ + "target", + factory.createStringLiteral("es2017") + ] + ]; + if (moduleKind === 1 /* CommonJS */ ) options.push([ + "module", + factory.createStringLiteral("commonjs") + ]); + setJsonCompilerOptionValues(tracker, configFile, options); + }); + codeFixes.push(createCodeFixActionWithoutFixAll("fixTargetOption", changes, [ + Diagnostics.Set_the_target_option_in_your_configuration_file_to_0, + "es2017" + ])); } - return { - name: entry.name, - kind: "" /* unknown */ , - kindModifiers: "", - displayParts: [], - sourceDisplay: void 0 - }; + return codeFixes.length ? codeFixes : void 0; } - case "none": - return allKeywordsCompletions().some((c)=>c.name === name) ? createSimpleDetails(name, "keyword" /* keyword */ , 5 /* keyword */ ) : void 0; - default: - Debug.assertNever(symbolCompletion); + }); } + }); + // src/services/codefixes/fixPropertyAssignment.ts + function doChange23(changes, sourceFile, node) { + changes.replaceNode(sourceFile, node, factory.createPropertyAssignment(node.name, node.objectAssignmentInitializer)); } - function createSimpleDetails(name, kind, kind2) { - return createCompletionDetails(name, "" /* none */ , kind, [ - displayPart(name, kind2) - ]); + function getProperty2(sourceFile, pos) { + return cast(getTokenAtPosition(sourceFile, pos).parent, isShorthandPropertyAssignment); } - function createCompletionDetailsForSymbol(symbol, name, checker, sourceFile, location, cancellationToken, codeActions, sourceDisplay) { - const { displayParts: displayParts , documentation: documentation , symbolKind: symbolKind , tags: tags } = checker.runWithCancellationToken(cancellationToken, (checker2)=>ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(checker2, symbol, sourceFile, location, location, 7 /* All */ )); - return createCompletionDetails(name, ts_SymbolDisplay_exports.getSymbolModifiers(checker, symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); + var fixId29, errorCodes35; + var init_fixPropertyAssignment = __esm({ + "src/services/codefixes/fixPropertyAssignment.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId29 = "fixPropertyAssignment"; + errorCodes35 = [ + 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 + ]; + registerCodeFix({ + errorCodes: errorCodes35, + fixIds: [ + fixId29 + ], + getCodeActions (context) { + const { sourceFile: sourceFile, span: span } = context; + const property = getProperty2(sourceFile, span.start); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange23(t, context.sourceFile, property)); + return [ + createCodeFixAction(fixId29, changes, [ + Diagnostics.Change_0_to_1, + "=", + ":" + ], fixId29, [ + Diagnostics.Switch_each_misused_0_to_1, + "=", + ":" + ]) + ]; + }, + getAllCodeActions: (context)=>codeFixAll(context, errorCodes35, (changes, diag2)=>doChange23(changes, diag2.file, getProperty2(diag2.file, diag2.start))) + }); + } + }); + // src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts + function getNodes2(sourceFile, pos) { + const token = getTokenAtPosition(sourceFile, pos); + const heritageClauses = getContainingClass(token).heritageClauses; + const extendsToken = heritageClauses[0].getFirstToken(); + return extendsToken.kind === 96 /* ExtendsKeyword */ ? { + extendsToken: extendsToken, + heritageClauses: heritageClauses + } : void 0; } - function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { - return { - name: name, - kindModifiers: kindModifiers, - kind: kind, - displayParts: displayParts, - documentation: documentation, - tags: tags, - codeActions: codeActions, - source: source, - sourceDisplay: source - }; + function doChanges2(changes, sourceFile, extendsToken, heritageClauses) { + changes.replaceNode(sourceFile, extendsToken, factory.createToken(119 /* ImplementsKeyword */ )); + if (heritageClauses.length === 2 && heritageClauses[0].token === 96 /* ExtendsKeyword */ && heritageClauses[1].token === 119 /* ImplementsKeyword */ ) { + const implementsToken = heritageClauses[1].getFirstToken(); + const implementsFullStart = implementsToken.getFullStart(); + changes.replaceRange(sourceFile, { + pos: implementsFullStart, + end: implementsFullStart + }, factory.createToken(28 /* CommaToken */ )); + const text = sourceFile.text; + let end = implementsToken.end; + while(end < text.length && isWhiteSpaceSingleLine(text.charCodeAt(end)))end++; + changes.deleteRange(sourceFile, { + pos: implementsToken.getStart(), + end: end + }); + } } - function getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source, cancellationToken) { - if (data == null ? void 0 : data.moduleSpecifier) { - if (previousToken && getImportStatementCompletionInfo(contextToken || previousToken).replacementSpan) return { - codeActions: void 0, - sourceDisplay: [ - textPart(data.moduleSpecifier) - ] - }; + var fixId30, errorCodes36; + var init_fixExtendsInterfaceBecomesImplements = __esm({ + "src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId30 = "extendsInterfaceBecomesImplements"; + errorCodes36 = [ + Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code + ]; + registerCodeFix({ + errorCodes: errorCodes36, + getCodeActions (context) { + const { sourceFile: sourceFile } = context; + const nodes = getNodes2(sourceFile, context.span.start); + if (!nodes) return void 0; + const { extendsToken: extendsToken, heritageClauses: heritageClauses } = nodes; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChanges2(t, sourceFile, extendsToken, heritageClauses)); + return [ + createCodeFixAction(fixId30, changes, Diagnostics.Change_extends_to_implements, fixId30, Diagnostics.Change_all_extended_interfaces_to_implements) + ]; + }, + fixIds: [ + fixId30 + ], + getAllCodeActions: (context)=>codeFixAll(context, errorCodes36, (changes, diag2)=>{ + const nodes = getNodes2(diag2.file, diag2.start); + if (nodes) doChanges2(changes, diag2.file, nodes.extendsToken, nodes.heritageClauses); + }) + }); } - if (source === "ClassMemberSnippet/" /* ClassMemberSnippet */ ) { - const { importAdder: importAdder } = getEntryForMemberCompletion(host, program, compilerOptions, preferences, name, symbol, location, position, contextToken, formatContext); - if (importAdder) { - const changes = ts_textChanges_exports.ChangeTracker.with({ - host: host, - formatContext: formatContext, - preferences: preferences - }, importAdder.writeFixes); - return { - sourceDisplay: void 0, - codeActions: [ - { - changes: changes, - description: diagnosticToString([ - Diagnostics.Includes_imports_of_types_referenced_by_0, - name - ]) - } - ] - }; - } + }); + // src/services/codefixes/fixForgottenThisPropertyAccess.ts + function getInfo12(sourceFile, pos, diagCode) { + const node = getTokenAtPosition(sourceFile, pos); + if (isIdentifier(node) || isPrivateIdentifier(node)) return { + node: node, + className: diagCode === didYouMeanStaticMemberCode ? getContainingClass(node).name.text : void 0 + }; + } + function doChange24(changes, sourceFile, { node: node, className: className }) { + suppressLeadingAndTrailingTrivia(node); + changes.replaceNode(sourceFile, node, factory.createPropertyAccessExpression(className ? factory.createIdentifier(className) : factory.createThis(), node)); + } + var fixId31, didYouMeanStaticMemberCode, errorCodes37; + var init_fixForgottenThisPropertyAccess = __esm({ + "src/services/codefixes/fixForgottenThisPropertyAccess.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId31 = "forgottenThisPropertyAccess"; + didYouMeanStaticMemberCode = Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code; + errorCodes37 = [ + Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.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, + didYouMeanStaticMemberCode + ]; + registerCodeFix({ + errorCodes: errorCodes37, + getCodeActions (context) { + const { sourceFile: sourceFile } = context; + const info = getInfo12(sourceFile, context.span.start, context.errorCode); + if (!info) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange24(t, sourceFile, info)); + return [ + createCodeFixAction(fixId31, changes, [ + Diagnostics.Add_0_to_unresolved_variable, + info.className || "this" + ], fixId31, Diagnostics.Add_qualifier_to_all_unresolved_variables_matching_a_member_name) + ]; + }, + fixIds: [ + fixId31 + ], + getAllCodeActions: (context)=>codeFixAll(context, errorCodes37, (changes, diag2)=>{ + const info = getInfo12(diag2.file, diag2.start, diag2.code); + if (info) doChange24(changes, context.sourceFile, info); + }) + }); } - if (originIsTypeOnlyAlias(origin)) { - const codeAction2 = ts_codefix_exports.getPromoteTypeOnlyCompletionAction(sourceFile, origin.declaration.name, program, host, formatContext, preferences); - Debug.assertIsDefined(codeAction2, "Expected to have a code action for promoting type-only alias"); - return { - codeActions: [ - codeAction2 + }); + // src/services/codefixes/fixInvalidJsxCharacters.ts + function isValidCharacter(character) { + return hasProperty(htmlEntity, character); + } + function doChange25(changes, preferences, sourceFile, start, useHtmlEntity) { + const character = sourceFile.getText()[start]; + if (!isValidCharacter(character)) return; + const replacement = useHtmlEntity ? htmlEntity[character] : `{${quote(sourceFile, preferences, character)}}`; + changes.replaceRangeWithText(sourceFile, { + pos: start, + end: start + 1 + }, replacement); + } + var fixIdExpression, fixIdHtmlEntity, errorCodes38, htmlEntity; + var init_fixInvalidJsxCharacters = __esm({ + "src/services/codefixes/fixInvalidJsxCharacters.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixIdExpression = "fixInvalidJsxCharacters_expression"; + fixIdHtmlEntity = "fixInvalidJsxCharacters_htmlEntity"; + errorCodes38 = [ + Diagnostics.Unexpected_token_Did_you_mean_or_gt.code, + Diagnostics.Unexpected_token_Did_you_mean_or_rbrace.code + ]; + registerCodeFix({ + errorCodes: errorCodes38, + fixIds: [ + fixIdExpression, + fixIdHtmlEntity ], - sourceDisplay: void 0 + getCodeActions (context) { + const { sourceFile: sourceFile, preferences: preferences, span: span } = context; + const changeToExpression = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange25(t, preferences, sourceFile, span.start, /*useHtmlEntity*/ false)); + const changeToHtmlEntity = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange25(t, preferences, sourceFile, span.start, /*useHtmlEntity*/ true)); + return [ + createCodeFixAction(fixIdExpression, changeToExpression, Diagnostics.Wrap_invalid_character_in_an_expression_container, fixIdExpression, Diagnostics.Wrap_all_invalid_characters_in_an_expression_container), + createCodeFixAction(fixIdHtmlEntity, changeToHtmlEntity, Diagnostics.Convert_invalid_character_to_its_html_entity_code, fixIdHtmlEntity, Diagnostics.Convert_all_invalid_characters_to_HTML_entity_code) + ]; + }, + getAllCodeActions (context) { + return codeFixAll(context, errorCodes38, (changes, diagnostic)=>doChange25(changes, context.preferences, diagnostic.file, diagnostic.start, context.fixId === fixIdHtmlEntity)); + } + }); + htmlEntity = { + ">": ">", + "}": "}" }; } - if (!origin || !(originIsExport(origin) || originIsResolvedExport(origin))) return { - codeActions: void 0, - sourceDisplay: void 0 - }; - const checker = origin.isFromPackageJson ? host.getPackageJsonAutoImportProvider().getTypeChecker() : program.getTypeChecker(); - const { moduleSymbol: moduleSymbol } = origin; - const targetSymbol = checker.getMergedSymbol(skipAlias(symbol.exportSymbol || symbol, checker)); - const isJsxOpeningTagName = (contextToken == null ? void 0 : contextToken.kind) === 29 /* LessThanToken */ && isJsxOpeningLikeElement(contextToken.parent); - const { moduleSpecifier: moduleSpecifier , codeAction: codeAction } = ts_codefix_exports.getImportCompletionAction(targetSymbol, moduleSymbol, data == null ? void 0 : data.exportMapKey, sourceFile, name, isJsxOpeningTagName, host, program, formatContext, previousToken && isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences, cancellationToken); - Debug.assert(!(data == null ? void 0 : data.moduleSpecifier) || moduleSpecifier === data.moduleSpecifier); - return { - sourceDisplay: [ - textPart(moduleSpecifier) - ], - codeActions: [ - codeAction - ] - }; + }); + // src/services/codefixes/fixUnmatchedParameter.ts + function getDeleteAction(context, { name: name, jsDocHost: jsDocHost, jsDocParameterTag: jsDocParameterTag }) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (changeTracker)=>changeTracker.filterJSDocTags(context.sourceFile, jsDocHost, (t)=>t !== jsDocParameterTag)); + return createCodeFixAction(deleteUnmatchedParameter, changes, [ + Diagnostics.Delete_unused_param_tag_0, + name.getText(context.sourceFile) + ], deleteUnmatchedParameter, Diagnostics.Delete_all_unused_param_tags); } - function getCompletionEntrySymbol(program, log, sourceFile, position, entryId, host, preferences) { - const completion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences); - return completion.type === "symbol" ? completion.symbol : void 0; + function getRenameAction(context, { name: name, jsDocHost: jsDocHost, signature: signature, jsDocParameterTag: jsDocParameterTag }) { + if (!length(signature.parameters)) return void 0; + const sourceFile = context.sourceFile; + const tags = getJSDocTags(signature); + const names = /* @__PURE__ */ new Set(); + for (const tag of tags)if (isJSDocParameterTag(tag) && isIdentifier(tag.name)) names.add(tag.name.escapedText); + const parameterName = firstDefined(signature.parameters, (p)=>isIdentifier(p.name) && !names.has(p.name.escapedText) ? p.name.getText(sourceFile) : void 0); + if (parameterName === void 0) return void 0; + const newJSDocParameterTag = factory.updateJSDocParameterTag(jsDocParameterTag, jsDocParameterTag.tagName, factory.createIdentifier(parameterName), jsDocParameterTag.isBracketed, jsDocParameterTag.typeExpression, jsDocParameterTag.isNameFirst, jsDocParameterTag.comment); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (changeTracker)=>changeTracker.replaceJSDocComment(sourceFile, jsDocHost, map(tags, (t)=>t === jsDocParameterTag ? newJSDocParameterTag : t))); + return createCodeFixActionWithoutFixAll(renameUnmatchedParameter, changes, [ + Diagnostics.Rename_param_tag_name_0_to_1, + name.getText(sourceFile), + parameterName + ]); } - function getRecommendedCompletion(previousToken, contextualType, checker) { - return firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [ - contextualType - ]), (type)=>{ - const symbol = type && type.symbol; - return symbol && symbol.flags & 424 /* Class */ && !isAbstractConstructorSymbol(symbol) ? getFirstSymbolInChain(symbol, previousToken, checker) : void 0; - }); + function getInfo13(sourceFile, pos) { + const token = getTokenAtPosition(sourceFile, pos); + if (token.parent && isJSDocParameterTag(token.parent) && isIdentifier(token.parent.name)) { + const jsDocParameterTag = token.parent; + const jsDocHost = getJSDocHost(jsDocParameterTag); + const signature = getHostSignatureFromJSDoc(jsDocParameterTag); + if (jsDocHost && signature) return { + jsDocHost: jsDocHost, + signature: signature, + name: token.parent.name, + jsDocParameterTag: jsDocParameterTag + }; + } + return void 0; } - function getContextualType(previousToken, position, sourceFile, checker) { - const { parent: parent2 } = previousToken; - switch(previousToken.kind){ - case 79 /* Identifier */ : - return getContextualTypeFromParent(previousToken, checker); - case 63 /* EqualsToken */ : - switch(parent2.kind){ - case 257 /* VariableDeclaration */ : - return checker.getContextualType(parent2.initializer); - case 223 /* BinaryExpression */ : - return checker.getTypeAtLocation(parent2.left); - case 288 /* JsxAttribute */ : - return checker.getContextualTypeForJsxAttribute(parent2); - default: - return void 0; + var deleteUnmatchedParameter, renameUnmatchedParameter, errorCodes39; + var init_fixUnmatchedParameter = __esm({ + "src/services/codefixes/fixUnmatchedParameter.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + deleteUnmatchedParameter = "deleteUnmatchedParameter"; + renameUnmatchedParameter = "renameUnmatchedParameter"; + errorCodes39 = [ + Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name.code + ]; + registerCodeFix({ + fixIds: [ + deleteUnmatchedParameter, + renameUnmatchedParameter + ], + errorCodes: errorCodes39, + getCodeActions: function getCodeActionsToFixUnmatchedParameter(context) { + const { sourceFile: sourceFile, span: span } = context; + const actions2 = []; + const info = getInfo13(sourceFile, span.start); + if (info) { + append(actions2, getDeleteAction(context, info)); + append(actions2, getRenameAction(context, info)); + return actions2; + } + return void 0; + }, + getAllCodeActions: function getAllCodeActionsToFixUnmatchedParameter(context) { + const tagsToSignature = /* @__PURE__ */ new Map(); + return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes)=>{ + eachDiagnostic(context, errorCodes39, ({ file: file, start: start })=>{ + const info = getInfo13(file, start); + if (info) tagsToSignature.set(info.signature, append(tagsToSignature.get(info.signature), info.jsDocParameterTag)); + }); + tagsToSignature.forEach((tags, signature)=>{ + if (context.fixId === deleteUnmatchedParameter) { + const tagsSet = new Set(tags); + changes.filterJSDocTags(signature.getSourceFile(), signature, (t)=>!tagsSet.has(t)); + } + }); + })); } - case 103 /* NewKeyword */ : - return checker.getContextualType(parent2); - case 82 /* CaseKeyword */ : - const caseClause = tryCast(parent2, isCaseClause); - return caseClause ? getSwitchedType(caseClause, checker) : void 0; - case 18 /* OpenBraceToken */ : - return isJsxExpression(parent2) && !isJsxElement(parent2.parent) && !isJsxFragment(parent2.parent) ? checker.getContextualTypeForJsxAttribute(parent2.parent) : void 0; - default: - const argInfo = ts_SignatureHelp_exports.getArgumentInfoForCompletions(previousToken, position, sourceFile); - return argInfo ? // At `,`, treat this as the next argument after the comma. - checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 27 /* CommaToken */ ? 1 : 0)) : isEqualityOperatorKind(previousToken.kind) && isBinaryExpression(parent2) && isEqualityOperatorKind(parent2.operatorToken.kind) ? // completion at `x ===/**/` should be for the right side - checker.getTypeAtLocation(parent2.left) : checker.getContextualType(previousToken); + }); } + }); + // src/services/codefixes/fixUnreferenceableDecoratorMetadata.ts + function getImportDeclaration(sourceFile, program, start) { + const identifier = tryCast(getTokenAtPosition(sourceFile, start), isIdentifier); + if (!identifier || identifier.parent.kind !== 183 /* TypeReference */ ) return; + const checker = program.getTypeChecker(); + const symbol = checker.getSymbolAtLocation(identifier); + return find((symbol == null ? void 0 : symbol.declarations) || emptyArray, or(isImportClause, isImportSpecifier, isImportEqualsDeclaration)); } - function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { - const chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ 67108863 /* All */ , /*useOnlyExternalAliasing*/ false); - if (chain) return first(chain); - return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker)); + function doTypeOnlyImportChange(changes, sourceFile, importDeclaration, program) { + if (importDeclaration.kind === 271 /* ImportEqualsDeclaration */ ) { + changes.insertModifierBefore(sourceFile, 156 /* TypeKeyword */ , importDeclaration.name); + return; + } + const importClause = importDeclaration.kind === 273 /* ImportClause */ ? importDeclaration : importDeclaration.parent.parent; + if (importClause.name && importClause.namedBindings) return; + const checker = program.getTypeChecker(); + const importsValue = !!forEachImportClauseDeclaration(importClause, (decl)=>{ + if (skipAlias(decl.symbol, checker).flags & 111551 /* Value */ ) return true; + }); + if (importsValue) return; + changes.insertModifierBefore(sourceFile, 156 /* TypeKeyword */ , importClause); } - function isModuleSymbol(symbol) { - var _a2; - return !!((_a2 = symbol.declarations) == null ? void 0 : _a2.some((d)=>d.kind === 308 /* SourceFile */ )); + function doNamespaceImportChange(changes, sourceFile, importDeclaration, program) { + ts_refactor_exports.doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, importDeclaration.parent); } - function getCompletionData(program, log, sourceFile, compilerOptions, position, preferences, detailsEntryId, host, formatContext, cancellationToken) { - const typeChecker = program.getTypeChecker(); - const inCheckedFile = isCheckedFile(sourceFile, compilerOptions); - let start = timestamp(); - let currentToken = getTokenAtPosition(sourceFile, position); - log("getCompletionData: Get current token: " + (timestamp() - start)); - start = timestamp(); - const insideComment = isInComment(sourceFile, position, currentToken); - log("getCompletionData: Is inside comment: " + (timestamp() - start)); - let insideJsDocTagTypeExpression = false; - let isInSnippetScope = false; - if (insideComment) { - if (hasDocComment(sourceFile, position)) { - if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */ ) return { - kind: 1 /* JsDocTagName */ - }; - else { - const lineStart = getLineStartPositionForPosition(position, sourceFile); - if (!/[^\*|\s(/)]/.test(sourceFile.text.substring(lineStart, position))) return { - kind: 2 /* JsDocTag */ - }; - } - } - const tag = getJsDocTagAtPosition(currentToken, position); - if (tag) { - if (tag.tagName.pos <= position && position <= tag.tagName.end) return { - kind: 1 /* JsDocTagName */ - }; - const typeExpression = tryGetTypeExpressionFromTag(tag); - if (typeExpression) { - currentToken = getTokenAtPosition(sourceFile, position); - if (!currentToken || !isDeclarationName(currentToken) && (currentToken.parent.kind !== 351 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken)) insideJsDocTagTypeExpression = isCurrentlyEditingNode(typeExpression); - } - if (!insideJsDocTagTypeExpression && isJSDocParameterTag(tag) && (nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) return { - kind: 3 /* JsDocParameterName */ , - tag: tag - }; - } - if (!insideJsDocTagTypeExpression) { - log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); - return void 0; - } + var fixId32, errorCodes40; + var init_fixUnreferenceableDecoratorMetadata = __esm({ + "src/services/codefixes/fixUnreferenceableDecoratorMetadata.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId32 = "fixUnreferenceableDecoratorMetadata"; + errorCodes40 = [ + Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled.code + ]; + registerCodeFix({ + errorCodes: errorCodes40, + getCodeActions: (context)=>{ + const importDeclaration = getImportDeclaration(context.sourceFile, context.program, context.span.start); + if (!importDeclaration) return; + const namespaceChanges = ts_textChanges_exports.ChangeTracker.with(context, (t)=>importDeclaration.kind === 276 /* ImportSpecifier */ && doNamespaceImportChange(t, context.sourceFile, importDeclaration, context.program)); + const typeOnlyChanges = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doTypeOnlyImportChange(t, context.sourceFile, importDeclaration, context.program)); + let actions2; + if (namespaceChanges.length) actions2 = append(actions2, createCodeFixActionWithoutFixAll(fixId32, namespaceChanges, Diagnostics.Convert_named_imports_to_namespace_import)); + if (typeOnlyChanges.length) actions2 = append(actions2, createCodeFixActionWithoutFixAll(fixId32, typeOnlyChanges, Diagnostics.Use_import_type)); + return actions2; + }, + fixIds: [ + fixId32 + ] + }); } - start = timestamp(); - const isJsOnlyLocation = !insideJsDocTagTypeExpression && isSourceFileJS(sourceFile); - const tokens = getRelevantTokens(position, sourceFile); - const previousToken = tokens.previousToken; - let contextToken = tokens.contextToken; - log("getCompletionData: Get previous token: " + (timestamp() - start)); - let node = currentToken; - let propertyAccessToConvert; - let isRightOfDot = false; - let isRightOfQuestionDot = false; - let isRightOfOpenTag = false; - let isStartingCloseTag = false; - let isJsxInitializer = false; - let isJsxIdentifierExpected = false; - let importStatementCompletion; - let location = getTouchingPropertyName(sourceFile, position); - let keywordFilters = 0 /* None */ ; - let isNewIdentifierLocation = false; - let flags = 0 /* None */ ; - if (contextToken) { - const importStatementCompletionInfo = getImportStatementCompletionInfo(contextToken); - if (importStatementCompletionInfo.keywordCompletion) { - if (importStatementCompletionInfo.isKeywordOnlyCompletion) return { - kind: 4 /* Keywords */ , - keywordCompletions: [ - keywordToCompletionEntry(importStatementCompletionInfo.keywordCompletion) - ], - isNewIdentifierLocation: importStatementCompletionInfo.isNewIdentifierLocation - }; - keywordFilters = keywordFiltersFromSyntaxKind(importStatementCompletionInfo.keywordCompletion); - } - if (importStatementCompletionInfo.replacementSpan && preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) { - flags |= 2 /* IsImportStatementCompletion */ ; - importStatementCompletion = importStatementCompletionInfo; - isNewIdentifierLocation = importStatementCompletionInfo.isNewIdentifierLocation; - } - if (!importStatementCompletionInfo.replacementSpan && isCompletionListBlocker(contextToken)) { - log("Returning an empty list because completion was requested in an invalid position."); - return keywordFilters ? keywordCompletionData(keywordFilters, isJsOnlyLocation, isNewIdentifierDefinitionLocation()) : void 0; - } - let parent2 = contextToken.parent; - if (contextToken.kind === 24 /* DotToken */ || contextToken.kind === 28 /* QuestionDotToken */ ) { - isRightOfDot = contextToken.kind === 24 /* DotToken */ ; - isRightOfQuestionDot = contextToken.kind === 28 /* QuestionDotToken */ ; - switch(parent2.kind){ - case 208 /* PropertyAccessExpression */ : - propertyAccessToConvert = parent2; - node = propertyAccessToConvert.expression; - const leftmostAccessExpression = getLeftmostAccessExpression(propertyAccessToConvert); - if (nodeIsMissing(leftmostAccessExpression) || (isCallExpression(node) || isFunctionLike(node)) && node.end === contextToken.pos && node.getChildCount(sourceFile) && last(node.getChildren(sourceFile)).kind !== 21 /* CloseParenToken */ ) return void 0; - break; - case 163 /* QualifiedName */ : - node = parent2.left; - break; - case 264 /* ModuleDeclaration */ : - node = parent2.name; - break; - case 202 /* ImportType */ : - node = parent2; - break; - case 233 /* MetaProperty */ : - node = parent2.getFirstToken(sourceFile); - Debug.assert(node.kind === 100 /* ImportKeyword */ || node.kind === 103 /* NewKeyword */ ); - break; - default: - return void 0; - } - } else if (!importStatementCompletion) { - if (parent2 && parent2.kind === 208 /* PropertyAccessExpression */ ) { - contextToken = parent2; - parent2 = parent2.parent; - } - if (currentToken.parent === location) switch(currentToken.kind){ - case 31 /* GreaterThanToken */ : - if (currentToken.parent.kind === 281 /* JsxElement */ || currentToken.parent.kind === 283 /* JsxOpeningElement */ ) location = currentToken; - break; - case 43 /* SlashToken */ : - if (currentToken.parent.kind === 282 /* JsxSelfClosingElement */ ) location = currentToken; - break; - } - switch(parent2.kind){ - case 284 /* JsxClosingElement */ : - if (contextToken.kind === 43 /* SlashToken */ ) { - isStartingCloseTag = true; - location = contextToken; - } - break; - case 223 /* BinaryExpression */ : - if (!binaryExpressionMayBeOpenTag(parent2)) break; - case 282 /* JsxSelfClosingElement */ : - case 281 /* JsxElement */ : - case 283 /* JsxOpeningElement */ : - isJsxIdentifierExpected = true; - if (contextToken.kind === 29 /* LessThanToken */ ) { - isRightOfOpenTag = true; - location = contextToken; - } - break; - case 291 /* JsxExpression */ : - case 290 /* JsxSpreadAttribute */ : - if (previousToken.kind === 19 /* CloseBraceToken */ || previousToken.kind === 79 /* Identifier */ && previousToken.parent.kind === 288 /* JsxAttribute */ ) isJsxIdentifierExpected = true; - break; - case 288 /* JsxAttribute */ : - if (parent2.initializer === previousToken && previousToken.end < position) { - isJsxIdentifierExpected = true; - break; - } - switch(previousToken.kind){ - case 63 /* EqualsToken */ : - isJsxInitializer = true; - break; - case 79 /* Identifier */ : - isJsxIdentifierExpected = true; - if (parent2 !== previousToken.parent && !parent2.initializer && findChildOfKind(parent2, 63 /* EqualsToken */ , sourceFile)) isJsxInitializer = previousToken; - } - break; + }); + // src/services/codefixes/fixUnusedIdentifier.ts + function changeInferToUnknown(changes, sourceFile, token) { + changes.replaceNode(sourceFile, token.parent, factory.createKeywordTypeNode(159 /* UnknownKeyword */ )); + } + function createDeleteFix(changes, diag2) { + return createCodeFixAction(fixName3, changes, diag2, fixIdDelete, Diagnostics.Delete_all_unused_declarations); + } + function deleteTypeParameters(changes, sourceFile, token) { + changes.delete(sourceFile, Debug.checkDefined(cast(token.parent, isDeclarationWithTypeParameterChildren).typeParameters, "The type parameter to delete should exist")); + } + function isImport(token) { + return token.kind === 102 /* ImportKeyword */ || token.kind === 80 /* Identifier */ && (token.parent.kind === 276 /* ImportSpecifier */ || token.parent.kind === 273 /* ImportClause */ ); + } + function tryGetFullImport(token) { + return token.kind === 102 /* ImportKeyword */ ? tryCast(token.parent, isImportDeclaration) : void 0; + } + function canDeleteEntireVariableStatement(sourceFile, token) { + return isVariableDeclarationList(token.parent) && first(token.parent.getChildren(sourceFile)) === token; + } + function deleteEntireVariableStatement(changes, sourceFile, node) { + changes.delete(sourceFile, node.parent.kind === 243 /* VariableStatement */ ? node.parent : node); + } + function deleteDestructuringElements(changes, sourceFile, node) { + forEach(node.elements, (n)=>changes.delete(sourceFile, n)); + } + function deleteDestructuring(context, changes, sourceFile, { parent: parent2 }) { + if (isVariableDeclaration(parent2) && parent2.initializer && isCallLikeExpression(parent2.initializer)) { + if (isVariableDeclarationList(parent2.parent) && length(parent2.parent.declarations) > 1) { + const varStatement = parent2.parent.parent; + const pos = varStatement.getStart(sourceFile); + const end = varStatement.end; + changes.delete(sourceFile, parent2); + changes.insertNodeAt(sourceFile, end, parent2.initializer, { + prefix: getNewLineOrDefaultFromHost(context.host, context.formatContext.options) + sourceFile.text.slice(getPrecedingNonSpaceCharacterPosition(sourceFile.text, pos - 1), pos), + suffix: probablyUsesSemicolons(sourceFile) ? ";" : "" + }); + } else changes.replaceNode(sourceFile, parent2.parent, parent2.initializer); + } else changes.delete(sourceFile, parent2); + } + function tryPrefixDeclaration(changes, errorCode, sourceFile, token) { + if (errorCode === Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code) return; + if (token.kind === 140 /* InferKeyword */ ) token = cast(token.parent, isInferTypeNode).typeParameter.name; + if (isIdentifier(token) && canPrefix(token)) { + changes.replaceNode(sourceFile, token, factory.createIdentifier(`_${token.text}`)); + if (isParameter(token.parent)) getJSDocParameterTags(token.parent).forEach((tag)=>{ + if (isIdentifier(tag.name)) changes.replaceNode(sourceFile, tag.name, factory.createIdentifier(`_${tag.name.text}`)); + }); + } + } + function canPrefix(token) { + switch(token.parent.kind){ + case 169 /* Parameter */ : + case 168 /* TypeParameter */ : + return true; + case 260 /* VariableDeclaration */ : + { + const varDecl = token.parent; + switch(varDecl.parent.parent.kind){ + case 250 /* ForOfStatement */ : + case 249 /* ForInStatement */ : + return true; + } } - } } - const semanticStart = timestamp(); - let completionKind = 5 /* None */ ; - let isNonContextualObjectLiteral = false; - let hasUnresolvedAutoImports = false; - let symbols = []; - let importSpecifierResolver; - const symbolToOriginInfoMap = []; - const symbolToSortTextMap = []; - const seenPropertySymbols = /* @__PURE__ */ new Map(); - const isTypeOnlyLocation = isTypeOnlyCompletion(); - const getModuleSpecifierResolutionHost = memoizeOne((isFromPackageJson)=>{ - return createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); + return false; + } + function tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, program, cancellationToken, isFixAll) { + tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, program, cancellationToken, isFixAll); + if (isIdentifier(token)) ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(token, checker, sourceFile, (ref)=>{ + if (isPropertyAccessExpression(ref.parent) && ref.parent.name === ref) ref = ref.parent; + if (!isFixAll && mayDeleteExpression(ref)) changes.delete(sourceFile, ref.parent.parent); }); - if (isRightOfDot || isRightOfQuestionDot) getTypeScriptMemberSymbols(); - else if (isRightOfOpenTag) { - symbols = typeChecker.getJsxIntrinsicTagNamesAt(location); - Debug.assertEachIsDefined(symbols, "getJsxIntrinsicTagNames() should all be defined"); - tryGetGlobalSymbols(); - completionKind = 1 /* Global */ ; - keywordFilters = 0 /* None */ ; - } else if (isStartingCloseTag) { - const tagName = contextToken.parent.parent.openingElement.tagName; - const tagSymbol = typeChecker.getSymbolAtLocation(tagName); - if (tagSymbol) symbols = [ - tagSymbol - ]; - completionKind = 1 /* Global */ ; - keywordFilters = 0 /* None */ ; - } else { - if (!tryGetGlobalSymbols()) return keywordFilters ? keywordCompletionData(keywordFilters, isJsOnlyLocation, isNewIdentifierLocation) : void 0; + } + function tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, program, cancellationToken, isFixAll) { + const { parent: parent2 } = token; + if (isParameter(parent2)) tryDeleteParameter(changes, sourceFile, parent2, checker, sourceFiles, program, cancellationToken, isFixAll); + else if (!(isFixAll && isIdentifier(token) && ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(token, checker, sourceFile))) { + const node = isImportClause(parent2) ? token : isComputedPropertyName(parent2) ? parent2.parent : parent2; + Debug.assert(node !== sourceFile, "should not delete whole source file"); + changes.delete(sourceFile, node); } - log("getCompletionData: Semantic work: " + (timestamp() - semanticStart)); - const contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker); - const literals = mapDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [ - contextualType - ]), (t)=>t.isLiteral() && !(t.flags & 1024 /* EnumLiteral */ ) ? t.value : void 0); - const recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker); - return { - kind: 0 /* Data */ , - symbols: symbols, - completionKind: completionKind, - isInSnippetScope: isInSnippetScope, - propertyAccessToConvert: propertyAccessToConvert, - isNewIdentifierLocation: isNewIdentifierLocation, - location: location, - keywordFilters: keywordFilters, - literals: literals, - symbolToOriginInfoMap: symbolToOriginInfoMap, - recommendedCompletion: recommendedCompletion, - previousToken: previousToken, - contextToken: contextToken, - isJsxInitializer: isJsxInitializer, - insideJsDocTagTypeExpression: insideJsDocTagTypeExpression, - symbolToSortTextMap: symbolToSortTextMap, - isTypeOnlyLocation: isTypeOnlyLocation, - isJsxIdentifierExpected: isJsxIdentifierExpected, - isRightOfOpenTag: isRightOfOpenTag, - isRightOfDotOrQuestionDot: isRightOfDot || isRightOfQuestionDot, - importStatementCompletion: importStatementCompletion, - hasUnresolvedAutoImports: hasUnresolvedAutoImports, - flags: flags - }; - function isTagWithTypeExpression(tag) { - switch(tag.kind){ - case 344 /* JSDocParameterTag */ : - case 351 /* JSDocPropertyTag */ : - case 345 /* JSDocReturnTag */ : - case 347 /* JSDocTypeTag */ : - case 349 /* JSDocTypedefTag */ : - case 352 /* JSDocThrowsTag */ : - case 353 /* JSDocSatisfiesTag */ : - return true; - case 348 /* JSDocTemplateTag */ : - return !!tag.constraint; - default: - return false; - } + } + function tryDeleteParameter(changes, sourceFile, parameter, checker, sourceFiles, program, cancellationToken, isFixAll = false) { + if (mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program, cancellationToken, isFixAll)) { + if (parameter.modifiers && parameter.modifiers.length > 0 && (!isIdentifier(parameter.name) || ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(parameter.name, checker, sourceFile))) { + for (const modifier of parameter.modifiers)if (isModifier(modifier)) changes.deleteModifier(sourceFile, modifier); + } else if (!parameter.initializer && isNotProvidedArguments(parameter, checker, sourceFiles)) changes.delete(sourceFile, parameter); } - function tryGetTypeExpressionFromTag(tag) { - if (isTagWithTypeExpression(tag)) { - const typeExpression = isJSDocTemplateTag(tag) ? tag.constraint : tag.typeExpression; - return typeExpression && typeExpression.kind === 312 /* JSDocTypeExpression */ ? typeExpression : void 0; - } - if (isJSDocAugmentsTag(tag) || isJSDocImplementsTag(tag)) return tag.class; - return void 0; + } + function isNotProvidedArguments(parameter, checker, sourceFiles) { + const index = parameter.parent.parameters.indexOf(parameter); + return !ts_FindAllReferences_exports.Core.someSignatureUsage(parameter.parent, sourceFiles, checker, (_, call)=>!call || call.arguments.length > index); + } + function mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program, cancellationToken, isFixAll) { + const { parent: parent2 } = parameter; + switch(parent2.kind){ + case 174 /* MethodDeclaration */ : + case 176 /* Constructor */ : + const index = parent2.parameters.indexOf(parameter); + const referent = isMethodDeclaration(parent2) ? parent2.name : parent2; + const entries = ts_FindAllReferences_exports.Core.getReferencedSymbolsForNode(parent2.pos, referent, program, sourceFiles, cancellationToken); + if (entries) for (const entry of entries){ + for (const reference of entry.references)if (reference.kind === ts_FindAllReferences_exports.EntryKind.Node) { + const isSuperCall2 = isSuperKeyword(reference.node) && isCallExpression(reference.node.parent) && reference.node.parent.arguments.length > index; + const isSuperMethodCall = isPropertyAccessExpression(reference.node.parent) && isSuperKeyword(reference.node.parent.expression) && isCallExpression(reference.node.parent.parent) && reference.node.parent.parent.arguments.length > index; + const isOverriddenMethod = (isMethodDeclaration(reference.node.parent) || isMethodSignature(reference.node.parent)) && reference.node.parent !== parameter.parent && reference.node.parent.parameters.length > index; + if (isSuperCall2 || isSuperMethodCall || isOverriddenMethod) return false; + } + } + return true; + case 262 /* FunctionDeclaration */ : + if (parent2.name && isCallbackLike(checker, sourceFile, parent2.name)) return isLastParameter(parent2, parameter, isFixAll); + return true; + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + return isLastParameter(parent2, parameter, isFixAll); + case 178 /* SetAccessor */ : + return false; + case 177 /* GetAccessor */ : + return true; + default: + return Debug.failBadSyntaxKind(parent2); } - function getTypeScriptMemberSymbols() { - completionKind = 2 /* PropertyAccess */ ; - const isImportType = isLiteralImportTypeNode(node); - const isTypeLocation = insideJsDocTagTypeExpression || isImportType && !node.isTypeOf || isPartOfTypeNode(node.parent) || isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); - const isRhsOfImportDeclaration = isInRightSideOfInternalImportEqualsDeclaration(node); - if (isEntityName(node) || isImportType || isPropertyAccessExpression(node)) { - const isNamespaceName = isModuleDeclaration(node.parent); - if (isNamespaceName) isNewIdentifierLocation = true; - let symbol = typeChecker.getSymbolAtLocation(node); - if (symbol) { - symbol = skipAlias(symbol, typeChecker); - if (symbol.flags & 1920 /* Enum */ ) { - const exportedSymbols = typeChecker.getExportsOfModule(symbol); - Debug.assertEachIsDefined(exportedSymbols, "getExportsOfModule() should all be defined"); - const isValidValueAccess = (symbol2)=>typeChecker.isValidPropertyAccess(isImportType ? node : node.parent, symbol2.name); - const isValidTypeAccess = (symbol2)=>symbolCanBeReferencedAtTypeLocation(symbol2, typeChecker); - const isValidAccess = isNamespaceName ? (symbol2)=>{ - var _a2; - return !!(symbol2.flags & 1920 /* Namespace */ ) && !((_a2 = symbol2.declarations) == null ? void 0 : _a2.every((d)=>d.parent === node.parent)); - } : isRhsOfImportDeclaration ? // Any kind is allowed when dotting off namespace in internal import equals declaration - (symbol2)=>isValidTypeAccess(symbol2) || isValidValueAccess(symbol2) : isTypeLocation ? isValidTypeAccess : isValidValueAccess; - for (const exportedSymbol of exportedSymbols)if (isValidAccess(exportedSymbol)) symbols.push(exportedSymbol); - if (!isTypeLocation && symbol.declarations && symbol.declarations.some((d)=>d.kind !== 308 /* SourceFile */ && d.kind !== 264 /* ModuleDeclaration */ && d.kind !== 263 /* EnumDeclaration */ )) { - let type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType(); - let insertQuestionDot = false; - if (type.isNullableType()) { - const canCorrectToQuestionDot = isRightOfDot && !isRightOfQuestionDot && preferences.includeAutomaticOptionalChainCompletions !== false; - if (canCorrectToQuestionDot || isRightOfQuestionDot) { - type = type.getNonNullableType(); - if (canCorrectToQuestionDot) insertQuestionDot = true; - } - } - addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */ ), insertQuestionDot); + } + function isCallbackLike(checker, sourceFile, name) { + return !!ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(name, checker, sourceFile, (reference)=>isIdentifier(reference) && isCallExpression(reference.parent) && reference.parent.arguments.indexOf(reference) >= 0); + } + function isLastParameter(func, parameter, isFixAll) { + const parameters = func.parameters; + const index = parameters.indexOf(parameter); + Debug.assert(index !== -1, "The parameter should already be in the list"); + return isFixAll ? parameters.slice(index + 1).every((p)=>isIdentifier(p.name) && !p.symbol.isReferenced) : index === parameters.length - 1; + } + function mayDeleteExpression(node) { + return (isBinaryExpression(node.parent) && node.parent.left === node || (isPostfixUnaryExpression(node.parent) || isPrefixUnaryExpression(node.parent)) && node.parent.operand === node) && isExpressionStatement(node.parent.parent); + } + var fixName3, fixIdPrefix, fixIdDelete, fixIdDeleteImports, fixIdInfer, errorCodes41; + var init_fixUnusedIdentifier = __esm({ + "src/services/codefixes/fixUnusedIdentifier.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixName3 = "unusedIdentifier"; + fixIdPrefix = "unusedIdentifier_prefix"; + fixIdDelete = "unusedIdentifier_delete"; + fixIdDeleteImports = "unusedIdentifier_deleteImports"; + fixIdInfer = "unusedIdentifier_infer"; + errorCodes41 = [ + Diagnostics._0_is_declared_but_its_value_is_never_read.code, + Diagnostics._0_is_declared_but_never_used.code, + Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, + Diagnostics.All_imports_in_import_declaration_are_unused.code, + Diagnostics.All_destructured_elements_are_unused.code, + Diagnostics.All_variables_are_unused.code, + Diagnostics.All_type_parameters_are_unused.code + ]; + registerCodeFix({ + errorCodes: errorCodes41, + getCodeActions (context) { + const { errorCode: errorCode, sourceFile: sourceFile, program: program, cancellationToken: cancellationToken } = context; + const checker = program.getTypeChecker(); + const sourceFiles = program.getSourceFiles(); + const token = getTokenAtPosition(sourceFile, context.span.start); + if (isJSDocTemplateTag(token)) return [ + createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, (t)=>t.delete(sourceFile, token)), Diagnostics.Remove_template_tag) + ]; + if (token.kind === 30 /* LessThanToken */ ) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>deleteTypeParameters(t, sourceFile, token)); + return [ + createDeleteFix(changes, Diagnostics.Remove_type_parameters) + ]; + } + const importDecl = tryGetFullImport(token); + if (importDecl) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>t.delete(sourceFile, importDecl)); + return [ + createCodeFixAction(fixName3, changes, [ + Diagnostics.Remove_import_from_0, + showModuleSpecifier(importDecl) + ], fixIdDeleteImports, Diagnostics.Delete_all_unused_imports) + ]; + } else if (isImport(token)) { + const deletion = ts_textChanges_exports.ChangeTracker.with(context, (t)=>tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, program, cancellationToken, /*isFixAll*/ false)); + if (deletion.length) return [ + createCodeFixAction(fixName3, deletion, [ + Diagnostics.Remove_unused_declaration_for_Colon_0, + token.getText(sourceFile) + ], fixIdDeleteImports, Diagnostics.Delete_all_unused_imports) + ]; + } + if (isObjectBindingPattern(token.parent) || isArrayBindingPattern(token.parent)) { + if (isParameter(token.parent.parent)) { + const elements = token.parent.elements; + const diagnostic = [ + elements.length > 1 ? Diagnostics.Remove_unused_declarations_for_Colon_0 : Diagnostics.Remove_unused_declaration_for_Colon_0, + map(elements, (e)=>e.getText(sourceFile)).join(", ") + ]; + return [ + createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, (t)=>deleteDestructuringElements(t, sourceFile, token.parent)), diagnostic) + ]; } - return; + return [ + createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, (t)=>deleteDestructuring(context, t, sourceFile, token.parent)), Diagnostics.Remove_unused_destructuring_declaration) + ]; } - } - } - if (!isTypeLocation) { - typeChecker.tryGetThisTypeAt(node, /*includeGlobalThis*/ false); - let type = typeChecker.getTypeAtLocation(node).getNonOptionalType(); - let insertQuestionDot = false; - if (type.isNullableType()) { - const canCorrectToQuestionDot = isRightOfDot && !isRightOfQuestionDot && preferences.includeAutomaticOptionalChainCompletions !== false; - if (canCorrectToQuestionDot || isRightOfQuestionDot) { - type = type.getNonNullableType(); - if (canCorrectToQuestionDot) insertQuestionDot = true; + if (canDeleteEntireVariableStatement(sourceFile, token)) return [ + createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, (t)=>deleteEntireVariableStatement(t, sourceFile, token.parent)), Diagnostics.Remove_variable_statement) + ]; + const result = []; + if (token.kind === 140 /* InferKeyword */ ) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>changeInferToUnknown(t, sourceFile, token)); + const name = cast(token.parent, isInferTypeNode).typeParameter.name.text; + result.push(createCodeFixAction(fixName3, changes, [ + Diagnostics.Replace_infer_0_with_unknown, + name + ], fixIdInfer, Diagnostics.Replace_all_unused_infer_with_unknown)); + } else { + const deletion = ts_textChanges_exports.ChangeTracker.with(context, (t)=>tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, program, cancellationToken, /*isFixAll*/ false)); + if (deletion.length) { + const name = isComputedPropertyName(token.parent) ? token.parent : token; + result.push(createDeleteFix(deletion, [ + Diagnostics.Remove_unused_declaration_for_Colon_0, + name.getText(sourceFile) + ])); + } } + const prefix = ts_textChanges_exports.ChangeTracker.with(context, (t)=>tryPrefixDeclaration(t, errorCode, sourceFile, token)); + if (prefix.length) result.push(createCodeFixAction(fixName3, prefix, [ + Diagnostics.Prefix_0_with_an_underscore, + token.getText(sourceFile) + ], fixIdPrefix, Diagnostics.Prefix_all_unused_declarations_with_where_possible)); + return result; + }, + fixIds: [ + fixIdPrefix, + fixIdDelete, + fixIdDeleteImports, + fixIdInfer + ], + getAllCodeActions: (context)=>{ + const { sourceFile: sourceFile, program: program, cancellationToken: cancellationToken } = context; + const checker = program.getTypeChecker(); + const sourceFiles = program.getSourceFiles(); + return codeFixAll(context, errorCodes41, (changes, diag2)=>{ + const token = getTokenAtPosition(sourceFile, diag2.start); + switch(context.fixId){ + case fixIdPrefix: + tryPrefixDeclaration(changes, diag2.code, sourceFile, token); + break; + case fixIdDeleteImports: + { + const importDecl = tryGetFullImport(token); + if (importDecl) changes.delete(sourceFile, importDecl); + else if (isImport(token)) tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, program, cancellationToken, /*isFixAll*/ true); + break; + } + case fixIdDelete: + if (token.kind === 140 /* InferKeyword */ || isImport(token)) break; + else if (isJSDocTemplateTag(token)) changes.delete(sourceFile, token); + else if (token.kind === 30 /* LessThanToken */ ) deleteTypeParameters(changes, sourceFile, token); + else if (isObjectBindingPattern(token.parent)) { + if (token.parent.parent.initializer) break; + else if (!isParameter(token.parent.parent) || isNotProvidedArguments(token.parent.parent, checker, sourceFiles)) changes.delete(sourceFile, token.parent.parent); + } else if (isArrayBindingPattern(token.parent.parent) && token.parent.parent.parent.initializer) break; + else if (canDeleteEntireVariableStatement(sourceFile, token)) deleteEntireVariableStatement(changes, sourceFile, token.parent); + else tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, program, cancellationToken, /*isFixAll*/ true); + break; + case fixIdInfer: + if (token.kind === 140 /* InferKeyword */ ) changeInferToUnknown(changes, sourceFile, token); + break; + default: + Debug.fail(JSON.stringify(context.fixId)); + } + }); } - addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */ ), insertQuestionDot); - } + }); } - function addTypeProperties(type, insertAwait, insertQuestionDot) { - isNewIdentifierLocation = !!type.getStringIndexType(); - if (isRightOfQuestionDot && some(type.getCallSignatures())) isNewIdentifierLocation = true; - const propertyAccess = node.kind === 202 /* ImportType */ ? node : node.parent; - if (inCheckedFile) { - for (const symbol of type.getApparentProperties())if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, symbol)) addPropertySymbol(symbol, /* insertAwait */ false, insertQuestionDot); - } else symbols.push(...filter(getPropertiesForCompletion(type, typeChecker), (s)=>typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, s))); - if (insertAwait && preferences.includeCompletionsWithInsertText) { - const promiseType = typeChecker.getPromisedTypeOfPromise(type); - if (promiseType) { - for (const symbol of promiseType.getApparentProperties())if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, promiseType, symbol)) addPropertySymbol(symbol, /* insertAwait */ true, insertQuestionDot); + }); + // src/services/codefixes/fixUnreachableCode.ts + function doChange26(changes, sourceFile, start, length2, errorCode) { + const token = getTokenAtPosition(sourceFile, start); + const statement = findAncestor(token, isStatement); + if (statement.getStart(sourceFile) !== token.getStart(sourceFile)) { + const logData = JSON.stringify({ + statementKind: Debug.formatSyntaxKind(statement.kind), + tokenKind: Debug.formatSyntaxKind(token.kind), + errorCode: errorCode, + start: start, + length: length2 + }); + Debug.fail("Token and statement should start at the same point. " + logData); + } + const container = (isBlock(statement.parent) ? statement.parent : statement).parent; + if (!isBlock(statement.parent) || statement === first(statement.parent.statements)) switch(container.kind){ + case 245 /* IfStatement */ : + if (container.elseStatement) { + if (isBlock(statement.parent)) break; + else changes.replaceNode(sourceFile, statement, factory.createBlock(emptyArray)); + return; } - } + case 247 /* WhileStatement */ : + case 248 /* ForStatement */ : + changes.delete(sourceFile, container); + return; } - function addPropertySymbol(symbol, insertAwait, insertQuestionDot) { - var _a2; - const computedPropertyName = firstDefined(symbol.declarations, (decl)=>tryCast(getNameOfDeclaration(decl), isComputedPropertyName)); - if (computedPropertyName) { - const leftMostName = getLeftMostName(computedPropertyName.expression); - const nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName); - const firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker); - if (firstAccessibleSymbol && addToSeen(seenPropertySymbols, getSymbolId(firstAccessibleSymbol))) { - const index = symbols.length; - symbols.push(firstAccessibleSymbol); - const moduleSymbol = firstAccessibleSymbol.parent; - if (!moduleSymbol || !isExternalModuleSymbol(moduleSymbol) || typeChecker.tryGetMemberInModuleExportsAndProperties(firstAccessibleSymbol.name, moduleSymbol) !== firstAccessibleSymbol) symbolToOriginInfoMap[index] = { - kind: getNullableSymbolOriginInfoKind(2 /* SymbolMemberNoExport */ ) - }; - else { - const fileName = isExternalModuleNameRelative(stripQuotes(moduleSymbol.name)) ? (_a2 = getSourceFileOfModule(moduleSymbol)) == null ? void 0 : _a2.fileName : void 0; - const { moduleSpecifier: moduleSpecifier } = (importSpecifierResolver || (importSpecifierResolver = ts_codefix_exports.createImportSpecifierResolver(sourceFile, program, host, preferences))).getModuleSpecifierForBestExportInfo([ - { - exportKind: 0 /* Named */ , - moduleFileName: fileName, - isFromPackageJson: false, - moduleSymbol: moduleSymbol, - symbol: firstAccessibleSymbol, - targetFlags: skipAlias(firstAccessibleSymbol, typeChecker).flags - } - ], position, isValidTypeOnlyAliasUseSite(location)) || {}; - if (moduleSpecifier) { - const origin = { - kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */ ), - moduleSymbol: moduleSymbol, - isDefaultExport: false, - symbolName: firstAccessibleSymbol.name, - exportName: firstAccessibleSymbol.name, - fileName: fileName, - moduleSpecifier: moduleSpecifier - }; - symbolToOriginInfoMap[index] = origin; - } - } - } else if (preferences.includeCompletionsWithInsertText) { - addSymbolOriginInfo(symbol); - addSymbolSortInfo(symbol); - symbols.push(symbol); - } - } else { - addSymbolOriginInfo(symbol); - addSymbolSortInfo(symbol); - symbols.push(symbol); - } - function addSymbolSortInfo(symbol2) { - if (isStaticProperty(symbol2)) symbolToSortTextMap[getSymbolId(symbol2)] = SortText.LocalDeclarationPriority; - } - function addSymbolOriginInfo(symbol2) { - if (preferences.includeCompletionsWithInsertText) { - if (insertAwait && addToSeen(seenPropertySymbols, getSymbolId(symbol2))) symbolToOriginInfoMap[symbols.length] = { - kind: getNullableSymbolOriginInfoKind(8 /* Promise */ ) - }; - else if (insertQuestionDot) symbolToOriginInfoMap[symbols.length] = { - kind: 16 /* Nullable */ - }; - } - } - function getNullableSymbolOriginInfoKind(kind) { - return insertQuestionDot ? kind | 16 /* Nullable */ : kind; - } - } - function getLeftMostName(e) { - return isIdentifier(e) ? e : isPropertyAccessExpression(e) ? getLeftMostName(e.expression) : void 0; + if (isBlock(statement.parent)) { + const end = start + length2; + const lastStatement = Debug.checkDefined(lastWhere(sliceAfter(statement.parent.statements, statement), (s)=>s.pos < end), "Some statement should be last"); + changes.deleteNodeRange(sourceFile, statement, lastStatement); + } else changes.delete(sourceFile, statement); + } + function lastWhere(a, pred) { + let last2; + for (const value1 of a){ + if (!pred(value1)) break; + last2 = value1; } - function tryGetGlobalSymbols() { - const result = tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() || tryGetObjectLikeCompletionSymbols() || tryGetImportCompletionSymbols() || tryGetImportOrExportClauseCompletionSymbols() || tryGetLocalNamedExportCompletionSymbols() || tryGetConstructorCompletion() || tryGetClassLikeCompletionSymbols() || tryGetJsxCompletionSymbols() || (getGlobalCompletions(), 1 /* Success */ ); - return result === 1 /* Success */ ; + return last2; + } + var fixId33, errorCodes42; + var init_fixUnreachableCode = __esm({ + "src/services/codefixes/fixUnreachableCode.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId33 = "fixUnreachableCode"; + errorCodes42 = [ + Diagnostics.Unreachable_code_detected.code + ]; + registerCodeFix({ + errorCodes: errorCodes42, + getCodeActions (context) { + const syntacticDiagnostics = context.program.getSyntacticDiagnostics(context.sourceFile, context.cancellationToken); + if (syntacticDiagnostics.length) return; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange26(t, context.sourceFile, context.span.start, context.span.length, context.errorCode)); + return [ + createCodeFixAction(fixId33, changes, Diagnostics.Remove_unreachable_code, fixId33, Diagnostics.Remove_all_unreachable_code) + ]; + }, + fixIds: [ + fixId33 + ], + getAllCodeActions: (context)=>codeFixAll(context, errorCodes42, (changes, diag2)=>doChange26(changes, diag2.file, diag2.start, diag2.length, diag2.code)) + }); } - function tryGetConstructorCompletion() { - if (!tryGetConstructorLikeCompletionContainer(contextToken)) return 0 /* Continue */ ; - completionKind = 5 /* None */ ; - isNewIdentifierLocation = true; - keywordFilters = 4 /* ConstructorParameterKeywords */ ; - return 1 /* Success */ ; + }); + // src/services/codefixes/fixUnusedLabel.ts + function doChange27(changes, sourceFile, start) { + const token = getTokenAtPosition(sourceFile, start); + const labeledStatement = cast(token.parent, isLabeledStatement); + const pos = token.getStart(sourceFile); + const statementPos = labeledStatement.statement.getStart(sourceFile); + const end = positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos : skipTrivia(sourceFile.text, findChildOfKind(labeledStatement, 59 /* ColonToken */ , sourceFile).end, /*stopAfterLineBreak*/ true); + changes.deleteRange(sourceFile, { + pos: pos, + end: end + }); + } + var fixId34, errorCodes43; + var init_fixUnusedLabel = __esm({ + "src/services/codefixes/fixUnusedLabel.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId34 = "fixUnusedLabel"; + errorCodes43 = [ + Diagnostics.Unused_label.code + ]; + registerCodeFix({ + errorCodes: errorCodes43, + getCodeActions (context) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange27(t, context.sourceFile, context.span.start)); + return [ + createCodeFixAction(fixId34, changes, Diagnostics.Remove_unused_label, fixId34, Diagnostics.Remove_all_unused_labels) + ]; + }, + fixIds: [ + fixId34 + ], + getAllCodeActions: (context)=>codeFixAll(context, errorCodes43, (changes, diag2)=>doChange27(changes, diag2.file, diag2.start)) + }); } - function tryGetJsxCompletionSymbols() { - const jsxContainer = tryGetContainingJsxElement(contextToken); - const attrsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes); - if (!attrsType) return 0 /* Continue */ ; - const completionsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes, 4 /* Completions */ ); - symbols = concatenate(symbols, filterJsxAttributes(getPropertiesForObjectExpression(attrsType, completionsType, jsxContainer.attributes, typeChecker), jsxContainer.attributes.properties)); - setSortTextToOptionalMember(); - completionKind = 3 /* MemberLike */ ; - isNewIdentifierLocation = false; - return 1 /* Success */ ; + }); + // src/services/codefixes/fixJSDocTypes.ts + function doChange28(changes, sourceFile, oldTypeNode, newType, checker) { + changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode, /*flags*/ void 0)); + } + function getInfo14(sourceFile, pos, checker) { + const decl = findAncestor(getTokenAtPosition(sourceFile, pos), isTypeContainer); + const typeNode = decl && decl.type; + return typeNode && { + typeNode: typeNode, + type: getType(checker, typeNode) + }; + } + function isTypeContainer(node) { + switch(node.kind){ + case 234 /* AsExpression */ : + case 179 /* CallSignature */ : + case 180 /* ConstructSignature */ : + case 262 /* FunctionDeclaration */ : + case 177 /* GetAccessor */ : + case 181 /* IndexSignature */ : + case 200 /* MappedType */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 169 /* Parameter */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : + case 178 /* SetAccessor */ : + case 265 /* TypeAliasDeclaration */ : + case 216 /* TypeAssertionExpression */ : + case 260 /* VariableDeclaration */ : + return true; + default: + return false; } - function tryGetImportCompletionSymbols() { - if (!importStatementCompletion) return 0 /* Continue */ ; - isNewIdentifierLocation = true; - collectAutoImports(); - return 1 /* Success */ ; + } + function getType(checker, node) { + if (isJSDocNullableType(node)) { + const type = checker.getTypeFromTypeNode(node.type); + if (type === checker.getNeverType() || type === checker.getVoidType()) return type; + return checker.getUnionType(append([ + type, + checker.getUndefinedType() + ], node.postfix ? void 0 : checker.getNullType())); } - function getGlobalCompletions() { - keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */ ; - completionKind = 1 /* Global */ ; - isNewIdentifierLocation = isNewIdentifierDefinitionLocation(); - if (previousToken !== contextToken) Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); - const adjustedPosition = previousToken !== contextToken ? previousToken.getStart() : position; - const scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; - isInSnippetScope = isSnippetScope(scopeNode); - const symbolMeanings = (isTypeOnlyLocation ? 0 /* None */ : 111551 /* Value */ ) | 2887656 /* Alias */ ; - const typeOnlyAliasNeedsPromotion = previousToken && !isValidTypeOnlyAliasUseSite(previousToken); - symbols = concatenate(symbols, typeChecker.getSymbolsInScope(scopeNode, symbolMeanings)); - Debug.assertEachIsDefined(symbols, "getSymbolsInScope() should all be defined"); - for(let i = 0; i < symbols.length; i++){ - const symbol = symbols[i]; - if (!typeChecker.isArgumentsSymbol(symbol) && !some(symbol.declarations, (d)=>d.getSourceFile() === sourceFile)) symbolToSortTextMap[getSymbolId(symbol)] = SortText.GlobalsOrKeywords; - if (typeOnlyAliasNeedsPromotion && !(symbol.flags & 111551 /* Value */ )) { - const typeOnlyAliasDeclaration = symbol.declarations && find(symbol.declarations, isTypeOnlyImportDeclaration); - if (typeOnlyAliasDeclaration) { - const origin = { - kind: 64 /* TypeOnlyAlias */ , - declaration: typeOnlyAliasDeclaration - }; - symbolToOriginInfoMap[i] = origin; + return checker.getTypeFromTypeNode(node); + } + var fixIdPlain, fixIdNullable, errorCodes44; + var init_fixJSDocTypes = __esm({ + "src/services/codefixes/fixJSDocTypes.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixIdPlain = "fixJSDocTypes_plain"; + fixIdNullable = "fixJSDocTypes_nullable"; + errorCodes44 = [ + Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code, + Diagnostics._0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1.code, + Diagnostics._0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1.code + ]; + registerCodeFix({ + errorCodes: errorCodes44, + getCodeActions (context) { + const { sourceFile: sourceFile } = context; + const checker = context.program.getTypeChecker(); + const info = getInfo14(sourceFile, context.span.start, checker); + if (!info) return void 0; + const { typeNode: typeNode, type: type } = info; + const original = typeNode.getText(sourceFile); + const actions2 = [ + fix(type, fixIdPlain, Diagnostics.Change_all_jsdoc_style_types_to_TypeScript) + ]; + if (typeNode.kind === 321 /* JSDocNullableType */ ) actions2.push(fix(type, fixIdNullable, Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); + return actions2; + function fix(type2, fixId52, fixAllDescription) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange28(t, sourceFile, typeNode, type2, checker)); + return createCodeFixAction("jdocTypes", changes, [ + Diagnostics.Change_0_to_1, + original, + checker.typeToString(type2) + ], fixId52, fixAllDescription); } + }, + fixIds: [ + fixIdPlain, + fixIdNullable + ], + getAllCodeActions (context) { + const { fixId: fixId52, program: program, sourceFile: sourceFile } = context; + const checker = program.getTypeChecker(); + return codeFixAll(context, errorCodes44, (changes, err)=>{ + const info = getInfo14(err.file, err.start, checker); + if (!info) return; + const { typeNode: typeNode, type: type } = info; + const fixedType = typeNode.kind === 321 /* JSDocNullableType */ && fixId52 === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */ ) : type; + doChange28(changes, sourceFile, typeNode, fixedType, checker); + }); } - } - if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 308 /* SourceFile */ ) { - const thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false, isClassLike(scopeNode.parent) ? scopeNode : void 0); - if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) for (const symbol of getPropertiesForCompletion(thisType, typeChecker)){ - symbolToOriginInfoMap[symbols.length] = { - kind: 1 /* ThisType */ - }; - symbols.push(symbol); - symbolToSortTextMap[getSymbolId(symbol)] = SortText.SuggestedClassMembers; - } - } - collectAutoImports(); - if (isTypeOnlyLocation) keywordFilters = contextToken && isAssertionExpression(contextToken.parent) ? 6 /* TypeAssertionKeywords */ : 7 /* TypeKeywords */ ; - } - function shouldOfferImportCompletions() { - if (importStatementCompletion) return true; - if (isNonContextualObjectLiteral) return false; - if (!preferences.includeCompletionsForModuleExports) return false; - if (sourceFile.externalModuleIndicator || sourceFile.commonJsModuleIndicator) return true; - if (compilerOptionsIndicateEsModules(program.getCompilerOptions())) return true; - return programContainsModules(program); + }); } - function isSnippetScope(scopeNode) { - switch(scopeNode.kind){ - case 308 /* SourceFile */ : - case 225 /* TemplateExpression */ : - case 291 /* JsxExpression */ : - case 238 /* Block */ : - return true; - default: - return isStatement(scopeNode); - } + }); + // src/services/codefixes/fixMissingCallParentheses.ts + function doChange29(changes, sourceFile, name) { + changes.replaceNodeWithText(sourceFile, name, `${name.text}()`); + } + function getCallName(sourceFile, start) { + const token = getTokenAtPosition(sourceFile, start); + if (isPropertyAccessExpression(token.parent)) { + let current = token.parent; + while(isPropertyAccessExpression(current.parent))current = current.parent; + return current.name; } - function isTypeOnlyCompletion() { - return insideJsDocTagTypeExpression || !!importStatementCompletion && isTypeOnlyImportOrExportDeclaration(location.parent) || !isContextTokenValueLocation(contextToken) && (isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker) || isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); + if (isIdentifier(token)) return token; + return void 0; + } + var fixId35, errorCodes45; + var init_fixMissingCallParentheses = __esm({ + "src/services/codefixes/fixMissingCallParentheses.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId35 = "fixMissingCallParentheses"; + errorCodes45 = [ + Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead.code + ]; + registerCodeFix({ + errorCodes: errorCodes45, + fixIds: [ + fixId35 + ], + getCodeActions (context) { + const { sourceFile: sourceFile, span: span } = context; + const callName = getCallName(sourceFile, span.start); + if (!callName) return; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange29(t, context.sourceFile, callName)); + return [ + createCodeFixAction(fixId35, changes, Diagnostics.Add_missing_call_parentheses, fixId35, Diagnostics.Add_all_missing_call_parentheses) + ]; + }, + getAllCodeActions: (context)=>codeFixAll(context, errorCodes45, (changes, diag2)=>{ + const callName = getCallName(diag2.file, diag2.start); + if (callName) doChange29(changes, diag2.file, callName); + }) + }); } - function isContextTokenValueLocation(contextToken2) { - return contextToken2 && (contextToken2.kind === 112 /* TypeOfKeyword */ && (contextToken2.parent.kind === 183 /* TypeQuery */ || isTypeOfExpression(contextToken2.parent)) || contextToken2.kind === 129 /* AssertsKeyword */ && contextToken2.parent.kind === 179 /* TypePredicate */ ); + }); + // src/services/codefixes/fixAwaitInSyncFunction.ts + function getReturnType(expr) { + if (expr.type) return expr.type; + if (isVariableDeclaration(expr.parent) && expr.parent.type && isFunctionTypeNode(expr.parent.type)) return expr.parent.type.type; + } + function getNodes3(sourceFile, start) { + const token = getTokenAtPosition(sourceFile, start); + const containingFunction = getContainingFunction(token); + if (!containingFunction) return; + let insertBefore; + switch(containingFunction.kind){ + case 174 /* MethodDeclaration */ : + insertBefore = containingFunction.name; + break; + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + insertBefore = findChildOfKind(containingFunction, 100 /* FunctionKeyword */ , sourceFile); + break; + case 219 /* ArrowFunction */ : + const kind = containingFunction.typeParameters ? 30 /* LessThanToken */ : 21 /* OpenParenToken */ ; + insertBefore = findChildOfKind(containingFunction, kind, sourceFile) || first(containingFunction.parameters); + break; + default: + return; } - function isContextTokenTypeLocation(contextToken2) { - if (contextToken2) { - const parentKind = contextToken2.parent.kind; - switch(contextToken2.kind){ - case 58 /* ColonToken */ : - return parentKind === 169 /* PropertyDeclaration */ || parentKind === 168 /* PropertySignature */ || parentKind === 166 /* Parameter */ || parentKind === 257 /* VariableDeclaration */ || isFunctionLikeKind(parentKind); - case 63 /* EqualsToken */ : - return parentKind === 262 /* TypeAliasDeclaration */ ; - case 128 /* AsKeyword */ : - return parentKind === 231 /* AsExpression */ ; - case 29 /* LessThanToken */ : - return parentKind === 180 /* TypeReference */ || parentKind === 213 /* TypeAssertionExpression */ ; - case 94 /* ExtendsKeyword */ : - return parentKind === 165 /* TypeParameter */ ; - case 150 /* SatisfiesKeyword */ : - return parentKind === 235 /* SatisfiesExpression */ ; - } - } - return false; + return insertBefore && { + insertBefore: insertBefore, + returnType: getReturnType(containingFunction) + }; + } + function doChange30(changes, sourceFile, { insertBefore: insertBefore, returnType: returnType }) { + if (returnType) { + const entityName = getEntityNameFromTypeNode(returnType); + if (!entityName || entityName.kind !== 80 /* Identifier */ || entityName.text !== "Promise") changes.replaceNode(sourceFile, returnType, factory.createTypeReferenceNode("Promise", factory.createNodeArray([ + returnType + ]))); } - function collectAutoImports() { - var _a2, _b; - if (!shouldOfferImportCompletions()) return; - Debug.assert(!(detailsEntryId == null ? void 0 : detailsEntryId.data), "Should not run 'collectAutoImports' when faster path is available via `data`"); - if (detailsEntryId && !detailsEntryId.source) return; - flags |= 1 /* MayIncludeAutoImports */ ; - const isAfterTypeOnlyImportSpecifierModifier = previousToken === contextToken && importStatementCompletion; - const lowerCaseTokenText = isAfterTypeOnlyImportSpecifierModifier ? "" : previousToken && isIdentifier(previousToken) ? previousToken.text.toLowerCase() : ""; - const moduleSpecifierCache = (_a2 = host.getModuleSpecifierCache) == null ? void 0 : _a2.call(host); - const exportInfo = getExportInfoMap(sourceFile, host, program, preferences, cancellationToken); - const packageJsonAutoImportProvider = (_b = host.getPackageJsonAutoImportProvider) == null ? void 0 : _b.call(host); - const packageJsonFilter = detailsEntryId ? void 0 : createPackageJsonImportFilter(sourceFile, preferences, host); - resolvingModuleSpecifiers("collectAutoImports", host, importSpecifierResolver || (importSpecifierResolver = ts_codefix_exports.createImportSpecifierResolver(sourceFile, program, host, preferences)), program, position, preferences, !!importStatementCompletion, isValidTypeOnlyAliasUseSite(location), (context)=>{ - exportInfo.search(sourceFile.path, /*preferCapitalized*/ isRightOfOpenTag, (symbolName2, targetFlags)=>{ - if (!isIdentifierText(symbolName2, getEmitScriptTarget(host.getCompilationSettings()))) return false; - if (!detailsEntryId && isStringANonContextualKeyword(symbolName2)) return false; - if (!isTypeOnlyLocation && !importStatementCompletion && !(targetFlags & 111551 /* Value */ )) return false; - if (isTypeOnlyLocation && !(targetFlags & 790504 /* Type */ )) return false; - const firstChar = symbolName2.charCodeAt(0); - if (isRightOfOpenTag && (firstChar < 65 /* A */ || firstChar > 90 /* Z */ )) return false; - if (detailsEntryId) return true; - return charactersFuzzyMatchInString(symbolName2, lowerCaseTokenText); - }, (info, symbolName2, isFromAmbientModule, exportMapKey)=>{ - if (detailsEntryId && !some(info, (i)=>detailsEntryId.source === stripQuotes(i.moduleSymbol.name))) return; - info = filter(info, isImportableExportInfo); - if (!info.length) return; - const result = context.tryResolve(info, isFromAmbientModule) || {}; - if (result === "failed") return; - let exportInfo2 = info[0], moduleSpecifier; - if (result !== "skipped") ({ exportInfo: exportInfo2 = info[0] , moduleSpecifier: moduleSpecifier } = result); - const isDefaultExport = exportInfo2.exportKind === 1 /* Default */ ; - const symbol = isDefaultExport && getLocalSymbolForExportDefault(exportInfo2.symbol) || exportInfo2.symbol; - pushAutoImportSymbol(symbol, { - kind: moduleSpecifier ? 32 /* ResolvedExport */ : 4 /* Export */ , - moduleSpecifier: moduleSpecifier, - symbolName: symbolName2, - exportMapKey: exportMapKey, - exportName: exportInfo2.exportKind === 2 /* ExportEquals */ ? "export=" /* ExportEquals */ : exportInfo2.symbol.name, - fileName: exportInfo2.moduleFileName, - isDefaultExport: isDefaultExport, - moduleSymbol: exportInfo2.moduleSymbol, - isFromPackageJson: exportInfo2.isFromPackageJson + changes.insertModifierBefore(sourceFile, 134 /* AsyncKeyword */ , insertBefore); + } + var fixId36, errorCodes46; + var init_fixAwaitInSyncFunction = __esm({ + "src/services/codefixes/fixAwaitInSyncFunction.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId36 = "fixAwaitInSyncFunction"; + errorCodes46 = [ + Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, + Diagnostics.await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, + Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, + Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function.code + ]; + registerCodeFix({ + errorCodes: errorCodes46, + getCodeActions (context) { + const { sourceFile: sourceFile, span: span } = context; + const nodes = getNodes3(sourceFile, span.start); + if (!nodes) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange30(t, sourceFile, nodes)); + return [ + createCodeFixAction(fixId36, changes, Diagnostics.Add_async_modifier_to_containing_function, fixId36, Diagnostics.Add_all_missing_async_modifiers) + ]; + }, + fixIds: [ + fixId36 + ], + getAllCodeActions: function getAllCodeActionsToFixAwaitInSyncFunction(context) { + const seen = /* @__PURE__ */ new Map(); + return codeFixAll(context, errorCodes46, (changes, diag2)=>{ + const nodes = getNodes3(diag2.file, diag2.start); + if (!nodes || !addToSeen(seen, getNodeId(nodes.insertBefore))) return; + doChange30(changes, context.sourceFile, nodes); }); - }); - hasUnresolvedAutoImports = context.skippedAny(); - flags |= context.resolvedAny() ? 8 /* ResolvedModuleSpecifiers */ : 0; - flags |= context.resolvedBeyondLimit() ? 16 /* ResolvedModuleSpecifiersBeyondLimit */ : 0; - }); - function isImportableExportInfo(info) { - const moduleFile = tryCast(info.moduleSymbol.valueDeclaration, isSourceFile); - if (!moduleFile) { - const moduleName = stripQuotes(info.moduleSymbol.name); - if (ts_JsTyping_exports.nodeCoreModules.has(moduleName) && startsWith(moduleName, "node:") !== shouldUseUriStyleNodeCoreModules(sourceFile, program)) return false; - return packageJsonFilter ? packageJsonFilter.allowsImportingAmbientModule(info.moduleSymbol, getModuleSpecifierResolutionHost(info.isFromPackageJson)) : true; } - return isImportableFile(info.isFromPackageJson ? packageJsonAutoImportProvider : program, sourceFile, moduleFile, preferences, packageJsonFilter, getModuleSpecifierResolutionHost(info.isFromPackageJson), moduleSpecifierCache); - } - } - function pushAutoImportSymbol(symbol, origin) { - const symbolId = getSymbolId(symbol); - if (symbolToSortTextMap[symbolId] === SortText.GlobalsOrKeywords) return; - symbolToOriginInfoMap[symbols.length] = origin; - symbolToSortTextMap[symbolId] = importStatementCompletion ? SortText.LocationPriority : SortText.AutoImportSuggestions; - symbols.push(symbol); - } - function collectObjectLiteralMethodSymbols(members, enclosingDeclaration) { - if (isInJSFile(location)) return; - members.forEach((member)=>{ - if (!isObjectLiteralMethodSymbol(member)) return; - const displayName = getCompletionEntryDisplayNameForSymbol(member, getEmitScriptTarget(compilerOptions), /*origin*/ void 0, 0 /* ObjectPropertyDeclaration */ , /*jsxIdentifierExpected*/ false); - if (!displayName) return; - const { name: name } = displayName; - const entryProps = getEntryForObjectLiteralMethodCompletion(member, name, enclosingDeclaration, program, host, compilerOptions, preferences, formatContext); - if (!entryProps) return; - const origin = { - kind: 128 /* ObjectLiteralMethod */ , - ...entryProps - }; - flags |= 32 /* MayIncludeMethodSnippets */ ; - symbolToOriginInfoMap[symbols.length] = origin; - symbols.push(member); }); } - function isObjectLiteralMethodSymbol(symbol) { - if (!(symbol.flags & 8196 /* Method */ )) return false; - return true; - } - function getScopeNode(initialToken, position2, sourceFile2) { - let scope = initialToken; - while(scope && !positionBelongsToNode(scope, position2, sourceFile2))scope = scope.parent; - return scope; - } - function isCompletionListBlocker(contextToken2) { - const start2 = timestamp(); - const result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken2) || isSolelyIdentifierDefinitionLocation(contextToken2) || isDotOfNumericLiteral(contextToken2) || isInJsxText(contextToken2) || isBigIntLiteral(contextToken2); - log("getCompletionsAtPosition: isCompletionListBlocker: " + (timestamp() - start2)); - return result; + }); + // src/services/codefixes/fixPropertyOverrideAccessor.ts + function doChange31(file, start, length2, code, context) { + let startPosition; + let endPosition; + if (code === Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property.code) { + startPosition = start; + endPosition = start + length2; + } else if (code === Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor.code) { + const checker = context.program.getTypeChecker(); + const node = getTokenAtPosition(file, start).parent; + Debug.assert(isAccessor(node), "error span of fixPropertyOverrideAccessor should only be on an accessor"); + const containingClass = node.parent; + Debug.assert(isClassLike(containingClass), "erroneous accessors should only be inside classes"); + const base = singleOrUndefined(getAllSupers(containingClass, checker)); + if (!base) return []; + const name = unescapeLeadingUnderscores(getTextOfPropertyName(node.name)); + const baseProp = checker.getPropertyOfType(checker.getTypeAtLocation(base), name); + if (!baseProp || !baseProp.valueDeclaration) return []; + startPosition = baseProp.valueDeclaration.pos; + endPosition = baseProp.valueDeclaration.end; + file = getSourceFileOfNode(baseProp.valueDeclaration); + } else Debug.fail("fixPropertyOverrideAccessor codefix got unexpected error code " + code); + return generateAccessorFromProperty(file, context.program, startPosition, endPosition, context, Diagnostics.Generate_get_and_set_accessors.message); + } + var errorCodes47, fixId37; + var init_fixPropertyOverrideAccessor = __esm({ + "src/services/codefixes/fixPropertyOverrideAccessor.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + errorCodes47 = [ + Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property.code, + Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor.code + ]; + fixId37 = "fixPropertyOverrideAccessor"; + registerCodeFix({ + errorCodes: errorCodes47, + getCodeActions (context) { + const edits = doChange31(context.sourceFile, context.span.start, context.span.length, context.errorCode, context); + if (edits) return [ + createCodeFixAction(fixId37, edits, Diagnostics.Generate_get_and_set_accessors, fixId37, Diagnostics.Generate_get_and_set_accessors_for_all_overriding_properties) + ]; + }, + fixIds: [ + fixId37 + ], + getAllCodeActions: (context)=>codeFixAll(context, errorCodes47, (changes, diag2)=>{ + const edits = doChange31(diag2.file, diag2.start, diag2.length, diag2.code, context); + if (edits) for (const edit of edits)changes.pushRaw(context.sourceFile, edit); + }) + }); } - function isInJsxText(contextToken2) { - if (contextToken2.kind === 11 /* JsxText */ ) return true; - if (contextToken2.kind === 31 /* GreaterThanToken */ && contextToken2.parent) { - if (location === contextToken2.parent && (location.kind === 283 /* JsxOpeningElement */ || location.kind === 282 /* JsxSelfClosingElement */ )) return false; - if (contextToken2.parent.kind === 283 /* JsxOpeningElement */ ) return location.parent.kind !== 283 /* JsxOpeningElement */ ; - if (contextToken2.parent.kind === 284 /* JsxClosingElement */ || contextToken2.parent.kind === 282 /* JsxSelfClosingElement */ ) return !!contextToken2.parent.parent && contextToken2.parent.parent.kind === 281 /* JsxElement */ ; - } - return false; + }); + // src/services/codefixes/inferFromUsage.ts + function getDiagnostic(errorCode, token) { + switch(errorCode){ + case Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + case Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return isSetAccessorDeclaration(getContainingFunction(token)) ? Diagnostics.Infer_type_of_0_from_usage : Diagnostics.Infer_parameter_types_from_usage; + case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: + return Diagnostics.Infer_parameter_types_from_usage; + case Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code: + return Diagnostics.Infer_this_type_of_0_from_usage; + default: + return Diagnostics.Infer_type_of_0_from_usage; } - function isNewIdentifierDefinitionLocation() { - if (contextToken) { - const containingNodeKind = contextToken.parent.kind; - const tokenKind = keywordForNode(contextToken); - switch(tokenKind){ - case 27 /* CommaToken */ : - return containingNodeKind === 210 /* CallExpression */ || containingNodeKind === 173 /* Constructor */ || containingNodeKind === 211 /* NewExpression */ || containingNodeKind === 206 /* ArrayLiteralExpression */ || containingNodeKind === 223 /* BinaryExpression */ || containingNodeKind === 181 /* FunctionType */ || containingNodeKind === 207 /* ObjectLiteralExpression */ ; - case 20 /* OpenParenToken */ : - return containingNodeKind === 210 /* CallExpression */ || containingNodeKind === 173 /* Constructor */ || containingNodeKind === 211 /* NewExpression */ || containingNodeKind === 214 /* ParenthesizedExpression */ || containingNodeKind === 193 /* ParenthesizedType */ ; - case 22 /* OpenBracketToken */ : - return containingNodeKind === 206 /* ArrayLiteralExpression */ || containingNodeKind === 178 /* IndexSignature */ || containingNodeKind === 164 /* ComputedPropertyName */ ; - case 142 /* ModuleKeyword */ : - case 143 /* NamespaceKeyword */ : - case 100 /* ImportKeyword */ : - return true; - case 24 /* DotToken */ : - return containingNodeKind === 264 /* ModuleDeclaration */ ; - case 18 /* OpenBraceToken */ : - return containingNodeKind === 260 /* ClassDeclaration */ || containingNodeKind === 207 /* ObjectLiteralExpression */ ; - case 63 /* EqualsToken */ : - return containingNodeKind === 257 /* VariableDeclaration */ || containingNodeKind === 223 /* BinaryExpression */ ; - case 15 /* TemplateHead */ : - return containingNodeKind === 225 /* TemplateExpression */ ; - case 16 /* TemplateMiddle */ : - return containingNodeKind === 236 /* TemplateSpan */ ; - case 132 /* AsyncKeyword */ : - return containingNodeKind === 171 /* MethodDeclaration */ || containingNodeKind === 300 /* ShorthandPropertyAssignment */ ; - case 41 /* AsteriskToken */ : - return containingNodeKind === 171 /* MethodDeclaration */ ; - } - if (isClassMemberCompletionKeyword(tokenKind)) return true; - } - return false; - } - function isInStringOrRegularExpressionOrTemplateLiteral(contextToken2) { - return (isRegularExpressionLiteral(contextToken2) || isStringTextContainingNode(contextToken2)) && (rangeContainsPositionExclusive(contextToken2, position) || position === contextToken2.end && (!!contextToken2.isUnterminated || isRegularExpressionLiteral(contextToken2))); - } - function tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() { - const typeLiteralNode = tryGetTypeLiteralNode(contextToken); - if (!typeLiteralNode) return 0 /* Continue */ ; - const intersectionTypeNode = isIntersectionTypeNode(typeLiteralNode.parent) ? typeLiteralNode.parent : void 0; - const containerTypeNode = intersectionTypeNode || typeLiteralNode; - const containerExpectedType = getConstraintOfTypeArgumentProperty(containerTypeNode, typeChecker); - if (!containerExpectedType) return 0 /* Continue */ ; - const containerActualType = typeChecker.getTypeFromTypeNode(containerTypeNode); - const members = getPropertiesForCompletion(containerExpectedType, typeChecker); - const existingMembers = getPropertiesForCompletion(containerActualType, typeChecker); - const existingMemberEscapedNames = /* @__PURE__ */ new Set(); - existingMembers.forEach((s)=>existingMemberEscapedNames.add(s.escapedName)); - symbols = concatenate(symbols, filter(members, (s)=>!existingMemberEscapedNames.has(s.escapedName))); - completionKind = 0 /* ObjectPropertyDeclaration */ ; - isNewIdentifierLocation = true; - return 1 /* Success */ ; + } + function mapSuggestionDiagnostic(errorCode) { + switch(errorCode){ + case Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code: + return Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code; + case Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return Diagnostics.Variable_0_implicitly_has_an_1_type.code; + case Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return Diagnostics.Parameter_0_implicitly_has_an_1_type.code; + case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: + return Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code; + case Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code: + return Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code; + case Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code: + return Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code; + case Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code: + return Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code; + case Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return Diagnostics.Member_0_implicitly_has_an_1_type.code; } - function tryGetObjectLikeCompletionSymbols() { - const symbolsStartIndex = symbols.length; - const objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken); - if (!objectLikeContainer) return 0 /* Continue */ ; - completionKind = 0 /* ObjectPropertyDeclaration */ ; - let typeMembers; - let existingMembers; - if (objectLikeContainer.kind === 207 /* ObjectLiteralExpression */ ) { - const instantiatedType = tryGetObjectLiteralContextualType(objectLikeContainer, typeChecker); - if (instantiatedType === void 0) { - if (objectLikeContainer.flags & 33554432 /* InWithStatement */ ) return 2 /* Fail */ ; - isNonContextualObjectLiteral = true; - return 0 /* Continue */ ; + return errorCode; + } + function doChange32(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, preferences) { + if (!isParameterPropertyModifier(token.kind) && token.kind !== 80 /* Identifier */ && token.kind !== 26 /* DotDotDotToken */ && token.kind !== 110 /* ThisKeyword */ ) return void 0; + const { parent: parent2 } = token; + const importAdder = createImportAdder(sourceFile, program, preferences, host); + errorCode = mapSuggestionDiagnostic(errorCode); + switch(errorCode){ + case Diagnostics.Member_0_implicitly_has_an_1_type.code: + case Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: + if (isVariableDeclaration(parent2) && markSeen(parent2) || isPropertyDeclaration(parent2) || isPropertySignature(parent2)) { + annotateVariableDeclaration(changes, importAdder, sourceFile, parent2, program, host, cancellationToken); + importAdder.writeFixes(changes); + return parent2; } - const completionsType = typeChecker.getContextualType(objectLikeContainer, 4 /* Completions */ ); - const hasStringIndexType = (completionsType || instantiatedType).getStringIndexType(); - const hasNumberIndextype = (completionsType || instantiatedType).getNumberIndexType(); - isNewIdentifierLocation = !!hasStringIndexType || !!hasNumberIndextype; - typeMembers = getPropertiesForObjectExpression(instantiatedType, completionsType, objectLikeContainer, typeChecker); - existingMembers = objectLikeContainer.properties; - if (typeMembers.length === 0) { - if (!hasNumberIndextype) { - isNonContextualObjectLiteral = true; - return 0 /* Continue */ ; + if (isPropertyAccessExpression(parent2)) { + const type = inferTypeForVariableFromUsage(parent2.name, program, cancellationToken); + const typeNode = getTypeNodeIfAccessible(type, parent2, program, host); + if (typeNode) { + const typeTag = factory.createJSDocTypeTag(/*tagName*/ void 0, factory.createJSDocTypeExpression(typeNode), /*comment*/ void 0); + changes.addJSDocTags(sourceFile, cast(parent2.parent.parent, isExpressionStatement), [ + typeTag + ]); } + importAdder.writeFixes(changes); + return parent2; } - } else { - Debug.assert(objectLikeContainer.kind === 203 /* ObjectBindingPattern */ ); - isNewIdentifierLocation = false; - const rootDeclaration = getRootDeclaration(objectLikeContainer.parent); - if (!isVariableLike(rootDeclaration)) return Debug.fail("Root declaration is not variable-like."); - let canGetType = hasInitializer(rootDeclaration) || !!getEffectiveTypeAnnotationNode(rootDeclaration) || rootDeclaration.parent.parent.kind === 247 /* ForOfStatement */ ; - if (!canGetType && rootDeclaration.kind === 166 /* Parameter */ ) { - if (isExpression(rootDeclaration.parent)) canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); - else if (rootDeclaration.parent.kind === 171 /* MethodDeclaration */ || rootDeclaration.parent.kind === 175 /* SetAccessor */ ) canGetType = isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); - } - if (canGetType) { - const typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); - if (!typeForObject) return 2 /* Fail */ ; - typeMembers = typeChecker.getPropertiesOfType(typeForObject).filter((propertySymbol)=>{ - return typeChecker.isPropertyAccessible(objectLikeContainer, /*isSuper*/ false, /*writing*/ false, typeForObject, propertySymbol); - }); - existingMembers = objectLikeContainer.elements; - } - } - if (typeMembers && typeMembers.length > 0) { - const filteredMembers = filterObjectMembersList(typeMembers, Debug.checkDefined(existingMembers)); - symbols = concatenate(symbols, filteredMembers); - setSortTextToOptionalMember(); - if (objectLikeContainer.kind === 207 /* ObjectLiteralExpression */ && preferences.includeCompletionsWithObjectLiteralMethodSnippets && preferences.includeCompletionsWithInsertText) { - transformObjectLiteralMembersSortText(symbolsStartIndex); - collectObjectLiteralMethodSymbols(filteredMembers, objectLikeContainer); + return void 0; + case Diagnostics.Variable_0_implicitly_has_an_1_type.code: + { + const symbol = program.getTypeChecker().getSymbolAtLocation(token); + if (symbol && symbol.valueDeclaration && isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { + annotateVariableDeclaration(changes, importAdder, getSourceFileOfNode(symbol.valueDeclaration), symbol.valueDeclaration, program, host, cancellationToken); + importAdder.writeFixes(changes); + return symbol.valueDeclaration; + } + return void 0; } - } - return 1 /* Success */ ; - } - function tryGetImportOrExportClauseCompletionSymbols() { - if (!contextToken) return 0 /* Continue */ ; - const namedImportsOrExports = contextToken.kind === 18 /* OpenBraceToken */ || contextToken.kind === 27 /* CommaToken */ ? tryCast(contextToken.parent, isNamedImportsOrExports) : isTypeKeywordTokenOrIdentifier(contextToken) ? tryCast(contextToken.parent.parent, isNamedImportsOrExports) : void 0; - if (!namedImportsOrExports) return 0 /* Continue */ ; - if (!isTypeKeywordTokenOrIdentifier(contextToken)) keywordFilters = 8 /* TypeKeyword */ ; - const { moduleSpecifier: moduleSpecifier } = namedImportsOrExports.kind === 272 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent; - if (!moduleSpecifier) { - isNewIdentifierLocation = true; - return namedImportsOrExports.kind === 272 /* NamedImports */ ? 2 /* Fail */ : 0 /* Continue */ ; - } - const moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); - if (!moduleSpecifierSymbol) { - isNewIdentifierLocation = true; - return 2 /* Fail */ ; - } - completionKind = 3 /* MemberLike */ ; - isNewIdentifierLocation = false; - const exports = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol); - const existing = new Set(namedImportsOrExports.elements.filter((n)=>!isCurrentlyEditingNode(n)).map((n)=>(n.propertyName || n.name).escapedText)); - const uniques = exports.filter((e)=>e.escapedName !== "default" /* Default */ && !existing.has(e.escapedName)); - symbols = concatenate(symbols, uniques); - if (!uniques.length) keywordFilters = 0 /* None */ ; - return 1 /* Success */ ; - } - function tryGetLocalNamedExportCompletionSymbols() { - var _a2; - const namedExports = contextToken && (contextToken.kind === 18 /* OpenBraceToken */ || contextToken.kind === 27 /* CommaToken */ ) ? tryCast(contextToken.parent, isNamedExports) : void 0; - if (!namedExports) return 0 /* Continue */ ; - const localsContainer = findAncestor(namedExports, or(isSourceFile, isModuleDeclaration)); - completionKind = 5 /* None */ ; - isNewIdentifierLocation = false; - (_a2 = localsContainer.locals) == null || _a2.forEach((symbol, name)=>{ - var _a3, _b; - symbols.push(symbol); - if ((_b = (_a3 = localsContainer.symbol) == null ? void 0 : _a3.exports) == null ? void 0 : _b.has(name)) symbolToSortTextMap[getSymbolId(symbol)] = SortText.OptionalMember; - }); - return 1 /* Success */ ; } - function tryGetClassLikeCompletionSymbols() { - const decl = tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location, position); - if (!decl) return 0 /* Continue */ ; - completionKind = 3 /* MemberLike */ ; - isNewIdentifierLocation = true; - keywordFilters = contextToken.kind === 41 /* AsteriskToken */ ? 0 /* None */ : isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */ ; - if (!isClassLike(decl)) return 1 /* Success */ ; - const classElement = contextToken.kind === 26 /* SemicolonToken */ ? contextToken.parent.parent : contextToken.parent; - let classElementModifierFlags = isClassElement(classElement) ? getEffectiveModifierFlags(classElement) : 0 /* None */ ; - if (contextToken.kind === 79 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) switch(contextToken.getText()){ - case "private": - classElementModifierFlags = classElementModifierFlags | 8 /* Private */ ; - break; - case "static": - classElementModifierFlags = classElementModifierFlags | 32 /* Static */ ; - break; - case "override": - classElementModifierFlags = classElementModifierFlags | 16384 /* Override */ ; + const containingFunction = getContainingFunction(token); + if (containingFunction === void 0) return void 0; + let declaration; + switch(errorCode){ + case Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + if (isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, importAdder, sourceFile, containingFunction, program, host, cancellationToken); + declaration = containingFunction; break; - } - if (isClassStaticBlockDeclaration(classElement)) classElementModifierFlags |= 32 /* Static */ ; - if (!(classElementModifierFlags & 8 /* Private */ )) { - const baseTypeNodes = isClassLike(decl) && classElementModifierFlags & 16384 /* Override */ ? singleElementArray(getEffectiveBaseTypeNode(decl)) : getAllSuperTypeNodes(decl); - const baseSymbols = flatMap(baseTypeNodes, (baseTypeNode)=>{ - const type = typeChecker.getTypeAtLocation(baseTypeNode); - return classElementModifierFlags & 32 /* Static */ ? (type == null ? void 0 : type.symbol) && typeChecker.getPropertiesOfType(typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl)) : type && typeChecker.getPropertiesOfType(type); - }); - symbols = concatenate(symbols, filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags)); - forEach(symbols, (symbol, index)=>{ - const declaration = symbol == null ? void 0 : symbol.valueDeclaration; - if (declaration && isClassElement(declaration) && declaration.name && isComputedPropertyName(declaration.name)) { - const origin = { - kind: 512 /* ComputedPropertyName */ , - symbolName: typeChecker.symbolToString(symbol) - }; - symbolToOriginInfoMap[index] = origin; - } - }); - } - return 1 /* Success */ ; - } - function isConstructorParameterCompletion(node2) { - return !!node2.parent && isParameter(node2.parent) && isConstructorDeclaration(node2.parent.parent) && (isParameterPropertyModifier(node2.kind) || isDeclarationName(node2)); - } - function tryGetConstructorLikeCompletionContainer(contextToken2) { - if (contextToken2) { - const parent2 = contextToken2.parent; - switch(contextToken2.kind){ - case 20 /* OpenParenToken */ : - case 27 /* CommaToken */ : - return isConstructorDeclaration(contextToken2.parent) ? contextToken2.parent : void 0; - default: - if (isConstructorParameterCompletion(contextToken2)) return parent2.parent; } - } - return void 0; - } - function tryGetFunctionLikeBodyCompletionContainer(contextToken2) { - if (contextToken2) { - let prev; - const container = findAncestor(contextToken2.parent, (node2)=>{ - if (isClassLike(node2)) return "quit"; - if (isFunctionLikeDeclaration(node2) && prev === node2.body) return true; - prev = node2; - return false; - }); - return container && container; - } - } - function tryGetContainingJsxElement(contextToken2) { - if (contextToken2) { - const parent2 = contextToken2.parent; - switch(contextToken2.kind){ - case 31 /* GreaterThanToken */ : - case 30 /* LessThanSlashToken */ : - case 43 /* SlashToken */ : - case 79 /* Identifier */ : - case 208 /* PropertyAccessExpression */ : - case 289 /* JsxAttributes */ : - case 288 /* JsxAttribute */ : - case 290 /* JsxSpreadAttribute */ : - if (parent2 && (parent2.kind === 282 /* JsxSelfClosingElement */ || parent2.kind === 283 /* JsxOpeningElement */ )) { - if (contextToken2.kind === 31 /* GreaterThanToken */ ) { - const precedingToken = findPrecedingToken(contextToken2.pos, sourceFile, /*startNode*/ void 0); - if (!parent2.typeArguments || precedingToken && precedingToken.kind === 43 /* SlashToken */ ) break; - } - return parent2; - } else if (parent2.kind === 288 /* JsxAttribute */ ) return parent2.parent.parent; - break; - case 10 /* StringLiteral */ : - if (parent2 && (parent2.kind === 288 /* JsxAttribute */ || parent2.kind === 290 /* JsxSpreadAttribute */ )) return parent2.parent.parent; - break; - case 19 /* CloseBraceToken */ : - if (parent2 && parent2.kind === 291 /* JsxExpression */ && parent2.parent && parent2.parent.kind === 288 /* JsxAttribute */ ) return parent2.parent.parent.parent; - if (parent2 && parent2.kind === 290 /* JsxSpreadAttribute */ ) return parent2.parent.parent; - break; + case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + if (markSeen(containingFunction)) { + const param = cast(parent2, isParameter); + annotateParameters(changes, importAdder, sourceFile, param, containingFunction, program, host, cancellationToken); + declaration = param; } - } - return void 0; - } - function isSolelyIdentifierDefinitionLocation(contextToken2) { - const parent2 = contextToken2.parent; - const containingNodeKind = parent2.kind; - switch(contextToken2.kind){ - case 27 /* CommaToken */ : - return containingNodeKind === 257 /* VariableDeclaration */ || isVariableDeclarationListButNotTypeArgument(contextToken2) || containingNodeKind === 240 /* VariableStatement */ || containingNodeKind === 263 /* EnumDeclaration */ || // enum a { foo, | - isFunctionLikeButNotConstructor(containingNodeKind) || containingNodeKind === 261 /* InterfaceDeclaration */ || // interface A= contextToken2.pos; - case 24 /* DotToken */ : - return containingNodeKind === 204 /* ArrayBindingPattern */ ; - case 58 /* ColonToken */ : - return containingNodeKind === 205 /* BindingElement */ ; - case 22 /* OpenBracketToken */ : - return containingNodeKind === 204 /* ArrayBindingPattern */ ; - case 20 /* OpenParenToken */ : - return containingNodeKind === 295 /* CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind); - case 18 /* OpenBraceToken */ : - return containingNodeKind === 263 /* EnumDeclaration */ ; - case 29 /* LessThanToken */ : - return containingNodeKind === 260 /* ClassDeclaration */ || // class A< | - containingNodeKind === 228 /* ClassExpression */ || // var C = class D< | - containingNodeKind === 261 /* InterfaceDeclaration */ || // interface A< | - containingNodeKind === 262 /* TypeAliasDeclaration */ || // type List< | - isFunctionLikeKind(containingNodeKind); - case 124 /* StaticKeyword */ : - return containingNodeKind === 169 /* PropertyDeclaration */ && !isClassLike(parent2.parent); - case 25 /* DotDotDotToken */ : - return containingNodeKind === 166 /* Parameter */ || !!parent2.parent && parent2.parent.kind === 204 /* ArrayBindingPattern */ ; - case 123 /* PublicKeyword */ : - case 121 /* PrivateKeyword */ : - case 122 /* ProtectedKeyword */ : - return containingNodeKind === 166 /* Parameter */ && !isConstructorDeclaration(parent2.parent); - case 128 /* AsKeyword */ : - return containingNodeKind === 273 /* ImportSpecifier */ || containingNodeKind === 278 /* ExportSpecifier */ || containingNodeKind === 271 /* NamespaceImport */ ; - case 137 /* GetKeyword */ : - case 151 /* SetKeyword */ : - return !isFromObjectTypeDeclaration(contextToken2); - case 79 /* Identifier */ : - if (containingNodeKind === 273 /* ImportSpecifier */ && contextToken2 === parent2.name && contextToken2.text === "type") return false; - break; - case 84 /* ClassKeyword */ : - case 92 /* EnumKeyword */ : - case 118 /* InterfaceKeyword */ : - case 98 /* FunctionKeyword */ : - case 113 /* VarKeyword */ : - case 100 /* ImportKeyword */ : - case 119 /* LetKeyword */ : - case 85 /* ConstKeyword */ : - case 138 /* InferKeyword */ : - return true; - case 154 /* TypeKeyword */ : - return containingNodeKind !== 273 /* ImportSpecifier */ ; - case 41 /* AsteriskToken */ : - return isFunctionLike(contextToken2.parent) && !isMethodDeclaration(contextToken2.parent); - } - if (isClassMemberCompletionKeyword(keywordForNode(contextToken2)) && isFromObjectTypeDeclaration(contextToken2)) return false; - if (isConstructorParameterCompletion(contextToken2)) { - if (!isIdentifier(contextToken2) || isParameterPropertyModifier(keywordForNode(contextToken2)) || isCurrentlyEditingNode(contextToken2)) return false; - } - switch(keywordForNode(contextToken2)){ - case 126 /* AbstractKeyword */ : - case 84 /* ClassKeyword */ : - case 85 /* ConstKeyword */ : - case 136 /* DeclareKeyword */ : - case 92 /* EnumKeyword */ : - case 98 /* FunctionKeyword */ : - case 118 /* InterfaceKeyword */ : - case 119 /* LetKeyword */ : - case 121 /* PrivateKeyword */ : - case 122 /* ProtectedKeyword */ : - case 123 /* PublicKeyword */ : - case 124 /* StaticKeyword */ : - case 113 /* VarKeyword */ : - return true; - case 132 /* AsyncKeyword */ : - return isPropertyDeclaration(contextToken2.parent); - } - const ancestorClassLike = findAncestor(contextToken2.parent, isClassLike); - if (ancestorClassLike && contextToken2 === previousToken && isPreviousPropertyDeclarationTerminated(contextToken2, position)) return false; - const ancestorPropertyDeclaraion = getAncestor(contextToken2.parent, 169 /* PropertyDeclaration */ ); - if (ancestorPropertyDeclaraion && contextToken2 !== previousToken && isClassLike(previousToken.parent.parent) && position <= previousToken.end) { - if (isPreviousPropertyDeclarationTerminated(contextToken2, previousToken.end)) return false; - else if (contextToken2.kind !== 63 /* EqualsToken */ && (isInitializedProperty(ancestorPropertyDeclaraion) || hasType(ancestorPropertyDeclaraion))) return true; - } - return isDeclarationName(contextToken2) && !isShorthandPropertyAssignment(contextToken2.parent) && !isJsxAttribute(contextToken2.parent) && !(isClassLike(contextToken2.parent) && (contextToken2 !== previousToken || position > previousToken.end)); - } - function isPreviousPropertyDeclarationTerminated(contextToken2, position2) { - return contextToken2.kind !== 63 /* EqualsToken */ && (contextToken2.kind === 26 /* SemicolonToken */ || !positionsAreOnSameLine(contextToken2.end, position2, sourceFile)); - } - function isFunctionLikeButNotConstructor(kind) { - return isFunctionLikeKind(kind) && kind !== 173 /* Constructor */ ; - } - function isDotOfNumericLiteral(contextToken2) { - if (contextToken2.kind === 8 /* NumericLiteral */ ) { - const text = contextToken2.getFullText(); - return text.charAt(text.length - 1) === "."; - } - return false; - } - function isVariableDeclarationListButNotTypeArgument(node2) { - return node2.parent.kind === 258 /* VariableDeclarationList */ && !isPossiblyTypeArgumentPosition(node2, sourceFile, typeChecker); - } - function filterObjectMembersList(contextualMemberSymbols, existingMembers) { - if (existingMembers.length === 0) return contextualMemberSymbols; - const membersDeclaredBySpreadAssignment = /* @__PURE__ */ new Set(); - const existingMemberNames = /* @__PURE__ */ new Set(); - for (const m of existingMembers){ - if (m.kind !== 299 /* PropertyAssignment */ && m.kind !== 300 /* ShorthandPropertyAssignment */ && m.kind !== 205 /* BindingElement */ && m.kind !== 171 /* MethodDeclaration */ && m.kind !== 174 /* GetAccessor */ && m.kind !== 175 /* SetAccessor */ && m.kind !== 301 /* SpreadAssignment */ ) continue; - if (isCurrentlyEditingNode(m)) continue; - let existingName; - if (isSpreadAssignment(m)) setMembersDeclaredBySpreadAssignment(m, membersDeclaredBySpreadAssignment); - else if (isBindingElement(m) && m.propertyName) { - if (m.propertyName.kind === 79 /* Identifier */ ) existingName = m.propertyName.escapedText; - } else { - const name = getNameOfDeclaration(m); - existingName = name && isPropertyNameLiteral(name) ? getEscapedTextOfIdentifierOrLiteral(name) : void 0; + break; + case Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: + case Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: + if (isGetAccessorDeclaration(containingFunction) && isIdentifier(containingFunction.name)) { + annotate(changes, importAdder, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); + declaration = containingFunction; } - if (existingName !== void 0) existingMemberNames.add(existingName); - } - const filteredSymbols = contextualMemberSymbols.filter((m)=>!existingMemberNames.has(m.escapedName)); - setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, filteredSymbols); - return filteredSymbols; - } - function setMembersDeclaredBySpreadAssignment(declaration, membersDeclaredBySpreadAssignment) { - const expression = declaration.expression; - const symbol = typeChecker.getSymbolAtLocation(expression); - const type = symbol && typeChecker.getTypeOfSymbolAtLocation(symbol, expression); - const properties = type && type.properties; - if (properties) properties.forEach((property)=>{ - membersDeclaredBySpreadAssignment.add(property.name); - }); - } - function setSortTextToOptionalMember() { - symbols.forEach((m)=>{ - var _a2; - if (m.flags & 16777216 /* Optional */ ) { - const symbolId = getSymbolId(m); - symbolToSortTextMap[symbolId] = (_a2 = symbolToSortTextMap[symbolId]) != null ? _a2 : SortText.OptionalMember; + break; + case Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: + if (isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, importAdder, sourceFile, containingFunction, program, host, cancellationToken); + declaration = containingFunction; } - }); + break; + case Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code: + if (ts_textChanges_exports.isThisTypeAnnotatable(containingFunction) && markSeen(containingFunction)) { + annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken); + declaration = containingFunction; + } + break; + default: + return Debug.fail(String(errorCode)); } - function setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, contextualMemberSymbols) { - if (membersDeclaredBySpreadAssignment.size === 0) return; - for (const contextualMemberSymbol of contextualMemberSymbols)if (membersDeclaredBySpreadAssignment.has(contextualMemberSymbol.name)) symbolToSortTextMap[getSymbolId(contextualMemberSymbol)] = SortText.MemberDeclaredBySpreadAssignment; + importAdder.writeFixes(changes); + return declaration; + } + function annotateVariableDeclaration(changes, importAdder, sourceFile, declaration, program, host, cancellationToken) { + if (isIdentifier(declaration.name)) annotate(changes, importAdder, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); + } + function annotateParameters(changes, importAdder, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { + if (!isIdentifier(parameterDeclaration.name)) return; + const parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken); + Debug.assert(containingFunction.parameters.length === parameterInferences.length, "Parameter count and inference count should match"); + if (isInJSFile(containingFunction)) annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); + else { + const needParens = isArrowFunction(containingFunction) && !findChildOfKind(containingFunction, 21 /* OpenParenToken */ , sourceFile); + if (needParens) changes.insertNodeBefore(sourceFile, first(containingFunction.parameters), factory.createToken(21 /* OpenParenToken */ )); + for (const { declaration: declaration, type: type } of parameterInferences)if (declaration && !declaration.type && !declaration.initializer) annotate(changes, importAdder, sourceFile, declaration, type, program, host); + if (needParens) changes.insertNodeAfter(sourceFile, last(containingFunction.parameters), factory.createToken(22 /* CloseParenToken */ )); } - function transformObjectLiteralMembersSortText(start2) { - var _a2; - for(let i = start2; i < symbols.length; i++){ - const symbol = symbols[i]; - const symbolId = getSymbolId(symbol); - const origin = symbolToOriginInfoMap == null ? void 0 : symbolToOriginInfoMap[i]; - const target = getEmitScriptTarget(compilerOptions); - const displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, 0 /* ObjectPropertyDeclaration */ , /*jsxIdentifierExpected*/ false); - if (displayName) { - const originalSortText = (_a2 = symbolToSortTextMap[symbolId]) != null ? _a2 : SortText.LocationPriority; - const { name: name } = displayName; - symbolToSortTextMap[symbolId] = SortText.ObjectLiteralProperty(originalSortText, name); + } + function annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken) { + const references = getFunctionReferences(containingFunction, sourceFile, program, cancellationToken); + if (!references || !references.length) return; + const thisInference = inferTypeFromReferences(program, references, cancellationToken).thisParameter(); + const typeNode = getTypeNodeIfAccessible(thisInference, containingFunction, program, host); + if (!typeNode) return; + if (isInJSFile(containingFunction)) annotateJSDocThis(changes, sourceFile, containingFunction, typeNode); + else changes.tryInsertThisTypeAnnotation(sourceFile, containingFunction, typeNode); + } + function annotateJSDocThis(changes, sourceFile, containingFunction, typeNode) { + changes.addJSDocTags(sourceFile, containingFunction, [ + factory.createJSDocThisTag(/*tagName*/ void 0, factory.createJSDocTypeExpression(typeNode)) + ]); + } + function annotateSetAccessor(changes, importAdder, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { + const param = firstOrUndefined(setAccessorDeclaration.parameters); + if (param && isIdentifier(setAccessorDeclaration.name) && isIdentifier(param.name)) { + let type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); + if (type === program.getTypeChecker().getAnyType()) type = inferTypeForVariableFromUsage(param.name, program, cancellationToken); + if (isInJSFile(setAccessorDeclaration)) annotateJSDocParameters(changes, sourceFile, [ + { + declaration: param, + type: type } - } - } - function filterClassMembersList(baseSymbols, existingMembers, currentClassElementModifierFlags) { - const existingMemberNames = /* @__PURE__ */ new Set(); - for (const m of existingMembers){ - if (m.kind !== 169 /* PropertyDeclaration */ && m.kind !== 171 /* MethodDeclaration */ && m.kind !== 174 /* GetAccessor */ && m.kind !== 175 /* SetAccessor */ ) continue; - if (isCurrentlyEditingNode(m)) continue; - if (hasEffectiveModifier(m, 8 /* Private */ )) continue; - if (isStatic(m) !== !!(currentClassElementModifierFlags & 32 /* Static */ )) continue; - const existingName = getPropertyNameForPropertyNameNode(m.name); - if (existingName) existingMemberNames.add(existingName); - } - return baseSymbols.filter((propertySymbol)=>!existingMemberNames.has(propertySymbol.escapedName) && !!propertySymbol.declarations && !(getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */ ) && !(propertySymbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(propertySymbol.valueDeclaration))); + ], program, host); + else annotate(changes, importAdder, sourceFile, param, type, program, host); } - function filterJsxAttributes(symbols2, attributes) { - const seenNames = /* @__PURE__ */ new Set(); - const membersDeclaredBySpreadAssignment = /* @__PURE__ */ new Set(); - for (const attr of attributes){ - if (isCurrentlyEditingNode(attr)) continue; - if (attr.kind === 288 /* JsxAttribute */ ) seenNames.add(attr.name.escapedText); - else if (isJsxSpreadAttribute(attr)) setMembersDeclaredBySpreadAssignment(attr, membersDeclaredBySpreadAssignment); - } - const filteredSymbols = symbols2.filter((a)=>!seenNames.has(a.escapedName)); - setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, filteredSymbols); - return filteredSymbols; + } + function annotate(changes, importAdder, sourceFile, declaration, type, program, host) { + const typeNode = getTypeNodeIfAccessible(type, declaration, program, host); + if (typeNode) { + if (isInJSFile(sourceFile) && declaration.kind !== 171 /* PropertySignature */ ) { + const parent2 = isVariableDeclaration(declaration) ? tryCast(declaration.parent.parent, isVariableStatement) : declaration; + if (!parent2) return; + const typeExpression = factory.createJSDocTypeExpression(typeNode); + const typeTag = isGetAccessorDeclaration(declaration) ? factory.createJSDocReturnTag(/*tagName*/ void 0, typeExpression, /*comment*/ void 0) : factory.createJSDocTypeTag(/*tagName*/ void 0, typeExpression, /*comment*/ void 0); + changes.addJSDocTags(sourceFile, parent2, [ + typeTag + ]); + } else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, sourceFile, changes, importAdder, getEmitScriptTarget(program.getCompilerOptions()))) changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); } - function isCurrentlyEditingNode(node2) { - return node2.getStart(sourceFile) <= position && position <= node2.getEnd(); + } + function tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, sourceFile, changes, importAdder, scriptTarget) { + const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget); + if (importableReference && changes.tryInsertTypeAnnotation(sourceFile, declaration, importableReference.typeNode)) { + forEach(importableReference.symbols, (s)=>importAdder.addImportFromExportedSymbol(s, /*isValidTypeOnlyUseSite*/ true)); + return true; } + return false; } - function tryGetObjectLikeCompletionContainer(contextToken) { - if (contextToken) { - const { parent: parent2 } = contextToken; - switch(contextToken.kind){ - case 18 /* OpenBraceToken */ : - case 27 /* CommaToken */ : - if (isObjectLiteralExpression(parent2) || isObjectBindingPattern(parent2)) return parent2; - break; - case 41 /* AsteriskToken */ : - return isMethodDeclaration(parent2) ? tryCast(parent2.parent, isObjectLiteralExpression) : void 0; - case 79 /* Identifier */ : - return contextToken.text === "async" && isShorthandPropertyAssignment(contextToken.parent) ? contextToken.parent.parent : void 0; + function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { + const signature = parameterInferences.length && parameterInferences[0].declaration.parent; + if (!signature) return; + const inferences = mapDefined(parameterInferences, (inference)=>{ + const param = inference.declaration; + if (param.initializer || getJSDocType(param) || !isIdentifier(param.name)) return; + const typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); + if (typeNode) { + const name = factory.cloneNode(param.name); + setEmitFlags(name, 7168 /* NoNestedComments */ ); + return { + name: factory.cloneNode(param.name), + param: param, + isOptional: !!inference.isOptional, + typeNode: typeNode + }; } + }); + if (!inferences.length) return; + if (isArrowFunction(signature) || isFunctionExpression(signature)) { + const needParens = isArrowFunction(signature) && !findChildOfKind(signature, 21 /* OpenParenToken */ , sourceFile); + if (needParens) changes.insertNodeBefore(sourceFile, first(signature.parameters), factory.createToken(21 /* OpenParenToken */ )); + forEach(inferences, ({ typeNode: typeNode, param: param })=>{ + const typeTag = factory.createJSDocTypeTag(/*tagName*/ void 0, factory.createJSDocTypeExpression(typeNode)); + const jsDoc = factory.createJSDocComment(/*comment*/ void 0, [ + typeTag + ]); + changes.insertNodeAt(sourceFile, param.getStart(sourceFile), jsDoc, { + suffix: " " + }); + }); + if (needParens) changes.insertNodeAfter(sourceFile, last(signature.parameters), factory.createToken(22 /* CloseParenToken */ )); + } else { + const paramTags = map(inferences, ({ name: name, typeNode: typeNode, isOptional: isOptional })=>factory.createJSDocParameterTag(/*tagName*/ void 0, name, /*isBracketed*/ !!isOptional, factory.createJSDocTypeExpression(typeNode), /*isNameFirst*/ false, /*comment*/ void 0)); + changes.addJSDocTags(sourceFile, signature, paramTags); } - return void 0; } - function getRelevantTokens(position, sourceFile) { - const previousToken = findPrecedingToken(position, sourceFile); - if (previousToken && position <= previousToken.end && (isMemberName(previousToken) || isKeyword(previousToken.kind))) { - const contextToken = findPrecedingToken(previousToken.getFullStart(), sourceFile, /*startNode*/ void 0); - return { - contextToken: contextToken, - previousToken: previousToken - }; + function getReferences(token, program, cancellationToken) { + return mapDefined(ts_FindAllReferences_exports.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), (entry)=>entry.kind !== ts_FindAllReferences_exports.EntryKind.Span ? tryCast(entry.node, isIdentifier) : void 0); + } + function inferTypeForVariableFromUsage(token, program, cancellationToken) { + const references = getReferences(token, program, cancellationToken); + return inferTypeFromReferences(program, references, cancellationToken).single(); + } + function inferTypeForParametersFromUsage(func, sourceFile, program, cancellationToken) { + const references = getFunctionReferences(func, sourceFile, program, cancellationToken); + return references && inferTypeFromReferences(program, references, cancellationToken).parameters(func) || func.parameters.map((p)=>({ + declaration: p, + type: isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType() + })); + } + function getFunctionReferences(containingFunction, sourceFile, program, cancellationToken) { + let searchToken; + switch(containingFunction.kind){ + case 176 /* Constructor */ : + searchToken = findChildOfKind(containingFunction, 137 /* ConstructorKeyword */ , sourceFile); + break; + case 219 /* ArrowFunction */ : + case 218 /* FunctionExpression */ : + const parent2 = containingFunction.parent; + searchToken = (isVariableDeclaration(parent2) || isPropertyDeclaration(parent2)) && isIdentifier(parent2.name) ? parent2.name : containingFunction.name; + break; + case 262 /* FunctionDeclaration */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + searchToken = containingFunction.name; + break; } + if (!searchToken) return void 0; + return getReferences(searchToken, program, cancellationToken); + } + function inferTypeFromReferences(program, references, cancellationToken) { + const checker = program.getTypeChecker(); + const builtinConstructors = { + string: ()=>checker.getStringType(), + number: ()=>checker.getNumberType(), + Array: (t)=>checker.createArrayType(t), + Promise: (t)=>checker.createPromiseType(t) + }; + const builtins = [ + checker.getStringType(), + checker.getNumberType(), + checker.createArrayType(checker.getAnyType()), + checker.createPromiseType(checker.getAnyType()) + ]; return { - contextToken: previousToken, - previousToken: previousToken + single: single2, + parameters: parameters, + thisParameter: thisParameter }; - } - function getAutoImportSymbolFromCompletionEntryData(name, data, program, host) { - const containingProgram = data.isPackageJsonImport ? host.getPackageJsonAutoImportProvider() : program; - const checker = containingProgram.getTypeChecker(); - const moduleSymbol = data.ambientModuleName ? checker.tryFindAmbientModule(data.ambientModuleName) : data.fileName ? checker.getMergedSymbol(Debug.checkDefined(containingProgram.getSourceFile(data.fileName)).symbol) : void 0; - if (!moduleSymbol) return void 0; - let symbol = data.exportName === "export=" /* ExportEquals */ ? checker.resolveExternalModuleSymbol(moduleSymbol) : checker.tryGetMemberInModuleExportsAndProperties(data.exportName, moduleSymbol); - if (!symbol) return void 0; - const isDefaultExport = data.exportName === "default" /* Default */ ; - symbol = isDefaultExport && getLocalSymbolForExportDefault(symbol) || symbol; - return { - symbol: symbol, - origin: completionEntryDataToSymbolOriginInfo(data, name, moduleSymbol) - }; - } - function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, jsxIdentifierExpected) { - if (originIsIgnore(origin)) return void 0; - const name = originIncludesSymbolName(origin) ? origin.symbolName : symbol.name; - if (name === void 0 || symbol.flags & 1536 /* Module */ && isSingleOrDoubleQuote(name.charCodeAt(0)) || isKnownSymbol(symbol)) return void 0; - const validNameResult = { - name: name, - needsConvertPropertyAccess: false - }; - if (isIdentifierText(name, target, jsxIdentifierExpected ? 1 /* JSX */ : 0 /* Standard */ ) || symbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) return validNameResult; - switch(kind){ - case 3 /* MemberLike */ : - return originIsComputedPropertyName(origin) ? { - name: origin.symbolName, - needsConvertPropertyAccess: false - } : void 0; - case 0 /* ObjectPropertyDeclaration */ : + function createEmptyUsage() { + return { + isNumber: void 0, + isString: void 0, + isNumberOrString: void 0, + candidateTypes: void 0, + properties: void 0, + calls: void 0, + constructs: void 0, + numberIndex: void 0, + stringIndex: void 0, + candidateThisTypes: void 0, + inferredTypes: void 0 + }; + } + function combineUsages(usages) { + const combinedProperties = /* @__PURE__ */ new Map(); + for (const u of usages)if (u.properties) u.properties.forEach((p, name)=>{ + if (!combinedProperties.has(name)) combinedProperties.set(name, []); + combinedProperties.get(name).push(p); + }); + const properties = /* @__PURE__ */ new Map(); + combinedProperties.forEach((ps, name)=>{ + properties.set(name, combineUsages(ps)); + }); + return { + isNumber: usages.some((u)=>u.isNumber), + isString: usages.some((u)=>u.isString), + isNumberOrString: usages.some((u)=>u.isNumberOrString), + candidateTypes: flatMap(usages, (u)=>u.candidateTypes), + properties: properties, + calls: flatMap(usages, (u)=>u.calls), + constructs: flatMap(usages, (u)=>u.constructs), + numberIndex: forEach(usages, (u)=>u.numberIndex), + stringIndex: forEach(usages, (u)=>u.stringIndex), + candidateThisTypes: flatMap(usages, (u)=>u.candidateThisTypes), + inferredTypes: void 0 + }; + } + function single2() { + return combineTypes(inferTypesFromReferencesSingle(references)); + } + function parameters(declaration) { + if (references.length === 0 || !declaration.parameters) return void 0; + const usage = createEmptyUsage(); + for (const reference of references){ + cancellationToken.throwIfCancellationRequested(); + calculateUsageOfNode(reference, usage); + } + const calls = [ + ...usage.constructs || [], + ...usage.calls || [] + ]; + return declaration.parameters.map((parameter, parameterIndex)=>{ + const types = []; + const isRest = isRestParameter(parameter); + let isOptional = false; + for (const call of calls){ + if (call.argumentTypes.length <= parameterIndex) { + isOptional = isInJSFile(declaration); + types.push(checker.getUndefinedType()); + } else if (isRest) for(let i = parameterIndex; i < call.argumentTypes.length; i++)types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[i])); + else types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[parameterIndex])); + } + if (isIdentifier(parameter.name)) { + const inferred = inferTypesFromReferencesSingle(getReferences(parameter.name, program, cancellationToken)); + types.push(...isRest ? mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred); + } + const type = combineTypes(types); return { - name: JSON.stringify(name), - needsConvertPropertyAccess: false - }; - case 2 /* PropertyAccess */ : - case 1 /* Global */ : - return name.charCodeAt(0) === 32 /* space */ ? void 0 : { - name: name, - needsConvertPropertyAccess: true + type: isRest ? checker.createArrayType(type) : type, + isOptional: isOptional && !isRest, + declaration: parameter }; - case 5 /* None */ : - case 4 /* String */ : - return validNameResult; - default: - Debug.assertNever(kind); + }); } - } - function getKeywordCompletions(keywordFilter, filterOutTsOnlyKeywords) { - if (!filterOutTsOnlyKeywords) return getTypescriptKeywordCompletions(keywordFilter); - const index = keywordFilter + 8 /* Last */ + 1; - return _keywordCompletions[index] || (_keywordCompletions[index] = getTypescriptKeywordCompletions(keywordFilter).filter((entry)=>!isTypeScriptOnlyKeyword(stringToToken(entry.name)))); - } - function getTypescriptKeywordCompletions(keywordFilter) { - return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter((entry)=>{ - const kind = stringToToken(entry.name); - switch(keywordFilter){ - case 0 /* None */ : - return false; - case 1 /* All */ : - return isFunctionLikeBodyKeyword(kind) || kind === 136 /* DeclareKeyword */ || kind === 142 /* ModuleKeyword */ || kind === 154 /* TypeKeyword */ || kind === 143 /* NamespaceKeyword */ || kind === 126 /* AbstractKeyword */ || isTypeKeyword(kind) && kind !== 155 /* UndefinedKeyword */ ; - case 5 /* FunctionLikeBodyKeywords */ : - return isFunctionLikeBodyKeyword(kind); - case 2 /* ClassElementKeywords */ : - return isClassMemberCompletionKeyword(kind); - case 3 /* InterfaceElementKeywords */ : - return isInterfaceOrTypeLiteralCompletionKeyword(kind); - case 4 /* ConstructorParameterKeywords */ : - return isParameterPropertyModifier(kind); - case 6 /* TypeAssertionKeywords */ : - return isTypeKeyword(kind) || kind === 85 /* ConstKeyword */ ; - case 7 /* TypeKeywords */ : - return isTypeKeyword(kind); - case 8 /* TypeKeyword */ : - return kind === 154 /* TypeKeyword */ ; + function thisParameter() { + const usage = createEmptyUsage(); + for (const reference of references){ + cancellationToken.throwIfCancellationRequested(); + calculateUsageOfNode(reference, usage); + } + return combineTypes(usage.candidateThisTypes || emptyArray); + } + function inferTypesFromReferencesSingle(references2) { + const usage = createEmptyUsage(); + for (const reference of references2){ + cancellationToken.throwIfCancellationRequested(); + calculateUsageOfNode(reference, usage); + } + return inferTypes(usage); + } + function calculateUsageOfNode(node, usage) { + while(isRightSideOfQualifiedNameOrPropertyAccess(node))node = node.parent; + switch(node.parent.kind){ + case 244 /* ExpressionStatement */ : + inferTypeFromExpressionStatement(node, usage); + break; + case 225 /* PostfixUnaryExpression */ : + usage.isNumber = true; + break; + case 224 /* PrefixUnaryExpression */ : + inferTypeFromPrefixUnaryExpression(node.parent, usage); + break; + case 226 /* BinaryExpression */ : + inferTypeFromBinaryExpression(node, node.parent, usage); + break; + case 296 /* CaseClause */ : + case 297 /* DefaultClause */ : + inferTypeFromSwitchStatementLabel(node.parent, usage); + break; + case 213 /* CallExpression */ : + case 214 /* NewExpression */ : + if (node.parent.expression === node) inferTypeFromCallExpression(node.parent, usage); + else inferTypeFromContextualType(node, usage); + break; + case 211 /* PropertyAccessExpression */ : + inferTypeFromPropertyAccessExpression(node.parent, usage); + break; + case 212 /* ElementAccessExpression */ : + inferTypeFromPropertyElementExpression(node.parent, node, usage); + break; + case 303 /* PropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : + inferTypeFromPropertyAssignment(node.parent, usage); + break; + case 172 /* PropertyDeclaration */ : + inferTypeFromPropertyDeclaration(node.parent, usage); + break; + case 260 /* VariableDeclaration */ : + { + const { name: name, initializer: initializer } = node.parent; + if (node === name) { + if (initializer) addCandidateType(usage, checker.getTypeAtLocation(initializer)); + break; + } + } default: - return Debug.assertNever(keywordFilter); + return inferTypeFromContextualType(node, usage); } - })); - } - function isTypeScriptOnlyKeyword(kind) { - switch(kind){ - case 126 /* AbstractKeyword */ : - case 131 /* AnyKeyword */ : - case 160 /* BigIntKeyword */ : - case 134 /* BooleanKeyword */ : - case 136 /* DeclareKeyword */ : - case 92 /* EnumKeyword */ : - case 159 /* GlobalKeyword */ : - case 117 /* ImplementsKeyword */ : - case 138 /* InferKeyword */ : - case 118 /* InterfaceKeyword */ : - case 140 /* IsKeyword */ : - case 141 /* KeyOfKeyword */ : - case 142 /* ModuleKeyword */ : - case 143 /* NamespaceKeyword */ : - case 144 /* NeverKeyword */ : - case 148 /* NumberKeyword */ : - case 149 /* ObjectKeyword */ : - case 161 /* OverrideKeyword */ : - case 121 /* PrivateKeyword */ : - case 122 /* ProtectedKeyword */ : - case 123 /* PublicKeyword */ : - case 146 /* ReadonlyKeyword */ : - case 152 /* StringKeyword */ : - case 153 /* SymbolKeyword */ : - case 154 /* TypeKeyword */ : - case 156 /* UniqueKeyword */ : - case 157 /* UnknownKeyword */ : - return true; - default: - return false; } - } - function isInterfaceOrTypeLiteralCompletionKeyword(kind) { - return kind === 146 /* ReadonlyKeyword */ ; - } - function isClassMemberCompletionKeyword(kind) { - switch(kind){ - case 126 /* AbstractKeyword */ : - case 127 /* AccessorKeyword */ : - case 135 /* ConstructorKeyword */ : - case 137 /* GetKeyword */ : - case 151 /* SetKeyword */ : - case 132 /* AsyncKeyword */ : - case 136 /* DeclareKeyword */ : - case 161 /* OverrideKeyword */ : - return true; - default: - return isClassMemberModifier(kind); + function inferTypeFromContextualType(node, usage) { + if (isExpressionNode(node)) addCandidateType(usage, checker.getContextualType(node)); } - } - function isFunctionLikeBodyKeyword(kind) { - return kind === 132 /* AsyncKeyword */ || kind === 133 /* AwaitKeyword */ || kind === 128 /* AsKeyword */ || kind === 150 /* SatisfiesKeyword */ || kind === 154 /* TypeKeyword */ || !isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); - } - function keywordForNode(node) { - var _a2; - return isIdentifier(node) ? (_a2 = identifierToKeywordKind(node)) != null ? _a2 : 0 /* Unknown */ : node.kind; - } - function getContextualKeywords(contextToken, position) { - const entries = []; - if (contextToken) { - const file = contextToken.getSourceFile(); - const parent2 = contextToken.parent; - const tokenLine = file.getLineAndCharacterOfPosition(contextToken.end).line; - const currentLine = file.getLineAndCharacterOfPosition(position).line; - if ((isImportDeclaration(parent2) || isExportDeclaration(parent2) && parent2.moduleSpecifier) && contextToken === parent2.moduleSpecifier && tokenLine === currentLine) entries.push({ - name: tokenToString(130 /* AssertKeyword */ ), - kind: "keyword" /* keyword */ , - kindModifiers: "" /* none */ , - sortText: SortText.GlobalsOrKeywords - }); + function inferTypeFromExpressionStatement(node, usage) { + addCandidateType(usage, isCallExpression(node) ? checker.getVoidType() : checker.getAnyType()); } - return entries; - } - function getJsDocTagAtPosition(node, position) { - return findAncestor(node, (n)=>isJSDocTag(n) && rangeContainsPosition(n, position) ? true : isJSDoc(n) ? "quit" : false); - } - function getPropertiesForObjectExpression(contextualType, completionsType, obj, checker) { - const hasCompletionsType = completionsType && completionsType !== contextualType; - const type = hasCompletionsType && !(completionsType.flags & 3 /* AnyOrUnknown */ ) ? checker.getUnionType([ - contextualType, - completionsType - ]) : contextualType; - const properties = getApparentProperties(type, obj, checker); - return type.isClass() && containsNonPublicProperties(properties) ? [] : hasCompletionsType ? filter(properties, hasDeclarationOtherThanSelf) : properties; - function hasDeclarationOtherThanSelf(member) { - if (!length(member.declarations)) return true; - return some(member.declarations, (decl)=>decl.parent !== obj); + function inferTypeFromPrefixUnaryExpression(node, usage) { + switch(node.operator){ + case 46 /* PlusPlusToken */ : + case 47 /* MinusMinusToken */ : + case 41 /* MinusToken */ : + case 55 /* TildeToken */ : + usage.isNumber = true; + break; + case 40 /* PlusToken */ : + usage.isNumberOrString = true; + break; + } } - } - function getApparentProperties(type, node, checker) { - if (!type.isUnion()) return type.getApparentProperties(); - return checker.getAllPossiblePropertiesOfTypes(filter(type.types, (memberType)=>!(memberType.flags & 134348796 /* Primitive */ || checker.isArrayLikeType(memberType) || checker.isTypeInvalidDueToUnionDiscriminant(memberType, node) || checker.typeHasCallOrConstructSignatures(memberType) || memberType.isClass() && containsNonPublicProperties(memberType.getApparentProperties())))); - } - function containsNonPublicProperties(props) { - return some(props, (p)=>!!(getDeclarationModifierFlagsFromSymbol(p) & 24 /* NonPublicAccessibilityModifier */ )); - } - function getPropertiesForCompletion(type, checker) { - return type.isUnion() ? Debug.checkEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined") : Debug.checkEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined"); - } - function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location, position) { - var _a2; - switch(location.kind){ - case 354 /* SyntaxList */ : - return tryCast(location.parent, isObjectTypeDeclaration); - case 1 /* EndOfFileToken */ : - const cls = tryCast(lastOrUndefined(cast(location.parent, isSourceFile).statements), isObjectTypeDeclaration); - if (cls && !findChildOfKind(cls, 19 /* CloseBraceToken */ , sourceFile)) return cls; - break; - case 79 /* Identifier */ : - { - const originalKeywordKind = identifierToKeywordKind(location); - if (originalKeywordKind) return void 0; - if (isPropertyDeclaration(location.parent) && location.parent.initializer === location) return void 0; - if (isFromObjectTypeDeclaration(location)) return findAncestor(location, isObjectTypeDeclaration); - } + function inferTypeFromBinaryExpression(node, parent2, usage) { + switch(parent2.operatorToken.kind){ + case 43 /* AsteriskAsteriskToken */ : + case 42 /* AsteriskToken */ : + case 44 /* SlashToken */ : + case 45 /* PercentToken */ : + case 48 /* LessThanLessThanToken */ : + case 49 /* GreaterThanGreaterThanToken */ : + case 50 /* GreaterThanGreaterThanGreaterThanToken */ : + case 51 /* AmpersandToken */ : + case 52 /* BarToken */ : + case 53 /* CaretToken */ : + case 66 /* MinusEqualsToken */ : + case 68 /* AsteriskAsteriskEqualsToken */ : + case 67 /* AsteriskEqualsToken */ : + case 69 /* SlashEqualsToken */ : + case 70 /* PercentEqualsToken */ : + case 74 /* AmpersandEqualsToken */ : + case 75 /* BarEqualsToken */ : + case 79 /* CaretEqualsToken */ : + case 71 /* LessThanLessThanEqualsToken */ : + case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */ : + case 72 /* GreaterThanGreaterThanEqualsToken */ : + case 41 /* MinusToken */ : + case 30 /* LessThanToken */ : + case 33 /* LessThanEqualsToken */ : + case 32 /* GreaterThanToken */ : + case 34 /* GreaterThanEqualsToken */ : + const operandType = checker.getTypeAtLocation(parent2.left === node ? parent2.right : parent2.left); + if (operandType.flags & 1056 /* EnumLike */ ) addCandidateType(usage, operandType); + else usage.isNumber = true; + break; + case 65 /* PlusEqualsToken */ : + case 40 /* PlusToken */ : + const otherOperandType = checker.getTypeAtLocation(parent2.left === node ? parent2.right : parent2.left); + if (otherOperandType.flags & 1056 /* EnumLike */ ) addCandidateType(usage, otherOperandType); + else if (otherOperandType.flags & 296 /* NumberLike */ ) usage.isNumber = true; + else if (otherOperandType.flags & 402653316 /* StringLike */ ) usage.isString = true; + else if (otherOperandType.flags & 1 /* Any */ ) ; + else usage.isNumberOrString = true; + break; + case 64 /* EqualsToken */ : + case 35 /* EqualsEqualsToken */ : + case 37 /* EqualsEqualsEqualsToken */ : + case 38 /* ExclamationEqualsEqualsToken */ : + case 36 /* ExclamationEqualsToken */ : + case 77 /* AmpersandAmpersandEqualsToken */ : + case 78 /* QuestionQuestionEqualsToken */ : + case 76 /* BarBarEqualsToken */ : + addCandidateType(usage, checker.getTypeAtLocation(parent2.left === node ? parent2.right : parent2.left)); + break; + case 103 /* InKeyword */ : + if (node === parent2.left) usage.isString = true; + break; + case 57 /* BarBarToken */ : + case 61 /* QuestionQuestionToken */ : + if (node === parent2.left && (node.parent.parent.kind === 260 /* VariableDeclaration */ || isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) addCandidateType(usage, checker.getTypeAtLocation(parent2.right)); + break; + case 56 /* AmpersandAmpersandToken */ : + case 28 /* CommaToken */ : + case 104 /* InstanceOfKeyword */ : + break; + } } - if (!contextToken) return void 0; - if (location.kind === 135 /* ConstructorKeyword */ || isIdentifier(contextToken) && isPropertyDeclaration(contextToken.parent) && isClassLike(location)) return findAncestor(contextToken, isClassLike); - switch(contextToken.kind){ - case 63 /* EqualsToken */ : - return void 0; - case 26 /* SemicolonToken */ : - case 19 /* CloseBraceToken */ : - return isFromObjectTypeDeclaration(location) && location.parent.name === location ? location.parent.parent : tryCast(location, isObjectTypeDeclaration); - case 18 /* OpenBraceToken */ : - case 27 /* CommaToken */ : - return tryCast(contextToken.parent, isObjectTypeDeclaration); - default: - if (isObjectTypeDeclaration(location)) { - if (getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line !== getLineAndCharacterOfPosition(sourceFile, position).line) return location; - const isValidKeyword = isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; - return isValidKeyword(contextToken.kind) || contextToken.kind === 41 /* AsteriskToken */ || isIdentifier(contextToken) && isValidKeyword((_a2 = identifierToKeywordKind(contextToken)) != null ? _a2 : 0 /* Unknown */ ) ? contextToken.parent.parent : void 0; - } - return void 0; + function inferTypeFromSwitchStatementLabel(parent2, usage) { + addCandidateType(usage, checker.getTypeAtLocation(parent2.parent.parent.expression)); } - } - function tryGetTypeLiteralNode(node) { - if (!node) return void 0; - const parent2 = node.parent; - switch(node.kind){ - case 18 /* OpenBraceToken */ : - if (isTypeLiteralNode(parent2)) return parent2; - break; - case 26 /* SemicolonToken */ : - case 27 /* CommaToken */ : - case 79 /* Identifier */ : - if (parent2.kind === 168 /* PropertySignature */ && isTypeLiteralNode(parent2.parent)) return parent2.parent; - break; + function inferTypeFromCallExpression(parent2, usage) { + const call = { + argumentTypes: [], + return_: createEmptyUsage() + }; + if (parent2.arguments) for (const argument of parent2.arguments)call.argumentTypes.push(checker.getTypeAtLocation(argument)); + calculateUsageOfNode(parent2, call.return_); + if (parent2.kind === 213 /* CallExpression */ ) (usage.calls || (usage.calls = [])).push(call); + else (usage.constructs || (usage.constructs = [])).push(call); } - return void 0; - } - function getConstraintOfTypeArgumentProperty(node, checker) { - if (!node) return void 0; - if (isTypeNode(node) && isTypeReferenceType(node.parent)) return checker.getTypeArgumentConstraint(node); - const t = getConstraintOfTypeArgumentProperty(node.parent, checker); - if (!t) return void 0; - switch(node.kind){ - case 168 /* PropertySignature */ : - return checker.getTypeOfPropertyOfContextualType(t, node.symbol.escapedName); - case 190 /* IntersectionType */ : - case 184 /* TypeLiteral */ : - case 189 /* UnionType */ : - return t; + function inferTypeFromPropertyAccessExpression(parent2, usage) { + const name = escapeLeadingUnderscores(parent2.name.text); + if (!usage.properties) usage.properties = /* @__PURE__ */ new Map(); + const propertyUsage = usage.properties.get(name) || createEmptyUsage(); + calculateUsageOfNode(parent2, propertyUsage); + usage.properties.set(name, propertyUsage); } - } - function isFromObjectTypeDeclaration(node) { - return node.parent && isClassOrTypeElement(node.parent) && isObjectTypeDeclaration(node.parent.parent); - } - function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) { - switch(triggerCharacter){ - case ".": - case "@": - return true; - case '"': - case "'": - case "`": - return !!contextToken && isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; - case "#": - return !!contextToken && isPrivateIdentifier(contextToken) && !!getContainingClass(contextToken); - case "<": - return !!contextToken && contextToken.kind === 29 /* LessThanToken */ && (!isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); - case "/": - return !!contextToken && (isStringLiteralLike(contextToken) ? !!tryGetImportFromModuleSpecifier(contextToken) : contextToken.kind === 43 /* SlashToken */ && isJsxClosingElement(contextToken.parent)); - case " ": - return !!contextToken && isImportKeyword(contextToken) && contextToken.parent.kind === 308 /* SourceFile */ ; - default: - return Debug.assertNever(triggerCharacter); + function inferTypeFromPropertyElementExpression(parent2, node, usage) { + if (node === parent2.argumentExpression) { + usage.isNumberOrString = true; + return; + } else { + const indexType = checker.getTypeAtLocation(parent2.argumentExpression); + const indexUsage = createEmptyUsage(); + calculateUsageOfNode(parent2, indexUsage); + if (indexType.flags & 296 /* NumberLike */ ) usage.numberIndex = indexUsage; + else usage.stringIndex = indexUsage; + } } - } - function binaryExpressionMayBeOpenTag({ left: left }) { - return nodeIsMissing(left); - } - function isProbablyGlobalType(type, sourceFile, checker) { - const selfSymbol = checker.resolveName("self", /*location*/ void 0, 111551 /* Value */ , /*excludeGlobals*/ false); - if (selfSymbol && checker.getTypeOfSymbolAtLocation(selfSymbol, sourceFile) === type) return true; - const globalSymbol = checker.resolveName("global", /*location*/ void 0, 111551 /* Value */ , /*excludeGlobals*/ false); - if (globalSymbol && checker.getTypeOfSymbolAtLocation(globalSymbol, sourceFile) === type) return true; - const globalThisSymbol = checker.resolveName("globalThis", /*location*/ void 0, 111551 /* Value */ , /*excludeGlobals*/ false); - if (globalThisSymbol && checker.getTypeOfSymbolAtLocation(globalThisSymbol, sourceFile) === type) return true; - return false; - } - function isStaticProperty(symbol) { - return !!(symbol.valueDeclaration && getEffectiveModifierFlags(symbol.valueDeclaration) & 32 /* Static */ && isClassLike(symbol.valueDeclaration.parent)); - } - function tryGetObjectLiteralContextualType(node, typeChecker) { - const type = typeChecker.getContextualType(node); - if (type) return type; - const parent2 = walkUpParenthesizedExpressions(node.parent); - if (isBinaryExpression(parent2) && parent2.operatorToken.kind === 63 /* EqualsToken */ && node === parent2.left) return typeChecker.getTypeAtLocation(parent2); - if (isExpression(parent2)) return typeChecker.getContextualType(parent2); - return void 0; - } - function getImportStatementCompletionInfo(contextToken) { - var _a2, _b, _c; - let keywordCompletion; - let isKeywordOnlyCompletion = false; - const candidate = getCandidate(); - return { - isKeywordOnlyCompletion: isKeywordOnlyCompletion, - keywordCompletion: keywordCompletion, - isNewIdentifierLocation: !!(candidate || keywordCompletion === 154 /* TypeKeyword */ ), - isTopLevelTypeOnly: !!((_b = (_a2 = tryCast(candidate, isImportDeclaration)) == null ? void 0 : _a2.importClause) == null ? void 0 : _b.isTypeOnly) || !!((_c = tryCast(candidate, isImportEqualsDeclaration)) == null ? void 0 : _c.isTypeOnly), - couldBeTypeOnlyImportSpecifier: !!candidate && couldBeTypeOnlyImportSpecifier(candidate, contextToken), - replacementSpan: getSingleLineReplacementSpanForImportCompletionNode(candidate) - }; - function getCandidate() { - const parent2 = contextToken.parent; - if (isImportEqualsDeclaration(parent2)) { - keywordCompletion = contextToken.kind === 154 /* TypeKeyword */ ? void 0 : 154 /* TypeKeyword */ ; - return isModuleSpecifierMissingOrEmpty(parent2.moduleReference) ? parent2 : void 0; + function inferTypeFromPropertyAssignment(assignment, usage) { + const nodeWithRealType = isVariableDeclaration(assignment.parent.parent) ? assignment.parent.parent : assignment.parent; + addCandidateThisType(usage, checker.getTypeAtLocation(nodeWithRealType)); + } + function inferTypeFromPropertyDeclaration(declaration, usage) { + addCandidateThisType(usage, checker.getTypeAtLocation(declaration.parent)); + } + function removeLowPriorityInferences(inferences, priorities) { + const toRemove = []; + for (const i of inferences){ + for (const { high: high, low: low } of priorities)if (high(i)) { + Debug.assert(!low(i), "Priority can't have both low and high"); + toRemove.push(low); + } } - if (couldBeTypeOnlyImportSpecifier(parent2, contextToken) && canCompleteFromNamedBindings(parent2.parent)) return parent2; - if (isNamedImports(parent2) || isNamespaceImport(parent2)) { - if (!parent2.parent.isTypeOnly && (contextToken.kind === 18 /* OpenBraceToken */ || contextToken.kind === 100 /* ImportKeyword */ || contextToken.kind === 27 /* CommaToken */ )) keywordCompletion = 154 /* TypeKeyword */ ; - if (canCompleteFromNamedBindings(parent2)) { - if (contextToken.kind === 19 /* CloseBraceToken */ || contextToken.kind === 79 /* Identifier */ ) { - isKeywordOnlyCompletion = true; - keywordCompletion = 158 /* FromKeyword */ ; - } else return parent2.parent.parent; + return inferences.filter((i)=>toRemove.every((f)=>!f(i))); + } + function combineFromUsage(usage) { + return combineTypes(inferTypes(usage)); + } + function combineTypes(inferences) { + if (!inferences.length) return checker.getAnyType(); + const stringNumber = checker.getUnionType([ + checker.getStringType(), + checker.getNumberType() + ]); + const priorities = [ + { + high: (t)=>t === checker.getStringType() || t === checker.getNumberType(), + low: (t)=>t === stringNumber + }, + { + high: (t)=>!(t.flags & 16385 /* Void */ ), + low: (t)=>!!(t.flags & 16385 /* Void */ ) + }, + { + high: (t)=>!(t.flags & 114689 /* Void */ ) && !(getObjectFlags(t) & 16 /* Anonymous */ ), + low: (t)=>!!(getObjectFlags(t) & 16 /* Anonymous */ ) } - return void 0; + ]; + let good = removeLowPriorityInferences(inferences, priorities); + const anons = good.filter((i)=>getObjectFlags(i) & 16 /* Anonymous */ ); + if (anons.length) { + good = good.filter((i)=>!(getObjectFlags(i) & 16 /* Anonymous */ )); + good.push(combineAnonymousTypes(anons)); } - if (isImportKeyword(contextToken) && isSourceFile(parent2)) { - keywordCompletion = 154 /* TypeKeyword */ ; - return contextToken; + return checker.getWidenedType(checker.getUnionType(good.map(checker.getBaseTypeOfLiteralType), 2 /* Subtype */ )); + } + function combineAnonymousTypes(anons) { + if (anons.length === 1) return anons[0]; + const calls = []; + const constructs = []; + const stringIndices = []; + const numberIndices = []; + let stringIndexReadonly = false; + let numberIndexReadonly = false; + const props = createMultiMap(); + for (const anon2 of anons){ + for (const p of checker.getPropertiesOfType(anon2))props.add(p.escapedName, p.valueDeclaration ? checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration) : checker.getAnyType()); + calls.push(...checker.getSignaturesOfType(anon2, 0 /* Call */ )); + constructs.push(...checker.getSignaturesOfType(anon2, 1 /* Construct */ )); + const stringIndexInfo = checker.getIndexInfoOfType(anon2, 0 /* String */ ); + if (stringIndexInfo) { + stringIndices.push(stringIndexInfo.type); + stringIndexReadonly = stringIndexReadonly || stringIndexInfo.isReadonly; + } + const numberIndexInfo = checker.getIndexInfoOfType(anon2, 1 /* Number */ ); + if (numberIndexInfo) { + numberIndices.push(numberIndexInfo.type); + numberIndexReadonly = numberIndexReadonly || numberIndexInfo.isReadonly; + } } - if (isImportKeyword(contextToken) && isImportDeclaration(parent2)) { - keywordCompletion = 154 /* TypeKeyword */ ; - return isModuleSpecifierMissingOrEmpty(parent2.moduleSpecifier) ? parent2 : void 0; + const members = mapEntries(props, (name, types)=>{ + const isOptional = types.length < anons.length ? 16777216 /* Optional */ : 0; + const s = checker.createSymbol(4 /* Property */ | isOptional, name); + s.links.type = checker.getUnionType(types); + return [ + name, + s + ]; + }); + const indexInfos = []; + if (stringIndices.length) indexInfos.push(checker.createIndexInfo(checker.getStringType(), checker.getUnionType(stringIndices), stringIndexReadonly)); + if (numberIndices.length) indexInfos.push(checker.createIndexInfo(checker.getNumberType(), checker.getUnionType(numberIndices), numberIndexReadonly)); + return checker.createAnonymousType(anons[0].symbol, members, calls, constructs, indexInfos); + } + function inferTypes(usage) { + var _a, _b, _c; + const types = []; + if (usage.isNumber) types.push(checker.getNumberType()); + if (usage.isString) types.push(checker.getStringType()); + if (usage.isNumberOrString) types.push(checker.getUnionType([ + checker.getStringType(), + checker.getNumberType() + ])); + if (usage.numberIndex) types.push(checker.createArrayType(combineFromUsage(usage.numberIndex))); + if (((_a = usage.properties) == null ? void 0 : _a.size) || ((_b = usage.constructs) == null ? void 0 : _b.length) || usage.stringIndex) types.push(inferStructuralType(usage)); + const candidateTypes = (usage.candidateTypes || []).map((t)=>checker.getBaseTypeOfLiteralType(t)); + const callsType = ((_c = usage.calls) == null ? void 0 : _c.length) ? inferStructuralType(usage) : void 0; + if (callsType && candidateTypes) types.push(checker.getUnionType([ + callsType, + ...candidateTypes + ], 2 /* Subtype */ )); + else { + if (callsType) types.push(callsType); + if (length(candidateTypes)) types.push(...candidateTypes); } - return void 0; + types.push(...inferNamedTypesFromProperties(usage)); + return types; } - } - function getSingleLineReplacementSpanForImportCompletionNode(node) { - var _a2, _b, _c; - if (!node) return void 0; - const top = (_a2 = findAncestor(node, or(isImportDeclaration, isImportEqualsDeclaration))) != null ? _a2 : node; - const sourceFile = top.getSourceFile(); - if (rangeIsOnSingleLine(top, sourceFile)) return createTextSpanFromNode(top, sourceFile); - Debug.assert(top.kind !== 100 /* ImportKeyword */ && top.kind !== 273 /* ImportSpecifier */ ); - const potentialSplitPoint = top.kind === 269 /* ImportDeclaration */ ? (_c = getPotentiallyInvalidImportSpecifier((_b = top.importClause) == null ? void 0 : _b.namedBindings)) != null ? _c : top.moduleSpecifier : top.moduleReference; - const withoutModuleSpecifier = { - pos: top.getFirstToken().getStart(), - end: potentialSplitPoint.pos - }; - if (rangeIsOnSingleLine(withoutModuleSpecifier, sourceFile)) return createTextSpanFromRange(withoutModuleSpecifier); - } - function getPotentiallyInvalidImportSpecifier(namedBindings) { - var _a2; - return find((_a2 = tryCast(namedBindings, isNamedImports)) == null ? void 0 : _a2.elements, (e)=>{ - var _a3; - return !e.propertyName && isStringANonContextualKeyword(e.name.text) && ((_a3 = findPrecedingToken(e.name.pos, namedBindings.getSourceFile(), namedBindings)) == null ? void 0 : _a3.kind) !== 27 /* CommaToken */ ; - }); - } - function couldBeTypeOnlyImportSpecifier(importSpecifier, contextToken) { - return isImportSpecifier(importSpecifier) && (importSpecifier.isTypeOnly || contextToken === importSpecifier.name && isTypeKeywordTokenOrIdentifier(contextToken)); - } - function canCompleteFromNamedBindings(namedBindings) { - if (!isModuleSpecifierMissingOrEmpty(namedBindings.parent.parent.moduleSpecifier) || namedBindings.parent.name) return false; - if (isNamedImports(namedBindings)) { - const invalidNamedImport = getPotentiallyInvalidImportSpecifier(namedBindings); - const validImports = invalidNamedImport ? namedBindings.elements.indexOf(invalidNamedImport) : namedBindings.elements.length; - return validImports < 2; + function inferStructuralType(usage) { + const members = /* @__PURE__ */ new Map(); + if (usage.properties) usage.properties.forEach((u, name)=>{ + const symbol = checker.createSymbol(4 /* Property */ , name); + symbol.links.type = combineFromUsage(u); + members.set(name, symbol); + }); + const callSignatures = usage.calls ? [ + getSignatureFromCalls(usage.calls) + ] : []; + const constructSignatures = usage.constructs ? [ + getSignatureFromCalls(usage.constructs) + ] : []; + const indexInfos = usage.stringIndex ? [ + checker.createIndexInfo(checker.getStringType(), combineFromUsage(usage.stringIndex), /*isReadonly*/ false) + ] : []; + return checker.createAnonymousType(/*symbol*/ void 0, members, callSignatures, constructSignatures, indexInfos); } - return true; - } - function isModuleSpecifierMissingOrEmpty(specifier) { - var _a2; - if (nodeIsMissing(specifier)) return true; - return !((_a2 = tryCast(isExternalModuleReference(specifier) ? specifier.expression : specifier, isStringLiteralLike)) == null ? void 0 : _a2.text); - } - function getVariableDeclaration(property) { - const variableDeclaration = findAncestor(property, (node)=>isFunctionBlock(node) || isArrowFunctionBody(node) || isBindingPattern(node) ? "quit" : isVariableDeclaration(node)); - return variableDeclaration; - } - function isArrowFunctionBody(node) { - return node.parent && isArrowFunction(node.parent) && node.parent.body === node; - } - function symbolCanBeReferencedAtTypeLocation(symbol, checker, seenModules = /* @__PURE__ */ new Map()) { - return nonAliasCanBeReferencedAtTypeLocation(symbol) || nonAliasCanBeReferencedAtTypeLocation(skipAlias(symbol.exportSymbol || symbol, checker)); - function nonAliasCanBeReferencedAtTypeLocation(symbol2) { - return !!(symbol2.flags & 788968 /* Type */ ) || checker.isUnknownSymbol(symbol2) || !!(symbol2.flags & 1536 /* Module */ ) && addToSeen(seenModules, getSymbolId(symbol2)) && checker.getExportsOfModule(symbol2).some((e)=>symbolCanBeReferencedAtTypeLocation(e, checker, seenModules)); + function inferNamedTypesFromProperties(usage) { + if (!usage.properties || !usage.properties.size) return []; + const types = builtins.filter((t)=>allPropertiesAreAssignableToUsage(t, usage)); + if (0 < types.length && types.length < 3) return types.map((t)=>inferInstantiationFromUsage(t, usage)); + return []; } - } - function isDeprecated(symbol, checker) { - const declarations = skipAlias(symbol, checker).declarations; - return !!length(declarations) && every(declarations, isDeprecatedDeclaration); - } - function charactersFuzzyMatchInString(identifierString, lowercaseCharacters) { - if (lowercaseCharacters.length === 0) return true; - let matchedFirstCharacter = false; - let prevChar; - let characterIndex = 0; - const len = identifierString.length; - for(let strIndex = 0; strIndex < len; strIndex++){ - const strChar = identifierString.charCodeAt(strIndex); - const testChar = lowercaseCharacters.charCodeAt(characterIndex); - if (strChar === testChar || strChar === toUpperCharCode(testChar)) { - matchedFirstCharacter || (matchedFirstCharacter = prevChar === void 0 || // Beginning of word - 97 /* a */ <= prevChar && prevChar <= 122 /* z */ && 65 /* A */ <= strChar && strChar <= 90 /* Z */ || // camelCase transition - prevChar === 95 /* _ */ && strChar !== 95 /* _ */ ); - if (matchedFirstCharacter) characterIndex++; - if (characterIndex === lowercaseCharacters.length) return true; + function allPropertiesAreAssignableToUsage(type, usage) { + if (!usage.properties) return false; + return !forEachEntry(usage.properties, (propUsage, name)=>{ + const source = checker.getTypeOfPropertyOfType(type, name); + if (!source) return true; + if (propUsage.calls) { + const sigs = checker.getSignaturesOfType(source, 0 /* Call */ ); + return !sigs.length || !checker.isTypeAssignableTo(source, getFunctionFromCalls(propUsage.calls)); + } else return !checker.isTypeAssignableTo(source, combineFromUsage(propUsage)); + }); + } + function inferInstantiationFromUsage(type, usage) { + if (!(getObjectFlags(type) & 4 /* Reference */ ) || !usage.properties) return type; + const generic = type.target; + const singleTypeParameter = singleOrUndefined(generic.typeParameters); + if (!singleTypeParameter) return type; + const types = []; + usage.properties.forEach((propUsage, name)=>{ + const genericPropertyType = checker.getTypeOfPropertyOfType(generic, name); + Debug.assert(!!genericPropertyType, "generic should have all the properties of its reference."); + types.push(...inferTypeParameters(genericPropertyType, combineFromUsage(propUsage), singleTypeParameter)); + }); + return builtinConstructors[type.symbol.escapedName](combineTypes(types)); + } + function inferTypeParameters(genericType, usageType, typeParameter) { + if (genericType === typeParameter) return [ + usageType + ]; + else if (genericType.flags & 3145728 /* UnionOrIntersection */ ) return flatMap(genericType.types, (t)=>inferTypeParameters(t, usageType, typeParameter)); + else if (getObjectFlags(genericType) & 4 /* Reference */ && getObjectFlags(usageType) & 4 /* Reference */ ) { + const genericArgs = checker.getTypeArguments(genericType); + const usageArgs = checker.getTypeArguments(usageType); + const types = []; + if (genericArgs && usageArgs) { + for(let i = 0; i < genericArgs.length; i++)if (usageArgs[i]) types.push(...inferTypeParameters(genericArgs[i], usageArgs[i], typeParameter)); + } + return types; } - prevChar = strChar; + const genericSigs = checker.getSignaturesOfType(genericType, 0 /* Call */ ); + const usageSigs = checker.getSignaturesOfType(usageType, 0 /* Call */ ); + if (genericSigs.length === 1 && usageSigs.length === 1) return inferFromSignatures(genericSigs[0], usageSigs[0], typeParameter); + return []; + } + function inferFromSignatures(genericSig, usageSig, typeParameter) { + var _a; + const types = []; + for(let i = 0; i < genericSig.parameters.length; i++){ + const genericParam = genericSig.parameters[i]; + const usageParam = usageSig.parameters[i]; + const isRest = genericSig.declaration && isRestParameter(genericSig.declaration.parameters[i]); + if (!usageParam) break; + let genericParamType = genericParam.valueDeclaration ? checker.getTypeOfSymbolAtLocation(genericParam, genericParam.valueDeclaration) : checker.getAnyType(); + const elementType = isRest && checker.getElementTypeOfArrayType(genericParamType); + if (elementType) genericParamType = elementType; + const targetType = ((_a = tryCast(usageParam, isTransientSymbol)) == null ? void 0 : _a.links.type) || (usageParam.valueDeclaration ? checker.getTypeOfSymbolAtLocation(usageParam, usageParam.valueDeclaration) : checker.getAnyType()); + types.push(...inferTypeParameters(genericParamType, targetType, typeParameter)); + } + const genericReturn = checker.getReturnTypeOfSignature(genericSig); + const usageReturn = checker.getReturnTypeOfSignature(usageSig); + types.push(...inferTypeParameters(genericReturn, usageReturn, typeParameter)); + return types; + } + function getFunctionFromCalls(calls) { + return checker.createAnonymousType(/*symbol*/ void 0, createSymbolTable(), [ + getSignatureFromCalls(calls) + ], emptyArray, emptyArray); + } + function getSignatureFromCalls(calls) { + const parameters2 = []; + const length2 = Math.max(...calls.map((c)=>c.argumentTypes.length)); + for(let i = 0; i < length2; i++){ + const symbol = checker.createSymbol(1 /* FunctionScopedVariable */ , escapeLeadingUnderscores(`arg${i}`)); + symbol.links.type = combineTypes(calls.map((call)=>call.argumentTypes[i] || checker.getUndefinedType())); + if (calls.some((call)=>call.argumentTypes[i] === void 0)) symbol.flags |= 16777216 /* Optional */ ; + parameters2.push(symbol); + } + const returnType = combineFromUsage(combineUsages(calls.map((call)=>call.return_))); + return checker.createSignature(/*declaration*/ void 0, /*typeParameters*/ void 0, /*thisParameter*/ void 0, parameters2, returnType, /*typePredicate*/ void 0, length2, 0 /* None */ ); + } + function addCandidateType(usage, type) { + if (type && !(type.flags & 1 /* Any */ ) && !(type.flags & 131072 /* Never */ )) (usage.candidateTypes || (usage.candidateTypes = [])).push(type); + } + function addCandidateThisType(usage, type) { + if (type && !(type.flags & 1 /* Any */ ) && !(type.flags & 131072 /* Never */ )) (usage.candidateThisTypes || (usage.candidateThisTypes = [])).push(type); } - return false; - } - function toUpperCharCode(charCode) { - if (97 /* a */ <= charCode && charCode <= 122 /* z */ ) return charCode - 32; - return charCode; } - var moduleSpecifierResolutionLimit, moduleSpecifierResolutionCacheAttemptLimit, SortText, CompletionSource, SymbolOriginInfoKind, CompletionKind, _keywordCompletions, allKeywordsCompletions; - var init_completions = __esm({ - "src/services/completions.ts" () { + var fixId38, errorCodes48; + var init_inferFromUsage = __esm({ + "src/services/codefixes/inferFromUsage.ts" () { "use strict"; init_ts4(); - init_ts_Completions(); - moduleSpecifierResolutionLimit = 100; - moduleSpecifierResolutionCacheAttemptLimit = 1e3; - SortText = { - // Presets - LocalDeclarationPriority: "10", - LocationPriority: "11", - OptionalMember: "12", - MemberDeclaredBySpreadAssignment: "13", - SuggestedClassMembers: "14", - GlobalsOrKeywords: "15", - AutoImportSuggestions: "16", - ClassMemberSnippets: "17", - JavascriptIdentifiers: "18", - // Transformations - Deprecated (sortText) { - return "z" + sortText; - }, - ObjectLiteralProperty (presetSortText, symbolDisplayName) { - return `${presetSortText}\0${symbolDisplayName}\0`; + init_ts_codefix(); + fixId38 = "inferFromUsage"; + errorCodes48 = [ + // Variable declarations + Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + // Variable uses + Diagnostics.Variable_0_implicitly_has_an_1_type.code, + // Parameter declarations + Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + // Get Accessor declarations + Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + // Set Accessor declarations + Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + // Property declarations + Diagnostics.Member_0_implicitly_has_an_1_type.code, + //// Suggestions + // Variable declarations + Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code, + // Variable uses + Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + // Parameter declarations + Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code, + // Get Accessor declarations + Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code, + Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code, + // Set Accessor declarations + Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code, + // Property declarations + Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + // Function expressions and declarations + Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code + ]; + registerCodeFix({ + errorCodes: errorCodes48, + getCodeActions (context) { + const { sourceFile: sourceFile, program: program, span: { start: start }, errorCode: errorCode, cancellationToken: cancellationToken, host: host, preferences: preferences } = context; + const token = getTokenAtPosition(sourceFile, start); + let declaration; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2)=>{ + declaration = doChange32(changes2, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ returnTrue, host, preferences); + }); + const name = declaration && getNameOfDeclaration(declaration); + return !name || changes.length === 0 ? void 0 : [ + createCodeFixAction(fixId38, changes, [ + getDiagnostic(errorCode, token), + getTextOfNode(name) + ], fixId38, Diagnostics.Infer_all_types_from_usage) + ]; }, - SortBelow (sortText) { - return sortText + "1"; + fixIds: [ + fixId38 + ], + getAllCodeActions (context) { + const { sourceFile: sourceFile, program: program, cancellationToken: cancellationToken, host: host, preferences: preferences } = context; + const markSeen = nodeSeenTracker(); + return codeFixAll(context, errorCodes48, (changes, err)=>{ + doChange32(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, preferences); + }); } - }; - CompletionSource = /* @__PURE__ */ ((CompletionSource2)=>{ - CompletionSource2["ThisProperty"] = "ThisProperty/"; - CompletionSource2["ClassMemberSnippet"] = "ClassMemberSnippet/"; - CompletionSource2["TypeOnlyAlias"] = "TypeOnlyAlias/"; - CompletionSource2["ObjectLiteralMethodSnippet"] = "ObjectLiteralMethodSnippet/"; - CompletionSource2["SwitchCases"] = "SwitchCases/"; - return CompletionSource2; - })(CompletionSource || {}); - SymbolOriginInfoKind = /* @__PURE__ */ ((SymbolOriginInfoKind2)=>{ - SymbolOriginInfoKind2[SymbolOriginInfoKind2["ThisType"] = 1] = "ThisType"; - SymbolOriginInfoKind2[SymbolOriginInfoKind2["SymbolMember"] = 2] = "SymbolMember"; - SymbolOriginInfoKind2[SymbolOriginInfoKind2["Export"] = 4] = "Export"; - SymbolOriginInfoKind2[SymbolOriginInfoKind2["Promise"] = 8] = "Promise"; - SymbolOriginInfoKind2[SymbolOriginInfoKind2["Nullable"] = 16] = "Nullable"; - SymbolOriginInfoKind2[SymbolOriginInfoKind2["ResolvedExport"] = 32] = "ResolvedExport"; - SymbolOriginInfoKind2[SymbolOriginInfoKind2["TypeOnlyAlias"] = 64] = "TypeOnlyAlias"; - SymbolOriginInfoKind2[SymbolOriginInfoKind2["ObjectLiteralMethod"] = 128] = "ObjectLiteralMethod"; - SymbolOriginInfoKind2[SymbolOriginInfoKind2["Ignore"] = 256] = "Ignore"; - SymbolOriginInfoKind2[SymbolOriginInfoKind2["ComputedPropertyName"] = 512] = "ComputedPropertyName"; - SymbolOriginInfoKind2[SymbolOriginInfoKind2["SymbolMemberNoExport"] = 2 /* SymbolMember */ ] = "SymbolMemberNoExport"; - SymbolOriginInfoKind2[SymbolOriginInfoKind2["SymbolMemberExport"] = 6] = "SymbolMemberExport"; - return SymbolOriginInfoKind2; - })(SymbolOriginInfoKind || {}); - CompletionKind = /* @__PURE__ */ ((CompletionKind2)=>{ - CompletionKind2[CompletionKind2["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration"; - CompletionKind2[CompletionKind2["Global"] = 1] = "Global"; - CompletionKind2[CompletionKind2["PropertyAccess"] = 2] = "PropertyAccess"; - CompletionKind2[CompletionKind2["MemberLike"] = 3] = "MemberLike"; - CompletionKind2[CompletionKind2["String"] = 4] = "String"; - CompletionKind2[CompletionKind2["None"] = 5] = "None"; - return CompletionKind2; - })(CompletionKind || {}); - _keywordCompletions = []; - allKeywordsCompletions = memoize(()=>{ - const res = []; - for(let i = 81 /* FirstKeyword */ ; i <= 162 /* LastKeyword */ ; i++)res.push({ - name: tokenToString(i), - kind: "keyword" /* keyword */ , - kindModifiers: "" /* none */ , - sortText: SortText.GlobalsOrKeywords - }); - return res; }); } }); - // src/services/stringCompletions.ts - function createNameAndKindSet() { - const map2 = /* @__PURE__ */ new Map(); - function add(value1) { - const existing = map2.get(value1.name); - if (!existing || kindPrecedence[existing.kind] < kindPrecedence[value1.kind]) map2.set(value1.name, value1); - } - return { - add: add, - has: map2.has.bind(map2), - values: map2.values.bind(map2) + // src/services/codefixes/fixReturnTypeInAsyncFunction.ts + function getInfo15(sourceFile, checker, pos) { + if (isInJSFile(sourceFile)) return void 0; + const token = getTokenAtPosition(sourceFile, pos); + const func = findAncestor(token, isFunctionLikeDeclaration); + const returnTypeNode = func == null ? void 0 : func.type; + if (!returnTypeNode) return void 0; + const returnType = checker.getTypeFromTypeNode(returnTypeNode); + const promisedType = checker.getAwaitedType(returnType) || checker.getVoidType(); + const promisedTypeNode = checker.typeToTypeNode(promisedType, /*enclosingDeclaration*/ returnTypeNode, /*flags*/ void 0); + if (promisedTypeNode) return { + returnTypeNode: returnTypeNode, + returnType: returnType, + promisedTypeNode: promisedTypeNode, + promisedType: promisedType }; } - function getStringLiteralCompletions(sourceFile, position, contextToken, options, host, program, log, preferences, includeSymbol) { - if (isInReferenceComment(sourceFile, position)) { - const entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); - return entries && convertPathCompletions(entries); - } - if (isInString(sourceFile, position, contextToken)) { - if (!contextToken || !isStringLiteralLike(contextToken)) return void 0; - const entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, program.getTypeChecker(), options, host, preferences); - return convertStringLiteralCompletions(entries, contextToken, sourceFile, host, program, log, options, preferences, position, includeSymbol); - } + function doChange33(changes, sourceFile, returnTypeNode, promisedTypeNode) { + changes.replaceNode(sourceFile, returnTypeNode, factory.createTypeReferenceNode("Promise", [ + promisedTypeNode + ])); } - function convertStringLiteralCompletions(completion, contextToken, sourceFile, host, program, log, options, preferences, position, includeSymbol) { - if (completion === void 0) return void 0; - const optionalReplacementSpan = createTextSpanFromStringLiteralLikeContent(contextToken); - switch(completion.kind){ - case 0 /* Paths */ : - return convertPathCompletions(completion.paths); - case 1 /* Properties */ : - { - const entries = createSortedArray(); - getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, contextToken, sourceFile, position, sourceFile, host, program, 99 /* ESNext */ , log, 4 /* String */ , preferences, options, /*formatContext*/ void 0, /*isTypeOnlyLocation */ void 0, /*propertyAccessToConvert*/ void 0, /*jsxIdentifierExpected*/ void 0, /*isJsxInitializer*/ void 0, /*importStatementCompletion*/ void 0, /*recommendedCompletion*/ void 0, /*symbolToOriginInfoMap*/ void 0, /*symbolToSortTextMap*/ void 0, /*isJsxIdentifierExpected*/ void 0, /*isRightOfOpenTag*/ void 0, includeSymbol); - return { - isGlobalCompletion: false, - isMemberCompletion: true, - isNewIdentifierLocation: completion.hasIndexSignature, - optionalReplacementSpan: optionalReplacementSpan, - entries: entries - }; - } - case 2 /* Types */ : - { - const entries = completion.types.map((type)=>({ - name: type.value, - kindModifiers: "" /* none */ , - kind: "string" /* string */ , - sortText: SortText.LocationPriority, - replacementSpan: getReplacementSpanForContextToken(contextToken) - })); - return { - isGlobalCompletion: false, - isMemberCompletion: false, - isNewIdentifierLocation: completion.isNewIdentifier, - optionalReplacementSpan: optionalReplacementSpan, - entries: entries - }; - } - default: - return Debug.assertNever(completion); + var fixId39, errorCodes49; + var init_fixReturnTypeInAsyncFunction = __esm({ + "src/services/codefixes/fixReturnTypeInAsyncFunction.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId39 = "fixReturnTypeInAsyncFunction"; + errorCodes49 = [ + Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0.code + ]; + registerCodeFix({ + errorCodes: errorCodes49, + fixIds: [ + fixId39 + ], + getCodeActions: function getCodeActionsToFixReturnTypeInAsyncFunction(context) { + const { sourceFile: sourceFile, program: program, span: span } = context; + const checker = program.getTypeChecker(); + const info = getInfo15(sourceFile, program.getTypeChecker(), span.start); + if (!info) return void 0; + const { returnTypeNode: returnTypeNode, returnType: returnType, promisedTypeNode: promisedTypeNode, promisedType: promisedType } = info; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange33(t, sourceFile, returnTypeNode, promisedTypeNode)); + return [ + createCodeFixAction(fixId39, changes, [ + Diagnostics.Replace_0_with_Promise_1, + checker.typeToString(returnType), + checker.typeToString(promisedType) + ], fixId39, Diagnostics.Fix_all_incorrect_return_type_of_an_async_functions) + ]; + }, + getAllCodeActions: (context)=>codeFixAll(context, errorCodes49, (changes, diag2)=>{ + const info = getInfo15(diag2.file, context.program.getTypeChecker(), diag2.start); + if (info) doChange33(changes, diag2.file, info.returnTypeNode, info.promisedTypeNode); + }) + }); } + }); + // src/services/codefixes/disableJsDiagnostics.ts + function makeChange8(changes, sourceFile, position, seenLines) { + const { line: lineNumber } = getLineAndCharacterOfPosition(sourceFile, position); + if (!seenLines || tryAddToSet(seenLines, lineNumber)) changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore"); } - function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken, preferences) { - if (!contextToken || !isStringLiteralLike(contextToken)) return void 0; - const completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host, preferences); - return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken); - } - function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) { - switch(completion.kind){ - case 0 /* Paths */ : - { - const match = find(completion.paths, (p)=>p.name === name); - return match && createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [ - textPart(name) - ]); - } - case 1 /* Properties */ : - { - const match = find(completion.symbols, (s)=>s.name === name); - return match && createCompletionDetailsForSymbol(match, match.name, checker, sourceFile, location, cancellationToken); + var fixName4, fixId40, errorCodes50; + var init_disableJsDiagnostics = __esm({ + "src/services/codefixes/disableJsDiagnostics.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixName4 = "disableJsDiagnostics"; + fixId40 = "disableJsDiagnostics"; + errorCodes50 = mapDefined(Object.keys(Diagnostics), (key)=>{ + const diag2 = Diagnostics[key]; + return diag2.category === 1 /* Error */ ? diag2.code : void 0; + }); + registerCodeFix({ + errorCodes: errorCodes50, + getCodeActions: function getCodeActionsToDisableJsDiagnostics(context) { + const { sourceFile: sourceFile, program: program, span: span, host: host, formatContext: formatContext } = context; + if (!isInJSFile(sourceFile) || !isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) return void 0; + const newLineCharacter = sourceFile.checkJsDirective ? "" : getNewLineOrDefaultFromHost(host, formatContext.options); + const fixes = [ + // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. + createCodeFixActionWithoutFixAll(fixName4, [ + createFileTextChanges(sourceFile.fileName, [ + createTextChange(sourceFile.checkJsDirective ? createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) : createTextSpan(0, 0), `// @ts-nocheck${newLineCharacter}`) + ]) + ], Diagnostics.Disable_checking_for_this_file) + ]; + if (ts_textChanges_exports.isValidLocationToAddComment(sourceFile, span.start)) fixes.unshift(createCodeFixAction(fixName4, ts_textChanges_exports.ChangeTracker.with(context, (t)=>makeChange8(t, sourceFile, span.start)), Diagnostics.Ignore_this_error_message, fixId40, Diagnostics.Add_ts_ignore_to_all_error_messages)); + return fixes; + }, + fixIds: [ + fixId40 + ], + getAllCodeActions: (context)=>{ + const seenLines = /* @__PURE__ */ new Set(); + return codeFixAll(context, errorCodes50, (changes, diag2)=>{ + if (ts_textChanges_exports.isValidLocationToAddComment(diag2.file, diag2.start)) makeChange8(changes, diag2.file, diag2.start, seenLines); + }); } - case 2 /* Types */ : - return find(completion.types, (t)=>t.value === name) ? createCompletionDetails(name, "" /* none */ , "string" /* string */ , [ - textPart(name) - ]) : void 0; - default: - return Debug.assertNever(completion); + }); } + }); + // src/services/codefixes/helpers.ts + function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, sourceFile, context, preferences, importAdder, addClassElement) { + const classMembers = classDeclaration.symbol.members; + for (const symbol of possiblyMissingSymbols)if (!classMembers.has(symbol.escapedName)) addNewNodeForMemberSymbol(symbol, classDeclaration, sourceFile, context, preferences, importAdder, addClassElement, /*body*/ void 0); } - function convertPathCompletions(pathCompletions) { - const isGlobalCompletion = false; - const isNewIdentifierLocation = true; - const entries = pathCompletions.map(({ name: name , kind: kind , span: span , extension: extension })=>({ - name: name, - kind: kind, - kindModifiers: kindModifiersFromExtension(extension), - sortText: SortText.LocationPriority, - replacementSpan: span - })); + function getNoopSymbolTrackerWithResolver(context) { return { - isGlobalCompletion: isGlobalCompletion, - isMemberCompletion: false, - isNewIdentifierLocation: isNewIdentifierLocation, - entries: entries + trackSymbol: ()=>false, + moduleResolverHost: getModuleSpecifierResolverHost(context.program, context.host) }; } - function kindModifiersFromExtension(extension) { - switch(extension){ - case ".d.ts" /* Dts */ : - return ".d.ts" /* dtsModifier */ ; - case ".js" /* Js */ : - return ".js" /* jsModifier */ ; - case ".json" /* Json */ : - return ".json" /* jsonModifier */ ; - case ".jsx" /* Jsx */ : - return ".jsx" /* jsxModifier */ ; - case ".ts" /* Ts */ : - return ".ts" /* tsModifier */ ; - case ".tsx" /* Tsx */ : - return ".tsx" /* tsxModifier */ ; - case ".d.mts" /* Dmts */ : - return ".d.mts" /* dmtsModifier */ ; - case ".mjs" /* Mjs */ : - return ".mjs" /* mjsModifier */ ; - case ".mts" /* Mts */ : - return ".mts" /* mtsModifier */ ; - case ".d.cts" /* Dcts */ : - return ".d.cts" /* dctsModifier */ ; - case ".cjs" /* Cjs */ : - return ".cjs" /* cjsModifier */ ; - case ".cts" /* Cts */ : - return ".cts" /* ctsModifier */ ; - case ".tsbuildinfo" /* TsBuildInfo */ : - return Debug.fail(`Extension ${".tsbuildinfo" /* TsBuildInfo */ } is unsupported.`); - case void 0: - return "" /* none */ ; - default: - return Debug.assertNever(extension); - } - } - function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host, preferences) { - const parent2 = walkUpParentheses(node.parent); - switch(parent2.kind){ - case 198 /* LiteralType */ : - { - const grandParent = walkUpParentheses(parent2.parent); - switch(grandParent.kind){ - case 230 /* ExpressionWithTypeArguments */ : - case 180 /* TypeReference */ : - { - const typeArgument = findAncestor(parent2, (n)=>n.parent === grandParent); - if (typeArgument) return { - kind: 2 /* Types */ , - types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(typeArgument)), - isNewIdentifier: false - }; - return void 0; - } - case 196 /* IndexedAccessType */ : - const { indexType: indexType , objectType: objectType } = grandParent; - if (!rangeContainsPosition(indexType, position)) return void 0; - return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(objectType)); - case 202 /* ImportType */ : - return { - kind: 0 /* Paths */ , - paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) - }; - case 189 /* UnionType */ : - { - if (!isTypeReferenceNode(grandParent.parent)) return void 0; - const alreadyUsedTypes = getAlreadyUsedTypesInStringLiteralUnion(grandParent, parent2); - const types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(grandParent)).filter((t)=>!contains(alreadyUsedTypes, t.value)); - return { - kind: 2 /* Types */ , - types: types, - isNewIdentifier: false - }; - } - default: - return void 0; + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, context, preferences, importAdder, addClassElement, body, preserveOptional = 3 /* All */ , isAmbient = false) { + const declarations = symbol.getDeclarations(); + const declaration = firstOrUndefined(declarations); + const checker = context.program.getTypeChecker(); + const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions()); + const kind = (declaration == null ? void 0 : declaration.kind) ?? 171 /* PropertySignature */ ; + const declarationName = createDeclarationName(symbol, declaration); + const effectiveModifierFlags = declaration ? getEffectiveModifierFlags(declaration) : 0 /* None */ ; + let modifierFlags = effectiveModifierFlags & 32 /* Static */ ; + modifierFlags |= effectiveModifierFlags & 4 /* Public */ ? 4 /* Public */ : effectiveModifierFlags & 16 /* Protected */ ? 16 /* Protected */ : 0 /* None */ ; + if (declaration && isAutoAccessorPropertyDeclaration(declaration)) modifierFlags |= 128 /* Accessor */ ; + const modifiers = createModifiers(); + const type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); + const optional = !!(symbol.flags & 16777216 /* Optional */ ); + const ambient = !!(enclosingDeclaration.flags & 33554432 /* Ambient */ ) || isAmbient; + const quotePreference = getQuotePreference(sourceFile, preferences); + switch(kind){ + case 171 /* PropertySignature */ : + case 172 /* PropertyDeclaration */ : + const flags = quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : void 0; + let typeNode = checker.typeToTypeNode(type, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context)); + if (importAdder) { + const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget); + if (importableReference) { + typeNode = importableReference.typeNode; + importSymbols(importAdder, importableReference.symbols); } } - case 299 /* PropertyAssignment */ : - if (isObjectLiteralExpression(parent2.parent) && parent2.name === node) return stringLiteralCompletionsForObjectLiteral(typeChecker, parent2.parent); - return fromContextualType() || fromContextualType(0 /* None */ ); - case 209 /* ElementAccessExpression */ : + addClassElement(factory.createPropertyDeclaration(modifiers, declaration ? createName(declarationName) : symbol.getName(), optional && preserveOptional & 2 /* Property */ ? factory.createToken(58 /* QuestionToken */ ) : void 0, typeNode, /*initializer*/ void 0)); + break; + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : { - const { expression: expression , argumentExpression: argumentExpression } = parent2; - if (node === skipParentheses(argumentExpression)) return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); - return void 0; + Debug.assertIsDefined(declarations); + let typeNode2 = checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ void 0, getNoopSymbolTrackerWithResolver(context)); + const allAccessors = getAllAccessorDeclarations(declarations, declaration); + const orderedAccessors = allAccessors.secondAccessor ? [ + allAccessors.firstAccessor, + allAccessors.secondAccessor + ] : [ + allAccessors.firstAccessor + ]; + if (importAdder) { + const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode2, scriptTarget); + if (importableReference) { + typeNode2 = importableReference.typeNode; + importSymbols(importAdder, importableReference.symbols); + } + } + for (const accessor of orderedAccessors)if (isGetAccessorDeclaration(accessor)) addClassElement(factory.createGetAccessorDeclaration(modifiers, createName(declarationName), emptyArray, createTypeNode(typeNode2), createBody(body, quotePreference, ambient))); + else { + Debug.assertNode(accessor, isSetAccessorDeclaration, "The counterpart to a getter should be a setter"); + const parameter = getSetAccessorValueParameter(accessor); + const parameterName = parameter && isIdentifier(parameter.name) ? idText(parameter.name) : void 0; + addClassElement(factory.createSetAccessorDeclaration(modifiers, createName(declarationName), createDummyParameters(1, [ + parameterName + ], [ + createTypeNode(typeNode2) + ], 1, /*inJs*/ false), createBody(body, quotePreference, ambient))); + } + break; } - case 210 /* CallExpression */ : - case 211 /* NewExpression */ : - case 288 /* JsxAttribute */ : - if (!isRequireCallArgument(node) && !isImportCall(parent2)) { - const argumentInfo = ts_SignatureHelp_exports.getArgumentInfoForCompletions(parent2.kind === 288 /* JsxAttribute */ ? parent2.parent : node, position, sourceFile); - return argumentInfo && getStringLiteralCompletionsFromSignature(argumentInfo.invocation, node, argumentInfo, typeChecker) || fromContextualType(); + case 173 /* MethodSignature */ : + case 174 /* MethodDeclaration */ : + Debug.assertIsDefined(declarations); + const signatures = type.isUnion() ? flatMap(type.types, (t)=>t.getCallSignatures()) : type.getCallSignatures(); + if (!some(signatures)) break; + if (declarations.length === 1) { + Debug.assert(signatures.length === 1, "One declaration implies one signature"); + const signature = signatures[0]; + outputMethod(quotePreference, signature, modifiers, createName(declarationName), createBody(body, quotePreference, ambient)); + break; } - case 269 /* ImportDeclaration */ : - case 275 /* ExportDeclaration */ : - case 280 /* ExternalModuleReference */ : - return { - kind: 0 /* Paths */ , - paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) - }; - case 292 /* CaseClause */ : - const tracker = newCaseClauseTracker(typeChecker, parent2.parent.clauses); - const contextualTypes = fromContextualType(); - if (!contextualTypes) return; - const literals = contextualTypes.types.filter((literal)=>!tracker.hasValue(literal.value)); - return { - kind: 2 /* Types */ , - types: literals, - isNewIdentifier: false - }; - default: - return fromContextualType() || fromContextualType(0 /* None */ ); + for (const signature of signatures)outputMethod(quotePreference, signature, modifiers, createName(declarationName)); + if (!ambient) { + if (declarations.length > signatures.length) { + const signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]); + outputMethod(quotePreference, signature, modifiers, createName(declarationName), createBody(body, quotePreference)); + } else { + Debug.assert(declarations.length === signatures.length, "Declarations and signatures should match count"); + addClassElement(createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, createName(declarationName), optional && !!(preserveOptional & 1 /* Method */ ), modifiers, quotePreference, body)); + } + } + break; } - function fromContextualType(contextFlags = 4 /* Completions */ ) { - const types = getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker, contextFlags)); - if (!types.length) return; - return { - kind: 2 /* Types */ , - types: types, - isNewIdentifier: false - }; + function outputMethod(quotePreference2, signature, modifiers2, name, body2) { + const method = createSignatureDeclarationFromSignature(174 /* MethodDeclaration */ , context, quotePreference2, signature, body2, name, modifiers2, optional && !!(preserveOptional & 1 /* Method */ ), enclosingDeclaration, importAdder); + if (method) addClassElement(method); + } + function createModifiers() { + let modifiers2; + if (modifierFlags) modifiers2 = combine(modifiers2, factory.createModifiersFromModifierFlags(modifierFlags)); + if (shouldAddOverrideKeyword()) modifiers2 = append(modifiers2, factory.createToken(164 /* OverrideKeyword */ )); + return modifiers2 && factory.createNodeArray(modifiers2); + } + function shouldAddOverrideKeyword() { + return !!(context.program.getCompilerOptions().noImplicitOverride && declaration && hasAbstractModifier(declaration)); + } + function createName(node) { + if (isIdentifier(node) && node.escapedText === "constructor") return factory.createComputedPropertyName(factory.createStringLiteral(idText(node), quotePreference === 0 /* Single */ )); + return getSynthesizedDeepClone(node, /*includeTrivia*/ false); + } + function createBody(block, quotePreference2, ambient2) { + return ambient2 ? void 0 : getSynthesizedDeepClone(block, /*includeTrivia*/ false) || createStubbedMethodBody(quotePreference2); + } + function createTypeNode(typeNode) { + return getSynthesizedDeepClone(typeNode, /*includeTrivia*/ false); + } + function createDeclarationName(symbol2, declaration2) { + if (getCheckFlags(symbol2) & 262144 /* Mapped */ ) { + const nameType = symbol2.links.nameType; + if (nameType && isTypeUsableAsPropertyName(nameType)) return factory.createIdentifier(unescapeLeadingUnderscores(getPropertyNameFromType(nameType))); + } + return getSynthesizedDeepClone(getNameOfDeclaration(declaration2), /*includeTrivia*/ false); } } - function walkUpParentheses(node) { - switch(node.kind){ - case 193 /* ParenthesizedType */ : - return walkUpParenthesizedTypes(node); - case 214 /* ParenthesizedExpression */ : - return walkUpParenthesizedExpressions(node); - default: - return node; + function createSignatureDeclarationFromSignature(kind, context, quotePreference, signature, body, name, modifiers, optional, enclosingDeclaration, importAdder) { + const program = context.program; + const checker = program.getTypeChecker(); + const scriptTarget = getEmitScriptTarget(program.getCompilerOptions()); + const isJs = isInJSFile(enclosingDeclaration); + const flags = 524545 /* AllowEmptyTuple */ | (quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : 0 /* None */ ); + const signatureDeclaration = checker.signatureToSignatureDeclaration(signature, kind, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context)); + if (!signatureDeclaration) return void 0; + let typeParameters = isJs ? void 0 : signatureDeclaration.typeParameters; + let parameters = signatureDeclaration.parameters; + let type = isJs ? void 0 : signatureDeclaration.type; + if (importAdder) { + if (typeParameters) { + const newTypeParameters = sameMap(typeParameters, (typeParameterDecl)=>{ + let constraint = typeParameterDecl.constraint; + let defaultType = typeParameterDecl.default; + if (constraint) { + const importableReference = tryGetAutoImportableReferenceFromTypeNode(constraint, scriptTarget); + if (importableReference) { + constraint = importableReference.typeNode; + importSymbols(importAdder, importableReference.symbols); + } + } + if (defaultType) { + const importableReference = tryGetAutoImportableReferenceFromTypeNode(defaultType, scriptTarget); + if (importableReference) { + defaultType = importableReference.typeNode; + importSymbols(importAdder, importableReference.symbols); + } + } + return factory.updateTypeParameterDeclaration(typeParameterDecl, typeParameterDecl.modifiers, typeParameterDecl.name, constraint, defaultType); + }); + if (typeParameters !== newTypeParameters) typeParameters = setTextRange(factory.createNodeArray(newTypeParameters, typeParameters.hasTrailingComma), typeParameters); + } + const newParameters = sameMap(parameters, (parameterDecl)=>{ + let type2 = isJs ? void 0 : parameterDecl.type; + if (type2) { + const importableReference = tryGetAutoImportableReferenceFromTypeNode(type2, scriptTarget); + if (importableReference) { + type2 = importableReference.typeNode; + importSymbols(importAdder, importableReference.symbols); + } + } + return factory.updateParameterDeclaration(parameterDecl, parameterDecl.modifiers, parameterDecl.dotDotDotToken, parameterDecl.name, isJs ? void 0 : parameterDecl.questionToken, type2, parameterDecl.initializer); + }); + if (parameters !== newParameters) parameters = setTextRange(factory.createNodeArray(newParameters, parameters.hasTrailingComma), parameters); + if (type) { + const importableReference = tryGetAutoImportableReferenceFromTypeNode(type, scriptTarget); + if (importableReference) { + type = importableReference.typeNode; + importSymbols(importAdder, importableReference.symbols); + } + } } + const questionToken = optional ? factory.createToken(58 /* QuestionToken */ ) : void 0; + const asteriskToken = signatureDeclaration.asteriskToken; + if (isFunctionExpression(signatureDeclaration)) return factory.updateFunctionExpression(signatureDeclaration, modifiers, signatureDeclaration.asteriskToken, tryCast(name, isIdentifier), typeParameters, parameters, type, body ?? signatureDeclaration.body); + if (isArrowFunction(signatureDeclaration)) return factory.updateArrowFunction(signatureDeclaration, modifiers, typeParameters, parameters, type, signatureDeclaration.equalsGreaterThanToken, body ?? signatureDeclaration.body); + if (isMethodDeclaration(signatureDeclaration)) return factory.updateMethodDeclaration(signatureDeclaration, modifiers, asteriskToken, name ?? factory.createIdentifier(""), questionToken, typeParameters, parameters, type, body); + if (isFunctionDeclaration(signatureDeclaration)) return factory.updateFunctionDeclaration(signatureDeclaration, modifiers, signatureDeclaration.asteriskToken, tryCast(name, isIdentifier), typeParameters, parameters, type, body ?? signatureDeclaration.body); + return void 0; } - function getAlreadyUsedTypesInStringLiteralUnion(union, current) { - return mapDefined(union.types, (type)=>type !== current && isLiteralTypeNode(type) && isStringLiteral(type.literal) ? type.literal.text : void 0); + function createSignatureDeclarationFromCallExpression(kind, context, importAdder, call, name, modifierFlags, contextNode) { + const quotePreference = getQuotePreference(context.sourceFile, context.preferences); + const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions()); + const tracker = getNoopSymbolTrackerWithResolver(context); + const checker = context.program.getTypeChecker(); + const isJs = isInJSFile(contextNode); + const { typeArguments: typeArguments, arguments: args, parent: parent2 } = call; + const contextualType = isJs ? void 0 : checker.getContextualType(call); + const names = map(args, (arg)=>isIdentifier(arg) ? arg.text : isPropertyAccessExpression(arg) && isIdentifier(arg.name) ? arg.name.text : void 0); + const instanceTypes = isJs ? [] : map(args, (arg)=>checker.getTypeAtLocation(arg)); + const { argumentTypeNodes: argumentTypeNodes, argumentTypeParameters: argumentTypeParameters } = getArgumentTypesAndTypeParameters(checker, importAdder, instanceTypes, contextNode, scriptTarget, 1 /* NoTruncation */ , tracker); + const modifiers = modifierFlags ? factory.createNodeArray(factory.createModifiersFromModifierFlags(modifierFlags)) : void 0; + const asteriskToken = isYieldExpression(parent2) ? factory.createToken(42 /* AsteriskToken */ ) : void 0; + const typeParameters = isJs ? void 0 : createTypeParametersForArguments(checker, argumentTypeParameters, typeArguments); + const parameters = createDummyParameters(args.length, names, argumentTypeNodes, /*minArgumentCount*/ void 0, isJs); + const type = isJs || contextualType === void 0 ? void 0 : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ void 0, tracker); + switch(kind){ + case 174 /* MethodDeclaration */ : + return factory.createMethodDeclaration(modifiers, asteriskToken, name, /*questionToken*/ void 0, typeParameters, parameters, type, createStubbedMethodBody(quotePreference)); + case 173 /* MethodSignature */ : + return factory.createMethodSignature(modifiers, name, /*questionToken*/ void 0, typeParameters, parameters, type === void 0 ? factory.createKeywordTypeNode(159 /* UnknownKeyword */ ) : type); + case 262 /* FunctionDeclaration */ : + Debug.assert(typeof name === "string" || isIdentifier(name), "Unexpected name"); + return factory.createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, createStubbedBody(Diagnostics.Function_not_implemented.message, quotePreference)); + default: + Debug.fail("Unexpected kind"); + } } - function getStringLiteralCompletionsFromSignature(call, arg, argumentInfo, checker) { - let isNewIdentifier = false; - const uniques = /* @__PURE__ */ new Map(); - const candidates = []; - const editingArgument = isJsxOpeningLikeElement(call) ? Debug.checkDefined(findAncestor(arg.parent, isJsxAttribute)) : arg; - checker.getResolvedSignatureForStringLiteralCompletions(call, editingArgument, candidates); - const types = flatMap(candidates, (candidate)=>{ - if (!signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length) return; - let type = candidate.getTypeParameterAtPosition(argumentInfo.argumentIndex); - if (isJsxOpeningLikeElement(call)) { - const propType = checker.getTypeOfPropertyOfType(type, editingArgument.name.text); - if (propType) type = propType; - } - isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */ ); - return getStringLiteralTypes(type, uniques); + function createTypeParametersForArguments(checker, argumentTypeParameters, typeArguments) { + const usedNames = new Set(argumentTypeParameters.map((pair)=>pair[0])); + const constraintsByName = new Map(argumentTypeParameters); + if (typeArguments) { + const typeArgumentsWithNewTypes = typeArguments.filter((typeArgument)=>!argumentTypeParameters.some((pair)=>{ + var _a; + return checker.getTypeAtLocation(typeArgument) === ((_a = pair[1]) == null ? void 0 : _a.argumentType); + })); + const targetSize = usedNames.size + typeArgumentsWithNewTypes.length; + for(let i = 0; usedNames.size < targetSize; i += 1)usedNames.add(createTypeParameterName(i)); + } + return arrayFrom(usedNames.values(), (usedName)=>{ + var _a; + return factory.createTypeParameterDeclaration(/*modifiers*/ void 0, usedName, (_a = constraintsByName.get(usedName)) == null ? void 0 : _a.constraint); }); - return length(types) ? { - kind: 2 /* Types */ , - types: types, - isNewIdentifier: isNewIdentifier - } : void 0; } - function stringLiteralCompletionsFromProperties(type) { - return type && { - kind: 1 /* Properties */ , - symbols: filter(type.getApparentProperties(), (prop)=>!(prop.valueDeclaration && isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration))), - hasIndexSignature: hasIndexSignature(type) - }; + function createTypeParameterName(index) { + return 84 /* T */ + index <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + index) : `T${index}`; } - function stringLiteralCompletionsForObjectLiteral(checker, objectLiteralExpression) { - const contextualType = checker.getContextualType(objectLiteralExpression); - if (!contextualType) return void 0; - const completionsType = checker.getContextualType(objectLiteralExpression, 4 /* Completions */ ); - const symbols = getPropertiesForObjectExpression(contextualType, completionsType, objectLiteralExpression, checker); - return { - kind: 1 /* Properties */ , - symbols: symbols, - hasIndexSignature: hasIndexSignature(contextualType) - }; + function typeToAutoImportableTypeNode(checker, importAdder, type, contextNode, scriptTarget, flags, tracker) { + let typeNode = checker.typeToTypeNode(type, contextNode, flags, tracker); + if (typeNode && isImportTypeNode(typeNode)) { + const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget); + if (importableReference) { + importSymbols(importAdder, importableReference.symbols); + typeNode = importableReference.typeNode; + } + } + return getSynthesizedDeepClone(typeNode); } - function getStringLiteralTypes(type, uniques = /* @__PURE__ */ new Map()) { - if (!type) return emptyArray; - type = skipConstraint(type); - return type.isUnion() ? flatMap(type.types, (t)=>getStringLiteralTypes(t, uniques)) : type.isStringLiteral() && !(type.flags & 1024 /* EnumLiteral */ ) && addToSeen(uniques, type.value) ? [ - type - ] : emptyArray; + function typeContainsTypeParameter(type) { + if (type.isUnionOrIntersection()) return type.types.some(typeContainsTypeParameter); + return type.flags & 262144 /* TypeParameter */ ; } - function nameAndKind(name, kind, extension) { + function getArgumentTypesAndTypeParameters(checker, importAdder, instanceTypes, contextNode, scriptTarget, flags, tracker) { + const argumentTypeNodes = []; + const argumentTypeParameters = /* @__PURE__ */ new Map(); + for(let i = 0; i < instanceTypes.length; i += 1){ + const instanceType = instanceTypes[i]; + if (instanceType.isUnionOrIntersection() && instanceType.types.some(typeContainsTypeParameter)) { + const synthesizedTypeParameterName = createTypeParameterName(i); + argumentTypeNodes.push(factory.createTypeReferenceNode(synthesizedTypeParameterName)); + argumentTypeParameters.set(synthesizedTypeParameterName, void 0); + continue; + } + const widenedInstanceType = checker.getBaseTypeOfLiteralType(instanceType); + const argumentTypeNode = typeToAutoImportableTypeNode(checker, importAdder, widenedInstanceType, contextNode, scriptTarget, flags, tracker); + if (!argumentTypeNode) continue; + argumentTypeNodes.push(argumentTypeNode); + const argumentTypeParameter = getFirstTypeParameterName(instanceType); + const instanceTypeConstraint = instanceType.isTypeParameter() && instanceType.constraint && !isAnonymousObjectConstraintType(instanceType.constraint) ? typeToAutoImportableTypeNode(checker, importAdder, instanceType.constraint, contextNode, scriptTarget, flags, tracker) : void 0; + if (argumentTypeParameter) argumentTypeParameters.set(argumentTypeParameter, { + argumentType: instanceType, + constraint: instanceTypeConstraint + }); + } return { - name: name, - kind: kind, - extension: extension + argumentTypeNodes: argumentTypeNodes, + argumentTypeParameters: arrayFrom(argumentTypeParameters.entries()) }; } - function directoryResult(name) { - return nameAndKind(name, "directory" /* directory */ , /*extension*/ void 0); - } - function addReplacementSpans(text, textStart, names) { - const span = getDirectoryFragmentTextSpan(text, textStart); - const wholeSpan = text.length === 0 ? void 0 : createTextSpan(textStart, text.length); - return names.map(({ name: name , kind: kind , extension: extension })=>Math.max(name.indexOf(directorySeparator), name.indexOf(altDirectorySeparator)) !== -1 ? { - name: name, - kind: kind, - extension: extension, - span: wholeSpan - } : { - name: name, - kind: kind, - extension: extension, - span: span - }); + function isAnonymousObjectConstraintType(type) { + return type.flags & 524288 /* Object */ && type.objectFlags === 16 /* Anonymous */ ; } - function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) { - return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker, preferences)); + function getFirstTypeParameterName(type) { + var _a; + if (type.flags & 3145728 /* Intersection */ ) for (const subType of type.types){ + const subTypeName = getFirstTypeParameterName(subType); + if (subTypeName) return subTypeName; + } + return type.flags & 262144 /* TypeParameter */ ? (_a = type.getSymbol()) == null ? void 0 : _a.getName() : void 0; } - function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker, preferences) { - const literalValue = normalizeSlashes(node.text); - const mode = isStringLiteralLike(node) ? getModeForUsageLocation(sourceFile, node) : void 0; - const scriptPath = sourceFile.path; - const scriptDirectory = getDirectoryPath(scriptPath); - const extensionOptions = getExtensionOptions(compilerOptions, 1 /* ModuleSpecifier */ , sourceFile, typeChecker, preferences, mode); - return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (isRootedDiskPath(literalValue) || isUrl(literalValue)) ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, extensionOptions) : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, mode, compilerOptions, host, extensionOptions, typeChecker); + function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { + const parameters = []; + const parameterNameCounts = /* @__PURE__ */ new Map(); + for(let i = 0; i < argCount; i++){ + const parameterName = (names == null ? void 0 : names[i]) || `arg${i}`; + const parameterNameCount = parameterNameCounts.get(parameterName); + parameterNameCounts.set(parameterName, (parameterNameCount || 0) + 1); + const newParameter = factory.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, /*name*/ parameterName + (parameterNameCount || ""), /*questionToken*/ minArgumentCount !== void 0 && i >= minArgumentCount ? factory.createToken(58 /* QuestionToken */ ) : void 0, /*type*/ inJs ? void 0 : (types == null ? void 0 : types[i]) || factory.createKeywordTypeNode(159 /* UnknownKeyword */ ), /*initializer*/ void 0); + parameters.push(newParameter); + } + return parameters; } - function getExtensionOptions(compilerOptions, referenceKind, importingSourceFile, typeChecker, preferences, resolutionMode) { - return { - extensionsToSearch: flatten(getSupportedExtensionsForModuleResolution(compilerOptions, typeChecker)), - referenceKind: referenceKind, - importingSourceFile: importingSourceFile, - endingPreference: preferences == null ? void 0 : preferences.importModuleSpecifierEnding, - resolutionMode: resolutionMode - }; + function createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference, body) { + let maxArgsSignature = signatures[0]; + let minArgumentCount = signatures[0].minArgumentCount; + let someSigHasRestParameter = false; + for (const sig of signatures){ + minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); + if (signatureHasRestParameter(sig)) someSigHasRestParameter = true; + if (sig.parameters.length >= maxArgsSignature.parameters.length && (!signatureHasRestParameter(sig) || signatureHasRestParameter(maxArgsSignature))) maxArgsSignature = sig; + } + const maxNonRestArgs = maxArgsSignature.parameters.length - (signatureHasRestParameter(maxArgsSignature) ? 1 : 0); + const maxArgsParameterSymbolNames = maxArgsSignature.parameters.map((symbol)=>symbol.name); + const parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /*types*/ void 0, minArgumentCount, /*inJs*/ false); + if (someSigHasRestParameter) { + const restParameter = factory.createParameterDeclaration(/*modifiers*/ void 0, factory.createToken(26 /* DotDotDotToken */ ), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", /*questionToken*/ maxNonRestArgs >= minArgumentCount ? factory.createToken(58 /* QuestionToken */ ) : void 0, factory.createArrayTypeNode(factory.createKeywordTypeNode(159 /* UnknownKeyword */ )), /*initializer*/ void 0); + parameters.push(restParameter); + } + return createStubbedMethod(modifiers, name, optional, /*typeParameters*/ void 0, parameters, getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration), quotePreference, body); } - function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, extensionOptions) { - if (compilerOptions.rootDirs) return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); - else return arrayFrom(getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, /*moduleSpecifierIsRelative*/ false, scriptPath).values()); + function getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration) { + if (length(signatures)) { + const type = checker.getUnionType(map(signatures, checker.getReturnTypeOfSignature)); + return checker.typeToTypeNode(type, enclosingDeclaration, 1 /* NoTruncation */ , getNoopSymbolTrackerWithResolver(context)); + } } - function getSupportedExtensionsForModuleResolution(compilerOptions, typeChecker) { - const ambientModulesExtensions = !typeChecker ? [] : mapDefined(typeChecker.getAmbientModules(), (module2)=>{ - const name = module2.name.slice(1, -1); - if (!name.startsWith("*.") || name.includes("/")) return; - return name.slice(1); - }); - const extensions = [ - ...getSupportedExtensions(compilerOptions), - ambientModulesExtensions - ]; - const moduleResolution = getEmitModuleResolutionKind(compilerOptions); - return moduleResolutionUsesNodeModules(moduleResolution) ? getSupportedExtensionsWithJsonIfResolveJsonModule(compilerOptions, extensions) : extensions; + function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference, body) { + return factory.createMethodDeclaration(modifiers, /*asteriskToken*/ void 0, name, optional ? factory.createToken(58 /* QuestionToken */ ) : void 0, typeParameters, parameters, returnType, body || createStubbedMethodBody(quotePreference)); } - function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase) { - rootDirs = rootDirs.map((rootDirectory)=>normalizePath(isRootedDiskPath(rootDirectory) ? rootDirectory : combinePaths(basePath, rootDirectory))); - const relativeDirectory = firstDefined(rootDirs, (rootDirectory)=>containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : void 0); - return deduplicate([ - ...rootDirs.map((rootDirectory)=>combinePaths(rootDirectory, relativeDirectory)), - scriptDirectory - ], equateStringsCaseSensitive, compareStringsCaseSensitive); + function createStubbedMethodBody(quotePreference) { + return createStubbedBody(Diagnostics.Method_not_implemented.message, quotePreference); } - function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, compilerOptions, host, exclude) { - const basePath = compilerOptions.project || host.getCurrentDirectory(); - const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); - const baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase); - return flatMap(baseDirectories, (baseDirectory)=>arrayFrom(getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, /*moduleSpecifierIsRelative*/ true, exclude).values())); + function createStubbedBody(text, quotePreference) { + return factory.createBlock([ + factory.createThrowStatement(factory.createNewExpression(factory.createIdentifier("Error"), /*typeArguments*/ void 0, // TODO Handle auto quote preference. + [ + factory.createStringLiteral(text, /*isSingleQuote*/ quotePreference === 0 /* Single */ ) + ])) + ], /*multiLine*/ true); } - function getCompletionEntriesForDirectoryFragment(fragment, scriptDirectory, extensionOptions, host, moduleSpecifierIsRelative, exclude, result = createNameAndKindSet()) { - var _a2; - if (fragment === void 0) fragment = ""; - fragment = normalizeSlashes(fragment); - if (!hasTrailingDirectorySeparator(fragment)) fragment = getDirectoryPath(fragment); - if (fragment === "") fragment = "." + directorySeparator; - fragment = ensureTrailingDirectorySeparator(fragment); - const absolutePath = resolvePath(scriptDirectory, fragment); - const baseDirectory = hasTrailingDirectorySeparator(absolutePath) ? absolutePath : getDirectoryPath(absolutePath); - if (!moduleSpecifierIsRelative) { - const packageJsonPath = findPackageJson(baseDirectory, host); - if (packageJsonPath) { - const packageJson = readJson(packageJsonPath, host); - const typesVersions = packageJson.typesVersions; - if (typeof typesVersions === "object") { - const versionPaths = (_a2 = getPackageJsonTypesVersionsPaths(typesVersions)) == null ? void 0 : _a2.paths; - if (versionPaths) { - const packageDirectory = getDirectoryPath(packageJsonPath); - const pathInPackage = absolutePath.slice(ensureTrailingDirectorySeparator(packageDirectory).length); - if (addCompletionEntriesFromPaths(result, pathInPackage, packageDirectory, extensionOptions, host, versionPaths)) return result; - } - } - } - } - const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); - if (!tryDirectoryExists(host, baseDirectory)) return result; - const files = tryReadDirectory(host, baseDirectory, extensionOptions.extensionsToSearch, /*exclude*/ void 0, /*include*/ [ - "./*" - ]); - if (files) for (let filePath of files){ - filePath = normalizePath(filePath); - if (exclude && comparePaths(filePath, exclude, scriptDirectory, ignoreCase) === 0 /* EqualTo */ ) continue; - const { name: name , extension: extension } = getFilenameWithExtensionOption(getBaseFileName(filePath), host.getCompilationSettings(), extensionOptions); - result.add(nameAndKind(name, "script" /* scriptElement */ , extension)); + function setJsonCompilerOptionValues(changeTracker, configFile, options) { + const tsconfigObjectLiteral = getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) return void 0; + const compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions"); + if (compilerOptionsProperty === void 0) { + changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", factory.createObjectLiteralExpression(options.map(([optionName, optionValue])=>createJsonPropertyAssignment(optionName, optionValue)), /*multiLine*/ true))); + return; } - const directories = tryGetDirectories(host, baseDirectory); - if (directories) for (const directory of directories){ - const directoryName = getBaseFileName(normalizePath(directory)); - if (directoryName !== "@types") result.add(directoryResult(directoryName)); + const compilerOptions = compilerOptionsProperty.initializer; + if (!isObjectLiteralExpression(compilerOptions)) return; + for (const [optionName, optionValue] of options){ + const optionProperty = findJsonProperty(compilerOptions, optionName); + if (optionProperty === void 0) changeTracker.insertNodeAtObjectStart(configFile, compilerOptions, createJsonPropertyAssignment(optionName, optionValue)); + else changeTracker.replaceNode(configFile, optionProperty.initializer, optionValue); } - return result; } - function getFilenameWithExtensionOption(name, compilerOptions, extensionOptions) { - const nonJsResult = ts_moduleSpecifiers_exports.tryGetRealFileNameForNonJsDeclarationFileName(name); - if (nonJsResult) return { - name: nonJsResult, - extension: tryGetExtensionFromPath2(nonJsResult) - }; - if (extensionOptions.referenceKind === 0 /* Filename */ ) return { - name: name, - extension: tryGetExtensionFromPath2(name) - }; - const endingPreference = getModuleSpecifierEndingPreference(extensionOptions.endingPreference, extensionOptions.resolutionMode, compilerOptions, extensionOptions.importingSourceFile); - if (endingPreference === 3 /* TsExtension */ ) { - if (fileExtensionIsOneOf(name, supportedTSImplementationExtensions)) return { - name: name, - extension: tryGetExtensionFromPath2(name) - }; - const outputExtension2 = ts_moduleSpecifiers_exports.tryGetJSExtensionForFile(name, compilerOptions); - return outputExtension2 ? { - name: changeExtension(name, outputExtension2), - extension: outputExtension2 - } : { - name: name, - extension: tryGetExtensionFromPath2(name) - }; - } - if ((endingPreference === 0 /* Minimal */ || endingPreference === 1 /* Index */ ) && fileExtensionIsOneOf(name, [ - ".js" /* Js */ , - ".jsx" /* Jsx */ , - ".ts" /* Ts */ , - ".tsx" /* Tsx */ , - ".d.ts" /* Dts */ - ])) return { - name: removeFileExtension(name), - extension: tryGetExtensionFromPath2(name) - }; - const outputExtension = ts_moduleSpecifiers_exports.tryGetJSExtensionForFile(name, compilerOptions); - return outputExtension ? { - name: changeExtension(name, outputExtension), - extension: outputExtension - } : { - name: name, - extension: tryGetExtensionFromPath2(name) - }; + function setJsonCompilerOptionValue(changeTracker, configFile, optionName, optionValue) { + setJsonCompilerOptionValues(changeTracker, configFile, [ + [ + optionName, + optionValue + ] + ]); } - function addCompletionEntriesFromPaths(result, fragment, baseDirectory, extensionOptions, host, paths) { - const getPatternsForKey = (key)=>paths[key]; - const comparePaths2 = (a, b)=>{ - const patternA = tryParsePattern(a); - const patternB = tryParsePattern(b); - const lengthA = typeof patternA === "object" ? patternA.prefix.length : a.length; - const lengthB = typeof patternB === "object" ? patternB.prefix.length : b.length; - return compareValues(lengthB, lengthA); - }; - return addCompletionEntriesFromPathsOrExports(result, fragment, baseDirectory, extensionOptions, host, getOwnKeys(paths), getPatternsForKey, comparePaths2); + function createJsonPropertyAssignment(name, initializer) { + return factory.createPropertyAssignment(factory.createStringLiteral(name), initializer); } - function addCompletionEntriesFromPathsOrExports(result, fragment, baseDirectory, extensionOptions, host, keys, getPatternsForKey, comparePaths2) { - let pathResults = []; - let matchedPath; - for (const key of keys){ - if (key === ".") continue; - const keyWithoutLeadingDotSlash = key.replace(/^\.\//, ""); - const patterns = getPatternsForKey(key); - if (patterns) { - const pathPattern = tryParsePattern(keyWithoutLeadingDotSlash); - if (!pathPattern) continue; - const isMatch = typeof pathPattern === "object" && isPatternMatch(pathPattern, fragment); - const isLongestMatch = isMatch && (matchedPath === void 0 || comparePaths2(key, matchedPath) === -1 /* LessThan */ ); - if (isLongestMatch) { - matchedPath = key; - pathResults = pathResults.filter((r)=>!r.matchedPattern); - } - if (typeof pathPattern === "string" || matchedPath === void 0 || comparePaths2(key, matchedPath) !== 1 /* GreaterThan */ ) pathResults.push({ - matchedPattern: isMatch, - results: getCompletionsForPathMapping(keyWithoutLeadingDotSlash, patterns, fragment, baseDirectory, extensionOptions, host).map(({ name: name , kind: kind , extension: extension })=>nameAndKind(name, kind, extension)) - }); + function findJsonProperty(obj, name) { + return find(obj.properties, (p)=>isPropertyAssignment(p) && !!p.name && isStringLiteral(p.name) && p.name.text === name); + } + function tryGetAutoImportableReferenceFromTypeNode(importTypeNode, scriptTarget) { + let symbols; + const typeNode = visitNode(importTypeNode, visit, isTypeNode); + if (symbols && typeNode) return { + typeNode: typeNode, + symbols: symbols + }; + function visit(node) { + if (isLiteralImportTypeNode(node) && node.qualifier) { + const firstIdentifier = getFirstIdentifier(node.qualifier); + const name = getNameForExportedSymbol(firstIdentifier.symbol, scriptTarget); + const qualifier = name !== firstIdentifier.text ? replaceFirstIdentifierOfEntityName(node.qualifier, factory.createIdentifier(name)) : node.qualifier; + symbols = append(symbols, firstIdentifier.symbol); + const typeArguments = visitNodes2(node.typeArguments, visit, isTypeNode); + return factory.createTypeReferenceNode(qualifier, typeArguments); } + return visitEachChild(node, visit, nullTransformationContext); } - pathResults.forEach((pathResult)=>pathResult.results.forEach((r)=>result.add(r))); - return matchedPath !== void 0; } - function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, compilerOptions, host, extensionOptions, typeChecker) { - const { baseUrl: baseUrl , paths: paths } = compilerOptions; - const result = createNameAndKindSet(); - const moduleResolution = getEmitModuleResolutionKind(compilerOptions); - if (baseUrl) { - const projectDir = compilerOptions.project || host.getCurrentDirectory(); - const absolute = normalizePath(combinePaths(projectDir, baseUrl)); - getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, host, /*moduleSpecifierIsRelative*/ false, /*exclude*/ void 0, result); - if (paths) addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions, host, paths); + function replaceFirstIdentifierOfEntityName(name, newIdentifier) { + if (name.kind === 80 /* Identifier */ ) return newIdentifier; + return factory.createQualifiedName(replaceFirstIdentifierOfEntityName(name.left, newIdentifier), name.right); + } + function importSymbols(importAdder, symbols) { + symbols.forEach((s)=>importAdder.addImportFromExportedSymbol(s, /*isValidTypeOnlyUseSite*/ true)); + } + function findAncestorMatchingSpan(sourceFile, span) { + const end = textSpanEnd(span); + let token = getTokenAtPosition(sourceFile, span.start); + while(token.end < end)token = token.parent; + return token; + } + var PreserveOptionalFlags; + var init_helpers2 = __esm({ + "src/services/codefixes/helpers.ts" () { + "use strict"; + init_ts4(); + PreserveOptionalFlags = /* @__PURE__ */ ((PreserveOptionalFlags2)=>{ + PreserveOptionalFlags2[PreserveOptionalFlags2["Method"] = 1] = "Method"; + PreserveOptionalFlags2[PreserveOptionalFlags2["Property"] = 2] = "Property"; + PreserveOptionalFlags2[PreserveOptionalFlags2["All"] = 3] = "All"; + return PreserveOptionalFlags2; + })(PreserveOptionalFlags || {}); } - const fragmentDirectory = getFragmentDirectory(fragment); - for (const ambientName of getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker))result.add(nameAndKind(ambientName, "external module name" /* externalModuleName */ , /*extension*/ void 0)); - getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result); - if (moduleResolutionUsesNodeModules(moduleResolution)) { - let foundGlobal = false; - if (fragmentDirectory === void 0) for (const moduleName of enumerateNodeModulesVisibleToScript(host, scriptPath)){ - const moduleResult = nameAndKind(moduleName, "external module name" /* externalModuleName */ , /*extension*/ void 0); - if (!result.has(moduleResult.name)) { - foundGlobal = true; - result.add(moduleResult); - } - } - if (!foundGlobal) { - let ancestorLookup = (ancestor)=>{ - const nodeModules = combinePaths(ancestor, "node_modules"); - if (tryDirectoryExists(host, nodeModules)) getCompletionEntriesForDirectoryFragment(fragment, nodeModules, extensionOptions, host, /*moduleSpecifierIsRelative*/ false, /*exclude*/ void 0, result); - }; - if (fragmentDirectory && getResolvePackageJsonExports(compilerOptions)) { - const nodeModulesDirectoryLookup = ancestorLookup; - ancestorLookup = (ancestor)=>{ - const components = getPathComponents(fragment); - components.shift(); - let packagePath = components.shift(); - if (!packagePath) return nodeModulesDirectoryLookup(ancestor); - if (startsWith(packagePath, "@")) { - const subName = components.shift(); - if (!subName) return nodeModulesDirectoryLookup(ancestor); - packagePath = combinePaths(packagePath, subName); - } - const packageDirectory = combinePaths(ancestor, "node_modules", packagePath); - const packageFile = combinePaths(packageDirectory, "package.json"); - if (tryFileExists(host, packageFile)) { - const packageJson = readJson(packageFile, host); - const exports = packageJson.exports; - if (exports) { - if (typeof exports !== "object" || exports === null) return; - const keys = getOwnKeys(exports); - const fragmentSubpath = components.join("/") + (components.length && hasTrailingDirectorySeparator(fragment) ? "/" : ""); - const conditions = mode === 99 /* ESNext */ ? [ - "node", - "import", - "types" - ] : [ - "node", - "require", - "types" - ]; - addCompletionEntriesFromPathsOrExports(result, fragmentSubpath, packageDirectory, extensionOptions, host, keys, (key)=>singleElementArray(getPatternFromFirstMatchingCondition(exports[key], conditions)), comparePatternKeys); - return; - } - } - return nodeModulesDirectoryLookup(ancestor); - }; - } - forEachAncestorDirectory(scriptPath, ancestorLookup); + }); + // src/services/codefixes/generateAccessors.ts + function generateAccessorFromProperty(file, program, start, end, context, _actionName) { + const fieldInfo = getAccessorConvertiblePropertyAtPosition(file, program, start, end); + if (!fieldInfo || ts_refactor_exports.isRefactorErrorInfo(fieldInfo)) return void 0; + const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context); + const { isStatic: isStatic2, isReadonly: isReadonly, fieldName: fieldName, accessorName: accessorName, originalName: originalName, type: type, container: container, declaration: declaration } = fieldInfo; + suppressLeadingAndTrailingTrivia(fieldName); + suppressLeadingAndTrailingTrivia(accessorName); + suppressLeadingAndTrailingTrivia(declaration); + suppressLeadingAndTrailingTrivia(container); + let accessorModifiers; + let fieldModifiers; + if (isClassLike(container)) { + const modifierFlags = getEffectiveModifierFlags(declaration); + if (isSourceFileJS(file)) { + const modifiers = factory.createModifiersFromModifierFlags(modifierFlags); + accessorModifiers = modifiers; + fieldModifiers = modifiers; + } else { + accessorModifiers = factory.createModifiersFromModifierFlags(prepareModifierFlagsForAccessor(modifierFlags)); + fieldModifiers = factory.createModifiersFromModifierFlags(prepareModifierFlagsForField(modifierFlags)); } + if (canHaveDecorators(declaration)) fieldModifiers = concatenate(getDecorators(declaration), fieldModifiers); } - return arrayFrom(result.values()); - } - function getPatternFromFirstMatchingCondition(target, conditions) { - if (typeof target === "string") return target; - if (target && typeof target === "object" && !isArray(target)) { - for(const condition in target)if (condition === "default" || conditions.indexOf(condition) > -1 || isApplicableVersionedTypesKey(conditions, condition)) { - const pattern = target[condition]; - return getPatternFromFirstMatchingCondition(pattern, conditions); - } + updateFieldDeclaration(changeTracker, file, declaration, type, fieldName, fieldModifiers); + const getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic2, container); + suppressLeadingAndTrailingTrivia(getAccessor); + insertAccessor(changeTracker, file, getAccessor, declaration, container); + if (isReadonly) { + const constructor = getFirstConstructorWithBody(container); + if (constructor) updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName.text, originalName); + } else { + const setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic2, container); + suppressLeadingAndTrailingTrivia(setAccessor); + insertAccessor(changeTracker, file, setAccessor, declaration, container); } + return changeTracker.getChanges(); } - function getFragmentDirectory(fragment) { - return containsSlash(fragment) ? hasTrailingDirectorySeparator(fragment) ? fragment : getDirectoryPath(fragment) : void 0; + function isConvertibleName(name) { + return isIdentifier(name) || isStringLiteral(name); } - function getCompletionsForPathMapping(path, patterns, fragment, packageDirectory, extensionOptions, host) { - if (!endsWith(path, "*")) return !stringContains(path, "*") ? justPathMappingName(path, "script" /* scriptElement */ ) : emptyArray; - const pathPrefix = path.slice(0, path.length - 1); - const remainingFragment = tryRemovePrefix(fragment, pathPrefix); - if (remainingFragment === void 0) { - const starIsFullPathComponent = path[path.length - 2] === "/"; - return starIsFullPathComponent ? justPathMappingName(pathPrefix, "directory" /* directory */ ) : flatMap(patterns, (pattern)=>{ - var _a2; - return (_a2 = getModulesForPathsPattern("", packageDirectory, pattern, extensionOptions, host)) == null ? void 0 : _a2.map(({ name: name , ...rest })=>({ - name: pathPrefix + name, - ...rest - })); - }); - } - return flatMap(patterns, (pattern)=>getModulesForPathsPattern(remainingFragment, packageDirectory, pattern, extensionOptions, host)); - function justPathMappingName(name, kind) { - return startsWith(name, fragment) ? [ - { - name: removeTrailingDirectorySeparator(name), - kind: kind, - extension: void 0 - } - ] : emptyArray; - } + function isAcceptedDeclaration(node) { + return isParameterPropertyDeclaration(node, node.parent) || isPropertyDeclaration(node) || isPropertyAssignment(node); } - function getModulesForPathsPattern(fragment, packageDirectory, pattern, extensionOptions, host) { - if (!host.readDirectory) return void 0; - const parsed = tryParsePattern(pattern); - if (parsed === void 0 || isString(parsed)) return void 0; - const normalizedPrefix = resolvePath(parsed.prefix); - const normalizedPrefixDirectory = hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : getDirectoryPath(normalizedPrefix); - const normalizedPrefixBase = hasTrailingDirectorySeparator(parsed.prefix) ? "" : getBaseFileName(normalizedPrefix); - const fragmentHasPath = containsSlash(fragment); - const fragmentDirectory = fragmentHasPath ? hasTrailingDirectorySeparator(fragment) ? fragment : getDirectoryPath(fragment) : void 0; - const expandedPrefixDirectory = fragmentHasPath ? combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; - const normalizedSuffix = normalizePath(parsed.suffix); - const baseDirectory = normalizePath(combinePaths(packageDirectory, expandedPrefixDirectory)); - const completePrefix = fragmentHasPath ? baseDirectory : ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; - const includeGlob = normalizedSuffix ? "**/*" + normalizedSuffix : "./*"; - const matches = mapDefined(tryReadDirectory(host, baseDirectory, extensionOptions.extensionsToSearch, /*exclude*/ void 0, [ - includeGlob - ]), (match)=>{ - const trimmedWithPattern = trimPrefixAndSuffix(match); - if (trimmedWithPattern) { - if (containsSlash(trimmedWithPattern)) return directoryResult(getPathComponents(removeLeadingDirectorySeparator(trimmedWithPattern))[1]); - const { name: name , extension: extension } = getFilenameWithExtensionOption(trimmedWithPattern, host.getCompilationSettings(), extensionOptions); - return nameAndKind(name, "script" /* scriptElement */ , extension); - } - }); - const directories = normalizedSuffix ? emptyArray : mapDefined(tryGetDirectories(host, baseDirectory), (dir)=>dir === "node_modules" ? void 0 : directoryResult(dir)); - return [ - ...matches, - ...directories - ]; - function trimPrefixAndSuffix(path) { - const inner = withoutStartAndEnd(normalizePath(path), completePrefix, normalizedSuffix); - return inner === void 0 ? void 0 : removeLeadingDirectorySeparator(inner); - } + function createPropertyName(name, originalName) { + return isIdentifier(originalName) ? factory.createIdentifier(name) : factory.createStringLiteral(name); } - function withoutStartAndEnd(s, start, end) { - return startsWith(s, start) && endsWith(s, end) ? s.slice(start.length, s.length - end.length) : void 0; + function createAccessorAccessExpression(fieldName, isStatic2, container) { + const leftHead = isStatic2 ? container.name : factory.createThis(); + return isIdentifier(fieldName) ? factory.createPropertyAccessExpression(leftHead, fieldName) : factory.createElementAccessExpression(leftHead, factory.createStringLiteralFromNode(fieldName)); } - function removeLeadingDirectorySeparator(path) { - return path[0] === directorySeparator ? path.slice(1) : path; + function prepareModifierFlagsForAccessor(modifierFlags) { + modifierFlags &= -65 /* Readonly */ ; + modifierFlags &= -9 /* Private */ ; + if (!(modifierFlags & 16 /* Protected */ )) modifierFlags |= 4 /* Public */ ; + return modifierFlags; } - function getAmbientModuleCompletions(fragment, fragmentDirectory, checker) { - const ambientModules = checker.getAmbientModules().map((sym)=>stripQuotes(sym.name)); - const nonRelativeModuleNames = ambientModules.filter((moduleName)=>startsWith(moduleName, fragment) && moduleName.indexOf("*") < 0); - if (fragmentDirectory !== void 0) { - const moduleNameWithSeparator = ensureTrailingDirectorySeparator(fragmentDirectory); - return nonRelativeModuleNames.map((nonRelativeModuleName)=>removePrefix(nonRelativeModuleName, moduleNameWithSeparator)); - } - return nonRelativeModuleNames; + function prepareModifierFlagsForField(modifierFlags) { + modifierFlags &= -5 /* Public */ ; + modifierFlags &= -17 /* Protected */ ; + modifierFlags |= 8 /* Private */ ; + return modifierFlags; } - function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { - const token = getTokenAtPosition(sourceFile, position); - const commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos); - const range = commentRanges && find(commentRanges, (commentRange)=>position >= commentRange.pos && position <= commentRange.end); - if (!range) return void 0; - const text = sourceFile.text.slice(range.pos, position); - const match = tripleSlashDirectiveFragmentRegex.exec(text); - if (!match) return void 0; - const [, prefix, kind, toComplete] = match; - const scriptPath = getDirectoryPath(sourceFile.path); - const names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getExtensionOptions(compilerOptions, 0 /* Filename */ , sourceFile), host, /*moduleSpecifierIsRelative*/ true, sourceFile.path) : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions, 1 /* ModuleSpecifier */ , sourceFile)) : Debug.fail(); - return addReplacementSpans(toComplete, range.pos + prefix.length, arrayFrom(names.values())); + function getAccessorConvertiblePropertyAtPosition(file, program, start, end, considerEmptySpans = true) { + const node = getTokenAtPosition(file, start); + const cursorRequest = start === end && considerEmptySpans; + const declaration = findAncestor(node.parent, isAcceptedDeclaration); + const meaning = 124 /* Readonly */ ; + if (!declaration || !(nodeOverlapsWithStartEnd(declaration.name, file, start, end) || cursorRequest)) return { + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_property_for_which_to_generate_accessor) + }; + if (!isConvertibleName(declaration.name)) return { + error: getLocaleSpecificMessage(Diagnostics.Name_is_not_valid) + }; + if ((getEffectiveModifierFlags(declaration) & 126975 /* Modifier */ | meaning) !== meaning) return { + error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_property_with_modifier) + }; + const name = declaration.name.text; + const startWithUnderscore = startsWithUnderscore(name); + const fieldName = createPropertyName(startWithUnderscore ? name : getUniqueName(`_${name}`, file), declaration.name); + const accessorName = createPropertyName(startWithUnderscore ? getUniqueName(name.substring(1), file) : name, declaration.name); + return { + isStatic: hasStaticModifier(declaration), + isReadonly: hasEffectiveReadonlyModifier(declaration), + type: getDeclarationType(declaration, program), + container: declaration.kind === 169 /* Parameter */ ? declaration.parent.parent : declaration.parent, + originalName: declaration.name.text, + declaration: declaration, + fieldName: fieldName, + accessorName: accessorName, + renameAccessor: startWithUnderscore + }; } - function getCompletionEntriesFromTypings(host, options, scriptPath, fragmentDirectory, extensionOptions, result = createNameAndKindSet()) { - const seen = /* @__PURE__ */ new Map(); - const typeRoots = tryAndIgnoreErrors(()=>getEffectiveTypeRoots(options, host)) || emptyArray; - for (const root of typeRoots)getCompletionEntriesFromDirectories(root); - for (const packageJson of findPackageJsons(scriptPath, host)){ - const typesDir = combinePaths(getDirectoryPath(packageJson), "node_modules/@types"); - getCompletionEntriesFromDirectories(typesDir); - } - return result; - function getCompletionEntriesFromDirectories(directory) { - if (!tryDirectoryExists(host, directory)) return; - for (const typeDirectoryName of tryGetDirectories(host, directory)){ - const packageName = unmangleScopedPackageName(typeDirectoryName); - if (options.types && !contains(options.types, packageName)) continue; - if (fragmentDirectory === void 0) { - if (!seen.has(packageName)) { - result.add(nameAndKind(packageName, "external module name" /* externalModuleName */ , /*extension*/ void 0)); - seen.set(packageName, true); - } - } else { - const baseDirectory = combinePaths(directory, typeDirectoryName); - const remainingFragment = tryRemoveDirectoryPrefix(fragmentDirectory, packageName, hostGetCanonicalFileName(host)); - if (remainingFragment !== void 0) getCompletionEntriesForDirectoryFragment(remainingFragment, baseDirectory, extensionOptions, host, /*moduleSpecifierIsRelative*/ false, /*exclude*/ void 0, result); - } - } + function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic2, container) { + return factory.createGetAccessorDeclaration(modifiers, accessorName, [], type, factory.createBlock([ + factory.createReturnStatement(createAccessorAccessExpression(fieldName, isStatic2, container)) + ], /*multiLine*/ true)); + } + function generateSetAccessor(fieldName, accessorName, type, modifiers, isStatic2, container) { + return factory.createSetAccessorDeclaration(modifiers, accessorName, [ + factory.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, factory.createIdentifier("value"), /*questionToken*/ void 0, type) + ], factory.createBlock([ + factory.createExpressionStatement(factory.createAssignment(createAccessorAccessExpression(fieldName, isStatic2, container), factory.createIdentifier("value"))) + ], /*multiLine*/ true)); + } + function updatePropertyDeclaration(changeTracker, file, declaration, type, fieldName, modifiers) { + const property = factory.updatePropertyDeclaration(declaration, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, type, declaration.initializer); + changeTracker.replaceNode(file, declaration, property); + } + function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) { + let assignment = factory.updatePropertyAssignment(declaration, fieldName, declaration.initializer); + if (assignment.modifiers || assignment.questionToken || assignment.exclamationToken) { + if (assignment === declaration) assignment = factory.cloneNode(assignment); + assignment.modifiers = void 0; + assignment.questionToken = void 0; + assignment.exclamationToken = void 0; } + changeTracker.replacePropertyAssignment(file, declaration, assignment); } - function enumerateNodeModulesVisibleToScript(host, scriptPath) { - if (!host.readFile || !host.fileExists) return emptyArray; - const result = []; - for (const packageJson of findPackageJsons(scriptPath, host)){ - const contents = readJson(packageJson, host); - for (const key of nodeModulesDependencyKeys){ - const dependencies = contents[key]; - if (!dependencies) continue; - for(const dep in dependencies)if (hasProperty(dependencies, dep) && !startsWith(dep, "@types/")) result.push(dep); + function updateFieldDeclaration(changeTracker, file, declaration, type, fieldName, modifiers) { + if (isPropertyDeclaration(declaration)) updatePropertyDeclaration(changeTracker, file, declaration, type, fieldName, modifiers); + else if (isPropertyAssignment(declaration)) updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName); + else changeTracker.replaceNode(file, declaration, factory.updateParameterDeclaration(declaration, modifiers, declaration.dotDotDotToken, cast(fieldName, isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); + } + function insertAccessor(changeTracker, file, accessor, declaration, container) { + isParameterPropertyDeclaration(declaration, declaration.parent) ? changeTracker.insertMemberAtStart(file, container, accessor) : isPropertyAssignment(declaration) ? changeTracker.insertNodeAfterComma(file, declaration, accessor) : changeTracker.insertNodeAfter(file, declaration, accessor); + } + function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName, originalName) { + if (!constructor.body) return; + constructor.body.forEachChild(function recur(node) { + if (isElementAccessExpression(node) && node.expression.kind === 110 /* ThisKeyword */ && isStringLiteral(node.argumentExpression) && node.argumentExpression.text === originalName && isWriteAccess(node)) changeTracker.replaceNode(file, node.argumentExpression, factory.createStringLiteral(fieldName)); + if (isPropertyAccessExpression(node) && node.expression.kind === 110 /* ThisKeyword */ && node.name.text === originalName && isWriteAccess(node)) changeTracker.replaceNode(file, node.name, factory.createIdentifier(fieldName)); + if (!isFunctionLike(node) && !isClassLike(node)) node.forEachChild(recur); + }); + } + function getDeclarationType(declaration, program) { + const typeNode = getTypeAnnotationNode(declaration); + if (isPropertyDeclaration(declaration) && typeNode && declaration.questionToken) { + const typeChecker = program.getTypeChecker(); + const type = typeChecker.getTypeFromTypeNode(typeNode); + if (!typeChecker.isTypeAssignableTo(typeChecker.getUndefinedType(), type)) { + const types = isUnionTypeNode(typeNode) ? typeNode.types : [ + typeNode + ]; + return factory.createUnionTypeNode([ + ...types, + factory.createKeywordTypeNode(157 /* UndefinedKeyword */ ) + ]); } } - return result; + return typeNode; } - function getDirectoryFragmentTextSpan(text, textStart) { - const index = Math.max(text.lastIndexOf(directorySeparator), text.lastIndexOf(altDirectorySeparator)); - const offset = index !== -1 ? index + 1 : 0; - const length2 = text.length - offset; - return length2 === 0 || isIdentifierText(text.substr(offset, length2), 99 /* ESNext */ ) ? void 0 : createTextSpan(textStart + offset, length2); + function getAllSupers(decl, checker) { + const res = []; + while(decl){ + const superElement = getClassExtendsHeritageElement(decl); + const superSymbol = superElement && checker.getSymbolAtLocation(superElement.expression); + if (!superSymbol) break; + const symbol = superSymbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(superSymbol) : superSymbol; + const superDecl = symbol.declarations && find(symbol.declarations, isClassLike); + if (!superDecl) break; + res.push(superDecl); + decl = superDecl; + } + return res; } - function isPathRelativeToScript(path) { - if (path && path.length >= 2 && path.charCodeAt(0) === 46 /* dot */ ) { - const slashIndex = path.length >= 3 && path.charCodeAt(1) === 46 /* dot */ ? 2 : 1; - const slashCharCode = path.charCodeAt(slashIndex); - return slashCharCode === 47 /* slash */ || slashCharCode === 92 /* backslash */ ; + var init_generateAccessors = __esm({ + "src/services/codefixes/generateAccessors.ts" () { + "use strict"; + init_ts4(); } - return false; + }); + // src/services/codefixes/fixInvalidImportSyntax.ts + function getCodeFixesForImportDeclaration(context, node) { + const sourceFile = getSourceFileOfNode(node); + const namespace = getNamespaceDeclarationNode(node); + const opts = context.program.getCompilerOptions(); + const variations = []; + variations.push(createAction(context, sourceFile, node, makeImport(namespace.name, /*namedImports*/ void 0, node.moduleSpecifier, getQuotePreference(sourceFile, context.preferences)))); + if (getEmitModuleKind(opts) === 1 /* CommonJS */ ) variations.push(createAction(context, sourceFile, node, factory.createImportEqualsDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, namespace.name, factory.createExternalModuleReference(node.moduleSpecifier)))); + return variations; } - function containsSlash(fragment) { - return stringContains(fragment, directorySeparator); + function createAction(context, sourceFile, node, replacement) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>t.replaceNode(sourceFile, node, replacement)); + return createCodeFixActionWithoutFixAll(fixName5, changes, [ + Diagnostics.Replace_import_with_0, + changes[0].textChanges[0].newText + ]); } - function isRequireCallArgument(node) { - return isCallExpression(node.parent) && firstOrUndefined(node.parent.arguments) === node && isIdentifier(node.parent.expression) && node.parent.expression.escapedText === "require"; + function getActionsForUsageOfInvalidImport(context) { + const sourceFile = context.sourceFile; + const targetKind = Diagnostics.This_expression_is_not_callable.code === context.errorCode ? 213 /* CallExpression */ : 214 /* NewExpression */ ; + const node = findAncestor(getTokenAtPosition(sourceFile, context.span.start), (a)=>a.kind === targetKind); + if (!node) return []; + const expr = node.expression; + return getImportCodeFixesForExpression(context, expr); } - var kindPrecedence, tripleSlashDirectiveFragmentRegex, nodeModulesDependencyKeys; - var init_stringCompletions = __esm({ - "src/services/stringCompletions.ts" () { + function getActionsForInvalidImportLocation(context) { + const sourceFile = context.sourceFile; + const node = findAncestor(getTokenAtPosition(sourceFile, context.span.start), (a)=>a.getStart() === context.span.start && a.getEnd() === context.span.start + context.span.length); + if (!node) return []; + return getImportCodeFixesForExpression(context, node); + } + function getImportCodeFixesForExpression(context, expr) { + const type = context.program.getTypeChecker().getTypeAtLocation(expr); + if (!(type.symbol && isTransientSymbol(type.symbol) && type.symbol.links.originatingImport)) return []; + const fixes = []; + const relatedImport = type.symbol.links.originatingImport; + if (!isImportCall(relatedImport)) addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); + if (isExpression(expr) && !(isNamedDeclaration(expr.parent) && expr.parent.name === expr)) { + const sourceFile = context.sourceFile; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>t.replaceNode(sourceFile, expr, factory.createPropertyAccessExpression(expr, "default"), {})); + fixes.push(createCodeFixActionWithoutFixAll(fixName5, changes, Diagnostics.Use_synthetic_default_member)); + } + return fixes; + } + var fixName5; + var init_fixInvalidImportSyntax = __esm({ + "src/services/codefixes/fixInvalidImportSyntax.ts" () { "use strict"; init_ts4(); - init_ts_Completions(); - kindPrecedence = { - ["directory" /* directory */ ]: 0, - ["script" /* scriptElement */ ]: 1, - ["external module name" /* externalModuleName */ ]: 2 - }; - tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s*getStringLiteralCompletionDetails, - getStringLiteralCompletions: ()=>getStringLiteralCompletions - }); - var init_ts_Completions_StringCompletions = __esm({ - "src/services/_namespaces/ts.Completions.StringCompletions.ts" () { - "use strict"; - init_stringCompletions(); + // src/services/codefixes/fixStrictClassInitialization.ts + function getInfo16(sourceFile, pos) { + const token = getTokenAtPosition(sourceFile, pos); + if (isIdentifier(token) && isPropertyDeclaration(token.parent)) { + const type = getEffectiveTypeAnnotationNode(token.parent); + if (type) return { + type: type, + prop: token.parent, + isJs: isInJSFile(token.parent) + }; } - }); - // src/services/_namespaces/ts.Completions.ts - var ts_Completions_exports = {}; - __export(ts_Completions_exports, { - CompletionKind: ()=>CompletionKind, - CompletionSource: ()=>CompletionSource, - SortText: ()=>SortText, - StringCompletions: ()=>ts_Completions_StringCompletions_exports, - SymbolOriginInfoKind: ()=>SymbolOriginInfoKind, - createCompletionDetails: ()=>createCompletionDetails, - createCompletionDetailsForSymbol: ()=>createCompletionDetailsForSymbol, - getCompletionEntriesFromSymbols: ()=>getCompletionEntriesFromSymbols, - getCompletionEntryDetails: ()=>getCompletionEntryDetails, - getCompletionEntrySymbol: ()=>getCompletionEntrySymbol, - getCompletionsAtPosition: ()=>getCompletionsAtPosition, - getPropertiesForObjectExpression: ()=>getPropertiesForObjectExpression, - moduleSpecifierResolutionCacheAttemptLimit: ()=>moduleSpecifierResolutionCacheAttemptLimit, - moduleSpecifierResolutionLimit: ()=>moduleSpecifierResolutionLimit - }); - var init_ts_Completions = __esm({ - "src/services/_namespaces/ts.Completions.ts" () { - "use strict"; - init_completions(); - init_ts_Completions_StringCompletions(); - } - }); - // src/services/importTracker.ts - function createImportTracker(sourceFiles, sourceFilesSet, checker, cancellationToken) { - const allDirectImports = getDirectImportsMap(sourceFiles, checker, cancellationToken); - return (exportSymbol, exportInfo, isForRename)=>{ - const { directImports: directImports , indirectUsers: indirectUsers } = getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, exportInfo, checker, cancellationToken); - return { - indirectUsers: indirectUsers, - ...getSearchesFromDirectImports(directImports, exportSymbol, exportInfo.exportKind, checker, isForRename) - }; - }; + return void 0; } - function getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, { exportingModuleSymbol: exportingModuleSymbol , exportKind: exportKind }, checker, cancellationToken) { - const markSeenDirectImport = nodeSeenTracker(); - const markSeenIndirectUser = nodeSeenTracker(); - const directImports = []; - const isAvailableThroughGlobal = !!exportingModuleSymbol.globalExports; - const indirectUserDeclarations = isAvailableThroughGlobal ? void 0 : []; - handleDirectImports(exportingModuleSymbol); - return { - directImports: directImports, - indirectUsers: getIndirectUsers() - }; - function getIndirectUsers() { - if (isAvailableThroughGlobal) return sourceFiles; - if (exportingModuleSymbol.declarations) { - for (const decl of exportingModuleSymbol.declarations)if (isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) addIndirectUser(decl); - } - return indirectUserDeclarations.map(getSourceFileOfNode); - } - function handleDirectImports(exportingModuleSymbol2) { - const theseDirectImports = getDirectImports(exportingModuleSymbol2); - if (theseDirectImports) for (const direct of theseDirectImports){ - if (!markSeenDirectImport(direct)) continue; - if (cancellationToken) cancellationToken.throwIfCancellationRequested(); - switch(direct.kind){ - case 210 /* CallExpression */ : - if (isImportCall(direct)) { - handleImportCall(direct); - break; - } - if (!isAvailableThroughGlobal) { - const parent2 = direct.parent; - if (exportKind === 2 /* ExportEquals */ && parent2.kind === 257 /* VariableDeclaration */ ) { - const { name: name } = parent2; - if (name.kind === 79 /* Identifier */ ) { - directImports.push(name); - break; - } - } + function getActionForAddMissingDefiniteAssignmentAssertion(context, info) { + if (info.isJs) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addDefiniteAssignmentAssertion(t, context.sourceFile, info.prop)); + return createCodeFixAction(fixName6, changes, [ + Diagnostics.Add_definite_assignment_assertion_to_property_0, + info.prop.getText() + ], fixIdAddDefiniteAssignmentAssertions, Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); + } + function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { + suppressLeadingAndTrailingTrivia(propertyDeclaration); + const property = factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.modifiers, propertyDeclaration.name, factory.createToken(54 /* ExclamationToken */ ), propertyDeclaration.type, propertyDeclaration.initializer); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); + } + function getActionForAddMissingUndefinedType(context, info) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addUndefinedType(t, context.sourceFile, info)); + return createCodeFixAction(fixName6, changes, [ + Diagnostics.Add_undefined_type_to_property_0, + info.prop.name.getText() + ], fixIdAddUndefinedType, Diagnostics.Add_undefined_type_to_all_uninitialized_properties); + } + function addUndefinedType(changeTracker, sourceFile, info) { + const undefinedTypeNode = factory.createKeywordTypeNode(157 /* UndefinedKeyword */ ); + const types = isUnionTypeNode(info.type) ? info.type.types.concat(undefinedTypeNode) : [ + info.type, + undefinedTypeNode + ]; + const unionTypeNode = factory.createUnionTypeNode(types); + if (info.isJs) changeTracker.addJSDocTags(sourceFile, info.prop, [ + factory.createJSDocTypeTag(/*tagName*/ void 0, factory.createJSDocTypeExpression(unionTypeNode)) + ]); + else changeTracker.replaceNode(sourceFile, info.type, unionTypeNode); + } + function getActionForAddMissingInitializer(context, info) { + if (info.isJs) return void 0; + const checker = context.program.getTypeChecker(); + const initializer = getInitializer(checker, info.prop); + if (!initializer) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>addInitializer(t, context.sourceFile, info.prop, initializer)); + return createCodeFixAction(fixName6, changes, [ + Diagnostics.Add_initializer_to_property_0, + info.prop.name.getText() + ], fixIdAddInitializer, Diagnostics.Add_initializers_to_all_uninitialized_properties); + } + function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) { + suppressLeadingAndTrailingTrivia(propertyDeclaration); + const property = factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); + } + function getInitializer(checker, propertyDeclaration) { + return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); + } + function getDefaultValueFromType(checker, type) { + if (type.flags & 512 /* BooleanLiteral */ ) return type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true) ? factory.createFalse() : factory.createTrue(); + else if (type.isStringLiteral()) return factory.createStringLiteral(type.value); + else if (type.isNumberLiteral()) return factory.createNumericLiteral(type.value); + else if (type.flags & 2048 /* BigIntLiteral */ ) return factory.createBigIntLiteral(type.value); + else if (type.isUnion()) return firstDefined(type.types, (t)=>getDefaultValueFromType(checker, t)); + else if (type.isClass()) { + const classDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); + if (!classDeclaration || hasSyntacticModifier(classDeclaration, 256 /* Abstract */ )) return void 0; + const constructorDeclaration = getFirstConstructorWithBody(classDeclaration); + if (constructorDeclaration && constructorDeclaration.parameters.length) return void 0; + return factory.createNewExpression(factory.createIdentifier(type.symbol.name), /*typeArguments*/ void 0, /*argumentsArray*/ void 0); + } else if (checker.isArrayLikeType(type)) return factory.createArrayLiteralExpression(); + return void 0; + } + var fixName6, fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer, errorCodes51; + var init_fixStrictClassInitialization = __esm({ + "src/services/codefixes/fixStrictClassInitialization.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixName6 = "strictClassInitialization"; + fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions"; + fixIdAddUndefinedType = "addMissingPropertyUndefinedType"; + fixIdAddInitializer = "addMissingPropertyInitializer"; + errorCodes51 = [ + Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code + ]; + registerCodeFix({ + errorCodes: errorCodes51, + getCodeActions: function getCodeActionsForStrictClassInitializationErrors(context) { + const info = getInfo16(context.sourceFile, context.span.start); + if (!info) return; + const result = []; + append(result, getActionForAddMissingUndefinedType(context, info)); + append(result, getActionForAddMissingDefiniteAssignmentAssertion(context, info)); + append(result, getActionForAddMissingInitializer(context, info)); + return result; + }, + fixIds: [ + fixIdAddDefiniteAssignmentAssertions, + fixIdAddUndefinedType, + fixIdAddInitializer + ], + getAllCodeActions: (context)=>{ + return codeFixAll(context, errorCodes51, (changes, diag2)=>{ + const info = getInfo16(diag2.file, diag2.start); + if (!info) return; + switch(context.fixId){ + case fixIdAddDefiniteAssignmentAssertions: + addDefiniteAssignmentAssertion(changes, diag2.file, info.prop); + break; + case fixIdAddUndefinedType: + addUndefinedType(changes, diag2.file, info); + break; + case fixIdAddInitializer: + const checker = context.program.getTypeChecker(); + const initializer = getInitializer(checker, info.prop); + if (!initializer) return; + addInitializer(changes, diag2.file, info.prop, initializer); + break; + default: + Debug.fail(JSON.stringify(context.fixId)); } - break; - case 79 /* Identifier */ : - break; - case 268 /* ImportEqualsDeclaration */ : - handleNamespaceImport(direct, direct.name, hasSyntacticModifier(direct, 1 /* Export */ ), /*alreadyAddedDirect*/ false); - break; - case 269 /* ImportDeclaration */ : - directImports.push(direct); - const namedBindings = direct.importClause && direct.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 271 /* NamespaceImport */ ) handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true); - else if (!isAvailableThroughGlobal && isDefaultImport(direct)) addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); - break; - case 275 /* ExportDeclaration */ : - if (!direct.exportClause) handleDirectImports(getContainingModuleSymbol(direct, checker)); - else if (direct.exportClause.kind === 277 /* NamespaceExport */ ) addIndirectUser(getSourceFileLikeForImportDeclaration(direct), /** addTransitiveDependencies */ true); - else directImports.push(direct); - break; - case 202 /* ImportType */ : - if (!isAvailableThroughGlobal && direct.isTypeOf && !direct.qualifier && isExported2(direct)) addIndirectUser(direct.getSourceFile(), /** addTransitiveDependencies */ true); - directImports.push(direct); - break; - default: - Debug.failBadSyntaxKind(direct, "Unexpected import kind."); + }); } - } - } - function handleImportCall(importCall) { - const top = findAncestor(importCall, isAmbientModuleDeclaration) || importCall.getSourceFile(); - addIndirectUser(top, /** addTransitiveDependencies */ !!isExported2(importCall, /** stopAtAmbientModule */ true)); - } - function isExported2(node, stopAtAmbientModule = false) { - return findAncestor(node, (node2)=>{ - if (stopAtAmbientModule && isAmbientModuleDeclaration(node2)) return "quit"; - return canHaveModifiers(node2) && some(node2.modifiers, isExportModifier); }); } - function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) { - if (exportKind === 2 /* ExportEquals */ ) { - if (!alreadyAddedDirect) directImports.push(importDeclaration); - } else if (!isAvailableThroughGlobal) { - const sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); - Debug.assert(sourceFileLike.kind === 308 /* SourceFile */ || sourceFileLike.kind === 264 /* ModuleDeclaration */ ); - if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) addIndirectUser(sourceFileLike, /** addTransitiveDependencies */ true); - else addIndirectUser(sourceFileLike); - } - } - function addIndirectUser(sourceFileLike, addTransitiveDependencies = false) { - Debug.assert(!isAvailableThroughGlobal); - const isNew = markSeenIndirectUser(sourceFileLike); - if (!isNew) return; - indirectUserDeclarations.push(sourceFileLike); - if (!addTransitiveDependencies) return; - const moduleSymbol = checker.getMergedSymbol(sourceFileLike.symbol); - if (!moduleSymbol) return; - Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */ )); - const directImports2 = getDirectImports(moduleSymbol); - if (directImports2) { - for (const directImport of directImports2)if (!isImportTypeNode(directImport)) addIndirectUser(getSourceFileLikeForImportDeclaration(directImport), /** addTransitiveDependencies */ true); - } - } - function getDirectImports(moduleSymbol) { - return allDirectImports.get(getSymbolId(moduleSymbol).toString()); + }); + // src/services/codefixes/requireInTs.ts + function doChange34(changes, sourceFile, info) { + const { allowSyntheticDefaults: allowSyntheticDefaults, defaultImportName: defaultImportName, namedImports: namedImports, statement: statement, required: required } = info; + changes.replaceNode(sourceFile, statement, defaultImportName && !allowSyntheticDefaults ? factory.createImportEqualsDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, defaultImportName, factory.createExternalModuleReference(required)) : factory.createImportDeclaration(/*modifiers*/ void 0, factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, namedImports), required, /*assertClause*/ void 0)); + } + function getInfo17(sourceFile, program, pos) { + const { parent: parent2 } = getTokenAtPosition(sourceFile, pos); + if (!isRequireCall(parent2, /*requireStringLiteralLikeArgument*/ true)) Debug.failBadSyntaxKind(parent2); + const decl = cast(parent2.parent, isVariableDeclaration); + const defaultImportName = tryCast(decl.name, isIdentifier); + const namedImports = isObjectBindingPattern(decl.name) ? tryCreateNamedImportsFromObjectBindingPattern(decl.name) : void 0; + if (defaultImportName || namedImports) return { + allowSyntheticDefaults: getAllowSyntheticDefaultImports(program.getCompilerOptions()), + defaultImportName: defaultImportName, + namedImports: namedImports, + statement: cast(decl.parent.parent, isVariableStatement), + required: first(parent2.arguments) + }; + } + function tryCreateNamedImportsFromObjectBindingPattern(node) { + const importSpecifiers = []; + for (const element of node.elements){ + if (!isIdentifier(element.name) || element.initializer) return void 0; + importSpecifiers.push(factory.createImportSpecifier(/*isTypeOnly*/ false, tryCast(element.propertyName, isIdentifier), element.name)); } + if (importSpecifiers.length) return factory.createNamedImports(importSpecifiers); } - function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, checker, isForRename) { - const importSearches = []; - const singleReferences = []; - function addSearch(location, symbol) { - importSearches.push([ - location, - symbol - ]); + var fixId41, errorCodes52; + var init_requireInTs = __esm({ + "src/services/codefixes/requireInTs.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId41 = "requireInTs"; + errorCodes52 = [ + Diagnostics.require_call_may_be_converted_to_an_import.code + ]; + registerCodeFix({ + errorCodes: errorCodes52, + getCodeActions (context) { + const info = getInfo17(context.sourceFile, context.program, context.span.start); + if (!info) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange34(t, context.sourceFile, info)); + return [ + createCodeFixAction(fixId41, changes, Diagnostics.Convert_require_to_import, fixId41, Diagnostics.Convert_all_require_to_import) + ]; + }, + fixIds: [ + fixId41 + ], + getAllCodeActions: (context)=>codeFixAll(context, errorCodes52, (changes, diag2)=>{ + const info = getInfo17(diag2.file, context.program, diag2.start); + if (info) doChange34(changes, context.sourceFile, info); + }) + }); } - if (directImports) for (const decl of directImports)handleImport(decl); - return { - importSearches: importSearches, - singleReferences: singleReferences + }); + // src/services/codefixes/useDefaultImport.ts + function getInfo18(sourceFile, pos) { + const name = getTokenAtPosition(sourceFile, pos); + if (!isIdentifier(name)) return void 0; + const { parent: parent2 } = name; + if (isImportEqualsDeclaration(parent2) && isExternalModuleReference(parent2.moduleReference)) return { + importNode: parent2, + name: name, + moduleSpecifier: parent2.moduleReference.expression }; - function handleImport(decl) { - if (decl.kind === 268 /* ImportEqualsDeclaration */ ) { - if (isExternalModuleImportEquals(decl)) handleNamespaceImportLike(decl.name); - return; - } - if (decl.kind === 79 /* Identifier */ ) { - handleNamespaceImportLike(decl); - return; - } - if (decl.kind === 202 /* ImportType */ ) { - if (decl.qualifier) { - const firstIdentifier = getFirstIdentifier(decl.qualifier); - if (firstIdentifier.escapedText === symbolName(exportSymbol)) singleReferences.push(firstIdentifier); - } else if (exportKind === 2 /* ExportEquals */ ) singleReferences.push(decl.argument.literal); - return; - } - if (decl.moduleSpecifier.kind !== 10 /* StringLiteral */ ) return; - if (decl.kind === 275 /* ExportDeclaration */ ) { - if (decl.exportClause && isNamedExports(decl.exportClause)) searchForNamedImport(decl.exportClause); - return; - } - const { name: name , namedBindings: namedBindings } = decl.importClause || { - name: void 0, - namedBindings: void 0 + else if (isNamespaceImport(parent2)) { + const importNode = parent2.parent.parent; + return { + importNode: importNode, + name: name, + moduleSpecifier: importNode.moduleSpecifier }; - if (namedBindings) switch(namedBindings.kind){ - case 271 /* NamespaceImport */ : - handleNamespaceImportLike(namedBindings.name); - break; - case 272 /* NamedImports */ : - if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */ ) searchForNamedImport(namedBindings); - break; - default: - Debug.assertNever(namedBindings); - } - if (name && (exportKind === 1 /* Default */ || exportKind === 2 /* ExportEquals */ ) && (!isForRename || name.escapedText === symbolEscapedNameNoDefault(exportSymbol))) { - const defaultImportAlias = checker.getSymbolAtLocation(name); - addSearch(name, defaultImportAlias); - } - } - function handleNamespaceImportLike(importName) { - if (exportKind === 2 /* ExportEquals */ && (!isForRename || isNameMatch(importName.escapedText))) addSearch(importName, checker.getSymbolAtLocation(importName)); - } - function searchForNamedImport(namedBindings) { - if (!namedBindings) return; - for (const element of namedBindings.elements){ - const { name: name , propertyName: propertyName } = element; - if (!isNameMatch((propertyName || name).escapedText)) continue; - if (propertyName) { - singleReferences.push(propertyName); - if (!isForRename || name.escapedText === exportSymbol.escapedName) addSearch(name, checker.getSymbolAtLocation(name)); - } else { - const localSymbol = element.kind === 278 /* ExportSpecifier */ && element.propertyName ? checker.getExportSpecifierLocalTargetSymbol(element) : checker.getSymbolAtLocation(name); - addSearch(name, localSymbol); - } - } - } - function isNameMatch(name) { - return name === exportSymbol.escapedName || exportKind !== 0 /* Named */ && name === "default" /* Default */ ; } } - function findNamespaceReExports(sourceFileLike, name, checker) { - const namespaceImportSymbol = checker.getSymbolAtLocation(name); - return !!forEachPossibleImportOrExportStatement(sourceFileLike, (statement)=>{ - if (!isExportDeclaration(statement)) return; - const { exportClause: exportClause , moduleSpecifier: moduleSpecifier } = statement; - return !moduleSpecifier && exportClause && isNamedExports(exportClause) && exportClause.elements.some((element)=>checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol); - }); + function doChange35(changes, sourceFile, info, preferences) { + changes.replaceNode(sourceFile, info.importNode, makeImport(info.name, /*namedImports*/ void 0, info.moduleSpecifier, getQuotePreference(sourceFile, preferences))); } - function findModuleReferences(program, sourceFiles, searchModuleSymbol) { - var _a2; - const refs = []; - const checker = program.getTypeChecker(); - for (const referencingFile of sourceFiles){ - const searchSourceFile = searchModuleSymbol.valueDeclaration; - if ((searchSourceFile == null ? void 0 : searchSourceFile.kind) === 308 /* SourceFile */ ) { - for (const ref of referencingFile.referencedFiles)if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) refs.push({ - kind: "reference", - referencingFile: referencingFile, - ref: ref - }); - for (const ref of referencingFile.typeReferenceDirectives){ - const referenced = (_a2 = program.getResolvedTypeReferenceDirectives().get(ref.fileName, ref.resolutionMode || referencingFile.impliedNodeFormat)) == null ? void 0 : _a2.resolvedTypeReferenceDirective; - if (referenced !== void 0 && referenced.resolvedFileName === searchSourceFile.fileName) refs.push({ - kind: "reference", - referencingFile: referencingFile, - ref: ref - }); - } - } - forEachImport(referencingFile, (_importDecl, moduleSpecifier)=>{ - const moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); - if (moduleSymbol === searchModuleSymbol) refs.push({ - kind: "import", - literal: moduleSpecifier - }); + var fixId42, errorCodes53; + var init_useDefaultImport = __esm({ + "src/services/codefixes/useDefaultImport.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId42 = "useDefaultImport"; + errorCodes53 = [ + Diagnostics.Import_may_be_converted_to_a_default_import.code + ]; + registerCodeFix({ + errorCodes: errorCodes53, + getCodeActions (context) { + const { sourceFile: sourceFile, span: { start: start } } = context; + const info = getInfo18(sourceFile, start); + if (!info) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange35(t, sourceFile, info, context.preferences)); + return [ + createCodeFixAction(fixId42, changes, Diagnostics.Convert_to_default_import, fixId42, Diagnostics.Convert_all_to_default_imports) + ]; + }, + fixIds: [ + fixId42 + ], + getAllCodeActions: (context)=>codeFixAll(context, errorCodes53, (changes, diag2)=>{ + const info = getInfo18(diag2.file, diag2.start); + if (info) doChange35(changes, diag2.file, info, context.preferences); + }) }); } - return refs; + }); + // src/services/codefixes/useBigintLiteral.ts + function makeChange9(changeTracker, sourceFile, span) { + const numericLiteral = tryCast(getTokenAtPosition(sourceFile, span.start), isNumericLiteral); + if (!numericLiteral) return; + const newText = numericLiteral.getText(sourceFile) + "n"; + changeTracker.replaceNode(sourceFile, numericLiteral, factory.createBigIntLiteral(newText)); } - function getDirectImportsMap(sourceFiles, checker, cancellationToken) { - const map2 = /* @__PURE__ */ new Map(); - for (const sourceFile of sourceFiles){ - if (cancellationToken) cancellationToken.throwIfCancellationRequested(); - forEachImport(sourceFile, (importDecl, moduleSpecifier)=>{ - const moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); - if (moduleSymbol) { - const id = getSymbolId(moduleSymbol).toString(); - let imports = map2.get(id); - if (!imports) map2.set(id, imports = []); - imports.push(importDecl); + var fixId43, errorCodes54; + var init_useBigintLiteral = __esm({ + "src/services/codefixes/useBigintLiteral.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId43 = "useBigintLiteral"; + errorCodes54 = [ + Diagnostics.Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers.code + ]; + registerCodeFix({ + errorCodes: errorCodes54, + getCodeActions: function getCodeActionsToUseBigintLiteral(context) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>makeChange9(t, context.sourceFile, context.span)); + if (changes.length > 0) return [ + createCodeFixAction(fixId43, changes, Diagnostics.Convert_to_a_bigint_numeric_literal, fixId43, Diagnostics.Convert_all_to_bigint_numeric_literals) + ]; + }, + fixIds: [ + fixId43 + ], + getAllCodeActions: (context)=>{ + return codeFixAll(context, errorCodes54, (changes, diag2)=>makeChange9(changes, diag2.file, diag2)); } }); } - return map2; + }); + // src/services/codefixes/fixAddModuleReferTypeMissingTypeof.ts + function getImportTypeNode(sourceFile, pos) { + const token = getTokenAtPosition(sourceFile, pos); + Debug.assert(token.kind === 102 /* ImportKeyword */ , "This token should be an ImportKeyword"); + Debug.assert(token.parent.kind === 205 /* ImportType */ , "Token parent should be an ImportType"); + return token.parent; } - function forEachPossibleImportOrExportStatement(sourceFileLike, action) { - return forEach(sourceFileLike.kind === 308 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, (statement)=>// TODO: GH#18217 - action(statement) || isAmbientModuleDeclaration(statement) && forEach(statement.body && statement.body.statements, action)); + function doChange36(changes, sourceFile, importType) { + const newTypeNode = factory.updateImportTypeNode(importType, importType.argument, importType.assertions, importType.qualifier, importType.typeArguments, /*isTypeOf*/ true); + changes.replaceNode(sourceFile, importType, newTypeNode); } - function forEachImport(sourceFile, action) { - if (sourceFile.externalModuleIndicator || sourceFile.imports !== void 0) for (const i of sourceFile.imports)action(importFromModuleSpecifier(i), i); - else forEachPossibleImportOrExportStatement(sourceFile, (statement)=>{ - switch(statement.kind){ - case 275 /* ExportDeclaration */ : - case 269 /* ImportDeclaration */ : - { - const decl = statement; - if (decl.moduleSpecifier && isStringLiteral(decl.moduleSpecifier)) action(decl, decl.moduleSpecifier); - break; - } - case 268 /* ImportEqualsDeclaration */ : - { - const decl = statement; - if (isExternalModuleImportEquals(decl)) action(decl, decl.moduleReference.expression); - break; - } - } - }); + var fixIdAddMissingTypeof, fixId44, errorCodes55; + var init_fixAddModuleReferTypeMissingTypeof = __esm({ + "src/services/codefixes/fixAddModuleReferTypeMissingTypeof.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof"; + fixId44 = fixIdAddMissingTypeof; + errorCodes55 = [ + Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0.code + ]; + registerCodeFix({ + errorCodes: errorCodes55, + getCodeActions: function getCodeActionsToAddMissingTypeof(context) { + const { sourceFile: sourceFile, span: span } = context; + const importType = getImportTypeNode(sourceFile, span.start); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange36(t, sourceFile, importType)); + return [ + createCodeFixAction(fixId44, changes, Diagnostics.Add_missing_typeof, fixId44, Diagnostics.Add_missing_typeof) + ]; + }, + fixIds: [ + fixId44 + ], + getAllCodeActions: (context)=>codeFixAll(context, errorCodes55, (changes, diag2)=>doChange36(changes, context.sourceFile, getImportTypeNode(diag2.file, diag2.start))) + }); + } + }); + // src/services/codefixes/wrapJsxInFragment.ts + function findNodeToFix(sourceFile, pos) { + const lessThanToken = getTokenAtPosition(sourceFile, pos); + const firstJsxElementOrOpenElement = lessThanToken.parent; + let binaryExpr = firstJsxElementOrOpenElement.parent; + if (!isBinaryExpression(binaryExpr)) { + binaryExpr = binaryExpr.parent; + if (!isBinaryExpression(binaryExpr)) return void 0; + } + if (!nodeIsMissing(binaryExpr.operatorToken)) return void 0; + return binaryExpr; } - function getImportOrExportSymbol(node, symbol, checker, comingFromExport) { - return comingFromExport ? getExport() : getExport() || getImport(); - function getExport() { - var _a2; - const { parent: parent2 } = node; - const grandparent = parent2.parent; - if (symbol.exportSymbol) { - if (parent2.kind === 208 /* PropertyAccessExpression */ ) return ((_a2 = symbol.declarations) == null ? void 0 : _a2.some((d)=>d === parent2)) && isBinaryExpression(grandparent) ? getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ false) : void 0; - else return exportInfo(symbol.exportSymbol, getExportKindForDeclaration(parent2)); - } else { - const exportNode = getExportNode(parent2, node); - if (exportNode && hasSyntacticModifier(exportNode, 1 /* Export */ )) { - if (isImportEqualsDeclaration(exportNode) && exportNode.moduleReference === node) { - if (comingFromExport) return void 0; - const lhsSymbol = checker.getSymbolAtLocation(exportNode.name); - return { - kind: 0 /* Import */ , - symbol: lhsSymbol - }; - } else return exportInfo(symbol, getExportKindForDeclaration(exportNode)); - } else if (isNamespaceExport(parent2)) return exportInfo(symbol, 0 /* Named */ ); - else if (isExportAssignment(parent2)) return getExportAssignmentExport(parent2); - else if (isExportAssignment(grandparent)) return getExportAssignmentExport(grandparent); - else if (isBinaryExpression(parent2)) return getSpecialPropertyExport(parent2, /*useLhsSymbol*/ true); - else if (isBinaryExpression(grandparent)) return getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ true); - else if (isJSDocTypedefTag(parent2) || isJSDocCallbackTag(parent2)) return exportInfo(symbol, 0 /* Named */ ); - } - function getExportAssignmentExport(ex) { - if (!ex.symbol.parent) return void 0; - const exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */ ; - return { - kind: 1 /* Export */ , - symbol: symbol, - exportInfo: { - exportingModuleSymbol: ex.symbol.parent, - exportKind: exportKind - } - }; - } - function getSpecialPropertyExport(node2, useLhsSymbol) { - let kind; - switch(getAssignmentDeclarationKind(node2)){ - case 1 /* ExportsProperty */ : - kind = 0 /* Named */ ; - break; - case 2 /* ModuleExports */ : - kind = 2 /* ExportEquals */ ; - break; - default: - return void 0; - } - const sym = useLhsSymbol ? checker.getSymbolAtLocation(getNameOfAccessExpression(cast(node2.left, isAccessExpression))) : symbol; - return sym && exportInfo(sym, kind); - } - } - function getImport() { - const isImport3 = isNodeImport(node); - if (!isImport3) return void 0; - let importedSymbol = checker.getImmediateAliasedSymbol(symbol); - if (!importedSymbol) return void 0; - importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker); - if (importedSymbol.escapedName === "export=") { - importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker); - if (importedSymbol === void 0) return void 0; - } - const importedName = symbolEscapedNameNoDefault(importedSymbol); - if (importedName === void 0 || importedName === "default" /* Default */ || importedName === symbol.escapedName) return { - kind: 0 /* Import */ , - symbol: importedSymbol - }; - } - function exportInfo(symbol2, kind) { - const exportInfo2 = getExportInfo(symbol2, kind, checker); - return exportInfo2 && { - kind: 1 /* Export */ , - symbol: symbol2, - exportInfo: exportInfo2 - }; - } - function getExportKindForDeclaration(node2) { - return hasSyntacticModifier(node2, 1024 /* Default */ ) ? 1 /* Default */ : 0 /* Named */ ; - } - } - function getExportEqualsLocalSymbol(importedSymbol, checker) { - var _a2, _b; - if (importedSymbol.flags & 2097152 /* Alias */ ) return checker.getImmediateAliasedSymbol(importedSymbol); - const decl = Debug.checkDefined(importedSymbol.valueDeclaration); - if (isExportAssignment(decl)) return (_a2 = tryCast(decl.expression, canHaveSymbol)) == null ? void 0 : _a2.symbol; - else if (isBinaryExpression(decl)) return (_b = tryCast(decl.right, canHaveSymbol)) == null ? void 0 : _b.symbol; - else if (isSourceFile(decl)) return decl.symbol; - return void 0; - } - function getExportNode(parent2, node) { - const declaration = isVariableDeclaration(parent2) ? parent2 : isBindingElement(parent2) ? walkUpBindingElementsAndPatterns(parent2) : void 0; - if (declaration) return parent2.name !== node ? void 0 : isCatchClause(declaration.parent) ? void 0 : isVariableStatement(declaration.parent.parent) ? declaration.parent.parent : void 0; - else return parent2; - } - function isNodeImport(node) { - const { parent: parent2 } = node; - switch(parent2.kind){ - case 268 /* ImportEqualsDeclaration */ : - return parent2.name === node && isExternalModuleImportEquals(parent2); - case 273 /* ImportSpecifier */ : - return !parent2.propertyName; - case 270 /* ImportClause */ : - case 271 /* NamespaceImport */ : - Debug.assert(parent2.name === node); - return true; - case 205 /* BindingElement */ : - return isInJSFile(node) && isVariableDeclarationInitializedToBareOrAccessedRequire(parent2.parent.parent); - default: - return false; - } - } - function getExportInfo(exportSymbol, exportKind, checker) { - const moduleSymbol = exportSymbol.parent; - if (!moduleSymbol) return void 0; - const exportingModuleSymbol = checker.getMergedSymbol(moduleSymbol); - return isExternalModuleSymbol(exportingModuleSymbol) ? { - exportingModuleSymbol: exportingModuleSymbol, - exportKind: exportKind - } : void 0; + function doChange37(changeTracker, sf, node) { + const jsx = flattenInvalidBinaryExpr(node); + if (jsx) changeTracker.replaceNode(sf, node, factory.createJsxFragment(factory.createJsxOpeningFragment(), jsx, factory.createJsxJsxClosingFragment())); } - function skipExportSpecifierSymbol(symbol, checker) { - if (symbol.declarations) for (const declaration of symbol.declarations){ - if (isExportSpecifier(declaration) && !declaration.propertyName && !declaration.parent.parent.moduleSpecifier) return checker.getExportSpecifierLocalTargetSymbol(declaration) || symbol; - else if (isPropertyAccessExpression(declaration) && isModuleExportsAccessExpression(declaration.expression) && !isPrivateIdentifier(declaration.name)) return checker.getSymbolAtLocation(declaration); - else if (isShorthandPropertyAssignment(declaration) && isBinaryExpression(declaration.parent.parent) && getAssignmentDeclarationKind(declaration.parent.parent) === 2 /* ModuleExports */ ) return checker.getExportSpecifierLocalTargetSymbol(declaration.name); + function flattenInvalidBinaryExpr(node) { + const children = []; + let current = node; + while(true){ + if (isBinaryExpression(current) && nodeIsMissing(current.operatorToken) && current.operatorToken.kind === 28 /* CommaToken */ ) { + children.push(current.left); + if (isJsxChild(current.right)) { + children.push(current.right); + return children; + } else if (isBinaryExpression(current.right)) { + current = current.right; + continue; + } else return void 0; + } else return void 0; } - return symbol; - } - function getContainingModuleSymbol(importer, checker) { - return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol); - } - function getSourceFileLikeForImportDeclaration(node) { - if (node.kind === 210 /* CallExpression */ ) return node.getSourceFile(); - const { parent: parent2 } = node; - if (parent2.kind === 308 /* SourceFile */ ) return parent2; - Debug.assert(parent2.kind === 265 /* ModuleBlock */ ); - return cast(parent2.parent, isAmbientModuleDeclaration); } - function isAmbientModuleDeclaration(node) { - return node.kind === 264 /* ModuleDeclaration */ && node.name.kind === 10 /* StringLiteral */ ; - } - function isExternalModuleImportEquals(eq) { - return eq.moduleReference.kind === 280 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 10 /* StringLiteral */ ; - } - var ExportKind2, ImportExport; - var init_importTracker = __esm({ - "src/services/importTracker.ts" () { + var fixID2, errorCodes56; + var init_wrapJsxInFragment = __esm({ + "src/services/codefixes/wrapJsxInFragment.ts" () { "use strict"; init_ts4(); - ExportKind2 = /* @__PURE__ */ ((ExportKind3)=>{ - ExportKind3[ExportKind3["Named"] = 0] = "Named"; - ExportKind3[ExportKind3["Default"] = 1] = "Default"; - ExportKind3[ExportKind3["ExportEquals"] = 2] = "ExportEquals"; - return ExportKind3; - })(ExportKind2 || {}); - ImportExport = /* @__PURE__ */ ((ImportExport2)=>{ - ImportExport2[ImportExport2["Import"] = 0] = "Import"; - ImportExport2[ImportExport2["Export"] = 1] = "Export"; - return ImportExport2; - })(ImportExport || {}); + init_ts_codefix(); + fixID2 = "wrapJsxInFragment"; + errorCodes56 = [ + Diagnostics.JSX_expressions_must_have_one_parent_element.code + ]; + registerCodeFix({ + errorCodes: errorCodes56, + getCodeActions: function getCodeActionsToWrapJsxInFragment(context) { + const { sourceFile: sourceFile, span: span } = context; + const node = findNodeToFix(sourceFile, span.start); + if (!node) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange37(t, sourceFile, node)); + return [ + createCodeFixAction(fixID2, changes, Diagnostics.Wrap_in_JSX_fragment, fixID2, Diagnostics.Wrap_all_unparented_JSX_in_JSX_fragment) + ]; + }, + fixIds: [ + fixID2 + ], + getAllCodeActions: (context)=>codeFixAll(context, errorCodes56, (changes, diag2)=>{ + const node = findNodeToFix(context.sourceFile, diag2.start); + if (!node) return void 0; + doChange37(changes, context.sourceFile, node); + }) + }); } }); - // src/services/findAllReferences.ts - function nodeEntry(node, kind = 1 /* Node */ ) { + // src/services/codefixes/convertToMappedObjectType.ts + function getInfo19(sourceFile, pos) { + const token = getTokenAtPosition(sourceFile, pos); + const indexSignature = tryCast(token.parent.parent, isIndexSignatureDeclaration); + if (!indexSignature) return void 0; + const container = isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : tryCast(indexSignature.parent.parent, isTypeAliasDeclaration); + if (!container) return void 0; return { - kind: kind, - node: node.name || node, - context: getContextNodeForNodeEntry(node) + indexSignature: indexSignature, + container: container }; } - function isContextWithStartAndEndNode(node) { - return node && node.kind === void 0; + function createTypeAliasFromInterface(declaration, type) { + return factory.createTypeAliasDeclaration(declaration.modifiers, declaration.name, declaration.typeParameters, type); } - function getContextNodeForNodeEntry(node) { - if (isDeclaration(node)) return getContextNode(node); - if (!node.parent) return void 0; - if (!isDeclaration(node.parent) && !isExportAssignment(node.parent)) { - if (isInJSFile(node)) { - const binaryExpression = isBinaryExpression(node.parent) ? node.parent : isAccessExpression(node.parent) && isBinaryExpression(node.parent.parent) && node.parent.parent.left === node.parent ? node.parent.parent : void 0; - if (binaryExpression && getAssignmentDeclarationKind(binaryExpression) !== 0 /* None */ ) return getContextNode(binaryExpression); - } - if (isJsxOpeningElement(node.parent) || isJsxClosingElement(node.parent)) return node.parent.parent; - else if (isJsxSelfClosingElement(node.parent) || isLabeledStatement(node.parent) || isBreakOrContinueStatement(node.parent)) return node.parent; - else if (isStringLiteralLike(node)) { - const validImport = tryGetImportFromModuleSpecifier(node); - if (validImport) { - const declOrStatement = findAncestor(validImport, (node2)=>isDeclaration(node2) || isStatement(node2) || isJSDocTag(node2)); - return isDeclaration(declOrStatement) ? getContextNode(declOrStatement) : declOrStatement; - } + function doChange38(changes, sourceFile, { indexSignature: indexSignature, container: container }) { + const members = isInterfaceDeclaration(container) ? container.members : container.type.members; + const otherMembers = members.filter((member)=>!isIndexSignatureDeclaration(member)); + const parameter = first(indexSignature.parameters); + const mappedTypeParameter = factory.createTypeParameterDeclaration(/*modifiers*/ void 0, cast(parameter.name, isIdentifier), parameter.type); + const mappedIntersectionType = factory.createMappedTypeNode(hasEffectiveReadonlyModifier(indexSignature) ? factory.createModifier(148 /* ReadonlyKeyword */ ) : void 0, mappedTypeParameter, /*nameType*/ void 0, indexSignature.questionToken, indexSignature.type, /*members*/ void 0); + const intersectionType = factory.createIntersectionTypeNode([ + ...getAllSuperTypeNodes(container), + mappedIntersectionType, + ...otherMembers.length ? [ + factory.createTypeLiteralNode(otherMembers) + ] : emptyArray + ]); + changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType)); + } + var fixId45, errorCodes57; + var init_convertToMappedObjectType = __esm({ + "src/services/codefixes/convertToMappedObjectType.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId45 = "fixConvertToMappedObjectType"; + errorCodes57 = [ + Diagnostics.An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_object_type_instead.code + ]; + registerCodeFix({ + errorCodes: errorCodes57, + getCodeActions: function getCodeActionsToConvertToMappedTypeObject(context) { + const { sourceFile: sourceFile, span: span } = context; + const info = getInfo19(sourceFile, span.start); + if (!info) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange38(t, sourceFile, info)); + const name = idText(info.container.name); + return [ + createCodeFixAction(fixId45, changes, [ + Diagnostics.Convert_0_to_mapped_object_type, + name + ], fixId45, [ + Diagnostics.Convert_0_to_mapped_object_type, + name + ]) + ]; + }, + fixIds: [ + fixId45 + ], + getAllCodeActions: (context)=>codeFixAll(context, errorCodes57, (changes, diag2)=>{ + const info = getInfo19(diag2.file, diag2.start); + if (info) doChange38(changes, diag2.file, info); + }) + }); + } + }); + // src/services/codefixes/removeAccidentalCallParentheses.ts + var fixId46, errorCodes58; + var init_removeAccidentalCallParentheses = __esm({ + "src/services/codefixes/removeAccidentalCallParentheses.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId46 = "removeAccidentalCallParentheses"; + errorCodes58 = [ + Diagnostics.This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without.code + ]; + registerCodeFix({ + errorCodes: errorCodes58, + getCodeActions (context) { + const callExpression = findAncestor(getTokenAtPosition(context.sourceFile, context.span.start), isCallExpression); + if (!callExpression) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>{ + t.deleteRange(context.sourceFile, { + pos: callExpression.expression.end, + end: callExpression.end + }); + }); + return [ + createCodeFixActionWithoutFixAll(fixId46, changes, Diagnostics.Remove_parentheses) + ]; + }, + fixIds: [ + fixId46 + ] + }); + } + }); + // src/services/codefixes/removeUnnecessaryAwait.ts + function makeChange10(changeTracker, sourceFile, span) { + const awaitKeyword = tryCast(getTokenAtPosition(sourceFile, span.start), (node)=>node.kind === 135 /* AwaitKeyword */ ); + const awaitExpression = awaitKeyword && tryCast(awaitKeyword.parent, isAwaitExpression); + if (!awaitExpression) return; + let expressionToReplace = awaitExpression; + const hasSurroundingParens = isParenthesizedExpression(awaitExpression.parent); + if (hasSurroundingParens) { + const leftMostExpression = getLeftmostExpression(awaitExpression.expression, /*stopAtCallExpressions*/ false); + if (isIdentifier(leftMostExpression)) { + const precedingToken = findPrecedingToken(awaitExpression.parent.pos, sourceFile); + if (precedingToken && precedingToken.kind !== 105 /* NewKeyword */ ) expressionToReplace = awaitExpression.parent; } - const propertyName = findAncestor(node, isComputedPropertyName); - return propertyName ? getContextNode(propertyName.parent) : void 0; } - if (node.parent.name === node || // node is name of declaration, use parent - isConstructorDeclaration(node.parent) || isExportAssignment(node.parent) || // Property name of the import export specifier or binding pattern, use parent - (isImportOrExportSpecifier(node.parent) || isBindingElement(node.parent)) && node.parent.propertyName === node || // Is default export - node.kind === 88 /* DefaultKeyword */ && hasSyntacticModifier(node.parent, 1025 /* ExportDefault */ )) return getContextNode(node.parent); - return void 0; + changeTracker.replaceNode(sourceFile, expressionToReplace, awaitExpression.expression); } - function getContextNode(node) { - if (!node) return void 0; - switch(node.kind){ - case 257 /* VariableDeclaration */ : - return !isVariableDeclarationList(node.parent) || node.parent.declarations.length !== 1 ? node : isVariableStatement(node.parent.parent) ? node.parent.parent : isForInOrOfStatement(node.parent.parent) ? getContextNode(node.parent.parent) : node.parent; - case 205 /* BindingElement */ : - return getContextNode(node.parent.parent); - case 273 /* ImportSpecifier */ : - return node.parent.parent.parent; - case 278 /* ExportSpecifier */ : - case 271 /* NamespaceImport */ : - return node.parent.parent; - case 270 /* ImportClause */ : - case 277 /* NamespaceExport */ : - return node.parent; - case 223 /* BinaryExpression */ : - return isExpressionStatement(node.parent) ? node.parent : node; - case 247 /* ForOfStatement */ : - case 246 /* ForInStatement */ : - return { - start: node.initializer, - end: node.expression - }; - case 299 /* PropertyAssignment */ : - case 300 /* ShorthandPropertyAssignment */ : - return isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent) ? getContextNode(findAncestor(node.parent, (node2)=>isBinaryExpression(node2) || isForInOrOfStatement(node2))) : node; - default: - return node; + var fixId47, errorCodes59; + var init_removeUnnecessaryAwait = __esm({ + "src/services/codefixes/removeUnnecessaryAwait.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId47 = "removeUnnecessaryAwait"; + errorCodes59 = [ + Diagnostics.await_has_no_effect_on_the_type_of_this_expression.code + ]; + registerCodeFix({ + errorCodes: errorCodes59, + getCodeActions: function getCodeActionsToRemoveUnnecessaryAwait(context) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>makeChange10(t, context.sourceFile, context.span)); + if (changes.length > 0) return [ + createCodeFixAction(fixId47, changes, Diagnostics.Remove_unnecessary_await, fixId47, Diagnostics.Remove_all_unnecessary_uses_of_await) + ]; + }, + fixIds: [ + fixId47 + ], + getAllCodeActions: (context)=>{ + return codeFixAll(context, errorCodes59, (changes, diag2)=>makeChange10(changes, diag2.file, diag2)); + } + }); } + }); + // src/services/codefixes/splitTypeOnlyImport.ts + function getImportDeclaration2(sourceFile, span) { + return findAncestor(getTokenAtPosition(sourceFile, span.start), isImportDeclaration); } - function toContextSpan(textSpan, sourceFile, context) { - if (!context) return void 0; - const contextSpan = isContextWithStartAndEndNode(context) ? getTextSpan(context.start, sourceFile, context.end) : getTextSpan(context, sourceFile); - return contextSpan.start !== textSpan.start || contextSpan.length !== textSpan.length ? { - contextSpan: contextSpan - } : void 0; + function splitTypeOnlyImport(changes, importDeclaration, context) { + if (!importDeclaration) return; + const importClause = Debug.checkDefined(importDeclaration.importClause); + changes.replaceNode(context.sourceFile, importDeclaration, factory.updateImportDeclaration(importDeclaration, importDeclaration.modifiers, factory.updateImportClause(importClause, importClause.isTypeOnly, importClause.name, /*namedBindings*/ void 0), importDeclaration.moduleSpecifier, importDeclaration.assertClause)); + changes.insertNodeAfter(context.sourceFile, importDeclaration, factory.createImportDeclaration(/*modifiers*/ void 0, factory.updateImportClause(importClause, importClause.isTypeOnly, /*name*/ void 0, importClause.namedBindings), importDeclaration.moduleSpecifier, importDeclaration.assertClause)); } - function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { - const node = getTouchingPropertyName(sourceFile, position); - const options = { - use: 1 /* References */ - }; - const referencedSymbols = Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options); - const checker = program.getTypeChecker(); - const adjustedNode = Core.getAdjustedNode(node, options); - const symbol = isDefinitionForReference(adjustedNode) ? checker.getSymbolAtLocation(adjustedNode) : void 0; - return !referencedSymbols || !referencedSymbols.length ? void 0 : mapDefined(referencedSymbols, ({ definition: definition , references: references })=>// Only include referenced symbols that have a valid definition. - definition && { - definition: checker.runWithCancellationToken(cancellationToken, (checker2)=>definitionToReferencedSymbolDefinitionInfo(definition, checker2, node)), - references: references.map((r)=>toReferencedSymbolEntry(r, symbol)) + var errorCodes60, fixId48; + var init_splitTypeOnlyImport = __esm({ + "src/services/codefixes/splitTypeOnlyImport.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + errorCodes60 = [ + Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both.code + ]; + fixId48 = "splitTypeOnlyImport"; + registerCodeFix({ + errorCodes: errorCodes60, + fixIds: [ + fixId48 + ], + getCodeActions: function getCodeActionsToSplitTypeOnlyImport(context) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>{ + return splitTypeOnlyImport(t, getImportDeclaration2(context.sourceFile, context.span), context); + }); + if (changes.length) return [ + createCodeFixAction(fixId48, changes, Diagnostics.Split_into_two_separate_import_declarations, fixId48, Diagnostics.Split_all_invalid_type_only_imports) + ]; + }, + getAllCodeActions: (context)=>codeFixAll(context, errorCodes60, (changes, error2)=>{ + splitTypeOnlyImport(changes, getImportDeclaration2(context.sourceFile, error2), context); + }) }); - } - function isDefinitionForReference(node) { - return node.kind === 88 /* DefaultKeyword */ || !!getDeclarationFromName(node) || isLiteralComputedPropertyDeclarationName(node) || node.kind === 135 /* ConstructorKeyword */ && isConstructorDeclaration(node.parent); - } - function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { - const node = getTouchingPropertyName(sourceFile, position); - let referenceEntries; - const entries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); - if (node.parent.kind === 208 /* PropertyAccessExpression */ || node.parent.kind === 205 /* BindingElement */ || node.parent.kind === 209 /* ElementAccessExpression */ || node.kind === 106 /* SuperKeyword */ ) referenceEntries = entries && [ - ...entries - ]; - else if (entries) { - const queue = createQueue(entries); - const seenNodes = /* @__PURE__ */ new Map(); - while(!queue.isEmpty()){ - const entry = queue.dequeue(); - if (!addToSeen(seenNodes, getNodeId(entry.node))) continue; - referenceEntries = append(referenceEntries, entry); - const entries2 = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, entry.node, entry.node.pos); - if (entries2) queue.enqueue(...entries2); - } } + }); + // src/services/codefixes/convertConstToLet.ts + function getInfo20(sourceFile, pos, program) { + var _a; const checker = program.getTypeChecker(); - return map(referenceEntries, (entry)=>toImplementationLocation(entry, checker)); + const symbol = checker.getSymbolAtLocation(getTokenAtPosition(sourceFile, pos)); + if (symbol === void 0) return; + const declaration = tryCast((_a = symbol == null ? void 0 : symbol.valueDeclaration) == null ? void 0 : _a.parent, isVariableDeclarationList); + if (declaration === void 0) return; + const constToken = findChildOfKind(declaration, 87 /* ConstKeyword */ , sourceFile); + if (constToken === void 0) return; + return { + symbol: symbol, + token: constToken + }; } - function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { - if (node.kind === 308 /* SourceFile */ ) return void 0; - const checker = program.getTypeChecker(); - if (node.parent.kind === 300 /* ShorthandPropertyAssignment */ ) { - const result = []; - Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, (node2)=>result.push(nodeEntry(node2))); - return result; - } else if (node.kind === 106 /* SuperKeyword */ || isSuperProperty(node.parent)) { - const symbol = checker.getSymbolAtLocation(node); - return symbol.valueDeclaration && [ - nodeEntry(symbol.valueDeclaration) + function doChange39(changes, sourceFile, token) { + changes.replaceNode(sourceFile, token, factory.createToken(121 /* LetKeyword */ )); + } + var fixId49, errorCodes61; + var init_convertConstToLet = __esm({ + "src/services/codefixes/convertConstToLet.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId49 = "fixConvertConstToLet"; + errorCodes61 = [ + Diagnostics.Cannot_assign_to_0_because_it_is_a_constant.code ]; - } else return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { - implementations: true, - use: 1 /* References */ - }); + registerCodeFix({ + errorCodes: errorCodes61, + getCodeActions: function getCodeActionsToConvertConstToLet(context) { + const { sourceFile: sourceFile, span: span, program: program } = context; + const info = getInfo20(sourceFile, span.start, program); + if (info === void 0) return; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange39(t, sourceFile, info.token)); + return [ + createCodeFixActionMaybeFixAll(fixId49, changes, Diagnostics.Convert_const_to_let, fixId49, Diagnostics.Convert_all_const_to_let) + ]; + }, + getAllCodeActions: (context)=>{ + const { program: program } = context; + const seen = /* @__PURE__ */ new Map(); + return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes)=>{ + eachDiagnostic(context, errorCodes61, (diag2)=>{ + const info = getInfo20(diag2.file, diag2.start, program); + if (info) { + if (addToSeen(seen, getSymbolId(info.symbol))) return doChange39(changes, diag2.file, info.token); + } + return void 0; + }); + })); + }, + fixIds: [ + fixId49 + ] + }); + } + }); + // src/services/codefixes/fixExpectedComma.ts + function getInfo21(sourceFile, pos, _) { + const node = getTokenAtPosition(sourceFile, pos); + return node.kind === 27 /* SemicolonToken */ && node.parent && (isObjectLiteralExpression(node.parent) || isArrayLiteralExpression(node.parent)) ? { + node: node + } : void 0; } - function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) { - return map(flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), (entry)=>convertEntry(entry, node, program.getTypeChecker())); + function doChange40(changes, sourceFile, { node: node }) { + const newNode = factory.createToken(28 /* CommaToken */ ); + changes.replaceNode(sourceFile, node, newNode); } - function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options = {}, sourceFilesSet = new Set(sourceFiles.map((f)=>f.fileName))) { - return flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet)); + var fixId50, expectedErrorCode, errorCodes62; + var init_fixExpectedComma = __esm({ + "src/services/codefixes/fixExpectedComma.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixId50 = "fixExpectedComma"; + expectedErrorCode = Diagnostics._0_expected.code; + errorCodes62 = [ + expectedErrorCode + ]; + registerCodeFix({ + errorCodes: errorCodes62, + getCodeActions (context) { + const { sourceFile: sourceFile } = context; + const info = getInfo21(sourceFile, context.span.start, context.errorCode); + if (!info) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange40(t, sourceFile, info)); + return [ + createCodeFixAction(fixId50, changes, [ + Diagnostics.Change_0_to_1, + ";", + "," + ], fixId50, [ + Diagnostics.Change_0_to_1, + ";", + "," + ]) + ]; + }, + fixIds: [ + fixId50 + ], + getAllCodeActions: (context)=>codeFixAll(context, errorCodes62, (changes, diag2)=>{ + const info = getInfo21(diag2.file, diag2.start, diag2.code); + if (info) doChange40(changes, context.sourceFile, info); + }) + }); + } + }); + // src/services/codefixes/fixAddVoidToPromise.ts + function makeChange11(changes, sourceFile, span, program, seen) { + const node = getTokenAtPosition(sourceFile, span.start); + if (!isIdentifier(node) || !isCallExpression(node.parent) || node.parent.expression !== node || node.parent.arguments.length !== 0) return; + const checker = program.getTypeChecker(); + const symbol = checker.getSymbolAtLocation(node); + const decl = symbol == null ? void 0 : symbol.valueDeclaration; + if (!decl || !isParameter(decl) || !isNewExpression(decl.parent.parent)) return; + if (seen == null ? void 0 : seen.has(decl)) return; + seen == null || seen.add(decl); + const typeArguments = getEffectiveTypeArguments(decl.parent.parent); + if (some(typeArguments)) { + const typeArgument = typeArguments[0]; + const needsParens = !isUnionTypeNode(typeArgument) && !isParenthesizedTypeNode(typeArgument) && isParenthesizedTypeNode(factory.createUnionTypeNode([ + typeArgument, + factory.createKeywordTypeNode(116 /* VoidKeyword */ ) + ]).types[0]); + if (needsParens) changes.insertText(sourceFile, typeArgument.pos, "("); + changes.insertText(sourceFile, typeArgument.end, needsParens ? ") | void" : " | void"); + } else { + const signature = checker.getResolvedSignature(node.parent); + const parameter = signature == null ? void 0 : signature.parameters[0]; + const parameterType = parameter && checker.getTypeOfSymbolAtLocation(parameter, decl.parent.parent); + if (isInJSFile(decl)) { + if (!parameterType || parameterType.flags & 3 /* AnyOrUnknown */ ) { + changes.insertText(sourceFile, decl.parent.parent.end, `)`); + changes.insertText(sourceFile, skipTrivia(sourceFile.text, decl.parent.parent.pos), `/** @type {Promise} */(`); + } + } else if (!parameterType || parameterType.flags & 2 /* Unknown */ ) changes.insertText(sourceFile, decl.parent.parent.expression.end, ""); + } } - function flattenEntries(referenceSymbols) { - return referenceSymbols && flatMap(referenceSymbols, (r)=>r.references); + function getEffectiveTypeArguments(node) { + var _a; + if (isInJSFile(node)) { + if (isParenthesizedExpression(node.parent)) { + const jsDocType = (_a = getJSDocTypeTag(node.parent)) == null ? void 0 : _a.typeExpression.type; + if (jsDocType && isTypeReferenceNode(jsDocType) && isIdentifier(jsDocType.typeName) && idText(jsDocType.typeName) === "Promise") return jsDocType.typeArguments; + } + } else return node.typeArguments; } - function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { - const info = (()=>{ - switch(def.type){ - case 0 /* Symbol */ : - { - const { symbol: symbol } = def; - const { displayParts: displayParts2 , kind: kind2 } = getDefinitionKindAndDisplayParts(symbol, checker, originalNode); - const name2 = displayParts2.map((p)=>p.text).join(""); - const declaration = symbol.declarations && firstOrUndefined(symbol.declarations); - const node = declaration ? getNameOfDeclaration(declaration) || declaration : originalNode; - return { - ...getFileAndTextSpanFromNode(node), - name: name2, - kind: kind2, - displayParts: displayParts2, - context: getContextNode(declaration) - }; - } - case 1 /* Label */ : - { - const { node: node } = def; - return { - ...getFileAndTextSpanFromNode(node), - name: node.text, - kind: "label" /* label */ , - displayParts: [ - displayPart(node.text, 17 /* text */ ) - ] - }; - } - case 2 /* Keyword */ : - { - const { node: node } = def; - const name2 = tokenToString(node.kind); - return { - ...getFileAndTextSpanFromNode(node), - name: name2, - kind: "keyword" /* keyword */ , - displayParts: [ - { - text: name2, - kind: "keyword" /* keyword */ - } - ] - }; - } - case 3 /* This */ : - { - const { node: node } = def; - const symbol = checker.getSymbolAtLocation(node); - const displayParts2 = symbol && ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node.getSourceFile(), getContainerNode(node), node).displayParts || [ - textPart("this") - ]; - return { - ...getFileAndTextSpanFromNode(node), - name: "this", - kind: "var" /* variableElement */ , - displayParts: displayParts2 - }; - } - case 4 /* String */ : - { - const { node: node } = def; - return { - ...getFileAndTextSpanFromNode(node), - name: node.text, - kind: "var" /* variableElement */ , - displayParts: [ - displayPart(getTextOfNode(node), 8 /* stringLiteral */ ) - ] - }; - } - case 5 /* TripleSlashReference */ : - return { - textSpan: createTextSpanFromRange(def.reference), - sourceFile: def.file, - name: def.reference.fileName, - kind: "string" /* string */ , - displayParts: [ - displayPart(`"${def.reference.fileName}"`, 8 /* stringLiteral */ ) - ] - }; - default: - return Debug.assertNever(def); + var fixName7, fixId51, errorCodes63; + var init_fixAddVoidToPromise = __esm({ + "src/services/codefixes/fixAddVoidToPromise.ts" () { + "use strict"; + init_ts4(); + init_ts_codefix(); + fixName7 = "addVoidToPromise"; + fixId51 = "addVoidToPromise"; + errorCodes63 = [ + Diagnostics.Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_without_arguments.code, + Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise.code + ]; + registerCodeFix({ + errorCodes: errorCodes63, + fixIds: [ + fixId51 + ], + getCodeActions (context) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t)=>makeChange11(t, context.sourceFile, context.span, context.program)); + if (changes.length > 0) return [ + createCodeFixAction(fixName7, changes, Diagnostics.Add_void_to_Promise_resolved_without_a_value, fixId51, Diagnostics.Add_void_to_all_Promises_resolved_without_a_value) + ]; + }, + getAllCodeActions (context) { + return codeFixAll(context, errorCodes63, (changes, diag2)=>makeChange11(changes, diag2.file, diag2, context.program, /* @__PURE__ */ new Set())); + } + }); + } + }); + // src/services/_namespaces/ts.codefix.ts + var ts_codefix_exports = {}; + __export(ts_codefix_exports, { + PreserveOptionalFlags: ()=>PreserveOptionalFlags, + addNewNodeForMemberSymbol: ()=>addNewNodeForMemberSymbol, + codeFixAll: ()=>codeFixAll, + createCodeFixAction: ()=>createCodeFixAction, + createCodeFixActionMaybeFixAll: ()=>createCodeFixActionMaybeFixAll, + createCodeFixActionWithoutFixAll: ()=>createCodeFixActionWithoutFixAll, + createCombinedCodeActions: ()=>createCombinedCodeActions, + createFileTextChanges: ()=>createFileTextChanges, + createImportAdder: ()=>createImportAdder, + createImportSpecifierResolver: ()=>createImportSpecifierResolver, + createJsonPropertyAssignment: ()=>createJsonPropertyAssignment, + createMissingMemberNodes: ()=>createMissingMemberNodes, + createSignatureDeclarationFromCallExpression: ()=>createSignatureDeclarationFromCallExpression, + createSignatureDeclarationFromSignature: ()=>createSignatureDeclarationFromSignature, + createStubbedBody: ()=>createStubbedBody, + eachDiagnostic: ()=>eachDiagnostic, + findAncestorMatchingSpan: ()=>findAncestorMatchingSpan, + findJsonProperty: ()=>findJsonProperty, + generateAccessorFromProperty: ()=>generateAccessorFromProperty, + getAccessorConvertiblePropertyAtPosition: ()=>getAccessorConvertiblePropertyAtPosition, + getAllFixes: ()=>getAllFixes, + getAllSupers: ()=>getAllSupers, + getArgumentTypesAndTypeParameters: ()=>getArgumentTypesAndTypeParameters, + getFixes: ()=>getFixes, + getImportCompletionAction: ()=>getImportCompletionAction, + getImportKind: ()=>getImportKind, + getJSDocTypedefNodes: ()=>getJSDocTypedefNodes, + getNoopSymbolTrackerWithResolver: ()=>getNoopSymbolTrackerWithResolver, + getPromoteTypeOnlyCompletionAction: ()=>getPromoteTypeOnlyCompletionAction, + getSupportedErrorCodes: ()=>getSupportedErrorCodes, + importFixName: ()=>importFixName, + importSymbols: ()=>importSymbols, + moduleSpecifierToValidIdentifier: ()=>moduleSpecifierToValidIdentifier, + moduleSymbolToValidIdentifier: ()=>moduleSymbolToValidIdentifier, + parameterShouldGetTypeFromJSDoc: ()=>parameterShouldGetTypeFromJSDoc, + registerCodeFix: ()=>registerCodeFix, + setJsonCompilerOptionValue: ()=>setJsonCompilerOptionValue, + setJsonCompilerOptionValues: ()=>setJsonCompilerOptionValues, + tryGetAutoImportableReferenceFromTypeNode: ()=>tryGetAutoImportableReferenceFromTypeNode, + typeToAutoImportableTypeNode: ()=>typeToAutoImportableTypeNode + }); + var init_ts_codefix = __esm({ + "src/services/_namespaces/ts.codefix.ts" () { + "use strict"; + init_codeFixProvider(); + init_addConvertToUnknownForNonOverlappingTypes(); + init_addEmptyExportDeclaration(); + init_addMissingAsync(); + init_addMissingAwait(); + init_addMissingConst(); + init_addMissingDeclareProperty(); + init_addMissingInvocationForDecorator(); + init_addNameToNamelessParameter(); + init_addOptionalPropertyUndefined(); + init_annotateWithTypeFromJSDoc(); + init_convertFunctionToEs6Class(); + init_convertToAsyncFunction(); + init_convertToEsModule(); + init_correctQualifiedNameToIndexedAccessType(); + init_convertToTypeOnlyExport(); + init_convertToTypeOnlyImport(); + init_convertTypedefToType(); + init_convertLiteralTypeToMappedType(); + init_fixClassIncorrectlyImplementsInterface(); + init_importFixes(); + init_fixAddMissingConstraint(); + init_fixOverrideModifier(); + init_fixNoPropertyAccessFromIndexSignature(); + init_fixImplicitThis(); + init_fixImportNonExportedMember(); + init_fixIncorrectNamedTupleSyntax(); + init_fixSpelling(); + init_returnValueCorrect(); + init_fixAddMissingMember(); + init_fixAddMissingNewOperator(); + init_fixCannotFindModule(); + init_fixClassDoesntImplementInheritedAbstractMember(); + init_fixClassSuperMustPrecedeThisAccess(); + init_fixConstructorForDerivedNeedSuperCall(); + init_fixEnableJsxFlag(); + init_fixNaNEquality(); + init_fixModuleAndTargetOptions(); + init_fixPropertyAssignment(); + init_fixExtendsInterfaceBecomesImplements(); + init_fixForgottenThisPropertyAccess(); + init_fixInvalidJsxCharacters(); + init_fixUnmatchedParameter(); + init_fixUnreferenceableDecoratorMetadata(); + init_fixUnusedIdentifier(); + init_fixUnreachableCode(); + init_fixUnusedLabel(); + init_fixJSDocTypes(); + init_fixMissingCallParentheses(); + init_fixAwaitInSyncFunction(); + init_fixPropertyOverrideAccessor(); + init_inferFromUsage(); + init_fixReturnTypeInAsyncFunction(); + init_disableJsDiagnostics(); + init_helpers2(); + init_generateAccessors(); + init_fixInvalidImportSyntax(); + init_fixStrictClassInitialization(); + init_requireInTs(); + init_useDefaultImport(); + init_useBigintLiteral(); + init_fixAddModuleReferTypeMissingTypeof(); + init_wrapJsxInFragment(); + init_convertToMappedObjectType(); + init_removeAccidentalCallParentheses(); + init_removeUnnecessaryAwait(); + init_splitTypeOnlyImport(); + init_convertConstToLet(); + init_fixExpectedComma(); + init_fixAddVoidToPromise(); + } + }); + // src/services/completions.ts + function originIsThisType(origin) { + return !!(origin.kind & 1 /* ThisType */ ); + } + function originIsSymbolMember(origin) { + return !!(origin.kind & 2 /* SymbolMember */ ); + } + function originIsExport(origin) { + return !!(origin && origin.kind & 4 /* Export */ ); + } + function originIsResolvedExport(origin) { + return !!(origin && origin.kind === 32 /* ResolvedExport */ ); + } + function originIncludesSymbolName(origin) { + return originIsExport(origin) || originIsResolvedExport(origin) || originIsComputedPropertyName(origin); + } + function originIsPackageJsonImport(origin) { + return (originIsExport(origin) || originIsResolvedExport(origin)) && !!origin.isFromPackageJson; + } + function originIsPromise(origin) { + return !!(origin.kind & 8 /* Promise */ ); + } + function originIsNullableMember(origin) { + return !!(origin.kind & 16 /* Nullable */ ); + } + function originIsTypeOnlyAlias(origin) { + return !!(origin && origin.kind & 64 /* TypeOnlyAlias */ ); + } + function originIsObjectLiteralMethod(origin) { + return !!(origin && origin.kind & 128 /* ObjectLiteralMethod */ ); + } + function originIsIgnore(origin) { + return !!(origin && origin.kind & 256 /* Ignore */ ); + } + function originIsComputedPropertyName(origin) { + return !!(origin && origin.kind & 512 /* ComputedPropertyName */ ); + } + function resolvingModuleSpecifiers(logPrefix, host, resolver, program, position, preferences, isForImportStatementCompletion, isValidTypeOnlyUseSite, cb) { + var _a, _b, _c; + const start = timestamp(); + const needsFullResolution = isForImportStatementCompletion || moduleResolutionSupportsPackageJsonExportsAndImports(getEmitModuleResolutionKind(program.getCompilerOptions())); + let skippedAny = false; + let ambientCount = 0; + let resolvedCount = 0; + let resolvedFromCacheCount = 0; + let cacheAttemptCount = 0; + const result = cb({ + tryResolve: tryResolve, + skippedAny: ()=>skippedAny, + resolvedAny: ()=>resolvedCount > 0, + resolvedBeyondLimit: ()=>resolvedCount > moduleSpecifierResolutionLimit + }); + const hitRateMessage = cacheAttemptCount ? ` (${(resolvedFromCacheCount / cacheAttemptCount * 100).toFixed(1)}% hit rate)` : ""; + (_a = host.log) == null || _a.call(host, `${logPrefix}: resolved ${resolvedCount} module specifiers, plus ${ambientCount} ambient and ${resolvedFromCacheCount} from cache${hitRateMessage}`); + (_b = host.log) == null || _b.call(host, `${logPrefix}: response is ${skippedAny ? "incomplete" : "complete"}`); + (_c = host.log) == null || _c.call(host, `${logPrefix}: ${timestamp() - start}`); + return result; + function tryResolve(exportInfo, isFromAmbientModule) { + if (isFromAmbientModule) { + const result3 = resolver.getModuleSpecifierForBestExportInfo(exportInfo, position, isValidTypeOnlyUseSite); + if (result3) ambientCount++; + return result3 || "failed"; } - })(); - const { sourceFile: sourceFile , textSpan: textSpan , name: name , kind: kind , displayParts: displayParts , context: context } = info; - return { - containerKind: "" /* unknown */ , - containerName: "", - fileName: sourceFile.fileName, - kind: kind, - name: name, - textSpan: textSpan, - displayParts: displayParts, - ...toContextSpan(textSpan, sourceFile, context) - }; + const shouldResolveModuleSpecifier = needsFullResolution || preferences.allowIncompleteCompletions && resolvedCount < moduleSpecifierResolutionLimit; + const shouldGetModuleSpecifierFromCache = !shouldResolveModuleSpecifier && preferences.allowIncompleteCompletions && cacheAttemptCount < moduleSpecifierResolutionCacheAttemptLimit; + const result2 = shouldResolveModuleSpecifier || shouldGetModuleSpecifierFromCache ? resolver.getModuleSpecifierForBestExportInfo(exportInfo, position, isValidTypeOnlyUseSite, shouldGetModuleSpecifierFromCache) : void 0; + if (!shouldResolveModuleSpecifier && !shouldGetModuleSpecifierFromCache || shouldGetModuleSpecifierFromCache && !result2) skippedAny = true; + resolvedCount += (result2 == null ? void 0 : result2.computedWithoutCacheCount) || 0; + resolvedFromCacheCount += exportInfo.length - ((result2 == null ? void 0 : result2.computedWithoutCacheCount) || 0); + if (shouldGetModuleSpecifierFromCache) cacheAttemptCount++; + return result2 || (needsFullResolution ? "failed" : "skipped"); + } } - function getFileAndTextSpanFromNode(node) { - const sourceFile = node.getSourceFile(); - return { - sourceFile: sourceFile, - textSpan: getTextSpan(isComputedPropertyName(node) ? node.expression : node, sourceFile) - }; + function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter, completionKind, cancellationToken, formatContext, includeSymbol = false) { + var _a; + const { previousToken: previousToken } = getRelevantTokens(position, sourceFile); + if (triggerCharacter && !isInString(sourceFile, position, previousToken) && !isValidTrigger(sourceFile, triggerCharacter, previousToken, position)) return void 0; + if (triggerCharacter === " ") { + if (preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) return { + isGlobalCompletion: true, + isMemberCompletion: false, + isNewIdentifierLocation: true, + isIncomplete: true, + entries: [] + }; + return void 0; + } + const compilerOptions = program.getCompilerOptions(); + const checker = program.getTypeChecker(); + const incompleteCompletionsCache = preferences.allowIncompleteCompletions ? (_a = host.getIncompleteCompletionsCache) == null ? void 0 : _a.call(host) : void 0; + if (incompleteCompletionsCache && completionKind === 3 /* TriggerForIncompleteCompletions */ && previousToken && isIdentifier(previousToken)) { + const incompleteContinuation = continuePreviousIncompleteResponse(incompleteCompletionsCache, sourceFile, previousToken, program, host, preferences, cancellationToken, position); + if (incompleteContinuation) return incompleteContinuation; + } else incompleteCompletionsCache == null || incompleteCompletionsCache.clear(); + const stringCompletions = ts_Completions_StringCompletions_exports.getStringLiteralCompletions(sourceFile, position, previousToken, compilerOptions, host, program, log, preferences, includeSymbol); + if (stringCompletions) return stringCompletions; + if (previousToken && isBreakOrContinueStatement(previousToken.parent) && (previousToken.kind === 83 /* BreakKeyword */ || previousToken.kind === 88 /* ContinueKeyword */ || previousToken.kind === 80 /* Identifier */ )) return getLabelCompletionAtPosition(previousToken.parent); + const completionData = getCompletionData(program, log, sourceFile, compilerOptions, position, preferences, /*detailsEntryId*/ void 0, host, formatContext, cancellationToken); + if (!completionData) return void 0; + switch(completionData.kind){ + case 0 /* Data */ : + const response = completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences, formatContext, position, includeSymbol); + if (response == null ? void 0 : response.isIncomplete) incompleteCompletionsCache == null || incompleteCompletionsCache.set(response); + return response; + case 1 /* JsDocTagName */ : + return jsdocCompletionInfo([ + ...ts_JsDoc_exports.getJSDocTagNameCompletions(), + ...getJSDocParameterCompletions(sourceFile, position, checker, compilerOptions, preferences, /*tagNameOnly*/ true) + ]); + case 2 /* JsDocTag */ : + return jsdocCompletionInfo([ + ...ts_JsDoc_exports.getJSDocTagCompletions(), + ...getJSDocParameterCompletions(sourceFile, position, checker, compilerOptions, preferences, /*tagNameOnly*/ false) + ]); + case 3 /* JsDocParameterName */ : + return jsdocCompletionInfo(ts_JsDoc_exports.getJSDocParameterNameCompletions(completionData.tag)); + case 4 /* Keywords */ : + return specificKeywordCompletionInfo(completionData.keywordCompletions, completionData.isNewIdentifierLocation); + default: + return Debug.assertNever(completionData); + } } - function getDefinitionKindAndDisplayParts(symbol, checker, node) { - const meaning = Core.getIntersectingMeaningFromDeclarations(node, symbol); - const enclosingDeclaration = symbol.declarations && firstOrUndefined(symbol.declarations) || node; - const { displayParts: displayParts , symbolKind: symbolKind } = ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning); + function compareCompletionEntries(entryInArray, entryToInsert) { + var _a, _b; + let result = compareStringsCaseSensitiveUI(entryInArray.sortText, entryToInsert.sortText); + if (result === 0 /* EqualTo */ ) result = compareStringsCaseSensitiveUI(entryInArray.name, entryToInsert.name); + if (result === 0 /* EqualTo */ && ((_a = entryInArray.data) == null ? void 0 : _a.moduleSpecifier) && ((_b = entryToInsert.data) == null ? void 0 : _b.moduleSpecifier)) result = compareNumberOfDirectorySeparators(entryInArray.data.moduleSpecifier, entryToInsert.data.moduleSpecifier); + if (result === 0 /* EqualTo */ ) return -1 /* LessThan */ ; + return result; + } + function completionEntryDataIsResolved(data) { + return !!(data == null ? void 0 : data.moduleSpecifier); + } + function continuePreviousIncompleteResponse(cache, file, location, program, host, preferences, cancellationToken, position) { + const previousResponse = cache.get(); + if (!previousResponse) return void 0; + const touchNode = getTouchingPropertyName(file, position); + const lowerCaseTokenText = location.text.toLowerCase(); + const exportMap = getExportInfoMap(file, host, program, preferences, cancellationToken); + const newEntries = resolvingModuleSpecifiers("continuePreviousIncompleteResponse", host, ts_codefix_exports.createImportSpecifierResolver(file, program, host, preferences), program, location.getStart(), preferences, /*isForImportStatementCompletion*/ false, isValidTypeOnlyAliasUseSite(location), (context)=>{ + const entries = mapDefined(previousResponse.entries, (entry)=>{ + var _a; + if (!entry.hasAction || !entry.source || !entry.data || completionEntryDataIsResolved(entry.data)) return entry; + if (!charactersFuzzyMatchInString(entry.name, lowerCaseTokenText)) return void 0; + const { origin: origin } = Debug.checkDefined(getAutoImportSymbolFromCompletionEntryData(entry.name, entry.data, program, host)); + const info = exportMap.get(file.path, entry.data.exportMapKey); + const result = info && context.tryResolve(info, !isExternalModuleNameRelative(stripQuotes(origin.moduleSymbol.name))); + if (result === "skipped") return entry; + if (!result || result === "failed") { + (_a = host.log) == null || _a.call(host, `Unexpected failure resolving auto import for '${entry.name}' from '${entry.source}'`); + return void 0; + } + const newOrigin = { + ...origin, + kind: 32 /* ResolvedExport */ , + moduleSpecifier: result.moduleSpecifier + }; + entry.data = originToCompletionEntryData(newOrigin); + entry.source = getSourceFromOrigin(newOrigin); + entry.sourceDisplay = [ + textPart(newOrigin.moduleSpecifier) + ]; + return entry; + }); + if (!context.skippedAny()) previousResponse.isIncomplete = void 0; + return entries; + }); + previousResponse.entries = newEntries; + previousResponse.flags = (previousResponse.flags || 0) | 4 /* IsContinuation */ ; + previousResponse.optionalReplacementSpan = getOptionalReplacementSpan(touchNode); + return previousResponse; + } + function jsdocCompletionInfo(entries) { return { - displayParts: displayParts, - kind: symbolKind + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: false, + entries: entries }; } - function toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixText) { + function getJSDocParameterCompletions(sourceFile, position, checker, options, preferences, tagNameOnly) { + const currentToken = getTokenAtPosition(sourceFile, position); + if (!isJSDocTag(currentToken) && !isJSDoc(currentToken)) return []; + const jsDoc = isJSDoc(currentToken) ? currentToken : currentToken.parent; + if (!isJSDoc(jsDoc)) return []; + const func = jsDoc.parent; + if (!isFunctionLike(func)) return []; + const isJs = isSourceFileJS(sourceFile); + const isSnippet = preferences.includeCompletionsWithSnippetText || void 0; + const paramTagCount = countWhere(jsDoc.tags, (tag)=>isJSDocParameterTag(tag) && tag.getEnd() <= position); + return mapDefined(func.parameters, (param)=>{ + if (getJSDocParameterTags(param).length) return void 0; + if (isIdentifier(param.name)) { + const tabstopCounter = { + tabstop: 1 + }; + const paramName = param.name.text; + let displayText = getJSDocParamAnnotation(paramName, param.initializer, param.dotDotDotToken, isJs, /*isObject*/ false, /*isSnippet*/ false, checker, options, preferences); + let snippetText = isSnippet ? getJSDocParamAnnotation(paramName, param.initializer, param.dotDotDotToken, isJs, /*isObject*/ false, /*isSnippet*/ true, checker, options, preferences, tabstopCounter) : void 0; + if (tagNameOnly) { + displayText = displayText.slice(1); + if (snippetText) snippetText = snippetText.slice(1); + } + return { + name: displayText, + kind: "parameter" /* parameterElement */ , + sortText: SortText.LocationPriority, + insertText: isSnippet ? snippetText : void 0, + isSnippet: isSnippet + }; + } else if (param.parent.parameters.indexOf(param) === paramTagCount) { + const paramPath = `param${paramTagCount}`; + const displayTextResult = generateJSDocParamTagsForDestructuring(paramPath, param.name, param.initializer, param.dotDotDotToken, isJs, /*isSnippet*/ false, checker, options, preferences); + const snippetTextResult = isSnippet ? generateJSDocParamTagsForDestructuring(paramPath, param.name, param.initializer, param.dotDotDotToken, isJs, /*isSnippet*/ true, checker, options, preferences) : void 0; + let displayText = displayTextResult.join(getNewLineCharacter(options) + "* "); + let snippetText = snippetTextResult == null ? void 0 : snippetTextResult.join(getNewLineCharacter(options) + "* "); + if (tagNameOnly) { + displayText = displayText.slice(1); + if (snippetText) snippetText = snippetText.slice(1); + } + return { + name: displayText, + kind: "parameter" /* parameterElement */ , + sortText: SortText.LocationPriority, + insertText: isSnippet ? snippetText : void 0, + isSnippet: isSnippet + }; + } + }); + } + function generateJSDocParamTagsForDestructuring(path, pattern, initializer, dotDotDotToken, isJs, isSnippet, checker, options, preferences) { + if (!isJs) return [ + getJSDocParamAnnotation(path, initializer, dotDotDotToken, isJs, /*isObject*/ false, isSnippet, checker, options, preferences, { + tabstop: 1 + }) + ]; + return patternWorker(path, pattern, initializer, dotDotDotToken, { + tabstop: 1 + }); + function patternWorker(path2, pattern2, initializer2, dotDotDotToken2, counter) { + if (isObjectBindingPattern(pattern2) && !dotDotDotToken2) { + const oldTabstop = counter.tabstop; + const childCounter = { + tabstop: oldTabstop + }; + const rootParam = getJSDocParamAnnotation(path2, initializer2, dotDotDotToken2, isJs, /*isObject*/ true, isSnippet, checker, options, preferences, childCounter); + let childTags = []; + for (const element of pattern2.elements){ + const elementTags = elementWorker(path2, element, childCounter); + if (!elementTags) { + childTags = void 0; + break; + } else childTags.push(...elementTags); + } + if (childTags) { + counter.tabstop = childCounter.tabstop; + return [ + rootParam, + ...childTags + ]; + } + } + return [ + getJSDocParamAnnotation(path2, initializer2, dotDotDotToken2, isJs, /*isObject*/ false, isSnippet, checker, options, preferences, counter) + ]; + } + function elementWorker(path2, element, counter) { + if (!element.propertyName && isIdentifier(element.name) || isIdentifier(element.name)) { + const propertyName = element.propertyName ? tryGetTextOfPropertyName(element.propertyName) : element.name.text; + if (!propertyName) return void 0; + const paramName = `${path2}.${propertyName}`; + return [ + getJSDocParamAnnotation(paramName, element.initializer, element.dotDotDotToken, isJs, /*isObject*/ false, isSnippet, checker, options, preferences, counter) + ]; + } else if (element.propertyName) { + const propertyName = tryGetTextOfPropertyName(element.propertyName); + return propertyName && patternWorker(`${path2}.${propertyName}`, element.name, element.initializer, element.dotDotDotToken, counter); + } + return void 0; + } + } + function getJSDocParamAnnotation(paramName, initializer, dotDotDotToken, isJs, isObject, isSnippet, checker, options, preferences, tabstopCounter) { + if (isSnippet) Debug.assertIsDefined(tabstopCounter); + if (initializer) paramName = getJSDocParamNameWithInitializer(paramName, initializer); + if (isSnippet) paramName = escapeSnippetText(paramName); + if (isJs) { + let type = "*"; + if (isObject) { + Debug.assert(!dotDotDotToken, `Cannot annotate a rest parameter with type 'Object'.`); + type = "Object"; + } else { + if (initializer) { + const inferredType = checker.getTypeAtLocation(initializer.parent); + if (!(inferredType.flags & 16385 /* Void */ )) { + const sourceFile = initializer.getSourceFile(); + const quotePreference = getQuotePreference(sourceFile, preferences); + const builderFlags = quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : 0 /* None */ ; + const typeNode = checker.typeToTypeNode(inferredType, findAncestor(initializer, isFunctionLike), builderFlags); + if (typeNode) { + const printer = isSnippet ? createSnippetPrinter({ + removeComments: true, + module: options.module, + target: options.target + }) : createPrinter({ + removeComments: true, + module: options.module, + target: options.target + }); + setEmitFlags(typeNode, 1 /* SingleLine */ ); + type = printer.printNode(4 /* Unspecified */ , typeNode, sourceFile); + } + } + } + if (isSnippet && type === "*") type = `\${${tabstopCounter.tabstop++}:${type}}`; + } + const dotDotDot = !isObject && dotDotDotToken ? "..." : ""; + const description3 = isSnippet ? `\${${tabstopCounter.tabstop++}}` : ""; + return `@param {${dotDotDot}${type}} ${paramName} ${description3}`; + } else { + const description3 = isSnippet ? `\${${tabstopCounter.tabstop++}}` : ""; + return `@param ${paramName} ${description3}`; + } + } + function getJSDocParamNameWithInitializer(paramName, initializer) { + const initializerText = initializer.getText().trim(); + if (initializerText.includes("\n") || initializerText.length > 80) return `[${paramName}]`; + return `[${paramName}=${initializerText}]`; + } + function keywordToCompletionEntry(keyword) { return { - ...entryToDocumentSpan(entry), - ...providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker) + name: tokenToString(keyword), + kind: "keyword" /* keyword */ , + kindModifiers: "" /* none */ , + sortText: SortText.GlobalsOrKeywords }; } - function toReferencedSymbolEntry(entry, symbol) { - const referenceEntry = toReferenceEntry(entry); - if (!symbol) return referenceEntry; + function specificKeywordCompletionInfo(entries, isNewIdentifierLocation) { return { - ...referenceEntry, - isDefinition: entry.kind !== 0 /* Span */ && isDeclarationOfSymbol(entry.node, symbol) + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: isNewIdentifierLocation, + entries: entries.slice() }; } - function toReferenceEntry(entry) { - const documentSpan = entryToDocumentSpan(entry); - if (entry.kind === 0 /* Span */ ) return { - ...documentSpan, - isWriteAccess: false - }; - const { kind: kind , node: node } = entry; + function keywordCompletionData(keywordFilters, filterOutTsOnlyKeywords, isNewIdentifierLocation) { return { - ...documentSpan, - isWriteAccess: isWriteAccessForReference(node), - isInString: kind === 2 /* StringLiteral */ ? true : void 0 + kind: 4 /* Keywords */ , + keywordCompletions: getKeywordCompletions(keywordFilters, filterOutTsOnlyKeywords), + isNewIdentifierLocation: isNewIdentifierLocation }; } - function entryToDocumentSpan(entry) { - if (entry.kind === 0 /* Span */ ) return { - textSpan: entry.textSpan, - fileName: entry.fileName - }; - else { - const sourceFile = entry.node.getSourceFile(); - const textSpan = getTextSpan(entry.node, sourceFile); - return { - textSpan: textSpan, - fileName: sourceFile.fileName, - ...toContextSpan(textSpan, sourceFile, entry.context) - }; + function keywordFiltersFromSyntaxKind(keywordCompletion) { + switch(keywordCompletion){ + case 156 /* TypeKeyword */ : + return 8 /* TypeKeyword */ ; + default: + Debug.fail("Unknown mapping from SyntaxKind to KeywordCompletionFilters"); } } - function getPrefixAndSuffixText(entry, originalNode, checker) { - if (entry.kind !== 0 /* Span */ && isIdentifier(originalNode)) { - const { node: node , kind: kind } = entry; - const parent2 = node.parent; - const name = originalNode.text; - const isShorthandAssignment = isShorthandPropertyAssignment(parent2); - if (isShorthandAssignment || isObjectBindingElementWithoutPropertyName(parent2) && parent2.name === node && parent2.dotDotDotToken === void 0) { - const prefixColon = { - prefixText: name + ": " - }; - const suffixColon = { - suffixText: ": " + name - }; - if (kind === 3 /* SearchedLocalFoundProperty */ ) return prefixColon; - if (kind === 4 /* SearchedPropertyFoundLocal */ ) return suffixColon; - if (isShorthandAssignment) { - const grandParent = parent2.parent; - if (isObjectLiteralExpression(grandParent) && isBinaryExpression(grandParent.parent) && isModuleExportsAccessExpression(grandParent.parent.left)) return prefixColon; - return suffixColon; - } else return prefixColon; - } else if (isImportSpecifier(parent2) && !parent2.propertyName) { - const originalSymbol = isExportSpecifier(originalNode.parent) ? checker.getExportSpecifierLocalTargetSymbol(originalNode.parent) : checker.getSymbolAtLocation(originalNode); - return contains(originalSymbol.declarations, parent2) ? { - prefixText: name + " as " - } : emptyOptions; - } else if (isExportSpecifier(parent2) && !parent2.propertyName) return originalNode === entry.node || checker.getSymbolAtLocation(originalNode) === checker.getSymbolAtLocation(entry.node) ? { - prefixText: name + " as " - } : { - suffixText: " as " + name - }; - } - return emptyOptions; + function getOptionalReplacementSpan(location) { + return (location == null ? void 0 : location.kind) === 80 /* Identifier */ ? createTextSpanFromNode(location) : void 0; } - function toImplementationLocation(entry, checker) { - const documentSpan = entryToDocumentSpan(entry); - if (entry.kind !== 0 /* Span */ ) { - const { node: node } = entry; - return { - ...documentSpan, - ...implementationKindDisplayParts(node, checker) - }; - } else return { - ...documentSpan, - kind: "" /* unknown */ , - displayParts: [] + function completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences, formatContext, position, includeSymbol) { + const { symbols: symbols, contextToken: contextToken, completionKind: completionKind, isInSnippetScope: isInSnippetScope, isNewIdentifierLocation: isNewIdentifierLocation, location: location, propertyAccessToConvert: propertyAccessToConvert, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, isJsxInitializer: isJsxInitializer, isTypeOnlyLocation: isTypeOnlyLocation, isJsxIdentifierExpected: isJsxIdentifierExpected, isRightOfOpenTag: isRightOfOpenTag, isRightOfDotOrQuestionDot: isRightOfDotOrQuestionDot, importStatementCompletion: importStatementCompletion, insideJsDocTagTypeExpression: insideJsDocTagTypeExpression, symbolToSortTextMap: symbolToSortTextMap, hasUnresolvedAutoImports: hasUnresolvedAutoImports } = completionData; + let literals = completionData.literals; + const checker = program.getTypeChecker(); + if (getLanguageVariant(sourceFile.scriptKind) === 1 /* JSX */ ) { + const completionInfo = getJsxClosingTagCompletion(location, sourceFile); + if (completionInfo) return completionInfo; + } + const caseClause = findAncestor(contextToken, isCaseClause); + if (caseClause && (isCaseKeyword(contextToken) || isNodeDescendantOf(contextToken, caseClause.expression))) { + const tracker = newCaseClauseTracker(checker, caseClause.parent.clauses); + literals = literals.filter((literal)=>!tracker.hasValue(literal)); + symbols.forEach((symbol, i)=>{ + if (symbol.valueDeclaration && isEnumMember(symbol.valueDeclaration)) { + const value1 = checker.getConstantValue(symbol.valueDeclaration); + if (value1 !== void 0 && tracker.hasValue(value1)) symbolToOriginInfoMap[i] = { + kind: 256 /* Ignore */ + }; + } + }); + } + const entries = createSortedArray(); + const isChecked = isCheckedFile(sourceFile, compilerOptions); + if (isChecked && !isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* None */ ) return void 0; + const uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, /*replacementToken*/ void 0, contextToken, location, position, sourceFile, host, program, getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importStatementCompletion, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag, includeSymbol); + if (keywordFilters !== 0 /* None */ ) { + for (const keywordEntry of getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && isSourceFileJS(sourceFile)))if (isTypeOnlyLocation && isTypeKeyword(stringToToken(keywordEntry.name)) || !uniqueNames.has(keywordEntry.name)) { + uniqueNames.add(keywordEntry.name); + insertSorted(entries, keywordEntry, compareCompletionEntries, /*allowDuplicates*/ true); + } + } + for (const keywordEntry of getContextualKeywords(contextToken, position))if (!uniqueNames.has(keywordEntry.name)) { + uniqueNames.add(keywordEntry.name); + insertSorted(entries, keywordEntry, compareCompletionEntries, /*allowDuplicates*/ true); + } + for (const literal of literals){ + const literalEntry = createCompletionEntryForLiteral(sourceFile, preferences, literal); + uniqueNames.add(literalEntry.name); + insertSorted(entries, literalEntry, compareCompletionEntries, /*allowDuplicates*/ true); + } + if (!isChecked) getJSCompletionEntries(sourceFile, location.pos, uniqueNames, getEmitScriptTarget(compilerOptions), entries); + let caseBlock; + if (preferences.includeCompletionsWithInsertText && contextToken && !isRightOfOpenTag && !isRightOfDotOrQuestionDot && (caseBlock = findAncestor(contextToken, isCaseBlock))) { + const cases = getExhaustiveCaseSnippets(caseBlock, sourceFile, preferences, compilerOptions, host, program, formatContext); + if (cases) entries.push(cases.entry); + } + return { + flags: completionData.flags, + isGlobalCompletion: isInSnippetScope, + isIncomplete: preferences.allowIncompleteCompletions && hasUnresolvedAutoImports ? true : void 0, + isMemberCompletion: isMemberCompletionKind(completionKind), + isNewIdentifierLocation: isNewIdentifierLocation, + optionalReplacementSpan: getOptionalReplacementSpan(location), + entries: entries }; } - function implementationKindDisplayParts(node, checker) { - const symbol = checker.getSymbolAtLocation(isDeclaration(node) && node.name ? node.name : node); - if (symbol) return getDefinitionKindAndDisplayParts(symbol, checker, node); - else if (node.kind === 207 /* ObjectLiteralExpression */ ) return { - kind: "interface" /* interfaceElement */ , - displayParts: [ - punctuationPart(20 /* OpenParenToken */ ), - textPart("object literal"), - punctuationPart(21 /* CloseParenToken */ ) - ] - }; - else if (node.kind === 228 /* ClassExpression */ ) return { - kind: "local class" /* localClassElement */ , - displayParts: [ - punctuationPart(20 /* OpenParenToken */ ), - textPart("anonymous local class"), - punctuationPart(21 /* CloseParenToken */ ) - ] - }; - else return { - kind: getNodeKind(node), - displayParts: [] - }; + function isCheckedFile(sourceFile, compilerOptions) { + return !isSourceFileJS(sourceFile) || !!isCheckJsEnabledForFile(sourceFile, compilerOptions); } - function toHighlightSpan(entry) { - const documentSpan = entryToDocumentSpan(entry); - if (entry.kind === 0 /* Span */ ) return { - fileName: documentSpan.fileName, - span: { - textSpan: documentSpan.textSpan, - kind: "reference" /* reference */ + function getExhaustiveCaseSnippets(caseBlock, sourceFile, preferences, options, host, program, formatContext) { + const clauses = caseBlock.clauses; + const checker = program.getTypeChecker(); + const switchType = checker.getTypeAtLocation(caseBlock.parent.expression); + if (switchType && switchType.isUnion() && every(switchType.types, (type)=>type.isLiteral())) { + const tracker = newCaseClauseTracker(checker, clauses); + const target = getEmitScriptTarget(options); + const quotePreference = getQuotePreference(sourceFile, preferences); + const importAdder = ts_codefix_exports.createImportAdder(sourceFile, program, preferences, host); + const elements = []; + for (const type of switchType.types){ + if (type.flags & 1024 /* EnumLiteral */ ) { + Debug.assert(type.symbol, "An enum member type should have a symbol"); + Debug.assert(type.symbol.parent, "An enum member type should have a parent symbol (the enum symbol)"); + const enumValue = type.symbol.valueDeclaration && checker.getConstantValue(type.symbol.valueDeclaration); + if (enumValue !== void 0) { + if (tracker.hasValue(enumValue)) continue; + tracker.addValue(enumValue); + } + const typeNode = ts_codefix_exports.typeToAutoImportableTypeNode(checker, importAdder, type, caseBlock, target); + if (!typeNode) return void 0; + const expr = typeNodeToExpression(typeNode, target, quotePreference); + if (!expr) return void 0; + elements.push(expr); + } else if (!tracker.hasValue(type.value)) switch(typeof type.value){ + case "object": + elements.push(type.value.negative ? factory.createPrefixUnaryExpression(41 /* MinusToken */ , factory.createBigIntLiteral({ + negative: false, + base10Value: type.value.base10Value + })) : factory.createBigIntLiteral(type.value)); + break; + case "number": + elements.push(type.value < 0 ? factory.createPrefixUnaryExpression(41 /* MinusToken */ , factory.createNumericLiteral(-type.value)) : factory.createNumericLiteral(type.value)); + break; + case "string": + elements.push(factory.createStringLiteral(type.value, quotePreference === 0 /* Single */ )); + break; + } } - }; - const writeAccess = isWriteAccessForReference(entry.node); - const span = { - textSpan: documentSpan.textSpan, - kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */ , - isInString: entry.kind === 2 /* StringLiteral */ ? true : void 0, - ...documentSpan.contextSpan && { - contextSpan: documentSpan.contextSpan + if (elements.length === 0) return void 0; + const newClauses = map(elements, (element)=>factory.createCaseClause(element, [])); + const newLineChar = getNewLineOrDefaultFromHost(host, formatContext == null ? void 0 : formatContext.options); + const printer = createSnippetPrinter({ + removeComments: true, + module: options.module, + target: options.target, + newLine: getNewLineKind(newLineChar) + }); + const printNode = formatContext ? (node)=>printer.printAndFormatNode(4 /* Unspecified */ , node, sourceFile, formatContext) : (node)=>printer.printNode(4 /* Unspecified */ , node, sourceFile); + const insertText = map(newClauses, (clause, i)=>{ + if (preferences.includeCompletionsWithSnippetText) return `${printNode(clause)}$${i + 1}`; + return `${printNode(clause)}`; + }).join(newLineChar); + const firstClause = printer.printNode(4 /* Unspecified */ , newClauses[0], sourceFile); + return { + entry: { + name: `${firstClause} ...`, + kind: "" /* unknown */ , + sortText: SortText.GlobalsOrKeywords, + insertText: insertText, + hasAction: importAdder.hasFixes() || void 0, + source: "SwitchCases/" /* SwitchCases */ , + isSnippet: preferences.includeCompletionsWithSnippetText ? true : void 0 + }, + importAdder: importAdder + }; + } + return void 0; + } + function typeNodeToExpression(typeNode, languageVersion, quotePreference) { + switch(typeNode.kind){ + case 183 /* TypeReference */ : + const typeName = typeNode.typeName; + return entityNameToExpression(typeName, languageVersion, quotePreference); + case 199 /* IndexedAccessType */ : + const objectExpression = typeNodeToExpression(typeNode.objectType, languageVersion, quotePreference); + const indexExpression = typeNodeToExpression(typeNode.indexType, languageVersion, quotePreference); + return objectExpression && indexExpression && factory.createElementAccessExpression(objectExpression, indexExpression); + case 201 /* LiteralType */ : + const literal = typeNode.literal; + switch(literal.kind){ + case 11 /* StringLiteral */ : + return factory.createStringLiteral(literal.text, quotePreference === 0 /* Single */ ); + case 9 /* NumericLiteral */ : + return factory.createNumericLiteral(literal.text, literal.numericLiteralFlags); + } + return void 0; + case 196 /* ParenthesizedType */ : + const exp = typeNodeToExpression(typeNode.type, languageVersion, quotePreference); + return exp && (isIdentifier(exp) ? exp : factory.createParenthesizedExpression(exp)); + case 186 /* TypeQuery */ : + return entityNameToExpression(typeNode.exprName, languageVersion, quotePreference); + case 205 /* ImportType */ : + Debug.fail(`We should not get an import type after calling 'codefix.typeToAutoImportableTypeNode'.`); + } + return void 0; + } + function entityNameToExpression(entityName, languageVersion, quotePreference) { + if (isIdentifier(entityName)) return entityName; + const unescapedName = unescapeLeadingUnderscores(entityName.right.escapedText); + if (canUsePropertyAccess(unescapedName, languageVersion)) return factory.createPropertyAccessExpression(entityNameToExpression(entityName.left, languageVersion, quotePreference), unescapedName); + else return factory.createElementAccessExpression(entityNameToExpression(entityName.left, languageVersion, quotePreference), factory.createStringLiteral(unescapedName, quotePreference === 0 /* Single */ )); + } + function isMemberCompletionKind(kind) { + switch(kind){ + case 0 /* ObjectPropertyDeclaration */ : + case 3 /* MemberLike */ : + case 2 /* PropertyAccess */ : + return true; + default: + return false; + } + } + function getJsxClosingTagCompletion(location, sourceFile) { + const jsxClosingElement = findAncestor(location, (node)=>{ + switch(node.kind){ + case 287 /* JsxClosingElement */ : + return true; + case 44 /* SlashToken */ : + case 32 /* GreaterThanToken */ : + case 80 /* Identifier */ : + case 211 /* PropertyAccessExpression */ : + return false; + default: + return "quit"; } - }; + }); + if (jsxClosingElement) { + const hasClosingAngleBracket = !!findChildOfKind(jsxClosingElement, 32 /* GreaterThanToken */ , sourceFile); + const tagName = jsxClosingElement.parent.openingElement.tagName; + const closingTag = tagName.getText(sourceFile); + const fullClosingTag = closingTag + (hasClosingAngleBracket ? "" : ">"); + const replacementSpan = createTextSpanFromNode(jsxClosingElement.tagName); + const entry = { + name: fullClosingTag, + kind: "class" /* classElement */ , + kindModifiers: void 0, + sortText: SortText.LocationPriority + }; + return { + isGlobalCompletion: false, + isMemberCompletion: true, + isNewIdentifierLocation: false, + optionalReplacementSpan: replacementSpan, + entries: [ + entry + ] + }; + } + return; + } + function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + getNameTable(sourceFile).forEach((pos, name)=>{ + if (pos === position) return; + const realName = unescapeLeadingUnderscores(name); + if (!uniqueNames.has(realName) && isIdentifierText(realName, target)) { + uniqueNames.add(realName); + insertSorted(entries, { + name: realName, + kind: "warning" /* warning */ , + kindModifiers: "", + sortText: SortText.JavascriptIdentifiers, + isFromUncheckedFile: true + }, compareCompletionEntries); + } + }); + } + function completionNameForLiteral(sourceFile, preferences, literal) { + return typeof literal === "object" ? pseudoBigIntToString(literal) + "n" : isString(literal) ? quote(sourceFile, preferences, literal) : JSON.stringify(literal); + } + function createCompletionEntryForLiteral(sourceFile, preferences, literal) { return { - fileName: documentSpan.fileName, - span: span + name: completionNameForLiteral(sourceFile, preferences, literal), + kind: "string" /* string */ , + kindModifiers: "" /* none */ , + sortText: SortText.LocationPriority }; } - function getTextSpan(node, sourceFile, endNode2) { - let start = node.getStart(sourceFile); - let end = (endNode2 || node).getEnd(); - if (isStringLiteralLike(node) && end - start > 2) { - Debug.assert(endNode2 === void 0); - start += 1; - end -= 1; + function createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, position, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importStatementCompletion, useSemicolons, options, preferences, completionKind, formatContext, isJsxIdentifierExpected, isRightOfOpenTag, includeSymbol) { + var _a, _b; + let insertText; + let filterText; + let replacementSpan = getReplacementSpanForContextToken(replacementToken); + let data; + let isSnippet; + let source = getSourceFromOrigin(origin); + let sourceDisplay; + let hasAction; + let labelDetails; + const typeChecker = program.getTypeChecker(); + const insertQuestionDot = origin && originIsNullableMember(origin); + const useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess; + if (origin && originIsThisType(origin)) insertText = needsConvertPropertyAccess ? `this${insertQuestionDot ? "?." : ""}[${quotePropertyName(sourceFile, preferences, name)}]` : `this${insertQuestionDot ? "?." : "."}${name}`; + else if ((useBraces || insertQuestionDot) && propertyAccessToConvert) { + insertText = useBraces ? needsConvertPropertyAccess ? `[${quotePropertyName(sourceFile, preferences, name)}]` : `[${name}]` : name; + if (insertQuestionDot || propertyAccessToConvert.questionDotToken) insertText = `?.${insertText}`; + const dot = findChildOfKind(propertyAccessToConvert, 25 /* DotToken */ , sourceFile) || findChildOfKind(propertyAccessToConvert, 29 /* QuestionDotToken */ , sourceFile); + if (!dot) return void 0; + const end = startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end; + replacementSpan = createTextSpanFromBounds(dot.getStart(sourceFile), end); } - return createTextSpanFromBounds(start, end); + if (isJsxInitializer) { + if (insertText === void 0) insertText = name; + insertText = `{${insertText}}`; + if (typeof isJsxInitializer !== "boolean") replacementSpan = createTextSpanFromNode(isJsxInitializer, sourceFile); + } + if (origin && originIsPromise(origin) && propertyAccessToConvert) { + if (insertText === void 0) insertText = name; + const precedingToken = findPrecedingToken(propertyAccessToConvert.pos, sourceFile); + let awaitText = ""; + if (precedingToken && positionIsASICandidate(precedingToken.end, precedingToken.parent, sourceFile)) awaitText = ";"; + awaitText += `(await ${propertyAccessToConvert.expression.getText()})`; + insertText = needsConvertPropertyAccess ? `${awaitText}${insertText}` : `${awaitText}${insertQuestionDot ? "?." : "."}${insertText}`; + const isInAwaitExpression = tryCast(propertyAccessToConvert.parent, isAwaitExpression); + const wrapNode = isInAwaitExpression ? propertyAccessToConvert.parent : propertyAccessToConvert.expression; + replacementSpan = createTextSpanFromBounds(wrapNode.getStart(sourceFile), propertyAccessToConvert.end); + } + if (originIsResolvedExport(origin)) { + sourceDisplay = [ + textPart(origin.moduleSpecifier) + ]; + if (importStatementCompletion) { + ({ insertText: insertText, replacementSpan: replacementSpan } = getInsertTextAndReplacementSpanForImportCompletion(name, importStatementCompletion, origin, useSemicolons, sourceFile, options, preferences)); + isSnippet = preferences.includeCompletionsWithSnippetText ? true : void 0; + } + } + if ((origin == null ? void 0 : origin.kind) === 64 /* TypeOnlyAlias */ ) hasAction = true; + if (completionKind === 0 /* ObjectPropertyDeclaration */ && contextToken && ((_a = findPrecedingToken(contextToken.pos, sourceFile, contextToken)) == null ? void 0 : _a.kind) !== 28 /* CommaToken */ ) { + if (isMethodDeclaration(contextToken.parent.parent) || isGetAccessorDeclaration(contextToken.parent.parent) || isSetAccessorDeclaration(contextToken.parent.parent) || isSpreadAssignment(contextToken.parent) || ((_b = findAncestor(contextToken.parent, isPropertyAssignment)) == null ? void 0 : _b.getLastToken(sourceFile)) === contextToken || isShorthandPropertyAssignment(contextToken.parent) && getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line !== getLineAndCharacterOfPosition(sourceFile, position).line) { + source = "ObjectLiteralMemberWithComma/" /* ObjectLiteralMemberWithComma */ ; + hasAction = true; + } + } + if (preferences.includeCompletionsWithClassMemberSnippets && preferences.includeCompletionsWithInsertText && completionKind === 3 /* MemberLike */ && isClassLikeMemberCompletion(symbol, location, sourceFile)) { + let importAdder; + const memberCompletionEntry = getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, position, contextToken, formatContext); + if (memberCompletionEntry) { + ({ insertText: insertText, filterText: filterText, isSnippet: isSnippet, importAdder: importAdder } = memberCompletionEntry); + if (importAdder == null ? void 0 : importAdder.hasFixes()) { + hasAction = true; + source = "ClassMemberSnippet/" /* ClassMemberSnippet */ ; + } + } else return void 0; + } + if (origin && originIsObjectLiteralMethod(origin)) { + ({ insertText: insertText, isSnippet: isSnippet, labelDetails: labelDetails } = origin); + if (!preferences.useLabelDetailsInCompletionEntries) { + name = name + labelDetails.detail; + labelDetails = void 0; + } + source = "ObjectLiteralMethodSnippet/" /* ObjectLiteralMethodSnippet */ ; + sortText = SortText.SortBelow(sortText); + } + if (isJsxIdentifierExpected && !isRightOfOpenTag && preferences.includeCompletionsWithSnippetText && preferences.jsxAttributeCompletionStyle && preferences.jsxAttributeCompletionStyle !== "none" && !(isJsxAttribute(location.parent) && location.parent.initializer)) { + let useBraces2 = preferences.jsxAttributeCompletionStyle === "braces"; + const type = typeChecker.getTypeOfSymbolAtLocation(symbol, location); + if (preferences.jsxAttributeCompletionStyle === "auto" && !(type.flags & 528 /* BooleanLike */ ) && !(type.flags & 1048576 /* Union */ && find(type.types, (type2)=>!!(type2.flags & 528 /* BooleanLike */ )))) { + if (type.flags & 402653316 /* StringLike */ || type.flags & 1048576 /* Union */ && every(type.types, (type2)=>!!(type2.flags & 402686084 /* Undefined */ || isStringAndEmptyAnonymousObjectIntersection(type2)))) { + insertText = `${escapeSnippetText(name)}=${quote(sourceFile, preferences, "$1")}`; + isSnippet = true; + } else useBraces2 = true; + } + if (useBraces2) { + insertText = `${escapeSnippetText(name)}={$1}`; + isSnippet = true; + } + } + if (insertText !== void 0 && !preferences.includeCompletionsWithInsertText) return void 0; + if (originIsExport(origin) || originIsResolvedExport(origin)) { + data = originToCompletionEntryData(origin); + hasAction = !importStatementCompletion; + } + const parentNamedImportOrExport = findAncestor(location, isNamedImportsOrExports); + if ((parentNamedImportOrExport == null ? void 0 : parentNamedImportOrExport.kind) === 275 /* NamedImports */ ) { + const possibleToken = stringToToken(name); + if (parentNamedImportOrExport && possibleToken && (possibleToken === 135 /* AwaitKeyword */ || isNonContextualKeyword(possibleToken))) insertText = `${name} as ${name}_`; + } + return { + name: name, + kind: ts_SymbolDisplay_exports.getSymbolKind(typeChecker, symbol, location), + kindModifiers: ts_SymbolDisplay_exports.getSymbolModifiers(typeChecker, symbol), + sortText: sortText, + source: source, + hasAction: hasAction ? true : void 0, + isRecommended: isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker) || void 0, + insertText: insertText, + filterText: filterText, + replacementSpan: replacementSpan, + sourceDisplay: sourceDisplay, + labelDetails: labelDetails, + isSnippet: isSnippet, + isPackageJsonImport: originIsPackageJsonImport(origin) || void 0, + isImportStatementCompletion: !!importStatementCompletion || void 0, + data: data, + ...includeSymbol ? { + symbol: symbol + } : void 0 + }; } - function getTextSpanOfEntry(entry) { - return entry.kind === 0 /* Span */ ? entry.textSpan : getTextSpan(entry.node, entry.node.getSourceFile()); + function isClassLikeMemberCompletion(symbol, location, sourceFile) { + if (isInJSFile(location)) return false; + const memberFlags = 106500 /* EnumMemberExcludes */ ; + return !!(symbol.flags & memberFlags) && (isClassLike(location) || location.parent && location.parent.parent && isClassElement(location.parent) && location === location.parent.name && location.parent.getLastToken(sourceFile) === location.parent.name && isClassLike(location.parent.parent) || location.parent && isSyntaxList(location) && isClassLike(location.parent)); } - function isWriteAccessForReference(node) { - const decl = getDeclarationFromName(node); - return !!decl && declarationIsWriteAccess(decl) || node.kind === 88 /* DefaultKeyword */ || isWriteAccess(node); + function getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, position, contextToken, formatContext) { + const classLikeDeclaration = findAncestor(location, isClassLike); + if (!classLikeDeclaration) return void 0; + let isSnippet; + let insertText = name; + const filterText = name; + const checker = program.getTypeChecker(); + const sourceFile = location.getSourceFile(); + const printer = createSnippetPrinter({ + removeComments: true, + module: options.module, + target: options.target, + omitTrailingSemicolon: false, + newLine: getNewLineKind(getNewLineOrDefaultFromHost(host, formatContext == null ? void 0 : formatContext.options)) + }); + const importAdder = ts_codefix_exports.createImportAdder(sourceFile, program, preferences, host); + let body; + if (preferences.includeCompletionsWithSnippetText) { + isSnippet = true; + const emptyStmt = factory.createEmptyStatement(); + body = factory.createBlock([ + emptyStmt + ], /*multiLine*/ true); + setSnippetElement(emptyStmt, { + kind: 0 /* TabStop */ , + order: 0 + }); + } else body = factory.createBlock([], /*multiLine*/ true); + let modifiers = 0 /* None */ ; + const { modifiers: presentModifiers, range: eraseRange, decorators: presentDecorators } = getPresentModifiers(contextToken, sourceFile, position); + const isAbstract = presentModifiers & 256 /* Abstract */ && classLikeDeclaration.modifierFlagsCache & 256 /* Abstract */ ; + let completionNodes = []; + ts_codefix_exports.addNewNodeForMemberSymbol(symbol, classLikeDeclaration, sourceFile, { + program: program, + host: host + }, preferences, importAdder, // `addNewNodeForMemberSymbol` calls this callback function for each new member node + // it adds for the given member symbol. + // We store these member nodes in the `completionNodes` array. + // Note: there might be: + // - No nodes if `addNewNodeForMemberSymbol` cannot figure out a node for the member; + // - One node; + // - More than one node if the member is overloaded (e.g. a method with overload signatures). + (node)=>{ + let requiredModifiers = 0 /* None */ ; + if (isAbstract) requiredModifiers |= 256 /* Abstract */ ; + if (isClassElement(node) && checker.getMemberOverrideModifierStatus(classLikeDeclaration, node, symbol) === 1 /* NeedsOverride */ ) requiredModifiers |= 16384 /* Override */ ; + if (!completionNodes.length) modifiers = node.modifierFlagsCache | requiredModifiers; + node = factory.updateModifiers(node, modifiers); + completionNodes.push(node); + }, body, ts_codefix_exports.PreserveOptionalFlags.Property, !!isAbstract); + if (completionNodes.length) { + const isMethod = symbol.flags & 8192 /* Method */ ; + let allowedModifiers = modifiers | 16388 /* Public */ ; + if (!isMethod) allowedModifiers |= 66 /* Readonly */ ; + else allowedModifiers |= 512 /* Async */ ; + const allowedAndPresent = presentModifiers & allowedModifiers; + if (presentModifiers & ~allowedModifiers) return void 0; + if (modifiers & 16 /* Protected */ && allowedAndPresent & 4 /* Public */ ) modifiers &= -17 /* Protected */ ; + if (allowedAndPresent !== 0 /* None */ && !(allowedAndPresent & 4 /* Public */ )) modifiers &= -5 /* Public */ ; + modifiers |= allowedAndPresent; + completionNodes = completionNodes.map((node)=>factory.updateModifiers(node, modifiers)); + if (presentDecorators == null ? void 0 : presentDecorators.length) { + const lastNode = completionNodes[completionNodes.length - 1]; + if (canHaveDecorators(lastNode)) completionNodes[completionNodes.length - 1] = factory.updateModifierLike(lastNode, presentDecorators.concat(getModifiers(lastNode) || [])); + } + const format = 131073 /* NoTrailingNewLine */ ; + if (formatContext) insertText = printer.printAndFormatSnippetList(format, factory.createNodeArray(completionNodes), sourceFile, formatContext); + else insertText = printer.printSnippetList(format, factory.createNodeArray(completionNodes), sourceFile); + } + return { + insertText: insertText, + filterText: filterText, + isSnippet: isSnippet, + importAdder: importAdder, + eraseRange: eraseRange + }; } - function isDeclarationOfSymbol(node, target) { - var _a2; - if (!target) return false; - const source = getDeclarationFromName(node) || (node.kind === 88 /* DefaultKeyword */ ? node.parent : isLiteralComputedPropertyDeclarationName(node) ? node.parent.parent : node.kind === 135 /* ConstructorKeyword */ && isConstructorDeclaration(node.parent) ? node.parent.parent : void 0); - const commonjsSource = source && isBinaryExpression(source) ? source.left : void 0; - return !!(source && ((_a2 = target.declarations) == null ? void 0 : _a2.some((d)=>d === source || d === commonjsSource))); + function getPresentModifiers(contextToken, sourceFile, position) { + if (!contextToken || getLineAndCharacterOfPosition(sourceFile, position).line > getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line) return { + modifiers: 0 /* None */ + }; + let modifiers = 0 /* None */ ; + let decorators; + let contextMod; + const range = { + pos: position, + end: position + }; + if (isPropertyDeclaration(contextToken.parent) && contextToken.parent.modifiers) { + modifiers |= modifiersToFlags(contextToken.parent.modifiers) & 126975 /* Modifier */ ; + decorators = contextToken.parent.modifiers.filter(isDecorator) || []; + range.pos = Math.min(range.pos, contextToken.parent.modifiers.pos); + } + if (contextMod = isModifierLike2(contextToken)) { + const contextModifierFlag = modifierToFlag(contextMod); + if (!(modifiers & contextModifierFlag)) { + modifiers |= contextModifierFlag; + range.pos = Math.min(range.pos, contextToken.pos); + } + } + return { + modifiers: modifiers, + decorators: decorators, + range: range.pos !== position ? range : void 0 + }; } - function declarationIsWriteAccess(decl) { - if (!!(decl.flags & 16777216 /* Ambient */ )) return true; - switch(decl.kind){ - case 223 /* BinaryExpression */ : - case 205 /* BindingElement */ : - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : - case 88 /* DefaultKeyword */ : - case 263 /* EnumDeclaration */ : - case 302 /* EnumMember */ : - case 278 /* ExportSpecifier */ : - case 270 /* ImportClause */ : - case 268 /* ImportEqualsDeclaration */ : - case 273 /* ImportSpecifier */ : - case 261 /* InterfaceDeclaration */ : - case 341 /* JSDocCallbackTag */ : - case 349 /* JSDocTypedefTag */ : - case 288 /* JsxAttribute */ : - case 264 /* ModuleDeclaration */ : - case 267 /* NamespaceExportDeclaration */ : - case 271 /* NamespaceImport */ : - case 277 /* NamespaceExport */ : - case 166 /* Parameter */ : - case 300 /* ShorthandPropertyAssignment */ : - case 262 /* TypeAliasDeclaration */ : - case 165 /* TypeParameter */ : - return true; - case 299 /* PropertyAssignment */ : - return !isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 173 /* Constructor */ : - case 171 /* MethodDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - return !!decl.body; - case 257 /* VariableDeclaration */ : - case 169 /* PropertyDeclaration */ : - return !!decl.initializer || isCatchClause(decl.parent); - case 170 /* MethodSignature */ : - case 168 /* PropertySignature */ : - case 351 /* JSDocPropertyTag */ : - case 344 /* JSDocParameterTag */ : - return false; - default: - return Debug.failBadSyntaxKind(decl); + function isModifierLike2(node) { + if (isModifier(node)) return node.kind; + if (isIdentifier(node)) { + const originalKeywordKind = identifierToKeywordKind(node); + if (originalKeywordKind && isModifierKind(originalKeywordKind)) return originalKeywordKind; } + return void 0; } - var DefinitionKind, EntryKind, FindReferencesUse, Core; - var init_findAllReferences = __esm({ - "src/services/findAllReferences.ts" () { - "use strict"; - init_ts4(); - init_ts_FindAllReferences(); - DefinitionKind = /* @__PURE__ */ ((DefinitionKind2)=>{ - DefinitionKind2[DefinitionKind2["Symbol"] = 0] = "Symbol"; - DefinitionKind2[DefinitionKind2["Label"] = 1] = "Label"; - DefinitionKind2[DefinitionKind2["Keyword"] = 2] = "Keyword"; - DefinitionKind2[DefinitionKind2["This"] = 3] = "This"; - DefinitionKind2[DefinitionKind2["String"] = 4] = "String"; - DefinitionKind2[DefinitionKind2["TripleSlashReference"] = 5] = "TripleSlashReference"; - return DefinitionKind2; - })(DefinitionKind || {}); - EntryKind = /* @__PURE__ */ ((EntryKind2)=>{ - EntryKind2[EntryKind2["Span"] = 0] = "Span"; - EntryKind2[EntryKind2["Node"] = 1] = "Node"; - EntryKind2[EntryKind2["StringLiteral"] = 2] = "StringLiteral"; - EntryKind2[EntryKind2["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty"; - EntryKind2[EntryKind2["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal"; - return EntryKind2; - })(EntryKind || {}); - FindReferencesUse = /* @__PURE__ */ ((FindReferencesUse2)=>{ - FindReferencesUse2[FindReferencesUse2["Other"] = 0] = "Other"; - FindReferencesUse2[FindReferencesUse2["References"] = 1] = "References"; - FindReferencesUse2[FindReferencesUse2["Rename"] = 2] = "Rename"; - return FindReferencesUse2; - })(FindReferencesUse || {}); - ((Core2)=>{ - function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options = {}, sourceFilesSet = new Set(sourceFiles.map((f)=>f.fileName))) { - var _a2, _b, _c; - node = getAdjustedNode(node, options); - if (isSourceFile(node)) { - const resolvedRef = ts_GoToDefinition_exports.getReferenceAtPosition(node, position, program); - if (!(resolvedRef == null ? void 0 : resolvedRef.file)) return void 0; - const moduleSymbol = program.getTypeChecker().getMergedSymbol(resolvedRef.file.symbol); - if (moduleSymbol) return getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); - const fileIncludeReasons = program.getFileIncludeReasons(); - if (!fileIncludeReasons) return void 0; - return [ - { - definition: { - type: 5 /* TripleSlashReference */ , - reference: resolvedRef.reference, - file: node - }, - references: getReferencesForNonModule(resolvedRef.file, fileIncludeReasons, program) || emptyArray - } - ]; - } - if (!options.implementations) { - const special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); - if (special) return special; - } - const checker = program.getTypeChecker(); - const symbol = checker.getSymbolAtLocation(isConstructorDeclaration(node) && node.parent.name || node); - if (!symbol) { - if (!options.implementations && isStringLiteralLike(node)) { - if (isModuleSpecifierLike(node)) { - const fileIncludeReasons = program.getFileIncludeReasons(); - const referencedFileName = (_c = (_b = (_a2 = node.getSourceFile().resolvedModules) == null ? void 0 : _a2.get(node.text, getModeForUsageLocation(node.getSourceFile(), node))) == null ? void 0 : _b.resolvedModule) == null ? void 0 : _c.resolvedFileName; - const referencedFile = referencedFileName ? program.getSourceFile(referencedFileName) : void 0; - if (referencedFile) return [ - { - definition: { - type: 4 /* String */ , - node: node - }, - references: getReferencesForNonModule(referencedFile, fileIncludeReasons, program) || emptyArray - } - ]; - } - return getReferencesForStringLiteral(node, sourceFiles, checker, cancellationToken); - } - return void 0; + function getEntryForObjectLiteralMethodCompletion(symbol, name, enclosingDeclaration, program, host, options, preferences, formatContext) { + const isSnippet = preferences.includeCompletionsWithSnippetText || void 0; + let insertText = name; + const sourceFile = enclosingDeclaration.getSourceFile(); + const method = createObjectLiteralMethod(symbol, enclosingDeclaration, sourceFile, program, host, preferences); + if (!method) return void 0; + const printer = createSnippetPrinter({ + removeComments: true, + module: options.module, + target: options.target, + omitTrailingSemicolon: false, + newLine: getNewLineKind(getNewLineOrDefaultFromHost(host, formatContext == null ? void 0 : formatContext.options)) + }); + if (formatContext) insertText = printer.printAndFormatSnippetList(80 /* AllowTrailingComma */ , factory.createNodeArray([ + method + ], /*hasTrailingComma*/ true), sourceFile, formatContext); + else insertText = printer.printSnippetList(80 /* AllowTrailingComma */ , factory.createNodeArray([ + method + ], /*hasTrailingComma*/ true), sourceFile); + const signaturePrinter = createPrinter({ + removeComments: true, + module: options.module, + target: options.target, + omitTrailingSemicolon: true + }); + const methodSignature = factory.createMethodSignature(/*modifiers*/ void 0, /*name*/ "", method.questionToken, method.typeParameters, method.parameters, method.type); + const labelDetails = { + detail: signaturePrinter.printNode(4 /* Unspecified */ , methodSignature, sourceFile) + }; + return { + isSnippet: isSnippet, + insertText: insertText, + labelDetails: labelDetails + }; + } + function createObjectLiteralMethod(symbol, enclosingDeclaration, sourceFile, program, host, preferences) { + const declarations = symbol.getDeclarations(); + if (!(declarations && declarations.length)) return void 0; + const checker = program.getTypeChecker(); + const declaration = declarations[0]; + const name = getSynthesizedDeepClone(getNameOfDeclaration(declaration), /*includeTrivia*/ false); + const type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); + const quotePreference = getQuotePreference(sourceFile, preferences); + const builderFlags = 33554432 /* OmitThisParameter */ | (quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : 0 /* None */ ); + switch(declaration.kind){ + case 171 /* PropertySignature */ : + case 172 /* PropertyDeclaration */ : + case 173 /* MethodSignature */ : + case 174 /* MethodDeclaration */ : + { + let effectiveType = type.flags & 1048576 /* Union */ && type.types.length < 10 ? checker.getUnionType(type.types, 2 /* Subtype */ ) : type; + if (effectiveType.flags & 1048576 /* Union */ ) { + const functionTypes = filter(effectiveType.types, (type2)=>checker.getSignaturesOfType(type2, 0 /* Call */ ).length > 0); + if (functionTypes.length === 1) effectiveType = functionTypes[0]; + else return void 0; } - if (symbol.escapedName === "export=" /* ExportEquals */ ) return getReferencedSymbolsForModule(program, symbol.parent, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); - const moduleReferences = getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol, program, sourceFiles, cancellationToken, options, sourceFilesSet); - if (moduleReferences && !(symbol.flags & 33554432 /* Transient */ )) return moduleReferences; - const aliasedSymbol = getMergedAliasedSymbolOfNamespaceExportDeclaration(node, symbol, checker); - const moduleReferencesOfExportTarget = aliasedSymbol && getReferencedSymbolsForModuleIfDeclaredBySourceFile(aliasedSymbol, program, sourceFiles, cancellationToken, options, sourceFilesSet); - const references = getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options); - return mergeReferences(program, moduleReferences, references, moduleReferencesOfExportTarget); - } - Core2.getReferencedSymbolsForNode = getReferencedSymbolsForNode; - function getAdjustedNode(node, options) { - if (options.use === 1 /* References */ ) node = getAdjustedReferenceLocation(node); - else if (options.use === 2 /* Rename */ ) node = getAdjustedRenameLocation(node); - return node; - } - Core2.getAdjustedNode = getAdjustedNode; - function getReferencesForFileName(fileName, program, sourceFiles, sourceFilesSet = new Set(sourceFiles.map((f)=>f.fileName))) { - var _a2, _b; - const moduleSymbol = (_a2 = program.getSourceFile(fileName)) == null ? void 0 : _a2.symbol; - if (moduleSymbol) return ((_b = getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet)[0]) == null ? void 0 : _b.references) || emptyArray; - const fileIncludeReasons = program.getFileIncludeReasons(); - const referencedFile = program.getSourceFile(fileName); - return referencedFile && fileIncludeReasons && getReferencesForNonModule(referencedFile, fileIncludeReasons, program) || emptyArray; - } - Core2.getReferencesForFileName = getReferencesForFileName; - function getReferencesForNonModule(referencedFile, refFileMap, program) { - let entries; - const references = refFileMap.get(referencedFile.path) || emptyArray; - for (const ref of references)if (isReferencedFile(ref)) { - const referencingFile = program.getSourceFileByPath(ref.file); - const location = getReferencedFileLocation(program.getSourceFileByPath, ref); - if (isReferenceFileLocation(location)) entries = append(entries, { - kind: 0 /* Span */ , - fileName: referencingFile.fileName, - textSpan: createTextSpanFromRange(location) + const signatures = checker.getSignaturesOfType(effectiveType, 0 /* Call */ ); + if (signatures.length !== 1) return void 0; + const typeNode = checker.typeToTypeNode(effectiveType, enclosingDeclaration, builderFlags, ts_codefix_exports.getNoopSymbolTrackerWithResolver({ + program: program, + host: host + })); + if (!typeNode || !isFunctionTypeNode(typeNode)) return void 0; + let body; + if (preferences.includeCompletionsWithSnippetText) { + const emptyStmt = factory.createEmptyStatement(); + body = factory.createBlock([ + emptyStmt + ], /*multiLine*/ true); + setSnippetElement(emptyStmt, { + kind: 0 /* TabStop */ , + order: 0 }); - } - return entries; + } else body = factory.createBlock([], /*multiLine*/ true); + const parameters = typeNode.parameters.map((typedParam)=>factory.createParameterDeclaration(/*modifiers*/ void 0, typedParam.dotDotDotToken, typedParam.name, /*questionToken*/ void 0, /*type*/ void 0, typedParam.initializer)); + return factory.createMethodDeclaration(/*modifiers*/ void 0, /*asteriskToken*/ void 0, name, /*questionToken*/ void 0, /*typeParameters*/ void 0, parameters, /*type*/ void 0, body); } - function getMergedAliasedSymbolOfNamespaceExportDeclaration(node, symbol, checker) { - if (node.parent && isNamespaceExportDeclaration(node.parent)) { - const aliasedSymbol = checker.getAliasedSymbol(symbol); - const targetSymbol = checker.getMergedSymbol(aliasedSymbol); - if (aliasedSymbol !== targetSymbol) return targetSymbol; + default: + return void 0; + } + } + function createSnippetPrinter(printerOptions) { + let escapes; + const baseWriter = ts_textChanges_exports.createWriter(getNewLineCharacter(printerOptions)); + const printer = createPrinter(printerOptions, baseWriter); + const writer = { + ...baseWriter, + write: (s)=>escapingWrite(s, ()=>baseWriter.write(s)), + nonEscapingWrite: baseWriter.write, + writeLiteral: (s)=>escapingWrite(s, ()=>baseWriter.writeLiteral(s)), + writeStringLiteral: (s)=>escapingWrite(s, ()=>baseWriter.writeStringLiteral(s)), + writeSymbol: (s, symbol)=>escapingWrite(s, ()=>baseWriter.writeSymbol(s, symbol)), + writeParameter: (s)=>escapingWrite(s, ()=>baseWriter.writeParameter(s)), + writeComment: (s)=>escapingWrite(s, ()=>baseWriter.writeComment(s)), + writeProperty: (s)=>escapingWrite(s, ()=>baseWriter.writeProperty(s)) + }; + return { + printSnippetList: printSnippetList, + printAndFormatSnippetList: printAndFormatSnippetList, + printNode: printNode, + printAndFormatNode: printAndFormatNode + }; + function escapingWrite(s, write) { + const escaped = escapeSnippetText(s); + if (escaped !== s) { + const start = baseWriter.getTextPos(); + write(); + const end = baseWriter.getTextPos(); + escapes = append(escapes || (escapes = []), { + newText: escaped, + span: { + start: start, + length: end - start } - return void 0; - } - function getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol, program, sourceFiles, cancellationToken, options, sourceFilesSet) { - const moduleSourceFile = symbol.flags & 1536 /* Module */ && symbol.declarations && find(symbol.declarations, isSourceFile); - if (!moduleSourceFile) return void 0; - const exportEquals = symbol.exports.get("export=" /* ExportEquals */ ); - const moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet); - if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName)) return moduleReferences; - const checker = program.getTypeChecker(); - symbol = skipAlias(exportEquals, checker); - return mergeReferences(program, moduleReferences, getReferencedSymbolsForSymbol(symbol, /*node*/ void 0, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); + }); + } else write(); + } + function printSnippetList(format, list, sourceFile) { + const unescaped = printUnescapedSnippetList(format, list, sourceFile); + return escapes ? ts_textChanges_exports.applyChanges(unescaped, escapes) : unescaped; + } + function printUnescapedSnippetList(format, list, sourceFile) { + escapes = void 0; + writer.clear(); + printer.writeList(format, list, sourceFile, writer); + return writer.getText(); + } + function printAndFormatSnippetList(format, list, sourceFile, formatContext) { + const syntheticFile = { + text: printUnescapedSnippetList(format, list, sourceFile), + getLineAndCharacterOfPosition (pos) { + return getLineAndCharacterOfPosition(this, pos); } - function mergeReferences(program, ...referencesToMerge) { - let result; - for (const references of referencesToMerge){ - if (!references || !references.length) continue; - if (!result) { - result = references; - continue; - } - for (const entry of references){ - if (!entry.definition || entry.definition.type !== 0 /* Symbol */ ) { - result.push(entry); - continue; - } - const symbol = entry.definition.symbol; - const refIndex = findIndex(result, (ref)=>!!ref.definition && ref.definition.type === 0 /* Symbol */ && ref.definition.symbol === symbol); - if (refIndex === -1) { - result.push(entry); - continue; - } - const reference = result[refIndex]; - result[refIndex] = { - definition: reference.definition, - references: reference.references.concat(entry.references).sort((entry1, entry2)=>{ - const entry1File = getSourceFileIndexOfEntry(program, entry1); - const entry2File = getSourceFileIndexOfEntry(program, entry2); - if (entry1File !== entry2File) return compareValues(entry1File, entry2File); - const entry1Span = getTextSpanOfEntry(entry1); - const entry2Span = getTextSpanOfEntry(entry2); - return entry1Span.start !== entry2Span.start ? compareValues(entry1Span.start, entry2Span.start) : compareValues(entry1Span.length, entry2Span.length); - }) - }; - } - } - return result; + }; + const formatOptions = getFormatCodeSettingsForWriting(formatContext, sourceFile); + const changes = flatMap(list, (node)=>{ + const nodeWithPos = ts_textChanges_exports.assignPositionsToNode(node); + return ts_formatting_exports.formatNodeGivenIndentation(nodeWithPos, syntheticFile, sourceFile.languageVariant, /* indentation */ 0, /* delta */ 0, { + ...formatContext, + options: formatOptions + }); + }); + const allChanges = escapes ? stableSort(concatenate(changes, escapes), (a, b)=>compareTextSpans(a.span, b.span)) : changes; + return ts_textChanges_exports.applyChanges(syntheticFile.text, allChanges); + } + function printNode(hint, node, sourceFile) { + const unescaped = printUnescapedNode(hint, node, sourceFile); + return escapes ? ts_textChanges_exports.applyChanges(unescaped, escapes) : unescaped; + } + function printUnescapedNode(hint, node, sourceFile) { + escapes = void 0; + writer.clear(); + printer.writeNode(hint, node, sourceFile, writer); + return writer.getText(); + } + function printAndFormatNode(hint, node, sourceFile, formatContext) { + const syntheticFile = { + text: printUnescapedNode(hint, node, sourceFile), + getLineAndCharacterOfPosition (pos) { + return getLineAndCharacterOfPosition(this, pos); } - function getSourceFileIndexOfEntry(program, entry) { - const sourceFile = entry.kind === 0 /* Span */ ? program.getSourceFile(entry.fileName) : entry.node.getSourceFile(); - return program.getSourceFiles().indexOf(sourceFile); + }; + const formatOptions = getFormatCodeSettingsForWriting(formatContext, sourceFile); + const nodeWithPos = ts_textChanges_exports.assignPositionsToNode(node); + const changes = ts_formatting_exports.formatNodeGivenIndentation(nodeWithPos, syntheticFile, sourceFile.languageVariant, /* indentation */ 0, /* delta */ 0, { + ...formatContext, + options: formatOptions + }); + const allChanges = escapes ? stableSort(concatenate(changes, escapes), (a, b)=>compareTextSpans(a.span, b.span)) : changes; + return ts_textChanges_exports.applyChanges(syntheticFile.text, allChanges); + } + } + function originToCompletionEntryData(origin) { + const ambientModuleName = origin.fileName ? void 0 : stripQuotes(origin.moduleSymbol.name); + const isPackageJsonImport = origin.isFromPackageJson ? true : void 0; + if (originIsResolvedExport(origin)) { + const resolvedData = { + exportName: origin.exportName, + exportMapKey: origin.exportMapKey, + moduleSpecifier: origin.moduleSpecifier, + ambientModuleName: ambientModuleName, + fileName: origin.fileName, + isPackageJsonImport: isPackageJsonImport + }; + return resolvedData; + } + const unresolvedData = { + exportName: origin.exportName, + exportMapKey: origin.exportMapKey, + fileName: origin.fileName, + ambientModuleName: origin.fileName ? void 0 : stripQuotes(origin.moduleSymbol.name), + isPackageJsonImport: origin.isFromPackageJson ? true : void 0 + }; + return unresolvedData; + } + function completionEntryDataToSymbolOriginInfo(data, completionName, moduleSymbol) { + const isDefaultExport = data.exportName === "default" /* Default */ ; + const isFromPackageJson = !!data.isPackageJsonImport; + if (completionEntryDataIsResolved(data)) { + const resolvedOrigin = { + kind: 32 /* ResolvedExport */ , + exportName: data.exportName, + exportMapKey: data.exportMapKey, + moduleSpecifier: data.moduleSpecifier, + symbolName: completionName, + fileName: data.fileName, + moduleSymbol: moduleSymbol, + isDefaultExport: isDefaultExport, + isFromPackageJson: isFromPackageJson + }; + return resolvedOrigin; + } + const unresolvedOrigin = { + kind: 4 /* Export */ , + exportName: data.exportName, + exportMapKey: data.exportMapKey, + symbolName: completionName, + fileName: data.fileName, + moduleSymbol: moduleSymbol, + isDefaultExport: isDefaultExport, + isFromPackageJson: isFromPackageJson + }; + return unresolvedOrigin; + } + function getInsertTextAndReplacementSpanForImportCompletion(name, importStatementCompletion, origin, useSemicolons, sourceFile, options, preferences) { + const replacementSpan = importStatementCompletion.replacementSpan; + const quotedModuleSpecifier = escapeSnippetText(quote(sourceFile, preferences, origin.moduleSpecifier)); + const exportKind = origin.isDefaultExport ? 1 /* Default */ : origin.exportName === "export=" /* ExportEquals */ ? 2 /* ExportEquals */ : 0 /* Named */ ; + const tabStop = preferences.includeCompletionsWithSnippetText ? "$1" : ""; + const importKind = ts_codefix_exports.getImportKind(sourceFile, exportKind, options, /*forceImportKeyword*/ true); + const isImportSpecifierTypeOnly = importStatementCompletion.couldBeTypeOnlyImportSpecifier; + const topLevelTypeOnlyText = importStatementCompletion.isTopLevelTypeOnly ? ` ${tokenToString(156 /* TypeKeyword */ )} ` : " "; + const importSpecifierTypeOnlyText = isImportSpecifierTypeOnly ? `${tokenToString(156 /* TypeKeyword */ )} ` : ""; + const suffix = useSemicolons ? ";" : ""; + switch(importKind){ + case 3 /* CommonJS */ : + return { + replacementSpan: replacementSpan, + insertText: `import${topLevelTypeOnlyText}${escapeSnippetText(name)}${tabStop} = require(${quotedModuleSpecifier})${suffix}` + }; + case 1 /* Default */ : + return { + replacementSpan: replacementSpan, + insertText: `import${topLevelTypeOnlyText}${escapeSnippetText(name)}${tabStop} from ${quotedModuleSpecifier}${suffix}` + }; + case 2 /* Namespace */ : + return { + replacementSpan: replacementSpan, + insertText: `import${topLevelTypeOnlyText}* as ${escapeSnippetText(name)} from ${quotedModuleSpecifier}${suffix}` + }; + case 0 /* Named */ : + return { + replacementSpan: replacementSpan, + insertText: `import${topLevelTypeOnlyText}{ ${importSpecifierTypeOnlyText}${escapeSnippetText(name)}${tabStop} } from ${quotedModuleSpecifier}${suffix}` + }; + } + } + function quotePropertyName(sourceFile, preferences, name) { + if (/^\d+$/.test(name)) return name; + return quote(sourceFile, preferences, name); + } + function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { + return localSymbol === recommendedCompletion || !!(localSymbol.flags & 1048576 /* ExportValue */ ) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion; + } + function getSourceFromOrigin(origin) { + if (originIsExport(origin)) return stripQuotes(origin.moduleSymbol.name); + if (originIsResolvedExport(origin)) return origin.moduleSpecifier; + if ((origin == null ? void 0 : origin.kind) === 1 /* ThisType */ ) return "ThisProperty/" /* ThisProperty */ ; + if ((origin == null ? void 0 : origin.kind) === 64 /* TypeOnlyAlias */ ) return "TypeOnlyAlias/" /* TypeOnlyAlias */ ; + } + function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, contextToken, location, position, sourceFile, host, program, target, log, kind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importStatementCompletion, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag, includeSymbol = false) { + const start = timestamp(); + const variableOrParameterDeclaration = getVariableOrParameterDeclaration(contextToken, location); + const useSemicolons = probablyUsesSemicolons(sourceFile); + const typeChecker = program.getTypeChecker(); + const uniques = /* @__PURE__ */ new Map(); + for(let i = 0; i < symbols.length; i++){ + const symbol = symbols[i]; + const origin = symbolToOriginInfoMap == null ? void 0 : symbolToOriginInfoMap[i]; + const info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, !!jsxIdentifierExpected); + if (!info || uniques.get(info.name) && (!origin || !originIsObjectLiteralMethod(origin)) || kind === 1 /* Global */ && symbolToSortTextMap && !shouldIncludeSymbol(symbol, symbolToSortTextMap)) continue; + const { name: name, needsConvertPropertyAccess: needsConvertPropertyAccess } = info; + const originalSortText = (symbolToSortTextMap == null ? void 0 : symbolToSortTextMap[getSymbolId(symbol)]) ?? SortText.LocationPriority; + const sortText = isDeprecated(symbol, typeChecker) ? SortText.Deprecated(originalSortText) : originalSortText; + const entry = createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, position, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importStatementCompletion, useSemicolons, compilerOptions, preferences, kind, formatContext, isJsxIdentifierExpected, isRightOfOpenTag, includeSymbol); + if (!entry) continue; + const shouldShadowLaterSymbols = (!origin || originIsTypeOnlyAlias(origin)) && !(symbol.parent === void 0 && !some(symbol.declarations, (d)=>d.getSourceFile() === location.getSourceFile())); + uniques.set(name, shouldShadowLaterSymbols); + insertSorted(entries, entry, compareCompletionEntries, /*allowDuplicates*/ true); + } + log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (timestamp() - start)); + return { + has: (name)=>uniques.has(name), + add: (name)=>uniques.set(name, true) + }; + function shouldIncludeSymbol(symbol, symbolToSortTextMap2) { + var _a; + let allFlags = symbol.flags; + if (!isSourceFile(location)) { + if (isExportAssignment(location.parent)) return true; + if (tryCast(variableOrParameterDeclaration, isVariableDeclaration) && symbol.valueDeclaration === variableOrParameterDeclaration) return false; + const symbolDeclaration = symbol.valueDeclaration ?? ((_a = symbol.declarations) == null ? void 0 : _a[0]); + if (variableOrParameterDeclaration && symbolDeclaration && (isTypeParameterDeclaration(variableOrParameterDeclaration) && isTypeParameterDeclaration(symbolDeclaration) || isParameter(variableOrParameterDeclaration) && isParameter(symbolDeclaration))) { + const symbolDeclarationPos = symbolDeclaration.pos; + const parameters = isParameter(variableOrParameterDeclaration) ? variableOrParameterDeclaration.parent.parameters : isInferTypeNode(variableOrParameterDeclaration.parent) ? void 0 : variableOrParameterDeclaration.parent.typeParameters; + if (symbolDeclarationPos >= variableOrParameterDeclaration.pos && parameters && symbolDeclarationPos < parameters.end) return false; } - function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) { - Debug.assert(!!symbol.valueDeclaration); - const references = mapDefined(findModuleReferences(program, sourceFiles, symbol), (reference)=>{ - if (reference.kind === "import") { - const parent2 = reference.literal.parent; - if (isLiteralTypeNode(parent2)) { - const importType = cast(parent2.parent, isImportTypeNode); - if (excludeImportTypeOfExportEquals && !importType.qualifier) return void 0; - } - return nodeEntry(reference.literal); - } else return { - kind: 0 /* Span */ , - fileName: reference.referencingFile.fileName, - textSpan: createTextSpanFromRange(reference.ref) - }; + const symbolOrigin = skipAlias(symbol, typeChecker); + if (!!sourceFile.externalModuleIndicator && !compilerOptions.allowUmdGlobalAccess && symbolToSortTextMap2[getSymbolId(symbol)] === SortText.GlobalsOrKeywords && (symbolToSortTextMap2[getSymbolId(symbolOrigin)] === SortText.AutoImportSuggestions || symbolToSortTextMap2[getSymbolId(symbolOrigin)] === SortText.LocationPriority)) return false; + allFlags |= getCombinedLocalAndExportSymbolFlags(symbolOrigin); + if (isInRightSideOfInternalImportEqualsDeclaration(location)) return !!(allFlags & 1920 /* Namespace */ ); + if (isTypeOnlyLocation) return symbolCanBeReferencedAtTypeLocation(symbol, typeChecker); + } + return !!(allFlags & 111551 /* Value */ ); + } + } + function getLabelCompletionAtPosition(node) { + const entries = getLabelStatementCompletions(node); + if (entries.length) return { + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: false, + entries: entries + }; + } + function getLabelStatementCompletions(node) { + const entries = []; + const uniques = /* @__PURE__ */ new Map(); + let current = node; + while(current){ + if (isFunctionLike(current)) break; + if (isLabeledStatement(current)) { + const name = current.label.text; + if (!uniques.has(name)) { + uniques.set(name, true); + entries.push({ + name: name, + kindModifiers: "" /* none */ , + kind: "label" /* label */ , + sortText: SortText.LocationPriority }); - if (symbol.declarations) for (const decl of symbol.declarations)switch(decl.kind){ - case 308 /* SourceFile */ : - break; - case 264 /* ModuleDeclaration */ : - if (sourceFilesSet.has(decl.getSourceFile().fileName)) references.push(nodeEntry(decl.name)); - break; - default: - Debug.assert(!!(symbol.flags & 33554432 /* Transient */ ), "Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); - } - const exported = symbol.exports.get("export=" /* ExportEquals */ ); - if (exported == null ? void 0 : exported.declarations) for (const decl of exported.declarations){ - const sourceFile = decl.getSourceFile(); - if (sourceFilesSet.has(sourceFile.fileName)) { - const node = isBinaryExpression(decl) && isPropertyAccessExpression(decl.left) ? decl.left.expression : isExportAssignment(decl) ? Debug.checkDefined(findChildOfKind(decl, 93 /* ExportKeyword */ , sourceFile)) : getNameOfDeclaration(decl) || decl; - references.push(nodeEntry(node)); - } - } - return references.length ? [ - { - definition: { - type: 0 /* Symbol */ , - symbol: symbol - }, - references: references - } - ] : emptyArray; - } - function isReadonlyTypeOperator(node) { - return node.kind === 146 /* ReadonlyKeyword */ && isTypeOperatorNode(node.parent) && node.parent.operator === 146 /* ReadonlyKeyword */ ; - } - function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { - if (isTypeKeyword(node.kind)) { - if (node.kind === 114 /* VoidKeyword */ && isVoidExpression(node.parent)) return void 0; - if (node.kind === 146 /* ReadonlyKeyword */ && !isReadonlyTypeOperator(node)) return void 0; - return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken, node.kind === 146 /* ReadonlyKeyword */ ? isReadonlyTypeOperator : void 0); - } - if (isImportMeta(node.parent) && node.parent.name === node) return getAllReferencesForImportMeta(sourceFiles, cancellationToken); - if (isStaticModifier(node) && isClassStaticBlockDeclaration(node.parent)) return [ - { - definition: { - type: 2 /* Keyword */ , - node: node - }, - references: [ - nodeEntry(node) - ] - } - ]; - if (isJumpStatementTarget(node)) { - const labelDefinition = getTargetLabel(node.parent, node.text); - return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition); - } else if (isLabelOfLabeledStatement(node)) return getLabelReferencesInNode(node.parent, node); - if (isThis(node)) return getReferencesForThisKeyword(node, sourceFiles, cancellationToken); - if (node.kind === 106 /* SuperKeyword */ ) return getReferencesForSuperKeyword(node); - return void 0; } - function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { - const symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, /*useLocalSymbolForExportSpecifier*/ !isForRenameWithPrefixAndSuffixText(options)) || originalSymbol; - const searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */ ; - const result = []; - const state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */ , checker, cancellationToken, searchMeaning, options, result); - const exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) || !symbol.declarations ? void 0 : find(symbol.declarations, isExportSpecifier); - if (exportSpecifier) getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ void 0), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); - else if (node && node.kind === 88 /* DefaultKeyword */ && symbol.escapedName === "default" /* Default */ && symbol.parent) { - addReference(node, symbol, state); - searchForImportsOfExport(node, symbol, { - exportingModuleSymbol: symbol.parent, - exportKind: 1 /* Default */ - }, state); - } else { - const search = state.createSearch(node, symbol, /*comingFrom*/ void 0, { - allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.use === 2 /* Rename */ , !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [ - symbol - ] - }); - getReferencesInContainerOrFiles(symbol, state, search); - } - return result; - } - function getReferencesInContainerOrFiles(symbol, state, search) { - const scope = getSymbolScope(symbol); - if (scope) getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(isSourceFile(scope) && !contains(state.sourceFiles, scope))); - else for (const sourceFile of state.sourceFiles){ - state.cancellationToken.throwIfCancellationRequested(); - searchForName(sourceFile, search, state); - } - } - function getSpecialSearchKind(node) { - switch(node.kind){ - case 173 /* Constructor */ : - case 135 /* ConstructorKeyword */ : - return 1 /* Constructor */ ; - case 79 /* Identifier */ : - if (isClassLike(node.parent)) { - Debug.assert(node.parent.name === node); - return 2 /* Class */ ; - } + } + current = current.parent; + } + return entries; + } + function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences) { + if (entryId.source === "SwitchCases/" /* SwitchCases */ ) return { + type: "cases" + }; + if (entryId.data) { + const autoImport = getAutoImportSymbolFromCompletionEntryData(entryId.name, entryId.data, program, host); + if (autoImport) { + const { contextToken: contextToken2, previousToken: previousToken2 } = getRelevantTokens(position, sourceFile); + return { + type: "symbol", + symbol: autoImport.symbol, + location: getTouchingPropertyName(sourceFile, position), + previousToken: previousToken2, + contextToken: contextToken2, + isJsxInitializer: false, + isTypeOnlyLocation: false, + origin: autoImport.origin + }; + } + } + const compilerOptions = program.getCompilerOptions(); + const completionData = getCompletionData(program, log, sourceFile, compilerOptions, position, { + includeCompletionsForModuleExports: true, + includeCompletionsWithInsertText: true + }, entryId, host, /*formatContext*/ void 0); + if (!completionData) return { + type: "none" + }; + if (completionData.kind !== 0 /* Data */ ) return { + type: "request", + request: completionData + }; + const { symbols: symbols, literals: literals, location: location, completionKind: completionKind, symbolToOriginInfoMap: symbolToOriginInfoMap, contextToken: contextToken, previousToken: previousToken, isJsxInitializer: isJsxInitializer, isTypeOnlyLocation: isTypeOnlyLocation } = completionData; + const literal = find(literals, (l)=>completionNameForLiteral(sourceFile, preferences, l) === entryId.name); + if (literal !== void 0) return { + type: "literal", + literal: literal + }; + return firstDefined(symbols, (symbol, index)=>{ + const origin = symbolToOriginInfoMap[index]; + const info = getCompletionEntryDisplayNameForSymbol(symbol, getEmitScriptTarget(compilerOptions), origin, completionKind, completionData.isJsxIdentifierExpected); + return info && info.name === entryId.name && (entryId.source === "ClassMemberSnippet/" /* ClassMemberSnippet */ && symbol.flags & 106500 /* ClassMember */ || entryId.source === "ObjectLiteralMethodSnippet/" /* ObjectLiteralMethodSnippet */ && symbol.flags & 8196 /* Method */ || getSourceFromOrigin(origin) === entryId.source || entryId.source === "ObjectLiteralMemberWithComma/" /* ObjectLiteralMemberWithComma */ ) ? { + type: "symbol", + symbol: symbol, + location: location, + origin: origin, + contextToken: contextToken, + previousToken: previousToken, + isJsxInitializer: isJsxInitializer, + isTypeOnlyLocation: isTypeOnlyLocation + } : void 0; + }) || { + type: "none" + }; + } + function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, preferences, cancellationToken) { + const typeChecker = program.getTypeChecker(); + const compilerOptions = program.getCompilerOptions(); + const { name: name, source: source, data: data } = entryId; + const { previousToken: previousToken, contextToken: contextToken } = getRelevantTokens(position, sourceFile); + if (isInString(sourceFile, position, previousToken)) return ts_Completions_StringCompletions_exports.getStringLiteralCompletionDetails(name, sourceFile, position, previousToken, typeChecker, compilerOptions, host, cancellationToken, preferences); + const symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences); + switch(symbolCompletion.type){ + case "request": + { + const { request: request } = symbolCompletion; + switch(request.kind){ + case 1 /* JsDocTagName */ : + return ts_JsDoc_exports.getJSDocTagNameCompletionDetails(name); + case 2 /* JsDocTag */ : + return ts_JsDoc_exports.getJSDocTagCompletionDetails(name); + case 3 /* JsDocParameterName */ : + return ts_JsDoc_exports.getJSDocParameterNameCompletionDetails(name); + case 4 /* Keywords */ : + return some(request.keywordCompletions, (c)=>c.name === name) ? createSimpleDetails(name, "keyword" /* keyword */ , 5 /* keyword */ ) : void 0; default: - return 0 /* None */ ; + return Debug.assertNever(request); } } - function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, useLocalSymbolForExportSpecifier) { - const { parent: parent2 } = node; - if (isExportSpecifier(parent2) && useLocalSymbolForExportSpecifier) return getLocalSymbolForExportSpecifier(node, symbol, parent2, checker); - return firstDefined(symbol.declarations, (decl)=>{ - if (!decl.parent) { - if (symbol.flags & 33554432 /* Transient */ ) return void 0; - Debug.fail(`Unexpected symbol at ${Debug.formatSyntaxKind(node.kind)}: ${Debug.formatSymbol(symbol)}`); - } - return isTypeLiteralNode(decl.parent) && isUnionTypeNode(decl.parent.parent) ? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name) : void 0; - }); + case "symbol": + { + const { symbol: symbol, location: location, contextToken: contextToken2, origin: origin, previousToken: previousToken2 } = symbolCompletion; + const { codeActions: codeActions, sourceDisplay: sourceDisplay } = getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken2, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken2, formatContext, preferences, data, source, cancellationToken); + const symbolName2 = originIsComputedPropertyName(origin) ? origin.symbolName : symbol.name; + return createCompletionDetailsForSymbol(symbol, symbolName2, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); } - let SpecialSearchKind; - ((SpecialSearchKind2)=>{ - SpecialSearchKind2[SpecialSearchKind2["None"] = 0] = "None"; - SpecialSearchKind2[SpecialSearchKind2["Constructor"] = 1] = "Constructor"; - SpecialSearchKind2[SpecialSearchKind2["Class"] = 2] = "Class"; - })(SpecialSearchKind || (SpecialSearchKind = {})); - function getNonModuleSymbolOfMergedModuleSymbol(symbol) { - if (!(symbol.flags & 33555968 /* Transient */ )) return void 0; - const decl = symbol.declarations && find(symbol.declarations, (d)=>!isSourceFile(d) && !isModuleDeclaration(d)); - return decl && decl.symbol; + case "literal": + { + const { literal: literal } = symbolCompletion; + return createSimpleDetails(completionNameForLiteral(sourceFile, preferences, literal), "string" /* string */ , typeof literal === "string" ? 8 /* stringLiteral */ : 7 /* numericLiteral */ ); } - class State { - constructor(sourceFiles, sourceFilesSet, specialSearchKind, checker, cancellationToken, searchMeaning, options, result){ - this.sourceFiles = sourceFiles; - this.sourceFilesSet = sourceFilesSet; - this.specialSearchKind = specialSearchKind; - this.checker = checker; - this.cancellationToken = cancellationToken; - this.searchMeaning = searchMeaning; - this.options = options; - this.result = result; - /** Cache for `explicitlyinheritsFrom`. */ this.inheritsFromCache = /* @__PURE__ */ new Map(); - /** - * Type nodes can contain multiple references to the same type. For example: - * let x: Foo & (Foo & Bar) = ... - * Because we are returning the implementation locations and not the identifier locations, - * duplicate entries would be returned here as each of the type references is part of - * the same implementation. For that reason, check before we add a new entry. - */ this.markSeenContainingTypeReference = nodeSeenTracker(); - /** - * It's possible that we will encounter the right side of `export { foo as bar } from "x";` more than once. - * For example: - * // b.ts - * export { foo as bar } from "./a"; - * import { bar } from "./b"; - * - * Normally at `foo as bar` we directly add `foo` and do not locally search for it (since it doesn't declare a local). - * But another reference to it may appear in the same source file. - * See `tests/cases/fourslash/transitiveExportImports3.ts`. - */ this.markSeenReExportRHS = nodeSeenTracker(); - this.symbolIdToReferences = []; - // Source file ID → symbol ID → Whether the symbol has been searched for in the source file. - this.sourceFileToSeenSymbols = []; - } - includesSourceFile(sourceFile) { - return this.sourceFilesSet.has(sourceFile.fileName); - } - /** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */ getImportSearches(exportSymbol, exportInfo) { - if (!this.importTracker) this.importTracker = createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken); - return this.importTracker(exportSymbol, exportInfo, this.options.use === 2 /* Rename */ ); - } - /** @param allSearchSymbols set of additional symbols for use by `includes`. */ createSearch(location, symbol, comingFrom, searchOptions = {}) { - const { text: text = stripQuotes(symbolName(getLocalSymbolForExportDefault(symbol) || getNonModuleSymbolOfMergedModuleSymbol(symbol) || symbol)) , allSearchSymbols: allSearchSymbols = [ - symbol - ] } = searchOptions; - const escapedText = escapeLeadingUnderscores(text); - const parents = this.options.implementations && location ? getParentSymbolsOfPropertyAccess(location, symbol, this.checker) : void 0; + case "cases": + { + const { entry: entry, importAdder: importAdder } = getExhaustiveCaseSnippets(contextToken.parent, sourceFile, preferences, program.getCompilerOptions(), host, program, /*formatContext*/ void 0); + if (importAdder.hasFixes()) { + const changes = ts_textChanges_exports.ChangeTracker.with({ + host: host, + formatContext: formatContext, + preferences: preferences + }, importAdder.writeFixes); return { - symbol: symbol, - comingFrom: comingFrom, - text: text, - escapedText: escapedText, - parents: parents, - allSearchSymbols: allSearchSymbols, - includes: (sym)=>contains(allSearchSymbols, sym) - }; - } - /** - * Callback to add references for a particular searched symbol. - * This initializes a reference group, so only call this if you will add at least one reference. - */ referenceAdder(searchSymbol) { - const symbolId = getSymbolId(searchSymbol); - let references = this.symbolIdToReferences[symbolId]; - if (!references) { - references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ - definition: { - type: 0 /* Symbol */ , - symbol: searchSymbol - }, - references: references - }); - } - return (node, kind)=>references.push(nodeEntry(node, kind)); - } - /** Add a reference with no associated definition. */ addStringOrCommentReference(fileName, textSpan) { - this.result.push({ - definition: void 0, - references: [ + name: entry.name, + kind: "" /* unknown */ , + kindModifiers: "", + displayParts: [], + sourceDisplay: void 0, + codeActions: [ { - kind: 0 /* Span */ , - fileName: fileName, - textSpan: textSpan + changes: changes, + description: diagnosticToString([ + Diagnostics.Includes_imports_of_types_referenced_by_0, + name + ]) } ] - }); - } - /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ markSearchedSymbols(sourceFile, symbols) { - const sourceId = getNodeId(sourceFile); - const seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = /* @__PURE__ */ new Set()); - let anyNewSymbols = false; - for (const sym of symbols)anyNewSymbols = tryAddToSet(seenSymbols, getSymbolId(sym)) || anyNewSymbols; - return anyNewSymbols; + }; } + return { + name: entry.name, + kind: "" /* unknown */ , + kindModifiers: "", + displayParts: [], + sourceDisplay: void 0 + }; } - function searchForImportsOfExport(exportLocation, exportSymbol, exportInfo, state) { - const { importSearches: importSearches , singleReferences: singleReferences , indirectUsers: indirectUsers } = state.getImportSearches(exportSymbol, exportInfo); - if (singleReferences.length) { - const addRef = state.referenceAdder(exportSymbol); - for (const singleRef of singleReferences)if (shouldAddSingleReference(singleRef, state)) addRef(singleRef); - } - for (const [importLocation, importSymbol] of importSearches)getReferencesInSourceFile(importLocation.getSourceFile(), state.createSearch(importLocation, importSymbol, 1 /* Export */ ), state); - if (indirectUsers.length) { - let indirectSearch; - switch(exportInfo.exportKind){ - case 0 /* Named */ : - indirectSearch = state.createSearch(exportLocation, exportSymbol, 1 /* Export */ ); - break; - case 1 /* Default */ : - indirectSearch = state.options.use === 2 /* Rename */ ? void 0 : state.createSearch(exportLocation, exportSymbol, 1 /* Export */ , { - text: "default" - }); - break; - case 2 /* ExportEquals */ : - break; + case "none": + return allKeywordsCompletions().some((c)=>c.name === name) ? createSimpleDetails(name, "keyword" /* keyword */ , 5 /* keyword */ ) : void 0; + default: + Debug.assertNever(symbolCompletion); + } + } + function createSimpleDetails(name, kind, kind2) { + return createCompletionDetails(name, "" /* none */ , kind, [ + displayPart(name, kind2) + ]); + } + function createCompletionDetailsForSymbol(symbol, name, checker, sourceFile, location, cancellationToken, codeActions, sourceDisplay) { + const { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags } = checker.runWithCancellationToken(cancellationToken, (checker2)=>ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(checker2, symbol, sourceFile, location, location, 7 /* All */ )); + return createCompletionDetails(name, ts_SymbolDisplay_exports.getSymbolModifiers(checker, symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); + } + function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { + return { + name: name, + kindModifiers: kindModifiers, + kind: kind, + displayParts: displayParts, + documentation: documentation, + tags: tags, + codeActions: codeActions, + source: source, + sourceDisplay: source + }; + } + function getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source, cancellationToken) { + if (data == null ? void 0 : data.moduleSpecifier) { + if (previousToken && getImportStatementCompletionInfo(contextToken || previousToken, sourceFile).replacementSpan) return { + codeActions: void 0, + sourceDisplay: [ + textPart(data.moduleSpecifier) + ] + }; + } + if (source === "ClassMemberSnippet/" /* ClassMemberSnippet */ ) { + const { importAdder: importAdder, eraseRange: eraseRange } = getEntryForMemberCompletion(host, program, compilerOptions, preferences, name, symbol, location, position, contextToken, formatContext); + if (importAdder || eraseRange) { + const changes = ts_textChanges_exports.ChangeTracker.with({ + host: host, + formatContext: formatContext, + preferences: preferences + }, (tracker)=>{ + if (importAdder) importAdder.writeFixes(tracker); + if (eraseRange) tracker.deleteRange(sourceFile, eraseRange); + }); + return { + sourceDisplay: void 0, + codeActions: [ + { + changes: changes, + description: diagnosticToString([ + Diagnostics.Includes_imports_of_types_referenced_by_0, + name + ]) } - if (indirectSearch) for (const indirectUser of indirectUsers)searchForName(indirectUser, indirectSearch, state); + ] + }; + } + } + if (originIsTypeOnlyAlias(origin)) { + const codeAction2 = ts_codefix_exports.getPromoteTypeOnlyCompletionAction(sourceFile, origin.declaration.name, program, host, formatContext, preferences); + Debug.assertIsDefined(codeAction2, "Expected to have a code action for promoting type-only alias"); + return { + codeActions: [ + codeAction2 + ], + sourceDisplay: void 0 + }; + } + if (source === "ObjectLiteralMemberWithComma/" /* ObjectLiteralMemberWithComma */ && contextToken) { + const changes = ts_textChanges_exports.ChangeTracker.with({ + host: host, + formatContext: formatContext, + preferences: preferences + }, (tracker)=>tracker.insertText(sourceFile, contextToken.end, ",")); + if (changes) return { + sourceDisplay: void 0, + codeActions: [ + { + changes: changes, + description: diagnosticToString([ + Diagnostics.Add_missing_comma_for_object_member_completion_0, + name + ]) } + ] + }; + } + if (!origin || !(originIsExport(origin) || originIsResolvedExport(origin))) return { + codeActions: void 0, + sourceDisplay: void 0 + }; + const checker = origin.isFromPackageJson ? host.getPackageJsonAutoImportProvider().getTypeChecker() : program.getTypeChecker(); + const { moduleSymbol: moduleSymbol } = origin; + const targetSymbol = checker.getMergedSymbol(skipAlias(symbol.exportSymbol || symbol, checker)); + const isJsxOpeningTagName = (contextToken == null ? void 0 : contextToken.kind) === 30 /* LessThanToken */ && isJsxOpeningLikeElement(contextToken.parent); + const { moduleSpecifier: moduleSpecifier, codeAction: codeAction } = ts_codefix_exports.getImportCompletionAction(targetSymbol, moduleSymbol, data == null ? void 0 : data.exportMapKey, sourceFile, name, isJsxOpeningTagName, host, program, formatContext, previousToken && isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences, cancellationToken); + Debug.assert(!(data == null ? void 0 : data.moduleSpecifier) || moduleSpecifier === data.moduleSpecifier); + return { + sourceDisplay: [ + textPart(moduleSpecifier) + ], + codeActions: [ + codeAction + ] + }; + } + function getCompletionEntrySymbol(program, log, sourceFile, position, entryId, host, preferences) { + const completion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences); + return completion.type === "symbol" ? completion.symbol : void 0; + } + function getRecommendedCompletion(previousToken, contextualType, checker) { + return firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [ + contextualType + ]), (type)=>{ + const symbol = type && type.symbol; + return symbol && symbol.flags & 424 /* Class */ && !isAbstractConstructorSymbol(symbol) ? getFirstSymbolInChain(symbol, previousToken, checker) : void 0; + }); + } + function getContextualType(previousToken, position, sourceFile, checker) { + const { parent: parent2 } = previousToken; + switch(previousToken.kind){ + case 80 /* Identifier */ : + return getContextualTypeFromParent(previousToken, checker); + case 64 /* EqualsToken */ : + switch(parent2.kind){ + case 260 /* VariableDeclaration */ : + return checker.getContextualType(parent2.initializer); + case 226 /* BinaryExpression */ : + return checker.getTypeAtLocation(parent2.left); + case 291 /* JsxAttribute */ : + return checker.getContextualTypeForJsxAttribute(parent2); + default: + return void 0; } - function eachExportReference(sourceFiles, checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName, isDefaultExport, cb) { - const importTracker = createImportTracker(sourceFiles, new Set(sourceFiles.map((f)=>f.fileName)), checker, cancellationToken); - const { importSearches: importSearches , indirectUsers: indirectUsers , singleReferences: singleReferences } = importTracker(exportSymbol, { - exportKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */ , - exportingModuleSymbol: exportingModuleSymbol - }, /*isForRename*/ false); - for (const [importLocation] of importSearches)cb(importLocation); - for (const singleReference of singleReferences)if (isIdentifier(singleReference) && isImportTypeNode(singleReference.parent)) cb(singleReference); - for (const indirectUser of indirectUsers)for (const node of getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName)){ - const symbol = checker.getSymbolAtLocation(node); - const hasExportAssignmentDeclaration = some(symbol == null ? void 0 : symbol.declarations, (d)=>tryCast(d, isExportAssignment) ? true : false); - if (isIdentifier(node) && !isImportOrExportSpecifier(node.parent) && (symbol === exportSymbol || hasExportAssignmentDeclaration)) cb(node); - } + case 105 /* NewKeyword */ : + return checker.getContextualType(parent2); + case 84 /* CaseKeyword */ : + const caseClause = tryCast(parent2, isCaseClause); + return caseClause ? getSwitchedType(caseClause, checker) : void 0; + case 19 /* OpenBraceToken */ : + return isJsxExpression(parent2) && !isJsxElement(parent2.parent) && !isJsxFragment(parent2.parent) ? checker.getContextualTypeForJsxAttribute(parent2.parent) : void 0; + default: + const argInfo = ts_SignatureHelp_exports.getArgumentInfoForCompletions(previousToken, position, sourceFile); + return argInfo ? // At `,`, treat this as the next argument after the comma. + checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 28 /* CommaToken */ ? 1 : 0)) : isEqualityOperatorKind(previousToken.kind) && isBinaryExpression(parent2) && isEqualityOperatorKind(parent2.operatorToken.kind) ? // completion at `x ===/**/` should be for the right side + checker.getTypeAtLocation(parent2.left) : checker.getContextualType(previousToken, 4 /* Completions */ ) || checker.getContextualType(previousToken); + } + } + function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { + const chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ 67108863 /* All */ , /*useOnlyExternalAliasing*/ false); + if (chain) return first(chain); + return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker)); + } + function isModuleSymbol(symbol) { + var _a; + return !!((_a = symbol.declarations) == null ? void 0 : _a.some((d)=>d.kind === 312 /* SourceFile */ )); + } + function getCompletionData(program, log, sourceFile, compilerOptions, position, preferences, detailsEntryId, host, formatContext, cancellationToken) { + const typeChecker = program.getTypeChecker(); + const inCheckedFile = isCheckedFile(sourceFile, compilerOptions); + let start = timestamp(); + let currentToken = getTokenAtPosition(sourceFile, position); + log("getCompletionData: Get current token: " + (timestamp() - start)); + start = timestamp(); + const insideComment = isInComment(sourceFile, position, currentToken); + log("getCompletionData: Is inside comment: " + (timestamp() - start)); + let insideJsDocTagTypeExpression = false; + let isInSnippetScope = false; + if (insideComment) { + if (hasDocComment(sourceFile, position)) { + if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */ ) return { + kind: 1 /* JsDocTagName */ + }; + else { + const lineStart = getLineStartPositionForPosition(position, sourceFile); + if (!/[^*|\s(/)]/.test(sourceFile.text.substring(lineStart, position))) return { + kind: 2 /* JsDocTag */ + }; } - Core2.eachExportReference = eachExportReference; - function shouldAddSingleReference(singleRef, state) { - if (!hasMatchingMeaning(singleRef, state)) return false; - if (state.options.use !== 2 /* Rename */ ) return true; - if (!isIdentifier(singleRef)) return false; - return !(isImportOrExportSpecifier(singleRef.parent) && singleRef.escapedText === "default" /* Default */ ); + } + const tag = getJsDocTagAtPosition(currentToken, position); + if (tag) { + if (tag.tagName.pos <= position && position <= tag.tagName.end) return { + kind: 1 /* JsDocTagName */ + }; + const typeExpression = tryGetTypeExpressionFromTag(tag); + if (typeExpression) { + currentToken = getTokenAtPosition(sourceFile, position); + if (!currentToken || !isDeclarationName(currentToken) && (currentToken.parent.kind !== 355 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken)) insideJsDocTagTypeExpression = isCurrentlyEditingNode(typeExpression); } - function searchForImportedSymbol(symbol, state) { - if (!symbol.declarations) return; - for (const declaration of symbol.declarations){ - const exportingFile = declaration.getSourceFile(); - getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */ ), state, state.includesSourceFile(exportingFile)); - } + if (!insideJsDocTagTypeExpression && isJSDocParameterTag(tag) && (nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) return { + kind: 3 /* JsDocParameterName */ , + tag: tag + }; + } + if (!insideJsDocTagTypeExpression) { + log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); + return void 0; + } + } + start = timestamp(); + const isJsOnlyLocation = !insideJsDocTagTypeExpression && isSourceFileJS(sourceFile); + const tokens = getRelevantTokens(position, sourceFile); + const previousToken = tokens.previousToken; + let contextToken = tokens.contextToken; + log("getCompletionData: Get previous token: " + (timestamp() - start)); + let node = currentToken; + let propertyAccessToConvert; + let isRightOfDot = false; + let isRightOfQuestionDot = false; + let isRightOfOpenTag = false; + let isStartingCloseTag = false; + let isJsxInitializer = false; + let isJsxIdentifierExpected = false; + let importStatementCompletion; + let location = getTouchingPropertyName(sourceFile, position); + let keywordFilters = 0 /* None */ ; + let isNewIdentifierLocation = false; + let flags = 0 /* None */ ; + if (contextToken) { + const importStatementCompletionInfo = getImportStatementCompletionInfo(contextToken, sourceFile); + if (importStatementCompletionInfo.keywordCompletion) { + if (importStatementCompletionInfo.isKeywordOnlyCompletion) return { + kind: 4 /* Keywords */ , + keywordCompletions: [ + keywordToCompletionEntry(importStatementCompletionInfo.keywordCompletion) + ], + isNewIdentifierLocation: importStatementCompletionInfo.isNewIdentifierLocation + }; + keywordFilters = keywordFiltersFromSyntaxKind(importStatementCompletionInfo.keywordCompletion); + } + if (importStatementCompletionInfo.replacementSpan && preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) { + flags |= 2 /* IsImportStatementCompletion */ ; + importStatementCompletion = importStatementCompletionInfo; + isNewIdentifierLocation = importStatementCompletionInfo.isNewIdentifierLocation; + } + if (!importStatementCompletionInfo.replacementSpan && isCompletionListBlocker(contextToken)) { + log("Returning an empty list because completion was requested in an invalid position."); + return keywordFilters ? keywordCompletionData(keywordFilters, isJsOnlyLocation, isNewIdentifierDefinitionLocation()) : void 0; + } + let parent2 = contextToken.parent; + if (contextToken.kind === 25 /* DotToken */ || contextToken.kind === 29 /* QuestionDotToken */ ) { + isRightOfDot = contextToken.kind === 25 /* DotToken */ ; + isRightOfQuestionDot = contextToken.kind === 29 /* QuestionDotToken */ ; + switch(parent2.kind){ + case 211 /* PropertyAccessExpression */ : + propertyAccessToConvert = parent2; + node = propertyAccessToConvert.expression; + const leftmostAccessExpression = getLeftmostAccessExpression(propertyAccessToConvert); + if (nodeIsMissing(leftmostAccessExpression) || (isCallExpression(node) || isFunctionLike(node)) && node.end === contextToken.pos && node.getChildCount(sourceFile) && last(node.getChildren(sourceFile)).kind !== 22 /* CloseParenToken */ ) return void 0; + break; + case 166 /* QualifiedName */ : + node = parent2.left; + break; + case 267 /* ModuleDeclaration */ : + node = parent2.name; + break; + case 205 /* ImportType */ : + node = parent2; + break; + case 236 /* MetaProperty */ : + node = parent2.getFirstToken(sourceFile); + Debug.assert(node.kind === 102 /* ImportKeyword */ || node.kind === 105 /* NewKeyword */ ); + break; + default: + return void 0; } - function searchForName(sourceFile, search, state) { - if (getNameTable(sourceFile).get(search.escapedText) !== void 0) getReferencesInSourceFile(sourceFile, search, state); + } else if (!importStatementCompletion) { + if (parent2 && parent2.kind === 211 /* PropertyAccessExpression */ ) { + contextToken = parent2; + parent2 = parent2.parent; } - function getPropertySymbolOfDestructuringAssignment(location, checker) { - return isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) ? checker.getPropertySymbolOfDestructuringAssignment(location) : void 0; + if (currentToken.parent === location) switch(currentToken.kind){ + case 32 /* GreaterThanToken */ : + if (currentToken.parent.kind === 284 /* JsxElement */ || currentToken.parent.kind === 286 /* JsxOpeningElement */ ) location = currentToken; + break; + case 44 /* SlashToken */ : + if (currentToken.parent.kind === 285 /* JsxSelfClosingElement */ ) location = currentToken; + break; } - function getSymbolScope(symbol) { - const { declarations: declarations , flags: flags , parent: parent2 , valueDeclaration: valueDeclaration } = symbol; - if (valueDeclaration && (valueDeclaration.kind === 215 /* FunctionExpression */ || valueDeclaration.kind === 228 /* ClassExpression */ )) return valueDeclaration; - if (!declarations) return void 0; - if (flags & 8196 /* Method */ ) { - const privateDeclaration = find(declarations, (d)=>hasEffectiveModifier(d, 8 /* Private */ ) || isPrivateIdentifierClassElementDeclaration(d)); - if (privateDeclaration) return getAncestor(privateDeclaration, 260 /* ClassDeclaration */ ); - return void 0; - } - if (declarations.some(isObjectBindingElementWithoutPropertyName)) return void 0; - const exposedByParent = parent2 && !(symbol.flags & 262144 /* TypeParameter */ ); - if (exposedByParent && !(isExternalModuleSymbol(parent2) && !parent2.globalExports)) return void 0; - let scope; - for (const declaration of declarations){ - const container = getContainerNode(declaration); - if (scope && scope !== container) return void 0; - if (!container || container.kind === 308 /* SourceFile */ && !isExternalOrCommonJsModule(container)) return void 0; - scope = container; - if (isFunctionExpression(scope)) { - let next; - while(next = getNextJSDocCommentLocation(scope))scope = next; - } - } - return exposedByParent ? scope.getSourceFile() : scope; - } - function isSymbolReferencedInFile(definition, checker, sourceFile, searchContainer = sourceFile) { - return eachSymbolReferenceInFile(definition, checker, sourceFile, ()=>true, searchContainer) || false; - } - Core2.isSymbolReferencedInFile = isSymbolReferencedInFile; - function eachSymbolReferenceInFile(definition, checker, sourceFile, cb, searchContainer = sourceFile) { - const symbol = isParameterPropertyDeclaration(definition.parent, definition.parent.parent) ? first(checker.getSymbolsOfParameterPropertyDeclaration(definition.parent, definition.text)) : checker.getSymbolAtLocation(definition); - if (!symbol) return void 0; - for (const token of getPossibleSymbolReferenceNodes(sourceFile, symbol.name, searchContainer)){ - if (!isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) continue; - const referenceSymbol = checker.getSymbolAtLocation(token); - if (referenceSymbol === symbol || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol || isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) { - const res = cb(token); - if (res) return res; + switch(parent2.kind){ + case 287 /* JsxClosingElement */ : + if (contextToken.kind === 44 /* SlashToken */ ) { + isStartingCloseTag = true; + location = contextToken; } - } - } - Core2.eachSymbolReferenceInFile = eachSymbolReferenceInFile; - function getTopMostDeclarationNamesInFile(declarationName, sourceFile) { - const candidates = filter(getPossibleSymbolReferenceNodes(sourceFile, declarationName), (name)=>!!getDeclarationFromName(name)); - return candidates.reduce((topMost, decl)=>{ - const depth = getDepth(decl); - if (!some(topMost.declarationNames) || depth === topMost.depth) { - topMost.declarationNames.push(decl); - topMost.depth = depth; - } else if (depth < topMost.depth) { - topMost.declarationNames = [ - decl - ]; - topMost.depth = depth; + break; + case 226 /* BinaryExpression */ : + if (!binaryExpressionMayBeOpenTag(parent2)) break; + case 285 /* JsxSelfClosingElement */ : + case 284 /* JsxElement */ : + case 286 /* JsxOpeningElement */ : + isJsxIdentifierExpected = true; + if (contextToken.kind === 30 /* LessThanToken */ ) { + isRightOfOpenTag = true; + location = contextToken; } - return topMost; - }, { - depth: Infinity, - declarationNames: [] - }).declarationNames; - function getDepth(declaration) { - let depth = 0; - while(declaration){ - declaration = getContainerNode(declaration); - depth++; + break; + case 294 /* JsxExpression */ : + case 293 /* JsxSpreadAttribute */ : + if (previousToken.kind === 20 /* CloseBraceToken */ || previousToken.kind === 80 /* Identifier */ && previousToken.parent.kind === 291 /* JsxAttribute */ ) isJsxIdentifierExpected = true; + break; + case 291 /* JsxAttribute */ : + if (parent2.initializer === previousToken && previousToken.end < position) { + isJsxIdentifierExpected = true; + break; } - return depth; - } - } - Core2.getTopMostDeclarationNamesInFile = getTopMostDeclarationNamesInFile; - function someSignatureUsage(signature, sourceFiles, checker, cb) { - if (!signature.name || !isIdentifier(signature.name)) return false; - const symbol = Debug.checkDefined(checker.getSymbolAtLocation(signature.name)); - for (const sourceFile of sourceFiles)for (const name of getPossibleSymbolReferenceNodes(sourceFile, symbol.name)){ - if (!isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) continue; - const called = climbPastPropertyAccess(name); - const call = isCallExpression(called.parent) && called.parent.expression === called ? called.parent : void 0; - const referenceSymbol = checker.getSymbolAtLocation(name); - if (referenceSymbol && checker.getRootSymbols(referenceSymbol).some((s)=>s === symbol)) { - if (cb(name, call)) return true; + switch(previousToken.kind){ + case 64 /* EqualsToken */ : + isJsxInitializer = true; + break; + case 80 /* Identifier */ : + isJsxIdentifierExpected = true; + if (parent2 !== previousToken.parent && !parent2.initializer && findChildOfKind(parent2, 64 /* EqualsToken */ , sourceFile)) isJsxInitializer = previousToken; } - } - return false; - } - Core2.someSignatureUsage = someSignatureUsage; - function getPossibleSymbolReferenceNodes(sourceFile, symbolName2, container = sourceFile) { - return getPossibleSymbolReferencePositions(sourceFile, symbolName2, container).map((pos)=>getTouchingPropertyName(sourceFile, pos)); + break; } - function getPossibleSymbolReferencePositions(sourceFile, symbolName2, container = sourceFile) { - const positions = []; - if (!symbolName2 || !symbolName2.length) return positions; - const text = sourceFile.text; - const sourceLength = text.length; - const symbolNameLength = symbolName2.length; - let position = text.indexOf(symbolName2, container.pos); - while(position >= 0){ - if (position > container.end) break; - const endPosition = position + symbolNameLength; - if ((position === 0 || !isIdentifierPart(text.charCodeAt(position - 1), 99 /* Latest */ )) && (endPosition === sourceLength || !isIdentifierPart(text.charCodeAt(endPosition), 99 /* Latest */ ))) positions.push(position); - position = text.indexOf(symbolName2, position + symbolNameLength + 1); + } + } + const semanticStart = timestamp(); + let completionKind = 5 /* None */ ; + let isNonContextualObjectLiteral = false; + let hasUnresolvedAutoImports = false; + let symbols = []; + let importSpecifierResolver; + const symbolToOriginInfoMap = []; + const symbolToSortTextMap = []; + const seenPropertySymbols = /* @__PURE__ */ new Map(); + const isTypeOnlyLocation = isTypeOnlyCompletion(); + const getModuleSpecifierResolutionHost = memoizeOne((isFromPackageJson)=>{ + return createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); + }); + if (isRightOfDot || isRightOfQuestionDot) getTypeScriptMemberSymbols(); + else if (isRightOfOpenTag) { + symbols = typeChecker.getJsxIntrinsicTagNamesAt(location); + Debug.assertEachIsDefined(symbols, "getJsxIntrinsicTagNames() should all be defined"); + tryGetGlobalSymbols(); + completionKind = 1 /* Global */ ; + keywordFilters = 0 /* None */ ; + } else if (isStartingCloseTag) { + const tagName = contextToken.parent.parent.openingElement.tagName; + const tagSymbol = typeChecker.getSymbolAtLocation(tagName); + if (tagSymbol) symbols = [ + tagSymbol + ]; + completionKind = 1 /* Global */ ; + keywordFilters = 0 /* None */ ; + } else { + if (!tryGetGlobalSymbols()) return keywordFilters ? keywordCompletionData(keywordFilters, isJsOnlyLocation, isNewIdentifierLocation) : void 0; + } + log("getCompletionData: Semantic work: " + (timestamp() - semanticStart)); + const contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker); + const isLiteralExpected = !tryCast(previousToken, isStringLiteralLike) && !isJsxIdentifierExpected; + const literals = !isLiteralExpected ? [] : mapDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [ + contextualType + ]), (t)=>t.isLiteral() && !(t.flags & 1024 /* EnumLiteral */ ) ? t.value : void 0); + const recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker); + return { + kind: 0 /* Data */ , + symbols: symbols, + completionKind: completionKind, + isInSnippetScope: isInSnippetScope, + propertyAccessToConvert: propertyAccessToConvert, + isNewIdentifierLocation: isNewIdentifierLocation, + location: location, + keywordFilters: keywordFilters, + literals: literals, + symbolToOriginInfoMap: symbolToOriginInfoMap, + recommendedCompletion: recommendedCompletion, + previousToken: previousToken, + contextToken: contextToken, + isJsxInitializer: isJsxInitializer, + insideJsDocTagTypeExpression: insideJsDocTagTypeExpression, + symbolToSortTextMap: symbolToSortTextMap, + isTypeOnlyLocation: isTypeOnlyLocation, + isJsxIdentifierExpected: isJsxIdentifierExpected, + isRightOfOpenTag: isRightOfOpenTag, + isRightOfDotOrQuestionDot: isRightOfDot || isRightOfQuestionDot, + importStatementCompletion: importStatementCompletion, + hasUnresolvedAutoImports: hasUnresolvedAutoImports, + flags: flags + }; + function isTagWithTypeExpression(tag) { + switch(tag.kind){ + case 348 /* JSDocParameterTag */ : + case 355 /* JSDocPropertyTag */ : + case 349 /* JSDocReturnTag */ : + case 351 /* JSDocTypeTag */ : + case 353 /* JSDocTypedefTag */ : + case 356 /* JSDocThrowsTag */ : + case 357 /* JSDocSatisfiesTag */ : + return true; + case 352 /* JSDocTemplateTag */ : + return !!tag.constraint; + default: + return false; + } + } + function tryGetTypeExpressionFromTag(tag) { + if (isTagWithTypeExpression(tag)) { + const typeExpression = isJSDocTemplateTag(tag) ? tag.constraint : tag.typeExpression; + return typeExpression && typeExpression.kind === 316 /* JSDocTypeExpression */ ? typeExpression : void 0; + } + if (isJSDocAugmentsTag(tag) || isJSDocImplementsTag(tag)) return tag.class; + return void 0; + } + function getTypeScriptMemberSymbols() { + completionKind = 2 /* PropertyAccess */ ; + const isImportType = isLiteralImportTypeNode(node); + const isTypeLocation = isImportType && !node.isTypeOf || isPartOfTypeNode(node.parent) || isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); + const isRhsOfImportDeclaration = isInRightSideOfInternalImportEqualsDeclaration(node); + if (isEntityName(node) || isImportType || isPropertyAccessExpression(node)) { + const isNamespaceName = isModuleDeclaration(node.parent); + if (isNamespaceName) isNewIdentifierLocation = true; + let symbol = typeChecker.getSymbolAtLocation(node); + if (symbol) { + symbol = skipAlias(symbol, typeChecker); + if (symbol.flags & 1920 /* Enum */ ) { + const exportedSymbols = typeChecker.getExportsOfModule(symbol); + Debug.assertEachIsDefined(exportedSymbols, "getExportsOfModule() should all be defined"); + const isValidValueAccess = (symbol2)=>typeChecker.isValidPropertyAccess(isImportType ? node : node.parent, symbol2.name); + const isValidTypeAccess = (symbol2)=>symbolCanBeReferencedAtTypeLocation(symbol2, typeChecker); + const isValidAccess = isNamespaceName ? (symbol2)=>{ + var _a; + return !!(symbol2.flags & 1920 /* Namespace */ ) && !((_a = symbol2.declarations) == null ? void 0 : _a.every((d)=>d.parent === node.parent)); + } : isRhsOfImportDeclaration ? // Any kind is allowed when dotting off namespace in internal import equals declaration + (symbol2)=>isValidTypeAccess(symbol2) || isValidValueAccess(symbol2) : isTypeLocation || insideJsDocTagTypeExpression ? isValidTypeAccess : isValidValueAccess; + for (const exportedSymbol of exportedSymbols)if (isValidAccess(exportedSymbol)) symbols.push(exportedSymbol); + if (!isTypeLocation && !insideJsDocTagTypeExpression && symbol.declarations && symbol.declarations.some((d)=>d.kind !== 312 /* SourceFile */ && d.kind !== 267 /* ModuleDeclaration */ && d.kind !== 266 /* EnumDeclaration */ )) { + let type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType(); + let insertQuestionDot = false; + if (type.isNullableType()) { + const canCorrectToQuestionDot = isRightOfDot && !isRightOfQuestionDot && preferences.includeAutomaticOptionalChainCompletions !== false; + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) insertQuestionDot = true; + } + } + addTypeProperties(type, !!(node.flags & 65536 /* AwaitContext */ ), insertQuestionDot); + } + return; } - return positions; } - function getLabelReferencesInNode(container, targetLabel) { - const sourceFile = container.getSourceFile(); - const labelName = targetLabel.text; - const references = mapDefined(getPossibleSymbolReferenceNodes(sourceFile, labelName, container), (node)=>// Only pick labels that are either the target label, or have a target that is the target label - node === targetLabel || isJumpStatementTarget(node) && getTargetLabel(node, labelName) === targetLabel ? nodeEntry(node) : void 0); - return [ - { - definition: { - type: 1 /* Label */ , - node: targetLabel - }, - references: references + } + if (!isTypeLocation || isInTypeQuery(node)) { + typeChecker.tryGetThisTypeAt(node, /*includeGlobalThis*/ false); + let type = typeChecker.getTypeAtLocation(node).getNonOptionalType(); + if (!isTypeLocation) { + let insertQuestionDot = false; + if (type.isNullableType()) { + const canCorrectToQuestionDot = isRightOfDot && !isRightOfQuestionDot && preferences.includeAutomaticOptionalChainCompletions !== false; + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) insertQuestionDot = true; } - ]; + } + addTypeProperties(type, !!(node.flags & 65536 /* AwaitContext */ ), insertQuestionDot); + } else addTypeProperties(type.getNonNullableType(), /*insertAwait*/ false, /*insertQuestionDot*/ false); + } + } + function addTypeProperties(type, insertAwait, insertQuestionDot) { + isNewIdentifierLocation = !!type.getStringIndexType(); + if (isRightOfQuestionDot && some(type.getCallSignatures())) isNewIdentifierLocation = true; + const propertyAccess = node.kind === 205 /* ImportType */ ? node : node.parent; + if (inCheckedFile) { + for (const symbol of type.getApparentProperties())if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, symbol)) addPropertySymbol(symbol, /*insertAwait*/ false, insertQuestionDot); + } else symbols.push(...filter(getPropertiesForCompletion(type, typeChecker), (s)=>typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, s))); + if (insertAwait && preferences.includeCompletionsWithInsertText) { + const promiseType = typeChecker.getPromisedTypeOfPromise(type); + if (promiseType) { + for (const symbol of promiseType.getApparentProperties())if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, promiseType, symbol)) addPropertySymbol(symbol, /*insertAwait*/ true, insertQuestionDot); } - function isValidReferencePosition(node, searchSymbolName) { - switch(node.kind){ - case 80 /* PrivateIdentifier */ : - if (isJSDocMemberName(node.parent)) return true; - case 79 /* Identifier */ : - return node.text.length === searchSymbolName.length; - case 14 /* NoSubstitutionTemplateLiteral */ : - case 10 /* StringLiteral */ : + } + } + function addPropertySymbol(symbol, insertAwait, insertQuestionDot) { + var _a; + const computedPropertyName = firstDefined(symbol.declarations, (decl)=>tryCast(getNameOfDeclaration(decl), isComputedPropertyName)); + if (computedPropertyName) { + const leftMostName = getLeftMostName(computedPropertyName.expression); + const nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName); + const firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker); + const firstAccessibleSymbolId = firstAccessibleSymbol && getSymbolId(firstAccessibleSymbol); + if (firstAccessibleSymbolId && addToSeen(seenPropertySymbols, firstAccessibleSymbolId)) { + const index = symbols.length; + symbols.push(firstAccessibleSymbol); + const moduleSymbol = firstAccessibleSymbol.parent; + if (!moduleSymbol || !isExternalModuleSymbol(moduleSymbol) || typeChecker.tryGetMemberInModuleExportsAndProperties(firstAccessibleSymbol.name, moduleSymbol) !== firstAccessibleSymbol) symbolToOriginInfoMap[index] = { + kind: getNullableSymbolOriginInfoKind(2 /* SymbolMemberNoExport */ ) + }; + else { + const fileName = isExternalModuleNameRelative(stripQuotes(moduleSymbol.name)) ? (_a = getSourceFileOfModule(moduleSymbol)) == null ? void 0 : _a.fileName : void 0; + const { moduleSpecifier: moduleSpecifier } = (importSpecifierResolver || (importSpecifierResolver = ts_codefix_exports.createImportSpecifierResolver(sourceFile, program, host, preferences))).getModuleSpecifierForBestExportInfo([ { - const str = node; - return (isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || isNameOfModuleDeclaration(node) || isExpressionOfExternalModuleImportEqualsDeclaration(node) || isCallExpression(node.parent) && isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node) && str.text.length === searchSymbolName.length; + exportKind: 0 /* Named */ , + moduleFileName: fileName, + isFromPackageJson: false, + moduleSymbol: moduleSymbol, + symbol: firstAccessibleSymbol, + targetFlags: skipAlias(firstAccessibleSymbol, typeChecker).flags } - case 8 /* NumericLiteral */ : - return isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; - case 88 /* DefaultKeyword */ : - return 7 === searchSymbolName.length; - default: - return false; - } - } - function getAllReferencesForImportMeta(sourceFiles, cancellationToken) { - const references = flatMap(sourceFiles, (sourceFile)=>{ - cancellationToken.throwIfCancellationRequested(); - return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "meta", sourceFile), (node)=>{ - const parent2 = node.parent; - if (isImportMeta(parent2)) return nodeEntry(parent2); - }); - }); - return references.length ? [ - { - definition: { - type: 2 /* Keyword */ , - node: references[0].node - }, - references: references - } - ] : void 0; - } - function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken, filter2) { - const references = flatMap(sourceFiles, (sourceFile)=>{ - cancellationToken.throwIfCancellationRequested(); - return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, tokenToString(keywordKind), sourceFile), (referenceLocation)=>{ - if (referenceLocation.kind === keywordKind && (!filter2 || filter2(referenceLocation))) return nodeEntry(referenceLocation); - }); - }); - return references.length ? [ - { - definition: { - type: 2 /* Keyword */ , - node: references[0].node - }, - references: references + ], position, isValidTypeOnlyAliasUseSite(location)) || {}; + if (moduleSpecifier) { + const origin = { + kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */ ), + moduleSymbol: moduleSymbol, + isDefaultExport: false, + symbolName: firstAccessibleSymbol.name, + exportName: firstAccessibleSymbol.name, + fileName: fileName, + moduleSpecifier: moduleSpecifier + }; + symbolToOriginInfoMap[index] = origin; } - ] : void 0; - } - function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere = true) { - state.cancellationToken.throwIfCancellationRequested(); - return getReferencesInContainer(sourceFile, sourceFile, search, state, addReferencesHere); - } - function getReferencesInContainer(container, sourceFile, search, state, addReferencesHere) { - if (!state.markSearchedSymbols(sourceFile, search.allSearchSymbols)) return; - for (const position of getPossibleSymbolReferencePositions(sourceFile, search.text, container))getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere); - } - function hasMatchingMeaning(referenceLocation, state) { - return !!(getMeaningFromLocation(referenceLocation) & state.searchMeaning); - } - function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) { - const referenceLocation = getTouchingPropertyName(sourceFile, position); - if (!isValidReferencePosition(referenceLocation, search.text)) { - if (!state.options.implementations && (state.options.findInStrings && isInString(sourceFile, position) || state.options.findInComments && isInNonReferenceComment(sourceFile, position))) state.addStringOrCommentReference(sourceFile.fileName, createTextSpan(position, search.text.length)); - return; } - if (!hasMatchingMeaning(referenceLocation, state)) return; - let referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation); - if (!referenceSymbol) return; - const parent2 = referenceLocation.parent; - if (isImportSpecifier(parent2) && parent2.propertyName === referenceLocation) return; - if (isExportSpecifier(parent2)) { - Debug.assert(referenceLocation.kind === 79 /* Identifier */ ); - getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent2, search, state, addReferencesHere); - return; - } - const relatedSymbol = getRelatedSymbol(search, referenceSymbol, referenceLocation, state); - if (!relatedSymbol) { - getReferenceForShorthandProperty(referenceSymbol, search, state); - return; - } - switch(state.specialSearchKind){ - case 0 /* None */ : - if (addReferencesHere) addReference(referenceLocation, relatedSymbol, state); - break; - case 1 /* Constructor */ : - addConstructorReferences(referenceLocation, sourceFile, search, state); - break; - case 2 /* Class */ : - addClassStaticThisReferences(referenceLocation, search, state); - break; - default: - Debug.assertNever(state.specialSearchKind); - } - if (isInJSFile(referenceLocation) && isBindingElement(referenceLocation.parent) && isVariableDeclarationInitializedToBareOrAccessedRequire(referenceLocation.parent.parent.parent)) { - referenceSymbol = referenceLocation.parent.symbol; - if (!referenceSymbol) return; - } - getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); - } - function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { - Debug.assert(!alwaysGetReferences || !!state.options.providePrefixAndSuffixTextForRename, "If alwaysGetReferences is true, then prefix/suffix text must be enabled"); - const { parent: parent2 , propertyName: propertyName , name: name } = exportSpecifier; - const exportDeclaration = parent2.parent; - const localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); - if (!alwaysGetReferences && !search.includes(localSymbol)) return; - if (!propertyName) { - if (!(state.options.use === 2 /* Rename */ && name.escapedText === "default" /* Default */ )) addRef(); - } else if (referenceLocation === propertyName) { - if (!exportDeclaration.moduleSpecifier) addRef(); - if (addReferencesHere && state.options.use !== 2 /* Rename */ && state.markSeenReExportRHS(name)) addReference(name, Debug.checkDefined(exportSpecifier.symbol), state); - } else if (state.markSeenReExportRHS(referenceLocation)) addRef(); - if (!isForRenameWithPrefixAndSuffixText(state.options) || alwaysGetReferences) { - const isDefaultExport = referenceLocation.escapedText === "default" || exportSpecifier.name.escapedText === "default"; - const exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */ ; - const exportSymbol = Debug.checkDefined(exportSpecifier.symbol); - const exportInfo = getExportInfo(exportSymbol, exportKind, state.checker); - if (exportInfo) searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); - } - if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !isForRenameWithPrefixAndSuffixText(state.options)) { - const imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); - if (imported) searchForImportedSymbol(imported, state); - } - function addRef() { - if (addReferencesHere) addReference(referenceLocation, localSymbol, state); - } - } - function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) { - return isExportSpecifierAlias(referenceLocation, exportSpecifier) && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier) || referenceSymbol; - } - function isExportSpecifierAlias(referenceLocation, exportSpecifier) { - const { parent: parent2 , propertyName: propertyName , name: name } = exportSpecifier; - Debug.assert(propertyName === referenceLocation || name === referenceLocation); - if (propertyName) return propertyName === referenceLocation; - else return !parent2.parent.moduleSpecifier; - } - function getImportOrExportReferences(referenceLocation, referenceSymbol, search, state) { - const importOrExport = getImportOrExportSymbol(referenceLocation, referenceSymbol, state.checker, search.comingFrom === 1 /* Export */ ); - if (!importOrExport) return; - const { symbol: symbol } = importOrExport; - if (importOrExport.kind === 0 /* Import */ ) { - if (!isForRenameWithPrefixAndSuffixText(state.options)) searchForImportedSymbol(symbol, state); - } else searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state); - } - function getReferenceForShorthandProperty({ flags: flags , valueDeclaration: valueDeclaration }, search, state) { - const shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration); - const name = valueDeclaration && getNameOfDeclaration(valueDeclaration); - if (!(flags & 33554432 /* Transient */ ) && name && search.includes(shorthandValueSymbol)) addReference(name, shorthandValueSymbol, state); + } else if (preferences.includeCompletionsWithInsertText) { + if (firstAccessibleSymbolId && seenPropertySymbols.has(firstAccessibleSymbolId)) return; + addSymbolOriginInfo(symbol); + addSymbolSortInfo(symbol); + symbols.push(symbol); } - function addReference(referenceLocation, relatedSymbol, state) { - const { kind: kind , symbol: symbol } = "kind" in relatedSymbol ? relatedSymbol : { - kind: void 0, - symbol: relatedSymbol + } else { + addSymbolOriginInfo(symbol); + addSymbolSortInfo(symbol); + symbols.push(symbol); + } + function addSymbolSortInfo(symbol2) { + if (isStaticProperty(symbol2)) symbolToSortTextMap[getSymbolId(symbol2)] = SortText.LocalDeclarationPriority; + } + function addSymbolOriginInfo(symbol2) { + if (preferences.includeCompletionsWithInsertText) { + if (insertAwait && addToSeen(seenPropertySymbols, getSymbolId(symbol2))) symbolToOriginInfoMap[symbols.length] = { + kind: getNullableSymbolOriginInfoKind(8 /* Promise */ ) + }; + else if (insertQuestionDot) symbolToOriginInfoMap[symbols.length] = { + kind: 16 /* Nullable */ }; - if (state.options.use === 2 /* Rename */ && referenceLocation.kind === 88 /* DefaultKeyword */ ) return; - const addRef = state.referenceAdder(symbol); - if (state.options.implementations) addImplementationReferences(referenceLocation, addRef, state); - else addRef(referenceLocation, kind); } - function addConstructorReferences(referenceLocation, sourceFile, search, state) { - if (isNewExpressionTarget(referenceLocation)) addReference(referenceLocation, search.symbol, state); - const pusher = ()=>state.referenceAdder(search.symbol); - if (isClassLike(referenceLocation.parent)) { - Debug.assert(referenceLocation.kind === 88 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation); - findOwnConstructorReferences(search.symbol, sourceFile, pusher()); - } else { - const classExtending = tryGetClassByExtendingIdentifier(referenceLocation); - if (classExtending) { - findSuperConstructorAccesses(classExtending, pusher()); - findInheritedConstructorReferences(classExtending, state); - } + } + function getNullableSymbolOriginInfoKind(kind) { + return insertQuestionDot ? kind | 16 /* Nullable */ : kind; + } + } + function getLeftMostName(e) { + return isIdentifier(e) ? e : isPropertyAccessExpression(e) ? getLeftMostName(e.expression) : void 0; + } + function tryGetGlobalSymbols() { + const result = tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() || tryGetObjectLikeCompletionSymbols() || tryGetImportCompletionSymbols() || tryGetImportOrExportClauseCompletionSymbols() || tryGetLocalNamedExportCompletionSymbols() || tryGetConstructorCompletion() || tryGetClassLikeCompletionSymbols() || tryGetJsxCompletionSymbols() || (getGlobalCompletions(), 1 /* Success */ ); + return result === 1 /* Success */ ; + } + function tryGetConstructorCompletion() { + if (!tryGetConstructorLikeCompletionContainer(contextToken)) return 0 /* Continue */ ; + completionKind = 5 /* None */ ; + isNewIdentifierLocation = true; + keywordFilters = 4 /* ConstructorParameterKeywords */ ; + return 1 /* Success */ ; + } + function tryGetJsxCompletionSymbols() { + const jsxContainer = tryGetContainingJsxElement(contextToken); + const attrsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes); + if (!attrsType) return 0 /* Continue */ ; + const completionsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes, 4 /* Completions */ ); + symbols = concatenate(symbols, filterJsxAttributes(getPropertiesForObjectExpression(attrsType, completionsType, jsxContainer.attributes, typeChecker), jsxContainer.attributes.properties)); + setSortTextToOptionalMember(); + completionKind = 3 /* MemberLike */ ; + isNewIdentifierLocation = false; + return 1 /* Success */ ; + } + function tryGetImportCompletionSymbols() { + if (!importStatementCompletion) return 0 /* Continue */ ; + isNewIdentifierLocation = true; + collectAutoImports(); + return 1 /* Success */ ; + } + function getGlobalCompletions() { + keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */ ; + completionKind = 1 /* Global */ ; + isNewIdentifierLocation = isNewIdentifierDefinitionLocation(); + if (previousToken !== contextToken) Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); + const adjustedPosition = previousToken !== contextToken ? previousToken.getStart() : position; + const scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; + isInSnippetScope = isSnippetScope(scopeNode); + const symbolMeanings = (isTypeOnlyLocation ? 0 /* None */ : 111551 /* Value */ ) | 2887656 /* Alias */ ; + const typeOnlyAliasNeedsPromotion = previousToken && !isValidTypeOnlyAliasUseSite(previousToken); + symbols = concatenate(symbols, typeChecker.getSymbolsInScope(scopeNode, symbolMeanings)); + Debug.assertEachIsDefined(symbols, "getSymbolsInScope() should all be defined"); + for(let i = 0; i < symbols.length; i++){ + const symbol = symbols[i]; + if (!typeChecker.isArgumentsSymbol(symbol) && !some(symbol.declarations, (d)=>d.getSourceFile() === sourceFile)) symbolToSortTextMap[getSymbolId(symbol)] = SortText.GlobalsOrKeywords; + if (typeOnlyAliasNeedsPromotion && !(symbol.flags & 111551 /* Value */ )) { + const typeOnlyAliasDeclaration = symbol.declarations && find(symbol.declarations, isTypeOnlyImportDeclaration); + if (typeOnlyAliasDeclaration) { + const origin = { + kind: 64 /* TypeOnlyAlias */ , + declaration: typeOnlyAliasDeclaration + }; + symbolToOriginInfoMap[i] = origin; } } - function addClassStaticThisReferences(referenceLocation, search, state) { - addReference(referenceLocation, search.symbol, state); - const classLike = referenceLocation.parent; - if (state.options.use === 2 /* Rename */ || !isClassLike(classLike)) return; - Debug.assert(classLike.name === referenceLocation); - const addRef = state.referenceAdder(search.symbol); - for (const member of classLike.members){ - if (!(isMethodOrAccessor(member) && isStatic(member))) continue; - if (member.body) member.body.forEachChild(function cb(node) { - if (node.kind === 108 /* ThisKeyword */ ) addRef(node); - else if (!isFunctionLike(node) && !isClassLike(node)) node.forEachChild(cb); - }); - } + } + if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 312 /* SourceFile */ ) { + const thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false, isClassLike(scopeNode.parent) ? scopeNode : void 0); + if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) for (const symbol of getPropertiesForCompletion(thisType, typeChecker)){ + symbolToOriginInfoMap[symbols.length] = { + kind: 1 /* ThisType */ + }; + symbols.push(symbol); + symbolToSortTextMap[getSymbolId(symbol)] = SortText.SuggestedClassMembers; } - function findOwnConstructorReferences(classSymbol, sourceFile, addNode) { - const constructorSymbol = getClassConstructorSymbol(classSymbol); - if (constructorSymbol && constructorSymbol.declarations) for (const decl of constructorSymbol.declarations){ - const ctrKeyword = findChildOfKind(decl, 135 /* ConstructorKeyword */ , sourceFile); - Debug.assert(decl.kind === 173 /* Constructor */ && !!ctrKeyword); - addNode(ctrKeyword); - } - if (classSymbol.exports) classSymbol.exports.forEach((member)=>{ - const decl = member.valueDeclaration; - if (decl && decl.kind === 171 /* MethodDeclaration */ ) { - const body = decl.body; - if (body) forEachDescendantOfKind(body, 108 /* ThisKeyword */ , (thisKeyword)=>{ - if (isNewExpressionTarget(thisKeyword)) addNode(thisKeyword); - }); - } - }); - } - function getClassConstructorSymbol(classSymbol) { - return classSymbol.members && classSymbol.members.get("__constructor" /* Constructor */ ); - } - function findSuperConstructorAccesses(classDeclaration, addNode) { - const constructor = getClassConstructorSymbol(classDeclaration.symbol); - if (!(constructor && constructor.declarations)) return; - for (const decl of constructor.declarations){ - Debug.assert(decl.kind === 173 /* Constructor */ ); - const body = decl.body; - if (body) forEachDescendantOfKind(body, 106 /* SuperKeyword */ , (node)=>{ - if (isCallExpressionTarget(node)) addNode(node); - }); - } - } - function hasOwnConstructor(classDeclaration) { - return !!getClassConstructorSymbol(classDeclaration.symbol); + } + collectAutoImports(); + if (isTypeOnlyLocation) keywordFilters = contextToken && isAssertionExpression(contextToken.parent) ? 6 /* TypeAssertionKeywords */ : 7 /* TypeKeywords */ ; + } + function shouldOfferImportCompletions() { + if (importStatementCompletion) return true; + if (isNonContextualObjectLiteral) return false; + if (!preferences.includeCompletionsForModuleExports) return false; + if (sourceFile.externalModuleIndicator || sourceFile.commonJsModuleIndicator) return true; + if (compilerOptionsIndicateEsModules(program.getCompilerOptions())) return true; + return programContainsModules(program); + } + function isSnippetScope(scopeNode) { + switch(scopeNode.kind){ + case 312 /* SourceFile */ : + case 228 /* TemplateExpression */ : + case 294 /* JsxExpression */ : + case 241 /* Block */ : + return true; + default: + return isStatement(scopeNode); + } + } + function isTypeOnlyCompletion() { + return insideJsDocTagTypeExpression || !!importStatementCompletion && isTypeOnlyImportOrExportDeclaration(location.parent) || !isContextTokenValueLocation(contextToken) && (isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker) || isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); + } + function isContextTokenValueLocation(contextToken2) { + return contextToken2 && (contextToken2.kind === 114 /* TypeOfKeyword */ && (contextToken2.parent.kind === 186 /* TypeQuery */ || isTypeOfExpression(contextToken2.parent)) || contextToken2.kind === 131 /* AssertsKeyword */ && contextToken2.parent.kind === 182 /* TypePredicate */ ); + } + function isContextTokenTypeLocation(contextToken2) { + if (contextToken2) { + const parentKind = contextToken2.parent.kind; + switch(contextToken2.kind){ + case 59 /* ColonToken */ : + return parentKind === 172 /* PropertyDeclaration */ || parentKind === 171 /* PropertySignature */ || parentKind === 169 /* Parameter */ || parentKind === 260 /* VariableDeclaration */ || isFunctionLikeKind(parentKind); + case 64 /* EqualsToken */ : + return parentKind === 265 /* TypeAliasDeclaration */ ; + case 130 /* AsKeyword */ : + return parentKind === 234 /* AsExpression */ ; + case 30 /* LessThanToken */ : + return parentKind === 183 /* TypeReference */ || parentKind === 216 /* TypeAssertionExpression */ ; + case 96 /* ExtendsKeyword */ : + return parentKind === 168 /* TypeParameter */ ; + case 152 /* SatisfiesKeyword */ : + return parentKind === 238 /* SatisfiesExpression */ ; } - function findInheritedConstructorReferences(classDeclaration, state) { - if (hasOwnConstructor(classDeclaration)) return; - const classSymbol = classDeclaration.symbol; - const search = state.createSearch(/*location*/ void 0, classSymbol, /*comingFrom*/ void 0); - getReferencesInContainerOrFiles(classSymbol, state, search); + } + return false; + } + function collectAutoImports() { + var _a, _b; + if (!shouldOfferImportCompletions()) return; + Debug.assert(!(detailsEntryId == null ? void 0 : detailsEntryId.data), "Should not run 'collectAutoImports' when faster path is available via `data`"); + if (detailsEntryId && !detailsEntryId.source) return; + flags |= 1 /* MayIncludeAutoImports */ ; + const isAfterTypeOnlyImportSpecifierModifier = previousToken === contextToken && importStatementCompletion; + const lowerCaseTokenText = isAfterTypeOnlyImportSpecifierModifier ? "" : previousToken && isIdentifier(previousToken) ? previousToken.text.toLowerCase() : ""; + const moduleSpecifierCache = (_a = host.getModuleSpecifierCache) == null ? void 0 : _a.call(host); + const exportInfo = getExportInfoMap(sourceFile, host, program, preferences, cancellationToken); + const packageJsonAutoImportProvider = (_b = host.getPackageJsonAutoImportProvider) == null ? void 0 : _b.call(host); + const packageJsonFilter = detailsEntryId ? void 0 : createPackageJsonImportFilter(sourceFile, preferences, host); + resolvingModuleSpecifiers("collectAutoImports", host, importSpecifierResolver || (importSpecifierResolver = ts_codefix_exports.createImportSpecifierResolver(sourceFile, program, host, preferences)), program, position, preferences, !!importStatementCompletion, isValidTypeOnlyAliasUseSite(location), (context)=>{ + exportInfo.search(sourceFile.path, /*preferCapitalized*/ isRightOfOpenTag, (symbolName2, targetFlags)=>{ + if (!isIdentifierText(symbolName2, getEmitScriptTarget(host.getCompilationSettings()))) return false; + if (!detailsEntryId && isStringANonContextualKeyword(symbolName2)) return false; + if (!isTypeOnlyLocation && !importStatementCompletion && !(targetFlags & 111551 /* Value */ )) return false; + if (isTypeOnlyLocation && !(targetFlags & 790504 /* Type */ )) return false; + const firstChar = symbolName2.charCodeAt(0); + if (isRightOfOpenTag && (firstChar < 65 /* A */ || firstChar > 90 /* Z */ )) return false; + if (detailsEntryId) return true; + return charactersFuzzyMatchInString(symbolName2, lowerCaseTokenText); + }, (info, symbolName2, isFromAmbientModule, exportMapKey)=>{ + if (detailsEntryId && !some(info, (i)=>detailsEntryId.source === stripQuotes(i.moduleSymbol.name))) return; + info = filter(info, isImportableExportInfo); + if (!info.length) return; + const result = context.tryResolve(info, isFromAmbientModule) || {}; + if (result === "failed") return; + let exportInfo2 = info[0], moduleSpecifier; + if (result !== "skipped") ({ exportInfo: exportInfo2 = info[0], moduleSpecifier: moduleSpecifier } = result); + const isDefaultExport = exportInfo2.exportKind === 1 /* Default */ ; + const symbol = isDefaultExport && getLocalSymbolForExportDefault(exportInfo2.symbol) || exportInfo2.symbol; + pushAutoImportSymbol(symbol, { + kind: moduleSpecifier ? 32 /* ResolvedExport */ : 4 /* Export */ , + moduleSpecifier: moduleSpecifier, + symbolName: symbolName2, + exportMapKey: exportMapKey, + exportName: exportInfo2.exportKind === 2 /* ExportEquals */ ? "export=" /* ExportEquals */ : exportInfo2.symbol.name, + fileName: exportInfo2.moduleFileName, + isDefaultExport: isDefaultExport, + moduleSymbol: exportInfo2.moduleSymbol, + isFromPackageJson: exportInfo2.isFromPackageJson + }); + }); + hasUnresolvedAutoImports = context.skippedAny(); + flags |= context.resolvedAny() ? 8 /* ResolvedModuleSpecifiers */ : 0; + flags |= context.resolvedBeyondLimit() ? 16 /* ResolvedModuleSpecifiersBeyondLimit */ : 0; + }); + function isImportableExportInfo(info) { + const moduleFile = tryCast(info.moduleSymbol.valueDeclaration, isSourceFile); + if (!moduleFile) { + const moduleName = stripQuotes(info.moduleSymbol.name); + if (ts_JsTyping_exports.nodeCoreModules.has(moduleName) && startsWith(moduleName, "node:") !== shouldUseUriStyleNodeCoreModules(sourceFile, program)) return false; + return packageJsonFilter ? packageJsonFilter.allowsImportingAmbientModule(info.moduleSymbol, getModuleSpecifierResolutionHost(info.isFromPackageJson)) : true; } - function addImplementationReferences(refNode, addReference2, state) { - if (isDeclarationName(refNode) && isImplementation(refNode.parent)) { - addReference2(refNode); - return; - } - if (refNode.kind !== 79 /* Identifier */ ) return; - if (refNode.parent.kind === 300 /* ShorthandPropertyAssignment */ ) getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference2); - const containingClass = getContainingClassIfInHeritageClause(refNode); - if (containingClass) { - addReference2(containingClass); - return; - } - const typeNode = findAncestor(refNode, (a)=>!isQualifiedName(a.parent) && !isTypeNode(a.parent) && !isTypeElement(a.parent)); - const typeHavingNode = typeNode.parent; - if (hasType(typeHavingNode) && typeHavingNode.type === typeNode && state.markSeenContainingTypeReference(typeHavingNode)) { - if (hasInitializer(typeHavingNode)) addIfImplementation(typeHavingNode.initializer); - else if (isFunctionLike(typeHavingNode) && typeHavingNode.body) { - const body = typeHavingNode.body; - if (body.kind === 238 /* Block */ ) forEachReturnStatement(body, (returnStatement)=>{ - if (returnStatement.expression) addIfImplementation(returnStatement.expression); - }); - else addIfImplementation(body); - } else if (isAssertionExpression(typeHavingNode)) addIfImplementation(typeHavingNode.expression); - } - function addIfImplementation(e) { - if (isImplementationExpression(e)) addReference2(e); - } + return isImportableFile(info.isFromPackageJson ? packageJsonAutoImportProvider : program, sourceFile, moduleFile, preferences, packageJsonFilter, getModuleSpecifierResolutionHost(info.isFromPackageJson), moduleSpecifierCache); + } + } + function pushAutoImportSymbol(symbol, origin) { + const symbolId = getSymbolId(symbol); + if (symbolToSortTextMap[symbolId] === SortText.GlobalsOrKeywords) return; + symbolToOriginInfoMap[symbols.length] = origin; + symbolToSortTextMap[symbolId] = importStatementCompletion ? SortText.LocationPriority : SortText.AutoImportSuggestions; + symbols.push(symbol); + } + function collectObjectLiteralMethodSymbols(members, enclosingDeclaration) { + if (isInJSFile(location)) return; + members.forEach((member)=>{ + if (!isObjectLiteralMethodSymbol(member)) return; + const displayName = getCompletionEntryDisplayNameForSymbol(member, getEmitScriptTarget(compilerOptions), /*origin*/ void 0, 0 /* ObjectPropertyDeclaration */ , /*jsxIdentifierExpected*/ false); + if (!displayName) return; + const { name: name } = displayName; + const entryProps = getEntryForObjectLiteralMethodCompletion(member, name, enclosingDeclaration, program, host, compilerOptions, preferences, formatContext); + if (!entryProps) return; + const origin = { + kind: 128 /* ObjectLiteralMethod */ , + ...entryProps + }; + flags |= 32 /* MayIncludeMethodSnippets */ ; + symbolToOriginInfoMap[symbols.length] = origin; + symbols.push(member); + }); + } + function isObjectLiteralMethodSymbol(symbol) { + if (!(symbol.flags & 8196 /* Method */ )) return false; + return true; + } + function getScopeNode(initialToken, position2, sourceFile2) { + let scope = initialToken; + while(scope && !positionBelongsToNode(scope, position2, sourceFile2))scope = scope.parent; + return scope; + } + function isCompletionListBlocker(contextToken2) { + const start2 = timestamp(); + const result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken2) || isSolelyIdentifierDefinitionLocation(contextToken2) || isDotOfNumericLiteral(contextToken2) || isInJsxText(contextToken2) || isBigIntLiteral(contextToken2); + log("getCompletionsAtPosition: isCompletionListBlocker: " + (timestamp() - start2)); + return result; + } + function isInJsxText(contextToken2) { + if (contextToken2.kind === 12 /* JsxText */ ) return true; + if (contextToken2.kind === 32 /* GreaterThanToken */ && contextToken2.parent) { + if (location === contextToken2.parent && (location.kind === 286 /* JsxOpeningElement */ || location.kind === 285 /* JsxSelfClosingElement */ )) return false; + if (contextToken2.parent.kind === 286 /* JsxOpeningElement */ ) return location.parent.kind !== 286 /* JsxOpeningElement */ ; + if (contextToken2.parent.kind === 287 /* JsxClosingElement */ || contextToken2.parent.kind === 285 /* JsxSelfClosingElement */ ) return !!contextToken2.parent.parent && contextToken2.parent.parent.kind === 284 /* JsxElement */ ; + } + return false; + } + function isNewIdentifierDefinitionLocation() { + if (contextToken) { + const containingNodeKind = contextToken.parent.kind; + const tokenKind = keywordForNode(contextToken); + switch(tokenKind){ + case 28 /* CommaToken */ : + return containingNodeKind === 213 /* CallExpression */ || containingNodeKind === 176 /* Constructor */ || containingNodeKind === 214 /* NewExpression */ || containingNodeKind === 209 /* ArrayLiteralExpression */ || containingNodeKind === 226 /* BinaryExpression */ || containingNodeKind === 184 /* FunctionType */ || containingNodeKind === 210 /* ObjectLiteralExpression */ ; + case 21 /* OpenParenToken */ : + return containingNodeKind === 213 /* CallExpression */ || containingNodeKind === 176 /* Constructor */ || containingNodeKind === 214 /* NewExpression */ || containingNodeKind === 217 /* ParenthesizedExpression */ || containingNodeKind === 196 /* ParenthesizedType */ ; + case 23 /* OpenBracketToken */ : + return containingNodeKind === 209 /* ArrayLiteralExpression */ || containingNodeKind === 181 /* IndexSignature */ || containingNodeKind === 167 /* ComputedPropertyName */ ; + case 144 /* ModuleKeyword */ : + case 145 /* NamespaceKeyword */ : + case 102 /* ImportKeyword */ : + return true; + case 25 /* DotToken */ : + return containingNodeKind === 267 /* ModuleDeclaration */ ; + case 19 /* OpenBraceToken */ : + return containingNodeKind === 263 /* ClassDeclaration */ || containingNodeKind === 210 /* ObjectLiteralExpression */ ; + case 64 /* EqualsToken */ : + return containingNodeKind === 260 /* VariableDeclaration */ || containingNodeKind === 226 /* BinaryExpression */ ; + case 16 /* TemplateHead */ : + return containingNodeKind === 228 /* TemplateExpression */ ; + case 17 /* TemplateMiddle */ : + return containingNodeKind === 239 /* TemplateSpan */ ; + case 134 /* AsyncKeyword */ : + return containingNodeKind === 174 /* MethodDeclaration */ || containingNodeKind === 304 /* ShorthandPropertyAssignment */ ; + case 42 /* AsteriskToken */ : + return containingNodeKind === 174 /* MethodDeclaration */ ; } - function getContainingClassIfInHeritageClause(node) { - return isIdentifier(node) || isPropertyAccessExpression(node) ? getContainingClassIfInHeritageClause(node.parent) : isExpressionWithTypeArguments(node) ? tryCast(node.parent.parent, isClassLike) : void 0; + if (isClassMemberCompletionKeyword(tokenKind)) return true; + } + return false; + } + function isInStringOrRegularExpressionOrTemplateLiteral(contextToken2) { + return (isRegularExpressionLiteral(contextToken2) || isStringTextContainingNode(contextToken2)) && (rangeContainsPositionExclusive(contextToken2, position) || position === contextToken2.end && (!!contextToken2.isUnterminated || isRegularExpressionLiteral(contextToken2))); + } + function tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() { + const typeLiteralNode = tryGetTypeLiteralNode(contextToken); + if (!typeLiteralNode) return 0 /* Continue */ ; + const intersectionTypeNode = isIntersectionTypeNode(typeLiteralNode.parent) ? typeLiteralNode.parent : void 0; + const containerTypeNode = intersectionTypeNode || typeLiteralNode; + const containerExpectedType = getConstraintOfTypeArgumentProperty(containerTypeNode, typeChecker); + if (!containerExpectedType) return 0 /* Continue */ ; + const containerActualType = typeChecker.getTypeFromTypeNode(containerTypeNode); + const members = getPropertiesForCompletion(containerExpectedType, typeChecker); + const existingMembers = getPropertiesForCompletion(containerActualType, typeChecker); + const existingMemberEscapedNames = /* @__PURE__ */ new Set(); + existingMembers.forEach((s)=>existingMemberEscapedNames.add(s.escapedName)); + symbols = concatenate(symbols, filter(members, (s)=>!existingMemberEscapedNames.has(s.escapedName))); + completionKind = 0 /* ObjectPropertyDeclaration */ ; + isNewIdentifierLocation = true; + return 1 /* Success */ ; + } + function tryGetObjectLikeCompletionSymbols() { + const symbolsStartIndex = symbols.length; + const objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken, position, sourceFile); + if (!objectLikeContainer) return 0 /* Continue */ ; + completionKind = 0 /* ObjectPropertyDeclaration */ ; + let typeMembers; + let existingMembers; + if (objectLikeContainer.kind === 210 /* ObjectLiteralExpression */ ) { + const instantiatedType = tryGetObjectLiteralContextualType(objectLikeContainer, typeChecker); + if (instantiatedType === void 0) { + if (objectLikeContainer.flags & 67108864 /* InWithStatement */ ) return 2 /* Fail */ ; + isNonContextualObjectLiteral = true; + return 0 /* Continue */ ; } - function isImplementationExpression(node) { - switch(node.kind){ - case 214 /* ParenthesizedExpression */ : - return isImplementationExpression(node.expression); - case 216 /* ArrowFunction */ : - case 215 /* FunctionExpression */ : - case 207 /* ObjectLiteralExpression */ : - case 228 /* ClassExpression */ : - case 206 /* ArrayLiteralExpression */ : - return true; - default: - return false; + const completionsType = typeChecker.getContextualType(objectLikeContainer, 4 /* Completions */ ); + const hasStringIndexType = (completionsType || instantiatedType).getStringIndexType(); + const hasNumberIndextype = (completionsType || instantiatedType).getNumberIndexType(); + isNewIdentifierLocation = !!hasStringIndexType || !!hasNumberIndextype; + typeMembers = getPropertiesForObjectExpression(instantiatedType, completionsType, objectLikeContainer, typeChecker); + existingMembers = objectLikeContainer.properties; + if (typeMembers.length === 0) { + if (!hasNumberIndextype) { + isNonContextualObjectLiteral = true; + return 0 /* Continue */ ; } } - function explicitlyInheritsFrom(symbol, parent2, cachedResults, checker) { - if (symbol === parent2) return true; - const key = getSymbolId(symbol) + "," + getSymbolId(parent2); - const cached = cachedResults.get(key); - if (cached !== void 0) return cached; - cachedResults.set(key, false); - const inherits = !!symbol.declarations && symbol.declarations.some((declaration)=>getAllSuperTypeNodes(declaration).some((typeReference)=>{ - const type = checker.getTypeAtLocation(typeReference); - return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent2, cachedResults, checker); - })); - cachedResults.set(key, inherits); - return inherits; + } else { + Debug.assert(objectLikeContainer.kind === 206 /* ObjectBindingPattern */ ); + isNewIdentifierLocation = false; + const rootDeclaration = getRootDeclaration(objectLikeContainer.parent); + if (!isVariableLike(rootDeclaration)) return Debug.fail("Root declaration is not variable-like."); + let canGetType = hasInitializer(rootDeclaration) || !!getEffectiveTypeAnnotationNode(rootDeclaration) || rootDeclaration.parent.parent.kind === 250 /* ForOfStatement */ ; + if (!canGetType && rootDeclaration.kind === 169 /* Parameter */ ) { + if (isExpression(rootDeclaration.parent)) canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); + else if (rootDeclaration.parent.kind === 174 /* MethodDeclaration */ || rootDeclaration.parent.kind === 178 /* SetAccessor */ ) canGetType = isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } - function getReferencesForSuperKeyword(superKeyword) { - let searchSpaceNode = getSuperContainer(superKeyword, /*stopOnFunctions*/ false); - if (!searchSpaceNode) return void 0; - let staticFlag = 32 /* Static */ ; - switch(searchSpaceNode.kind){ - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 173 /* Constructor */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - staticFlag &= getSyntacticModifierFlags(searchSpaceNode); - searchSpaceNode = searchSpaceNode.parent; - break; - default: - return void 0; - } - const sourceFile = searchSpaceNode.getSourceFile(); - const references = mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), (node)=>{ - if (node.kind !== 106 /* SuperKeyword */ ) return; - const container = getSuperContainer(node, /*stopOnFunctions*/ false); - return container && isStatic(container) === !!staticFlag && container.parent.symbol === searchSpaceNode.symbol ? nodeEntry(node) : void 0; + if (canGetType) { + const typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + if (!typeForObject) return 2 /* Fail */ ; + typeMembers = typeChecker.getPropertiesOfType(typeForObject).filter((propertySymbol)=>{ + return typeChecker.isPropertyAccessible(objectLikeContainer, /*isSuper*/ false, /*isWrite*/ false, typeForObject, propertySymbol); }); - return [ - { - definition: { - type: 0 /* Symbol */ , - symbol: searchSpaceNode.symbol - }, - references: references - } - ]; + existingMembers = objectLikeContainer.elements; } - function isParameterName(node) { - return node.kind === 79 /* Identifier */ && node.parent.kind === 166 /* Parameter */ && node.parent.name === node; + } + if (typeMembers && typeMembers.length > 0) { + const filteredMembers = filterObjectMembersList(typeMembers, Debug.checkDefined(existingMembers)); + symbols = concatenate(symbols, filteredMembers); + setSortTextToOptionalMember(); + if (objectLikeContainer.kind === 210 /* ObjectLiteralExpression */ && preferences.includeCompletionsWithObjectLiteralMethodSnippets && preferences.includeCompletionsWithInsertText) { + transformObjectLiteralMembersSortText(symbolsStartIndex); + collectObjectLiteralMethodSymbols(filteredMembers, objectLikeContainer); } - function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { - let searchSpaceNode = getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false, /*includeClassComputedPropertyName*/ false); - let staticFlag = 32 /* Static */ ; - switch(searchSpaceNode.kind){ - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - if (isObjectLiteralMethod(searchSpaceNode)) { - staticFlag &= getSyntacticModifierFlags(searchSpaceNode); - searchSpaceNode = searchSpaceNode.parent; - break; - } - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : - case 173 /* Constructor */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - staticFlag &= getSyntacticModifierFlags(searchSpaceNode); - searchSpaceNode = searchSpaceNode.parent; - break; - case 308 /* SourceFile */ : - if (isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) return void 0; - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - break; - default: - return void 0; + } + return 1 /* Success */ ; + } + function tryGetImportOrExportClauseCompletionSymbols() { + if (!contextToken) return 0 /* Continue */ ; + const namedImportsOrExports = contextToken.kind === 19 /* OpenBraceToken */ || contextToken.kind === 28 /* CommaToken */ ? tryCast(contextToken.parent, isNamedImportsOrExports) : isTypeKeywordTokenOrIdentifier(contextToken) ? tryCast(contextToken.parent.parent, isNamedImportsOrExports) : void 0; + if (!namedImportsOrExports) return 0 /* Continue */ ; + if (!isTypeKeywordTokenOrIdentifier(contextToken)) keywordFilters = 8 /* TypeKeyword */ ; + const { moduleSpecifier: moduleSpecifier } = namedImportsOrExports.kind === 275 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent; + if (!moduleSpecifier) { + isNewIdentifierLocation = true; + return namedImportsOrExports.kind === 275 /* NamedImports */ ? 2 /* Fail */ : 0 /* Continue */ ; + } + const moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); + if (!moduleSpecifierSymbol) { + isNewIdentifierLocation = true; + return 2 /* Fail */ ; + } + completionKind = 3 /* MemberLike */ ; + isNewIdentifierLocation = false; + const exports = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol); + const existing = new Set(namedImportsOrExports.elements.filter((n)=>!isCurrentlyEditingNode(n)).map((n)=>(n.propertyName || n.name).escapedText)); + const uniques = exports.filter((e)=>e.escapedName !== "default" /* Default */ && !existing.has(e.escapedName)); + symbols = concatenate(symbols, uniques); + if (!uniques.length) keywordFilters = 0 /* None */ ; + return 1 /* Success */ ; + } + function tryGetLocalNamedExportCompletionSymbols() { + var _a; + const namedExports = contextToken && (contextToken.kind === 19 /* OpenBraceToken */ || contextToken.kind === 28 /* CommaToken */ ) ? tryCast(contextToken.parent, isNamedExports) : void 0; + if (!namedExports) return 0 /* Continue */ ; + const localsContainer = findAncestor(namedExports, or(isSourceFile, isModuleDeclaration)); + completionKind = 5 /* None */ ; + isNewIdentifierLocation = false; + (_a = localsContainer.locals) == null || _a.forEach((symbol, name)=>{ + var _a2, _b; + symbols.push(symbol); + if ((_b = (_a2 = localsContainer.symbol) == null ? void 0 : _a2.exports) == null ? void 0 : _b.has(name)) symbolToSortTextMap[getSymbolId(symbol)] = SortText.OptionalMember; + }); + return 1 /* Success */ ; + } + function tryGetClassLikeCompletionSymbols() { + const decl = tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location, position); + if (!decl) return 0 /* Continue */ ; + completionKind = 3 /* MemberLike */ ; + isNewIdentifierLocation = true; + keywordFilters = contextToken.kind === 42 /* AsteriskToken */ ? 0 /* None */ : isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */ ; + if (!isClassLike(decl)) return 1 /* Success */ ; + const classElement = contextToken.kind === 27 /* SemicolonToken */ ? contextToken.parent.parent : contextToken.parent; + let classElementModifierFlags = isClassElement(classElement) ? getEffectiveModifierFlags(classElement) : 0 /* None */ ; + if (contextToken.kind === 80 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) switch(contextToken.getText()){ + case "private": + classElementModifierFlags = classElementModifierFlags | 8 /* Private */ ; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | 32 /* Static */ ; + break; + case "override": + classElementModifierFlags = classElementModifierFlags | 16384 /* Override */ ; + break; + } + if (isClassStaticBlockDeclaration(classElement)) classElementModifierFlags |= 32 /* Static */ ; + if (!(classElementModifierFlags & 8 /* Private */ )) { + const baseTypeNodes = isClassLike(decl) && classElementModifierFlags & 16384 /* Override */ ? singleElementArray(getEffectiveBaseTypeNode(decl)) : getAllSuperTypeNodes(decl); + const baseSymbols = flatMap(baseTypeNodes, (baseTypeNode)=>{ + const type = typeChecker.getTypeAtLocation(baseTypeNode); + return classElementModifierFlags & 32 /* Static */ ? (type == null ? void 0 : type.symbol) && typeChecker.getPropertiesOfType(typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl)) : type && typeChecker.getPropertiesOfType(type); + }); + symbols = concatenate(symbols, filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags)); + forEach(symbols, (symbol, index)=>{ + const declaration = symbol == null ? void 0 : symbol.valueDeclaration; + if (declaration && isClassElement(declaration) && declaration.name && isComputedPropertyName(declaration.name)) { + const origin = { + kind: 512 /* ComputedPropertyName */ , + symbolName: typeChecker.symbolToString(symbol) + }; + symbolToOriginInfoMap[index] = origin; } - const references = flatMap(searchSpaceNode.kind === 308 /* SourceFile */ ? sourceFiles : [ - searchSpaceNode.getSourceFile() - ], (sourceFile)=>{ - cancellationToken.throwIfCancellationRequested(); - return getPossibleSymbolReferenceNodes(sourceFile, "this", isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter((node)=>{ - if (!isThis(node)) return false; - const container = getThisContainer(node, /* includeArrowFunctions */ false, /*includeClassComputedPropertyName*/ false); - if (!canHaveSymbol(container)) return false; - switch(searchSpaceNode.kind){ - case 215 /* FunctionExpression */ : - case 259 /* FunctionDeclaration */ : - return searchSpaceNode.symbol === container.symbol; - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - return isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; - case 228 /* ClassExpression */ : - case 260 /* ClassDeclaration */ : - case 207 /* ObjectLiteralExpression */ : - return container.parent && canHaveSymbol(container.parent) && searchSpaceNode.symbol === container.parent.symbol && isStatic(container) === !!staticFlag; - case 308 /* SourceFile */ : - return container.kind === 308 /* SourceFile */ && !isExternalModule(container) && !isParameterName(node); - } - }); - }).map((n)=>nodeEntry(n)); - const thisParameter = firstDefined(references, (r)=>isParameter(r.node.parent) ? r.node : void 0); - return [ - { - definition: { - type: 3 /* This */ , - node: thisParameter || thisOrSuperKeyword - }, - references: references - } - ]; + }); + } + return 1 /* Success */ ; + } + function isConstructorParameterCompletion(node2) { + return !!node2.parent && isParameter(node2.parent) && isConstructorDeclaration(node2.parent.parent) && (isParameterPropertyModifier(node2.kind) || isDeclarationName(node2)); + } + function tryGetConstructorLikeCompletionContainer(contextToken2) { + if (contextToken2) { + const parent2 = contextToken2.parent; + switch(contextToken2.kind){ + case 21 /* OpenParenToken */ : + case 28 /* CommaToken */ : + return isConstructorDeclaration(contextToken2.parent) ? contextToken2.parent : void 0; + default: + if (isConstructorParameterCompletion(contextToken2)) return parent2.parent; } - function getReferencesForStringLiteral(node, sourceFiles, checker, cancellationToken) { - const type = getContextualTypeFromParentOrAncestorTypeNode(node, checker); - const references = flatMap(sourceFiles, (sourceFile)=>{ - cancellationToken.throwIfCancellationRequested(); - return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), (ref)=>{ - if (isStringLiteralLike(ref) && ref.text === node.text) { - if (type) { - const refType = getContextualTypeFromParentOrAncestorTypeNode(ref, checker); - if (type !== checker.getStringType() && type === refType) return nodeEntry(ref, 2 /* StringLiteral */ ); - } else return isNoSubstitutionTemplateLiteral(ref) && !rangeIsOnSingleLine(ref, sourceFile) ? void 0 : nodeEntry(ref, 2 /* StringLiteral */ ); + } + return void 0; + } + function tryGetFunctionLikeBodyCompletionContainer(contextToken2) { + if (contextToken2) { + let prev; + const container = findAncestor(contextToken2.parent, (node2)=>{ + if (isClassLike(node2)) return "quit"; + if (isFunctionLikeDeclaration(node2) && prev === node2.body) return true; + prev = node2; + return false; + }); + return container && container; + } + } + function tryGetContainingJsxElement(contextToken2) { + if (contextToken2) { + const parent2 = contextToken2.parent; + switch(contextToken2.kind){ + case 32 /* GreaterThanToken */ : + case 31 /* LessThanSlashToken */ : + case 44 /* SlashToken */ : + case 80 /* Identifier */ : + case 211 /* PropertyAccessExpression */ : + case 292 /* JsxAttributes */ : + case 291 /* JsxAttribute */ : + case 293 /* JsxSpreadAttribute */ : + if (parent2 && (parent2.kind === 285 /* JsxSelfClosingElement */ || parent2.kind === 286 /* JsxOpeningElement */ )) { + if (contextToken2.kind === 32 /* GreaterThanToken */ ) { + const precedingToken = findPrecedingToken(contextToken2.pos, sourceFile, /*startNode*/ void 0); + if (!parent2.typeArguments || precedingToken && precedingToken.kind === 44 /* SlashToken */ ) break; } - }); - }); - return [ - { - definition: { - type: 4 /* String */ , - node: node - }, - references: references - } - ]; - } - function populateSearchSymbolSet(symbol, location, checker, isForRename, providePrefixAndSuffixText, implementations) { - const result = []; - forEachRelatedSymbol(symbol, location, checker, isForRename, !(isForRename && providePrefixAndSuffixText), (sym, root, base)=>{ - if (base) { - if (isStaticSymbol(symbol) !== isStaticSymbol(base)) base = void 0; - } - result.push(base || root || sym); - }, // when try to find implementation, implementations is true, and not allowed to find base class - /*allowBaseTypes*/ ()=>!implementations); - return result; + return parent2; + } else if (parent2.kind === 291 /* JsxAttribute */ ) return parent2.parent.parent; + break; + case 11 /* StringLiteral */ : + if (parent2 && (parent2.kind === 291 /* JsxAttribute */ || parent2.kind === 293 /* JsxSpreadAttribute */ )) return parent2.parent.parent; + break; + case 20 /* CloseBraceToken */ : + if (parent2 && parent2.kind === 294 /* JsxExpression */ && parent2.parent && parent2.parent.kind === 291 /* JsxAttribute */ ) return parent2.parent.parent.parent; + if (parent2 && parent2.kind === 293 /* JsxSpreadAttribute */ ) return parent2.parent.parent; + break; } - function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, onlyIncludeBindingElementAtReferenceLocation, cbSymbol, allowBaseTypes) { - const containingObjectLiteralElement = getContainingObjectLiteralElement(location); - if (containingObjectLiteralElement) { - const shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); - if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ void 0, /*baseSymbol*/ void 0, 3 /* SearchedLocalFoundProperty */ ); - const contextualType = checker.getContextualType(containingObjectLiteralElement.parent); - const res2 = contextualType && firstDefined(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), (sym)=>fromRoot(sym, 4 /* SearchedPropertyFoundLocal */ )); - if (res2) return res2; - const propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); - const res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ void 0, /*baseSymbol*/ void 0, 4 /* SearchedPropertyFoundLocal */ ); - if (res1) return res1; - const res22 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ void 0, /*baseSymbol*/ void 0, 3 /* SearchedLocalFoundProperty */ ); - if (res22) return res22; - } - const aliasedSymbol = getMergedAliasedSymbolOfNamespaceExportDeclaration(location, symbol, checker); - if (aliasedSymbol) { - const res2 = cbSymbol(aliasedSymbol, /*rootSymbol*/ void 0, /*baseSymbol*/ void 0, 1 /* Node */ ); - if (res2) return res2; - } - const res = fromRoot(symbol); - if (res) return res; - if (symbol.valueDeclaration && isParameterPropertyDeclaration(symbol.valueDeclaration, symbol.valueDeclaration.parent)) { - const paramProps = checker.getSymbolsOfParameterPropertyDeclaration(cast(symbol.valueDeclaration, isParameter), symbol.name); - Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */ ) && !!(paramProps[1].flags & 4 /* Property */ )); - return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); - } - const exportSpecifier = getDeclarationOfKind(symbol, 278 /* ExportSpecifier */ ); - if (!isForRenamePopulateSearchSymbolSet || exportSpecifier && !exportSpecifier.propertyName) { - const localSymbol = exportSpecifier && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); - if (localSymbol) { - const res2 = cbSymbol(localSymbol, /*rootSymbol*/ void 0, /*baseSymbol*/ void 0, 1 /* Node */ ); - if (res2) return res2; - } - } - if (!isForRenamePopulateSearchSymbolSet) { - let bindingElementPropertySymbol; - if (onlyIncludeBindingElementAtReferenceLocation) bindingElementPropertySymbol = isObjectBindingElementWithoutPropertyName(location.parent) ? getPropertySymbolFromBindingElement(checker, location.parent) : void 0; - else bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); - return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */ ); - } - Debug.assert(isForRenamePopulateSearchSymbolSet); - const includeOriginalSymbolOfBindingElement = onlyIncludeBindingElementAtReferenceLocation; - if (includeOriginalSymbolOfBindingElement) { - const bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); - return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */ ); - } - function fromRoot(sym, kind) { - return firstDefined(checker.getRootSymbols(sym), (rootSymbol)=>cbSymbol(sym, rootSymbol, /*baseSymbol*/ void 0, kind) || (rootSymbol.parent && rootSymbol.parent.flags & 96 /* Interface */ && allowBaseTypes(rootSymbol) ? getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, (base)=>cbSymbol(sym, rootSymbol, base, kind)) : void 0)); - } - function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol2, checker2) { - const bindingElement = getDeclarationOfKind(symbol2, 205 /* BindingElement */ ); - if (bindingElement && isObjectBindingElementWithoutPropertyName(bindingElement)) return getPropertySymbolFromBindingElement(checker2, bindingElement); - } - } - function getPropertySymbolsFromBaseTypes(symbol, propertyName, checker, cb) { - const seen = /* @__PURE__ */ new Map(); - return recur(symbol); - function recur(symbol2) { - if (!(symbol2.flags & 96 /* Interface */ ) || !addToSeen(seen, getSymbolId(symbol2))) return; - return firstDefined(symbol2.declarations, (declaration)=>firstDefined(getAllSuperTypeNodes(declaration), (typeReference)=>{ - const type = checker.getTypeAtLocation(typeReference); - const propertySymbol = type && type.symbol && checker.getPropertyOfType(type, propertyName); - return type && propertySymbol && (firstDefined(checker.getRootSymbols(propertySymbol), cb) || recur(type.symbol)); - })); - } - } - function isStaticSymbol(symbol) { - if (!symbol.valueDeclaration) return false; - const modifierFlags = getEffectiveModifierFlags(symbol.valueDeclaration); - return !!(modifierFlags & 32 /* Static */ ); - } - function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { - const { checker: checker } = state; - return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, /*onlyIncludeBindingElementAtReferenceLocation*/ state.options.use !== 2 /* Rename */ || !!state.options.providePrefixAndSuffixTextForRename, (sym, rootSymbol, baseSymbol, kind)=>{ - if (baseSymbol) { - if (isStaticSymbol(referenceSymbol) !== isStaticSymbol(baseSymbol)) baseSymbol = void 0; - } - return search.includes(baseSymbol || rootSymbol || sym) ? { - symbol: rootSymbol && !(getCheckFlags(sym) & 6 /* Synthetic */ ) ? rootSymbol : sym, - kind: kind - } : void 0; - }, /*allowBaseTypes*/ (rootSymbol)=>!(search.parents && !search.parents.some((parent2)=>explicitlyInheritsFrom(rootSymbol.parent, parent2, state.inheritsFromCache, checker)))); - } - function getIntersectingMeaningFromDeclarations(node, symbol) { - let meaning = getMeaningFromLocation(node); - const { declarations: declarations } = symbol; - if (declarations) { - let lastIterationMeaning; - do { - lastIterationMeaning = meaning; - for (const declaration of declarations){ - const declarationMeaning = getMeaningFromDeclaration(declaration); - if (declarationMeaning & meaning) meaning |= declarationMeaning; - } - }while (meaning !== lastIterationMeaning); - } - return meaning; - } - Core2.getIntersectingMeaningFromDeclarations = getIntersectingMeaningFromDeclarations; - function isImplementation(node) { - return !!(node.flags & 16777216 /* Ambient */ ) ? !(isInterfaceDeclaration(node) || isTypeAliasDeclaration(node)) : isVariableLike(node) ? hasInitializer(node) : isFunctionLikeDeclaration(node) ? !!node.body : isClassLike(node) || isModuleOrEnumDeclaration(node); - } - function getReferenceEntriesForShorthandPropertyAssignment(node, checker, addReference2) { - const refSymbol = checker.getSymbolAtLocation(node); - const shorthandSymbol = checker.getShorthandAssignmentValueSymbol(refSymbol.valueDeclaration); - if (shorthandSymbol) { - for (const declaration of shorthandSymbol.getDeclarations())if (getMeaningFromDeclaration(declaration) & 1 /* Value */ ) addReference2(declaration); - } - } - Core2.getReferenceEntriesForShorthandPropertyAssignment = getReferenceEntriesForShorthandPropertyAssignment; - function forEachDescendantOfKind(node, kind, action) { - forEachChild(node, (child)=>{ - if (child.kind === kind) action(child); - forEachDescendantOfKind(child, kind, action); - }); - } - function tryGetClassByExtendingIdentifier(node) { - return tryGetClassExtendingExpressionWithTypeArguments(climbPastPropertyAccess(node).parent); - } - function getParentSymbolsOfPropertyAccess(location, symbol, checker) { - const propertyAccessExpression = isRightSideOfPropertyAccess(location) ? location.parent : void 0; - const lhsType = propertyAccessExpression && checker.getTypeAtLocation(propertyAccessExpression.expression); - const res = mapDefined(lhsType && (lhsType.isUnionOrIntersection() ? lhsType.types : lhsType.symbol === symbol.parent ? void 0 : [ - lhsType - ]), (t)=>t.symbol && t.symbol.flags & 96 /* Interface */ ? t.symbol : void 0); - return res.length === 0 ? void 0 : res; - } - function isForRenameWithPrefixAndSuffixText(options) { - return options.use === 2 /* Rename */ && options.providePrefixAndSuffixTextForRename; - } - })(Core || (Core = {})); - } - }); - // src/services/_namespaces/ts.FindAllReferences.ts - var ts_FindAllReferences_exports = {}; - __export(ts_FindAllReferences_exports, { - Core: ()=>Core, - DefinitionKind: ()=>DefinitionKind, - EntryKind: ()=>EntryKind, - ExportKind: ()=>ExportKind2, - FindReferencesUse: ()=>FindReferencesUse, - ImportExport: ()=>ImportExport, - createImportTracker: ()=>createImportTracker, - findModuleReferences: ()=>findModuleReferences, - findReferenceOrRenameEntries: ()=>findReferenceOrRenameEntries, - findReferencedSymbols: ()=>findReferencedSymbols, - getContextNode: ()=>getContextNode, - getExportInfo: ()=>getExportInfo, - getImplementationsAtPosition: ()=>getImplementationsAtPosition, - getImportOrExportSymbol: ()=>getImportOrExportSymbol, - getReferenceEntriesForNode: ()=>getReferenceEntriesForNode, - getTextSpanOfEntry: ()=>getTextSpanOfEntry, - isContextWithStartAndEndNode: ()=>isContextWithStartAndEndNode, - isDeclarationOfSymbol: ()=>isDeclarationOfSymbol, - nodeEntry: ()=>nodeEntry, - toContextSpan: ()=>toContextSpan, - toHighlightSpan: ()=>toHighlightSpan, - toReferenceEntry: ()=>toReferenceEntry, - toRenameLocation: ()=>toRenameLocation - }); - var init_ts_FindAllReferences = __esm({ - "src/services/_namespaces/ts.FindAllReferences.ts" () { - "use strict"; - init_importTracker(); - init_findAllReferences(); - } - }); - // src/services/goToDefinition.ts - function getDefinitionAtPosition(program, sourceFile, position, searchOtherFilesOnly, stopAtAlias) { - var _a2, _b; - const resolvedRef = getReferenceAtPosition(sourceFile, position, program); - const fileReferenceDefinition = resolvedRef && [ - getDefinitionInfoForFileReference(resolvedRef.reference.fileName, resolvedRef.fileName, resolvedRef.unverified) - ] || emptyArray; - if (resolvedRef == null ? void 0 : resolvedRef.file) return fileReferenceDefinition; - const node = getTouchingPropertyName(sourceFile, position); - if (node === sourceFile) return void 0; - const { parent: parent2 } = node; - const typeChecker = program.getTypeChecker(); - if (node.kind === 161 /* OverrideKeyword */ || isIdentifier(node) && isJSDocOverrideTag(parent2) && parent2.tagName === node) return getDefinitionFromOverriddenMember(typeChecker, node) || emptyArray; - if (isJumpStatementTarget(node)) { - const label = getTargetLabel(node.parent, node.text); - return label ? [ - createDefinitionInfoFromName(typeChecker, label, "label" /* label */ , node.text, /*containerName*/ void 0) - ] : void 0; - } - if (node.kind === 105 /* ReturnKeyword */ ) { - const functionDeclaration = findAncestor(node.parent, (n)=>isClassStaticBlockDeclaration(n) ? "quit" : isFunctionLikeDeclaration(n)); - return functionDeclaration ? [ - createDefinitionFromSignatureDeclaration(typeChecker, functionDeclaration) - ] : void 0; + } + return void 0; } - if (node.kind === 133 /* AwaitKeyword */ ) { - const functionDeclaration = findAncestor(node, (n)=>isFunctionLikeDeclaration(n)); - const isAsyncFunction2 = functionDeclaration && some(functionDeclaration.modifiers, (node2)=>node2.kind === 132 /* AsyncKeyword */ ); - return isAsyncFunction2 ? [ - createDefinitionFromSignatureDeclaration(typeChecker, functionDeclaration) - ] : void 0; + function isSolelyIdentifierDefinitionLocation(contextToken2) { + const parent2 = contextToken2.parent; + const containingNodeKind = parent2.kind; + switch(contextToken2.kind){ + case 28 /* CommaToken */ : + return containingNodeKind === 260 /* VariableDeclaration */ || isVariableDeclarationListButNotTypeArgument(contextToken2) || containingNodeKind === 243 /* VariableStatement */ || containingNodeKind === 266 /* EnumDeclaration */ || // enum a { foo, | + isFunctionLikeButNotConstructor(containingNodeKind) || containingNodeKind === 264 /* InterfaceDeclaration */ || // interface A= contextToken2.pos; + case 25 /* DotToken */ : + return containingNodeKind === 207 /* ArrayBindingPattern */ ; + case 59 /* ColonToken */ : + return containingNodeKind === 208 /* BindingElement */ ; + case 23 /* OpenBracketToken */ : + return containingNodeKind === 207 /* ArrayBindingPattern */ ; + case 21 /* OpenParenToken */ : + return containingNodeKind === 299 /* CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind); + case 19 /* OpenBraceToken */ : + return containingNodeKind === 266 /* EnumDeclaration */ ; + case 30 /* LessThanToken */ : + return containingNodeKind === 263 /* ClassDeclaration */ || // class A< | + containingNodeKind === 231 /* ClassExpression */ || // var C = class D< | + containingNodeKind === 264 /* InterfaceDeclaration */ || // interface A< | + containingNodeKind === 265 /* TypeAliasDeclaration */ || // type List< | + isFunctionLikeKind(containingNodeKind); + case 126 /* StaticKeyword */ : + return containingNodeKind === 172 /* PropertyDeclaration */ && !isClassLike(parent2.parent); + case 26 /* DotDotDotToken */ : + return containingNodeKind === 169 /* Parameter */ || !!parent2.parent && parent2.parent.kind === 207 /* ArrayBindingPattern */ ; + case 125 /* PublicKeyword */ : + case 123 /* PrivateKeyword */ : + case 124 /* ProtectedKeyword */ : + return containingNodeKind === 169 /* Parameter */ && !isConstructorDeclaration(parent2.parent); + case 130 /* AsKeyword */ : + return containingNodeKind === 276 /* ImportSpecifier */ || containingNodeKind === 281 /* ExportSpecifier */ || containingNodeKind === 274 /* NamespaceImport */ ; + case 139 /* GetKeyword */ : + case 153 /* SetKeyword */ : + return !isFromObjectTypeDeclaration(contextToken2); + case 80 /* Identifier */ : + if (containingNodeKind === 276 /* ImportSpecifier */ && contextToken2 === parent2.name && contextToken2.text === "type") return false; + break; + case 86 /* ClassKeyword */ : + case 94 /* EnumKeyword */ : + case 120 /* InterfaceKeyword */ : + case 100 /* FunctionKeyword */ : + case 115 /* VarKeyword */ : + case 102 /* ImportKeyword */ : + case 121 /* LetKeyword */ : + case 87 /* ConstKeyword */ : + case 140 /* InferKeyword */ : + return true; + case 156 /* TypeKeyword */ : + return containingNodeKind !== 276 /* ImportSpecifier */ ; + case 42 /* AsteriskToken */ : + return isFunctionLike(contextToken2.parent) && !isMethodDeclaration(contextToken2.parent); + } + if (isClassMemberCompletionKeyword(keywordForNode(contextToken2)) && isFromObjectTypeDeclaration(contextToken2)) return false; + if (isConstructorParameterCompletion(contextToken2)) { + if (!isIdentifier(contextToken2) || isParameterPropertyModifier(keywordForNode(contextToken2)) || isCurrentlyEditingNode(contextToken2)) return false; + } + switch(keywordForNode(contextToken2)){ + case 128 /* AbstractKeyword */ : + case 86 /* ClassKeyword */ : + case 87 /* ConstKeyword */ : + case 138 /* DeclareKeyword */ : + case 94 /* EnumKeyword */ : + case 100 /* FunctionKeyword */ : + case 120 /* InterfaceKeyword */ : + case 121 /* LetKeyword */ : + case 123 /* PrivateKeyword */ : + case 124 /* ProtectedKeyword */ : + case 125 /* PublicKeyword */ : + case 126 /* StaticKeyword */ : + case 115 /* VarKeyword */ : + return true; + case 134 /* AsyncKeyword */ : + return isPropertyDeclaration(contextToken2.parent); + } + const ancestorClassLike = findAncestor(contextToken2.parent, isClassLike); + if (ancestorClassLike && contextToken2 === previousToken && isPreviousPropertyDeclarationTerminated(contextToken2, position)) return false; + const ancestorPropertyDeclaraion = getAncestor(contextToken2.parent, 172 /* PropertyDeclaration */ ); + if (ancestorPropertyDeclaraion && contextToken2 !== previousToken && isClassLike(previousToken.parent.parent) && position <= previousToken.end) { + if (isPreviousPropertyDeclarationTerminated(contextToken2, previousToken.end)) return false; + else if (contextToken2.kind !== 64 /* EqualsToken */ && (isInitializedProperty(ancestorPropertyDeclaraion) || hasType(ancestorPropertyDeclaraion))) return true; + } + return isDeclarationName(contextToken2) && !isShorthandPropertyAssignment(contextToken2.parent) && !isJsxAttribute(contextToken2.parent) && !((isClassLike(contextToken2.parent) || isInterfaceDeclaration(contextToken2.parent) || isTypeParameterDeclaration(contextToken2.parent)) && (contextToken2 !== previousToken || position > previousToken.end)); } - if (node.kind === 125 /* YieldKeyword */ ) { - const functionDeclaration = findAncestor(node, (n)=>isFunctionLikeDeclaration(n)); - const isGeneratorFunction = functionDeclaration && functionDeclaration.asteriskToken; - return isGeneratorFunction ? [ - createDefinitionFromSignatureDeclaration(typeChecker, functionDeclaration) - ] : void 0; + function isPreviousPropertyDeclarationTerminated(contextToken2, position2) { + return contextToken2.kind !== 64 /* EqualsToken */ && (contextToken2.kind === 27 /* SemicolonToken */ || !positionsAreOnSameLine(contextToken2.end, position2, sourceFile)); } - if (isStaticModifier(node) && isClassStaticBlockDeclaration(node.parent)) { - const classDecl = node.parent.parent; - const { symbol: symbol2 , failedAliasResolution: failedAliasResolution2 } = getSymbol(classDecl, typeChecker, stopAtAlias); - const staticBlocks = filter(classDecl.members, isClassStaticBlockDeclaration); - const containerName = symbol2 ? typeChecker.symbolToString(symbol2, classDecl) : ""; - const sourceFile2 = node.getSourceFile(); - return map(staticBlocks, (staticBlock)=>{ - let { pos: pos } = moveRangePastModifiers(staticBlock); - pos = skipTrivia(sourceFile2.text, pos); - return createDefinitionInfoFromName(typeChecker, staticBlock, "constructor" /* constructorImplementationElement */ , "static {}", containerName, /*unverified*/ false, failedAliasResolution2, { - start: pos, - length: 6 - }); - }); + function isFunctionLikeButNotConstructor(kind) { + return isFunctionLikeKind(kind) && kind !== 176 /* Constructor */ ; } - let { symbol: symbol , failedAliasResolution: failedAliasResolution } = getSymbol(node, typeChecker, stopAtAlias); - let fallbackNode = node; - if (searchOtherFilesOnly && failedAliasResolution) { - const importDeclaration = forEach([ - node, - ...(symbol == null ? void 0 : symbol.declarations) || emptyArray - ], (n)=>findAncestor(n, isAnyImportOrBareOrAccessedRequire)); - const moduleSpecifier = importDeclaration && tryGetModuleSpecifierFromDeclaration(importDeclaration); - if (moduleSpecifier) { - ({ symbol: symbol , failedAliasResolution: failedAliasResolution } = getSymbol(moduleSpecifier, typeChecker, stopAtAlias)); - fallbackNode = moduleSpecifier; + function isDotOfNumericLiteral(contextToken2) { + if (contextToken2.kind === 9 /* NumericLiteral */ ) { + const text = contextToken2.getFullText(); + return text.charAt(text.length - 1) === "."; } + return false; } - if (!symbol && isModuleSpecifierLike(fallbackNode)) { - const ref = (_b = (_a2 = sourceFile.resolvedModules) == null ? void 0 : _a2.get(fallbackNode.text, getModeForUsageLocation(sourceFile, fallbackNode))) == null ? void 0 : _b.resolvedModule; - if (ref) return [ - { - name: fallbackNode.text, - fileName: ref.resolvedFileName, - containerName: void 0, - containerKind: void 0, - kind: "script" /* scriptElement */ , - textSpan: createTextSpan(0, 0), - failedAliasResolution: failedAliasResolution, - isAmbient: isDeclarationFileName(ref.resolvedFileName), - unverified: fallbackNode !== node - } - ]; + function isVariableDeclarationListButNotTypeArgument(node2) { + return node2.parent.kind === 261 /* VariableDeclarationList */ && !isPossiblyTypeArgumentPosition(node2, sourceFile, typeChecker); } - if (!symbol) return concatenate(fileReferenceDefinition, getDefinitionInfoForIndexSignatures(node, typeChecker)); - if (searchOtherFilesOnly && every(symbol.declarations, (d)=>d.getSourceFile().fileName === sourceFile.fileName)) return void 0; - const calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); - if (calledDeclaration && !(isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { - const sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration, failedAliasResolution); - if (typeChecker.getRootSymbols(symbol).some((s)=>symbolMatchesSignature(s, calledDeclaration))) return [ - sigInfo - ]; - else { - const defs = getDefinitionFromSymbol(typeChecker, symbol, node, failedAliasResolution, calledDeclaration) || emptyArray; - return node.kind === 106 /* SuperKeyword */ ? [ - sigInfo, - ...defs - ] : [ - ...defs, - sigInfo - ]; + function filterObjectMembersList(contextualMemberSymbols, existingMembers) { + if (existingMembers.length === 0) return contextualMemberSymbols; + const membersDeclaredBySpreadAssignment = /* @__PURE__ */ new Set(); + const existingMemberNames = /* @__PURE__ */ new Set(); + for (const m of existingMembers){ + if (m.kind !== 303 /* PropertyAssignment */ && m.kind !== 304 /* ShorthandPropertyAssignment */ && m.kind !== 208 /* BindingElement */ && m.kind !== 174 /* MethodDeclaration */ && m.kind !== 177 /* GetAccessor */ && m.kind !== 178 /* SetAccessor */ && m.kind !== 305 /* SpreadAssignment */ ) continue; + if (isCurrentlyEditingNode(m)) continue; + let existingName; + if (isSpreadAssignment(m)) setMembersDeclaredBySpreadAssignment(m, membersDeclaredBySpreadAssignment); + else if (isBindingElement(m) && m.propertyName) { + if (m.propertyName.kind === 80 /* Identifier */ ) existingName = m.propertyName.escapedText; + } else { + const name = getNameOfDeclaration(m); + existingName = name && isPropertyNameLiteral(name) ? getEscapedTextOfIdentifierOrLiteral(name) : void 0; + } + if (existingName !== void 0) existingMemberNames.add(existingName); } + const filteredSymbols = contextualMemberSymbols.filter((m)=>!existingMemberNames.has(m.escapedName)); + setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, filteredSymbols); + return filteredSymbols; } - if (node.parent.kind === 300 /* ShorthandPropertyAssignment */ ) { - const shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); - const definitions = (shorthandSymbol == null ? void 0 : shorthandSymbol.declarations) ? shorthandSymbol.declarations.map((decl)=>createDefinitionInfo(decl, typeChecker, shorthandSymbol, node, /*unverified*/ false, failedAliasResolution)) : emptyArray; - return concatenate(definitions, getDefinitionFromObjectLiteralElement(typeChecker, node) || emptyArray); - } - if (isPropertyName(node) && isBindingElement(parent2) && isObjectBindingPattern(parent2.parent) && node === (parent2.propertyName || parent2.name)) { - const name = getNameFromPropertyName(node); - const type = typeChecker.getTypeAtLocation(parent2.parent); - return name === void 0 ? emptyArray : flatMap(type.isUnion() ? type.types : [ - type - ], (t)=>{ - const prop = t.getProperty(name); - return prop && getDefinitionFromSymbol(typeChecker, prop, node); + function setMembersDeclaredBySpreadAssignment(declaration, membersDeclaredBySpreadAssignment) { + const expression = declaration.expression; + const symbol = typeChecker.getSymbolAtLocation(expression); + const type = symbol && typeChecker.getTypeOfSymbolAtLocation(symbol, expression); + const properties = type && type.properties; + if (properties) properties.forEach((property)=>{ + membersDeclaredBySpreadAssignment.add(property.name); }); } - return concatenate(fileReferenceDefinition, getDefinitionFromObjectLiteralElement(typeChecker, node) || getDefinitionFromSymbol(typeChecker, symbol, node, failedAliasResolution)); - } - function symbolMatchesSignature(s, calledDeclaration) { - var _a2; - return s === calledDeclaration.symbol || s === calledDeclaration.symbol.parent || isAssignmentExpression(calledDeclaration.parent) || !isCallLikeExpression(calledDeclaration.parent) && s === ((_a2 = tryCast(calledDeclaration.parent, canHaveSymbol)) == null ? void 0 : _a2.symbol); - } - function getDefinitionFromObjectLiteralElement(typeChecker, node) { - const element = getContainingObjectLiteralElement(node); - if (element) { - const contextualType = element && typeChecker.getContextualType(element.parent); - if (contextualType) return flatMap(getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), (propertySymbol)=>getDefinitionFromSymbol(typeChecker, propertySymbol, node)); + function setSortTextToOptionalMember() { + symbols.forEach((m)=>{ + if (m.flags & 16777216 /* Optional */ ) { + const symbolId = getSymbolId(m); + symbolToSortTextMap[symbolId] = symbolToSortTextMap[symbolId] ?? SortText.OptionalMember; + } + }); } - } - function getDefinitionFromOverriddenMember(typeChecker, node) { - const classElement = findAncestor(node, isClassElement); - if (!(classElement && classElement.name)) return; - const baseDeclaration = findAncestor(classElement, isClassLike); - if (!baseDeclaration) return; - const baseTypeNode = getEffectiveBaseTypeNode(baseDeclaration); - if (!baseTypeNode) return; - const expression = skipParentheses(baseTypeNode.expression); - const base = isClassExpression(expression) ? expression.symbol : typeChecker.getSymbolAtLocation(expression); - if (!base) return; - const name = unescapeLeadingUnderscores(getTextOfPropertyName(classElement.name)); - const symbol = hasStaticModifier(classElement) ? typeChecker.getPropertyOfType(typeChecker.getTypeOfSymbol(base), name) : typeChecker.getPropertyOfType(typeChecker.getDeclaredTypeOfSymbol(base), name); - if (!symbol) return; - return getDefinitionFromSymbol(typeChecker, symbol, node); - } - function getReferenceAtPosition(sourceFile, position, program) { - var _a2, _b, _c, _d; - const referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); - if (referencePath) { - const file = program.getSourceFileFromReference(sourceFile, referencePath); - return file && { - reference: referencePath, - fileName: file.fileName, - file: file, - unverified: false - }; + function setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, contextualMemberSymbols) { + if (membersDeclaredBySpreadAssignment.size === 0) return; + for (const contextualMemberSymbol of contextualMemberSymbols)if (membersDeclaredBySpreadAssignment.has(contextualMemberSymbol.name)) symbolToSortTextMap[getSymbolId(contextualMemberSymbol)] = SortText.MemberDeclaredBySpreadAssignment; } - const typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); - if (typeReferenceDirective) { - const reference = (_a2 = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName, typeReferenceDirective.resolutionMode || sourceFile.impliedNodeFormat)) == null ? void 0 : _a2.resolvedTypeReferenceDirective; - const file = reference && program.getSourceFile(reference.resolvedFileName); - return file && { - reference: typeReferenceDirective, - fileName: file.fileName, - file: file, - unverified: false - }; + function transformObjectLiteralMembersSortText(start2) { + for(let i = start2; i < symbols.length; i++){ + const symbol = symbols[i]; + const symbolId = getSymbolId(symbol); + const origin = symbolToOriginInfoMap == null ? void 0 : symbolToOriginInfoMap[i]; + const target = getEmitScriptTarget(compilerOptions); + const displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, 0 /* ObjectPropertyDeclaration */ , /*jsxIdentifierExpected*/ false); + if (displayName) { + const originalSortText = symbolToSortTextMap[symbolId] ?? SortText.LocationPriority; + const { name: name } = displayName; + symbolToSortTextMap[symbolId] = SortText.ObjectLiteralProperty(originalSortText, name); + } + } } - const libReferenceDirective = findReferenceInPosition(sourceFile.libReferenceDirectives, position); - if (libReferenceDirective) { - const file = program.getLibFileFromReference(libReferenceDirective); - return file && { - reference: libReferenceDirective, - fileName: file.fileName, - file: file, - unverified: false - }; + function filterClassMembersList(baseSymbols, existingMembers, currentClassElementModifierFlags) { + const existingMemberNames = /* @__PURE__ */ new Set(); + for (const m of existingMembers){ + if (m.kind !== 172 /* PropertyDeclaration */ && m.kind !== 174 /* MethodDeclaration */ && m.kind !== 177 /* GetAccessor */ && m.kind !== 178 /* SetAccessor */ ) continue; + if (isCurrentlyEditingNode(m)) continue; + if (hasEffectiveModifier(m, 8 /* Private */ )) continue; + if (isStatic(m) !== !!(currentClassElementModifierFlags & 32 /* Static */ )) continue; + const existingName = getPropertyNameForPropertyNameNode(m.name); + if (existingName) existingMemberNames.add(existingName); + } + return baseSymbols.filter((propertySymbol)=>!existingMemberNames.has(propertySymbol.escapedName) && !!propertySymbol.declarations && !(getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */ ) && !(propertySymbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(propertySymbol.valueDeclaration))); } - if ((_b = sourceFile.resolvedModules) == null ? void 0 : _b.size()) { - const node = getTouchingToken(sourceFile, position); - if (isModuleSpecifierLike(node) && isExternalModuleNameRelative(node.text) && sourceFile.resolvedModules.has(node.text, getModeForUsageLocation(sourceFile, node))) { - const verifiedFileName = (_d = (_c = sourceFile.resolvedModules.get(node.text, getModeForUsageLocation(sourceFile, node))) == null ? void 0 : _c.resolvedModule) == null ? void 0 : _d.resolvedFileName; - const fileName = verifiedFileName || resolvePath(getDirectoryPath(sourceFile.fileName), node.text); - return { - file: program.getSourceFile(fileName), - fileName: fileName, - reference: { - pos: node.getStart(), - end: node.getEnd(), - fileName: node.text - }, - unverified: !verifiedFileName - }; + function filterJsxAttributes(symbols2, attributes) { + const seenNames = /* @__PURE__ */ new Set(); + const membersDeclaredBySpreadAssignment = /* @__PURE__ */ new Set(); + for (const attr of attributes){ + if (isCurrentlyEditingNode(attr)) continue; + if (attr.kind === 291 /* JsxAttribute */ ) seenNames.add(getEscapedTextOfJsxAttributeName(attr.name)); + else if (isJsxSpreadAttribute(attr)) setMembersDeclaredBySpreadAssignment(attr, membersDeclaredBySpreadAssignment); } + const filteredSymbols = symbols2.filter((a)=>!seenNames.has(a.escapedName)); + setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, filteredSymbols); + return filteredSymbols; + } + function isCurrentlyEditingNode(node2) { + return node2.getStart(sourceFile) <= position && position <= node2.getEnd(); } - return void 0; - } - function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { - const node = getTouchingPropertyName(sourceFile, position); - if (node === sourceFile) return void 0; - if (isImportMeta(node.parent) && node.parent.name === node) return definitionFromType(typeChecker.getTypeAtLocation(node.parent), typeChecker, node.parent, /*failedAliasResolution*/ false); - const { symbol: symbol , failedAliasResolution: failedAliasResolution } = getSymbol(node, typeChecker, /*stopAtAlias*/ false); - if (!symbol) return void 0; - const typeAtLocation = typeChecker.getTypeOfSymbolAtLocation(symbol, node); - const returnType = tryGetReturnTypeOfFunction(symbol, typeAtLocation, typeChecker); - const fromReturnType = returnType && definitionFromType(returnType, typeChecker, node, failedAliasResolution); - const typeDefinitions = fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node, failedAliasResolution); - return typeDefinitions.length ? typeDefinitions : !(symbol.flags & 111551 /* Value */ ) && symbol.flags & 788968 /* Type */ ? getDefinitionFromSymbol(typeChecker, skipAlias(symbol, typeChecker), node, failedAliasResolution) : void 0; - } - function definitionFromType(type, checker, node, failedAliasResolution) { - return flatMap(type.isUnion() && !(type.flags & 32 /* Enum */ ) ? type.types : [ - type - ], (t)=>t.symbol && getDefinitionFromSymbol(checker, t.symbol, node, failedAliasResolution)); } - function tryGetReturnTypeOfFunction(symbol, type, checker) { - if (type.symbol === symbol || // At `const f = () => {}`, the symbol is `f` and the type symbol is at `() => {}` - symbol.valueDeclaration && type.symbol && isVariableDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.initializer === type.symbol.valueDeclaration) { - const sigs = type.getCallSignatures(); - if (sigs.length === 1) return checker.getReturnTypeOfSignature(first(sigs)); + function tryGetObjectLikeCompletionContainer(contextToken, position, sourceFile) { + var _a; + if (contextToken) { + const { parent: parent2 } = contextToken; + switch(contextToken.kind){ + case 19 /* OpenBraceToken */ : + case 28 /* CommaToken */ : + if (isObjectLiteralExpression(parent2) || isObjectBindingPattern(parent2)) return parent2; + break; + case 42 /* AsteriskToken */ : + return isMethodDeclaration(parent2) ? tryCast(parent2.parent, isObjectLiteralExpression) : void 0; + case 134 /* AsyncKeyword */ : + return tryCast(parent2.parent, isObjectLiteralExpression); + case 80 /* Identifier */ : + if (contextToken.text === "async" && isShorthandPropertyAssignment(contextToken.parent)) return contextToken.parent.parent; + else { + if (isObjectLiteralExpression(contextToken.parent.parent) && (isSpreadAssignment(contextToken.parent) || isShorthandPropertyAssignment(contextToken.parent) && getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line !== getLineAndCharacterOfPosition(sourceFile, position).line)) return contextToken.parent.parent; + const ancestorNode2 = findAncestor(parent2, isPropertyAssignment); + if ((ancestorNode2 == null ? void 0 : ancestorNode2.getLastToken(sourceFile)) === contextToken && isObjectLiteralExpression(ancestorNode2.parent)) return ancestorNode2.parent; + } + break; + default: + if (((_a = parent2.parent) == null ? void 0 : _a.parent) && (isMethodDeclaration(parent2.parent) || isGetAccessorDeclaration(parent2.parent) || isSetAccessorDeclaration(parent2.parent)) && isObjectLiteralExpression(parent2.parent.parent)) return parent2.parent.parent; + if (isSpreadAssignment(parent2) && isObjectLiteralExpression(parent2.parent)) return parent2.parent; + const ancestorNode = findAncestor(parent2, isPropertyAssignment); + if (contextToken.kind !== 59 /* ColonToken */ && (ancestorNode == null ? void 0 : ancestorNode.getLastToken(sourceFile)) === contextToken && isObjectLiteralExpression(ancestorNode.parent)) return ancestorNode.parent; + } } return void 0; } - function getDefinitionAndBoundSpan(program, sourceFile, position) { - const definitions = getDefinitionAtPosition(program, sourceFile, position); - if (!definitions || definitions.length === 0) return void 0; - const comment = findReferenceInPosition(sourceFile.referencedFiles, position) || findReferenceInPosition(sourceFile.typeReferenceDirectives, position) || findReferenceInPosition(sourceFile.libReferenceDirectives, position); - if (comment) return { - definitions: definitions, - textSpan: createTextSpanFromRange(comment) - }; - const node = getTouchingPropertyName(sourceFile, position); - const textSpan = createTextSpan(node.getStart(), node.getWidth()); + function getRelevantTokens(position, sourceFile) { + const previousToken = findPrecedingToken(position, sourceFile); + if (previousToken && position <= previousToken.end && (isMemberName(previousToken) || isKeyword(previousToken.kind))) { + const contextToken = findPrecedingToken(previousToken.getFullStart(), sourceFile, /*startNode*/ void 0); + return { + contextToken: contextToken, + previousToken: previousToken + }; + } return { - definitions: definitions, - textSpan: textSpan + contextToken: previousToken, + previousToken: previousToken }; } - function getDefinitionInfoForIndexSignatures(node, checker) { - return mapDefined(checker.getIndexInfosAtLocation(node), (info)=>info.declaration && createDefinitionFromSignatureDeclaration(checker, info.declaration)); - } - function getSymbol(node, checker, stopAtAlias) { - const symbol = checker.getSymbolAtLocation(node); - let failedAliasResolution = false; - if ((symbol == null ? void 0 : symbol.declarations) && symbol.flags & 2097152 /* Alias */ && !stopAtAlias && shouldSkipAlias(node, symbol.declarations[0])) { - const aliased = checker.getAliasedSymbol(symbol); - if (aliased.declarations) return { - symbol: aliased - }; - else failedAliasResolution = true; - } + function getAutoImportSymbolFromCompletionEntryData(name, data, program, host) { + const containingProgram = data.isPackageJsonImport ? host.getPackageJsonAutoImportProvider() : program; + const checker = containingProgram.getTypeChecker(); + const moduleSymbol = data.ambientModuleName ? checker.tryFindAmbientModule(data.ambientModuleName) : data.fileName ? checker.getMergedSymbol(Debug.checkDefined(containingProgram.getSourceFile(data.fileName)).symbol) : void 0; + if (!moduleSymbol) return void 0; + let symbol = data.exportName === "export=" /* ExportEquals */ ? checker.resolveExternalModuleSymbol(moduleSymbol) : checker.tryGetMemberInModuleExportsAndProperties(data.exportName, moduleSymbol); + if (!symbol) return void 0; + const isDefaultExport = data.exportName === "default" /* Default */ ; + symbol = isDefaultExport && getLocalSymbolForExportDefault(symbol) || symbol; return { symbol: symbol, - failedAliasResolution: failedAliasResolution + origin: completionEntryDataToSymbolOriginInfo(data, name, moduleSymbol) }; } - function shouldSkipAlias(node, declaration) { - if (node.kind !== 79 /* Identifier */ ) return false; - if (node.parent === declaration) return true; - if (declaration.kind === 271 /* NamespaceImport */ ) return false; - return true; + function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, jsxIdentifierExpected) { + if (originIsIgnore(origin)) return void 0; + const name = originIncludesSymbolName(origin) ? origin.symbolName : symbol.name; + if (name === void 0 || symbol.flags & 1536 /* Module */ && isSingleOrDoubleQuote(name.charCodeAt(0)) || isKnownSymbol(symbol)) return void 0; + const validNameResult = { + name: name, + needsConvertPropertyAccess: false + }; + if (isIdentifierText(name, target, jsxIdentifierExpected ? 1 /* JSX */ : 0 /* Standard */ ) || symbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) return validNameResult; + switch(kind){ + case 3 /* MemberLike */ : + return originIsComputedPropertyName(origin) ? { + name: origin.symbolName, + needsConvertPropertyAccess: false + } : void 0; + case 0 /* ObjectPropertyDeclaration */ : + return { + name: JSON.stringify(name), + needsConvertPropertyAccess: false + }; + case 2 /* PropertyAccess */ : + case 1 /* Global */ : + return name.charCodeAt(0) === 32 /* space */ ? void 0 : { + name: name, + needsConvertPropertyAccess: true + }; + case 5 /* None */ : + case 4 /* String */ : + return validNameResult; + default: + Debug.assertNever(kind); + } } - function isExpandoDeclaration(node) { - if (!isAssignmentDeclaration(node)) return false; - const containingAssignment = findAncestor(node, (p)=>{ - if (isAssignmentExpression(p)) return true; - if (!isAssignmentDeclaration(p)) return "quit"; - return false; - }); - return !!containingAssignment && getAssignmentDeclarationKind(containingAssignment) === 5 /* Property */ ; + function getKeywordCompletions(keywordFilter, filterOutTsOnlyKeywords) { + if (!filterOutTsOnlyKeywords) return getTypescriptKeywordCompletions(keywordFilter); + const index = keywordFilter + 8 /* Last */ + 1; + return _keywordCompletions[index] || (_keywordCompletions[index] = getTypescriptKeywordCompletions(keywordFilter).filter((entry)=>!isTypeScriptOnlyKeyword(stringToToken(entry.name)))); } - function getDefinitionFromSymbol(typeChecker, symbol, node, failedAliasResolution, excludeDeclaration) { - const filteredDeclarations = filter(symbol.declarations, (d)=>d !== excludeDeclaration); - const withoutExpandos = filter(filteredDeclarations, (d)=>!isExpandoDeclaration(d)); - const results = some(withoutExpandos) ? withoutExpandos : filteredDeclarations; - return getConstructSignatureDefinition() || getCallSignatureDefinition() || map(results, (declaration)=>createDefinitionInfo(declaration, typeChecker, symbol, node, /*unverified*/ false, failedAliasResolution)); - function getConstructSignatureDefinition() { - if (symbol.flags & 32 /* Class */ && !(symbol.flags & 19 /* Variable */ ) && (isNewExpressionTarget(node) || node.kind === 135 /* ConstructorKeyword */ )) { - const cls = find(filteredDeclarations, isClassLike) || Debug.fail("Expected declaration to have at least one class-like declaration"); - return getSignatureDefinition(cls.members, /*selectConstructors*/ true); - } - } - function getCallSignatureDefinition() { - return isCallOrNewExpressionTarget(node) || isNameOfFunctionDeclaration(node) ? getSignatureDefinition(filteredDeclarations, /*selectConstructors*/ false) : void 0; - } - function getSignatureDefinition(signatureDeclarations, selectConstructors) { - if (!signatureDeclarations) return void 0; - const declarations = signatureDeclarations.filter(selectConstructors ? isConstructorDeclaration : isFunctionLike); - const declarationsWithBody = declarations.filter((d)=>!!d.body); - return declarations.length ? declarationsWithBody.length !== 0 ? declarationsWithBody.map((x)=>createDefinitionInfo(x, typeChecker, symbol, node)) : [ - createDefinitionInfo(last(declarations), typeChecker, symbol, node, /*unverified*/ false, failedAliasResolution) - ] : void 0; + function getTypescriptKeywordCompletions(keywordFilter) { + return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter((entry)=>{ + const kind = stringToToken(entry.name); + switch(keywordFilter){ + case 0 /* None */ : + return false; + case 1 /* All */ : + return isFunctionLikeBodyKeyword(kind) || kind === 138 /* DeclareKeyword */ || kind === 144 /* ModuleKeyword */ || kind === 156 /* TypeKeyword */ || kind === 145 /* NamespaceKeyword */ || kind === 128 /* AbstractKeyword */ || isTypeKeyword(kind) && kind !== 157 /* UndefinedKeyword */ ; + case 5 /* FunctionLikeBodyKeywords */ : + return isFunctionLikeBodyKeyword(kind); + case 2 /* ClassElementKeywords */ : + return isClassMemberCompletionKeyword(kind); + case 3 /* InterfaceElementKeywords */ : + return isInterfaceOrTypeLiteralCompletionKeyword(kind); + case 4 /* ConstructorParameterKeywords */ : + return isParameterPropertyModifier(kind); + case 6 /* TypeAssertionKeywords */ : + return isTypeKeyword(kind) || kind === 87 /* ConstKeyword */ ; + case 7 /* TypeKeywords */ : + return isTypeKeyword(kind); + case 8 /* TypeKeyword */ : + return kind === 156 /* TypeKeyword */ ; + default: + return Debug.assertNever(keywordFilter); + } + })); + } + function isTypeScriptOnlyKeyword(kind) { + switch(kind){ + case 128 /* AbstractKeyword */ : + case 133 /* AnyKeyword */ : + case 163 /* BigIntKeyword */ : + case 136 /* BooleanKeyword */ : + case 138 /* DeclareKeyword */ : + case 94 /* EnumKeyword */ : + case 162 /* GlobalKeyword */ : + case 119 /* ImplementsKeyword */ : + case 140 /* InferKeyword */ : + case 120 /* InterfaceKeyword */ : + case 142 /* IsKeyword */ : + case 143 /* KeyOfKeyword */ : + case 144 /* ModuleKeyword */ : + case 145 /* NamespaceKeyword */ : + case 146 /* NeverKeyword */ : + case 150 /* NumberKeyword */ : + case 151 /* ObjectKeyword */ : + case 164 /* OverrideKeyword */ : + case 123 /* PrivateKeyword */ : + case 124 /* ProtectedKeyword */ : + case 125 /* PublicKeyword */ : + case 148 /* ReadonlyKeyword */ : + case 154 /* StringKeyword */ : + case 155 /* SymbolKeyword */ : + case 156 /* TypeKeyword */ : + case 158 /* UniqueKeyword */ : + case 159 /* UnknownKeyword */ : + return true; + default: + return false; } } - function createDefinitionInfo(declaration, checker, symbol, node, unverified, failedAliasResolution) { - const symbolName2 = checker.symbolToString(symbol); - const symbolKind = ts_SymbolDisplay_exports.getSymbolKind(checker, symbol, node); - const containerName = symbol.parent ? checker.symbolToString(symbol.parent, node) : ""; - return createDefinitionInfoFromName(checker, declaration, symbolKind, symbolName2, containerName, unverified, failedAliasResolution); + function isInterfaceOrTypeLiteralCompletionKeyword(kind) { + return kind === 148 /* ReadonlyKeyword */ ; } - function createDefinitionInfoFromName(checker, declaration, symbolKind, symbolName2, containerName, unverified, failedAliasResolution, textSpan) { - const sourceFile = declaration.getSourceFile(); - if (!textSpan) { - const name = getNameOfDeclaration(declaration) || declaration; - textSpan = createTextSpanFromNode(name, sourceFile); + function isClassMemberCompletionKeyword(kind) { + switch(kind){ + case 128 /* AbstractKeyword */ : + case 129 /* AccessorKeyword */ : + case 137 /* ConstructorKeyword */ : + case 139 /* GetKeyword */ : + case 153 /* SetKeyword */ : + case 134 /* AsyncKeyword */ : + case 138 /* DeclareKeyword */ : + case 164 /* OverrideKeyword */ : + return true; + default: + return isClassMemberModifier(kind); } - return { - fileName: sourceFile.fileName, - textSpan: textSpan, - kind: symbolKind, - name: symbolName2, - containerKind: void 0, - containerName: // TODO: GH#18217 - containerName, - ...ts_FindAllReferences_exports.toContextSpan(textSpan, sourceFile, ts_FindAllReferences_exports.getContextNode(declaration)), - isLocal: !isDefinitionVisible(checker, declaration), - isAmbient: !!(declaration.flags & 16777216 /* Ambient */ ), - unverified: unverified, - failedAliasResolution: failedAliasResolution - }; } - function isDefinitionVisible(checker, declaration) { - if (checker.isDeclarationVisible(declaration)) return true; - if (!declaration.parent) return false; - if (hasInitializer(declaration.parent) && declaration.parent.initializer === declaration) return isDefinitionVisible(checker, declaration.parent); - switch(declaration.kind){ - case 169 /* PropertyDeclaration */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 171 /* MethodDeclaration */ : - if (hasEffectiveModifier(declaration, 8 /* Private */ )) return false; - case 173 /* Constructor */ : - case 299 /* PropertyAssignment */ : - case 300 /* ShorthandPropertyAssignment */ : - case 207 /* ObjectLiteralExpression */ : - case 228 /* ClassExpression */ : - case 216 /* ArrowFunction */ : - case 215 /* FunctionExpression */ : - return isDefinitionVisible(checker, declaration.parent); - default: - return false; + function isFunctionLikeBodyKeyword(kind) { + return kind === 134 /* AsyncKeyword */ || kind === 135 /* AwaitKeyword */ || kind === 130 /* AsKeyword */ || kind === 152 /* SatisfiesKeyword */ || kind === 156 /* TypeKeyword */ || !isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); + } + function keywordForNode(node) { + return isIdentifier(node) ? identifierToKeywordKind(node) ?? 0 /* Unknown */ : node.kind; + } + function getContextualKeywords(contextToken, position) { + const entries = []; + if (contextToken) { + const file = contextToken.getSourceFile(); + const parent2 = contextToken.parent; + const tokenLine = file.getLineAndCharacterOfPosition(contextToken.end).line; + const currentLine = file.getLineAndCharacterOfPosition(position).line; + if ((isImportDeclaration(parent2) || isExportDeclaration(parent2) && parent2.moduleSpecifier) && contextToken === parent2.moduleSpecifier && tokenLine === currentLine) entries.push({ + name: tokenToString(132 /* AssertKeyword */ ), + kind: "keyword" /* keyword */ , + kindModifiers: "" /* none */ , + sortText: SortText.GlobalsOrKeywords + }); } + return entries; } - function createDefinitionFromSignatureDeclaration(typeChecker, decl, failedAliasResolution) { - return createDefinitionInfo(decl, typeChecker, decl.symbol, decl, /*unverified*/ false, failedAliasResolution); + function getJsDocTagAtPosition(node, position) { + return findAncestor(node, (n)=>isJSDocTag(n) && rangeContainsPosition(n, position) ? true : isJSDoc(n) ? "quit" : false); } - function findReferenceInPosition(refs, pos) { - return find(refs, (ref)=>textRangeContainsPositionInclusive(ref, pos)); + function getPropertiesForObjectExpression(contextualType, completionsType, obj, checker) { + const hasCompletionsType = completionsType && completionsType !== contextualType; + const type = hasCompletionsType && !(completionsType.flags & 3 /* AnyOrUnknown */ ) ? checker.getUnionType([ + contextualType, + completionsType + ]) : contextualType; + const properties = getApparentProperties(type, obj, checker); + return type.isClass() && containsNonPublicProperties(properties) ? [] : hasCompletionsType ? filter(properties, hasDeclarationOtherThanSelf) : properties; + function hasDeclarationOtherThanSelf(member) { + if (!length(member.declarations)) return true; + return some(member.declarations, (decl)=>decl.parent !== obj); + } } - function getDefinitionInfoForFileReference(name, targetFileName, unverified) { - return { - fileName: targetFileName, - textSpan: createTextSpanFromBounds(0, 0), - kind: "script" /* scriptElement */ , - name: name, - containerName: void 0, - containerKind: void 0, - unverified: // TODO: GH#18217 - unverified - }; + function getApparentProperties(type, node, checker) { + if (!type.isUnion()) return type.getApparentProperties(); + return checker.getAllPossiblePropertiesOfTypes(filter(type.types, (memberType)=>!(memberType.flags & 402784252 /* Primitive */ || checker.isArrayLikeType(memberType) || checker.isTypeInvalidDueToUnionDiscriminant(memberType, node) || checker.typeHasCallOrConstructSignatures(memberType) || memberType.isClass() && containsNonPublicProperties(memberType.getApparentProperties())))); } - function getAncestorCallLikeExpression(node) { - const target = findAncestor(node, (n)=>!isRightSideOfPropertyAccess(n)); - const callLike = target == null ? void 0 : target.parent; - return callLike && isCallLikeExpression(callLike) && getInvokedExpression(callLike) === target ? callLike : void 0; + function containsNonPublicProperties(props) { + return some(props, (p)=>!!(getDeclarationModifierFlagsFromSymbol(p) & 24 /* NonPublicAccessibilityModifier */ )); } - function tryGetSignatureDeclaration(typeChecker, node) { - const callLike = getAncestorCallLikeExpression(node); - const signature = callLike && typeChecker.getResolvedSignature(callLike); - return tryCast(signature && signature.declaration, (d)=>isFunctionLike(d) && !isFunctionTypeNode(d)); + function getPropertiesForCompletion(type, checker) { + return type.isUnion() ? Debug.checkEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined") : Debug.checkEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined"); } - function isConstructorLike(node) { - switch(node.kind){ - case 173 /* Constructor */ : - case 182 /* ConstructorType */ : - case 177 /* ConstructSignature */ : - return true; + function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location, position) { + switch(location.kind){ + case 358 /* SyntaxList */ : + return tryCast(location.parent, isObjectTypeDeclaration); + case 1 /* EndOfFileToken */ : + const cls = tryCast(lastOrUndefined(cast(location.parent, isSourceFile).statements), isObjectTypeDeclaration); + if (cls && !findChildOfKind(cls, 20 /* CloseBraceToken */ , sourceFile)) return cls; + break; + case 81 /* PrivateIdentifier */ : + if (tryCast(location.parent, isPropertyDeclaration)) return findAncestor(location, isClassLike); + break; + case 80 /* Identifier */ : + { + const originalKeywordKind = identifierToKeywordKind(location); + if (originalKeywordKind) return void 0; + if (isPropertyDeclaration(location.parent) && location.parent.initializer === location) return void 0; + if (isFromObjectTypeDeclaration(location)) return findAncestor(location, isObjectTypeDeclaration); + } + } + if (!contextToken) return void 0; + if (location.kind === 137 /* ConstructorKeyword */ || isIdentifier(contextToken) && isPropertyDeclaration(contextToken.parent) && isClassLike(location)) return findAncestor(contextToken, isClassLike); + switch(contextToken.kind){ + case 64 /* EqualsToken */ : + return void 0; + case 27 /* SemicolonToken */ : + case 20 /* CloseBraceToken */ : + return isFromObjectTypeDeclaration(location) && location.parent.name === location ? location.parent.parent : tryCast(location, isObjectTypeDeclaration); + case 19 /* OpenBraceToken */ : + case 28 /* CommaToken */ : + return tryCast(contextToken.parent, isObjectTypeDeclaration); default: - return false; + if (isObjectTypeDeclaration(location)) { + if (getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line !== getLineAndCharacterOfPosition(sourceFile, position).line) return location; + const isValidKeyword = isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; + return isValidKeyword(contextToken.kind) || contextToken.kind === 42 /* AsteriskToken */ || isIdentifier(contextToken) && isValidKeyword(identifierToKeywordKind(contextToken) ?? 0 /* Unknown */ ) ? contextToken.parent.parent : void 0; + } + return void 0; } } - var init_goToDefinition = __esm({ - "src/services/goToDefinition.ts" () { - "use strict"; - init_ts4(); + function tryGetTypeLiteralNode(node) { + if (!node) return void 0; + const parent2 = node.parent; + switch(node.kind){ + case 19 /* OpenBraceToken */ : + if (isTypeLiteralNode(parent2)) return parent2; + break; + case 27 /* SemicolonToken */ : + case 28 /* CommaToken */ : + case 80 /* Identifier */ : + if (parent2.kind === 171 /* PropertySignature */ && isTypeLiteralNode(parent2.parent)) return parent2.parent; + break; } - }); - // src/services/_namespaces/ts.GoToDefinition.ts - var ts_GoToDefinition_exports = {}; - __export(ts_GoToDefinition_exports, { - createDefinitionInfo: ()=>createDefinitionInfo, - findReferenceInPosition: ()=>findReferenceInPosition, - getDefinitionAndBoundSpan: ()=>getDefinitionAndBoundSpan, - getDefinitionAtPosition: ()=>getDefinitionAtPosition, - getReferenceAtPosition: ()=>getReferenceAtPosition, - getTypeDefinitionAtPosition: ()=>getTypeDefinitionAtPosition - }); - var init_ts_GoToDefinition = __esm({ - "src/services/_namespaces/ts.GoToDefinition.ts" () { - "use strict"; - init_goToDefinition(); + return void 0; + } + function getConstraintOfTypeArgumentProperty(node, checker) { + if (!node) return void 0; + if (isTypeNode(node) && isTypeReferenceType(node.parent)) return checker.getTypeArgumentConstraint(node); + const t = getConstraintOfTypeArgumentProperty(node.parent, checker); + if (!t) return void 0; + switch(node.kind){ + case 171 /* PropertySignature */ : + return checker.getTypeOfPropertyOfContextualType(t, node.symbol.escapedName); + case 193 /* IntersectionType */ : + case 187 /* TypeLiteral */ : + case 192 /* UnionType */ : + return t; } - }); - // src/services/inlayHints.ts - function shouldShowParameterNameHints(preferences) { - return preferences.includeInlayParameterNameHints === "literals" || preferences.includeInlayParameterNameHints === "all"; } - function shouldShowLiteralParameterNameHintsOnly(preferences) { - return preferences.includeInlayParameterNameHints === "literals"; + function isFromObjectTypeDeclaration(node) { + return node.parent && isClassOrTypeElement(node.parent) && isObjectTypeDeclaration(node.parent.parent); } - function provideInlayHints(context) { - const { file: file , program: program , span: span , cancellationToken: cancellationToken , preferences: preferences } = context; - const sourceFileText = file.text; - const compilerOptions = program.getCompilerOptions(); - const checker = program.getTypeChecker(); - const result = []; - visitor(file); - return result; - function visitor(node) { - if (!node || node.getFullWidth() === 0) return; - switch(node.kind){ - case 264 /* ModuleDeclaration */ : - case 260 /* ClassDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 259 /* FunctionDeclaration */ : - case 228 /* ClassExpression */ : - case 215 /* FunctionExpression */ : - case 171 /* MethodDeclaration */ : - case 216 /* ArrowFunction */ : - cancellationToken.throwIfCancellationRequested(); - } - if (!textSpanIntersectsWith(span, node.pos, node.getFullWidth())) return; - if (isTypeNode(node) && !isExpressionWithTypeArguments(node)) return; - if (preferences.includeInlayVariableTypeHints && isVariableDeclaration(node)) visitVariableLikeDeclaration(node); - else if (preferences.includeInlayPropertyDeclarationTypeHints && isPropertyDeclaration(node)) visitVariableLikeDeclaration(node); - else if (preferences.includeInlayEnumMemberValueHints && isEnumMember(node)) visitEnumMember(node); - else if (shouldShowParameterNameHints(preferences) && (isCallExpression(node) || isNewExpression(node))) visitCallOrNewExpression(node); - else { - if (preferences.includeInlayFunctionParameterTypeHints && isFunctionLikeDeclaration(node) && hasContextSensitiveParameters(node)) visitFunctionLikeForParameterType(node); - if (preferences.includeInlayFunctionLikeReturnTypeHints && isSignatureSupportingReturnAnnotation(node)) visitFunctionDeclarationLikeForReturnType(node); - } - return forEachChild(node, visitor); - } - function isSignatureSupportingReturnAnnotation(node) { - return isArrowFunction(node) || isFunctionExpression(node) || isFunctionDeclaration(node) || isMethodDeclaration(node) || isGetAccessorDeclaration(node); - } - function addParameterHints(text, position, isFirstVariadicArgument) { - result.push({ - text: `${isFirstVariadicArgument ? "..." : ""}${truncation(text, maxHintsLength)}:`, - position: position, - kind: "Parameter" /* Parameter */ , - whitespaceAfter: true - }); - } - function addTypeHints(text, position) { - result.push({ - text: `: ${truncation(text, maxHintsLength)}`, - position: position, - kind: "Type" /* Type */ , - whitespaceBefore: true - }); - } - function addEnumMemberValueHints(text, position) { - result.push({ - text: `= ${truncation(text, maxHintsLength)}`, - position: position, - kind: "Enum" /* Enum */ , - whitespaceBefore: true - }); - } - function visitEnumMember(member) { - if (member.initializer) return; - const enumValue = checker.getConstantValue(member); - if (enumValue !== void 0) addEnumMemberValueHints(enumValue.toString(), member.end); - } - function isModuleReferenceType(type) { - return type.symbol && type.symbol.flags & 1536 /* Module */ ; - } - function visitVariableLikeDeclaration(decl) { - if (!decl.initializer || isBindingPattern(decl.name) || isVariableDeclaration(decl) && !isHintableDeclaration(decl)) return; - const effectiveTypeAnnotation = getEffectiveTypeAnnotationNode(decl); - if (effectiveTypeAnnotation) return; - const declarationType = checker.getTypeAtLocation(decl); - if (isModuleReferenceType(declarationType)) return; - const typeDisplayString = printTypeInSingleLine(declarationType); - if (typeDisplayString) { - const isVariableNameMatchesType = preferences.includeInlayVariableTypeHintsWhenTypeMatchesName === false && equateStringsCaseInsensitive(decl.name.getText(), typeDisplayString); - if (isVariableNameMatchesType) return; - addTypeHints(typeDisplayString, decl.name.end); - } + function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) { + switch(triggerCharacter){ + case ".": + case "@": + return true; + case '"': + case "'": + case "`": + return !!contextToken && isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; + case "#": + return !!contextToken && isPrivateIdentifier(contextToken) && !!getContainingClass(contextToken); + case "<": + return !!contextToken && contextToken.kind === 30 /* LessThanToken */ && (!isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); + case "/": + return !!contextToken && (isStringLiteralLike(contextToken) ? !!tryGetImportFromModuleSpecifier(contextToken) : contextToken.kind === 44 /* SlashToken */ && isJsxClosingElement(contextToken.parent)); + case " ": + return !!contextToken && isImportKeyword(contextToken) && contextToken.parent.kind === 312 /* SourceFile */ ; + default: + return Debug.assertNever(triggerCharacter); } - function visitCallOrNewExpression(expr) { - const args = expr.arguments; - if (!args || !args.length) return; - const candidates = []; - const signature = checker.getResolvedSignatureForSignatureHelp(expr, candidates); - if (!signature || !candidates.length) return; - for(let i = 0; i < args.length; ++i){ - const originalArg = args[i]; - const arg = skipParentheses(originalArg); - if (shouldShowLiteralParameterNameHintsOnly(preferences) && !isHintableLiteral(arg)) continue; - const identifierNameInfo = checker.getParameterIdentifierNameAtPosition(signature, i); - if (identifierNameInfo) { - const [parameterName, isFirstVariadicArgument] = identifierNameInfo; - const isParameterNameNotSameAsArgument = preferences.includeInlayParameterNameHintsWhenArgumentMatchesName || !identifierOrAccessExpressionPostfixMatchesParameterName(arg, parameterName); - if (!isParameterNameNotSameAsArgument && !isFirstVariadicArgument) continue; - const name = unescapeLeadingUnderscores(parameterName); - if (leadingCommentsContainsParameterName(arg, name)) continue; - addParameterHints(name, originalArg.getStart(), isFirstVariadicArgument); + } + function binaryExpressionMayBeOpenTag({ left: left }) { + return nodeIsMissing(left); + } + function isProbablyGlobalType(type, sourceFile, checker) { + const selfSymbol = checker.resolveName("self", /*location*/ void 0, 111551 /* Value */ , /*excludeGlobals*/ false); + if (selfSymbol && checker.getTypeOfSymbolAtLocation(selfSymbol, sourceFile) === type) return true; + const globalSymbol = checker.resolveName("global", /*location*/ void 0, 111551 /* Value */ , /*excludeGlobals*/ false); + if (globalSymbol && checker.getTypeOfSymbolAtLocation(globalSymbol, sourceFile) === type) return true; + const globalThisSymbol = checker.resolveName("globalThis", /*location*/ void 0, 111551 /* Value */ , /*excludeGlobals*/ false); + if (globalThisSymbol && checker.getTypeOfSymbolAtLocation(globalThisSymbol, sourceFile) === type) return true; + return false; + } + function isStaticProperty(symbol) { + return !!(symbol.valueDeclaration && getEffectiveModifierFlags(symbol.valueDeclaration) & 32 /* Static */ && isClassLike(symbol.valueDeclaration.parent)); + } + function tryGetObjectLiteralContextualType(node, typeChecker) { + const type = typeChecker.getContextualType(node); + if (type) return type; + const parent2 = walkUpParenthesizedExpressions(node.parent); + if (isBinaryExpression(parent2) && parent2.operatorToken.kind === 64 /* EqualsToken */ && node === parent2.left) return typeChecker.getTypeAtLocation(parent2); + if (isExpression(parent2)) return typeChecker.getContextualType(parent2); + return void 0; + } + function getImportStatementCompletionInfo(contextToken, sourceFile) { + var _a, _b, _c; + let keywordCompletion; + let isKeywordOnlyCompletion = false; + const candidate = getCandidate(); + return { + isKeywordOnlyCompletion: isKeywordOnlyCompletion, + keywordCompletion: keywordCompletion, + isNewIdentifierLocation: !!(candidate || keywordCompletion === 156 /* TypeKeyword */ ), + isTopLevelTypeOnly: !!((_b = (_a = tryCast(candidate, isImportDeclaration)) == null ? void 0 : _a.importClause) == null ? void 0 : _b.isTypeOnly) || !!((_c = tryCast(candidate, isImportEqualsDeclaration)) == null ? void 0 : _c.isTypeOnly), + couldBeTypeOnlyImportSpecifier: !!candidate && couldBeTypeOnlyImportSpecifier(candidate, contextToken), + replacementSpan: getSingleLineReplacementSpanForImportCompletionNode(candidate) + }; + function getCandidate() { + const parent2 = contextToken.parent; + if (isImportEqualsDeclaration(parent2)) { + const lastToken = parent2.getLastToken(sourceFile); + if (isIdentifier(contextToken) && lastToken !== contextToken) { + keywordCompletion = 161 /* FromKeyword */ ; + isKeywordOnlyCompletion = true; + return void 0; } + keywordCompletion = contextToken.kind === 156 /* TypeKeyword */ ? void 0 : 156 /* TypeKeyword */ ; + return isModuleSpecifierMissingOrEmpty(parent2.moduleReference) ? parent2 : void 0; } - } - function identifierOrAccessExpressionPostfixMatchesParameterName(expr, parameterName) { - if (isIdentifier(expr)) return expr.text === parameterName; - if (isPropertyAccessExpression(expr)) return expr.name.text === parameterName; - return false; - } - function leadingCommentsContainsParameterName(node, name) { - if (!isIdentifierText(name, compilerOptions.target, getLanguageVariant(file.scriptKind))) return false; - const ranges = getLeadingCommentRanges(sourceFileText, node.pos); - if (!(ranges == null ? void 0 : ranges.length)) return false; - const regex = leadingParameterNameCommentRegexFactory(name); - return some(ranges, (range)=>regex.test(sourceFileText.substring(range.pos, range.end))); - } - function isHintableLiteral(node) { - switch(node.kind){ - case 221 /* PrefixUnaryExpression */ : - { - const operand = node.operand; - return isLiteralExpression(operand) || isIdentifier(operand) && isInfinityOrNaNString(operand.escapedText); - } - case 110 /* TrueKeyword */ : - case 95 /* FalseKeyword */ : - case 104 /* NullKeyword */ : - case 14 /* NoSubstitutionTemplateLiteral */ : - case 225 /* TemplateExpression */ : - return true; - case 79 /* Identifier */ : - { - const name = node.escapedText; - return isUndefined(name) || isInfinityOrNaNString(name); - } - } - return isLiteralExpression(node); - } - function visitFunctionDeclarationLikeForReturnType(decl) { - if (isArrowFunction(decl)) { - if (!findChildOfKind(decl, 20 /* OpenParenToken */ , file)) return; + if (couldBeTypeOnlyImportSpecifier(parent2, contextToken) && canCompleteFromNamedBindings(parent2.parent)) return parent2; + if (isNamedImports(parent2) || isNamespaceImport(parent2)) { + if (!parent2.parent.isTypeOnly && (contextToken.kind === 19 /* OpenBraceToken */ || contextToken.kind === 102 /* ImportKeyword */ || contextToken.kind === 28 /* CommaToken */ )) keywordCompletion = 156 /* TypeKeyword */ ; + if (canCompleteFromNamedBindings(parent2)) { + if (contextToken.kind === 20 /* CloseBraceToken */ || contextToken.kind === 80 /* Identifier */ ) { + isKeywordOnlyCompletion = true; + keywordCompletion = 161 /* FromKeyword */ ; + } else return parent2.parent.parent; + } + return void 0; } - const effectiveTypeAnnotation = getEffectiveReturnTypeNode(decl); - if (effectiveTypeAnnotation || !decl.body) return; - const signature = checker.getSignatureFromDeclaration(decl); - if (!signature) return; - const returnType = checker.getReturnTypeOfSignature(signature); - if (isModuleReferenceType(returnType)) return; - const typeDisplayString = printTypeInSingleLine(returnType); - if (!typeDisplayString) return; - addTypeHints(typeDisplayString, getTypeAnnotationPosition(decl)); - } - function getTypeAnnotationPosition(decl) { - const closeParenToken = findChildOfKind(decl, 21 /* CloseParenToken */ , file); - if (closeParenToken) return closeParenToken.end; - return decl.parameters.end; - } - function visitFunctionLikeForParameterType(node) { - const signature = checker.getSignatureFromDeclaration(node); - if (!signature) return; - for(let i = 0; i < node.parameters.length && i < signature.parameters.length; ++i){ - const param = node.parameters[i]; - if (!isHintableDeclaration(param)) continue; - const effectiveTypeAnnotation = getEffectiveTypeAnnotationNode(param); - if (effectiveTypeAnnotation) continue; - const typeDisplayString = getParameterDeclarationTypeDisplayString(signature.parameters[i]); - if (!typeDisplayString) continue; - addTypeHints(typeDisplayString, param.questionToken ? param.questionToken.end : param.name.end); + if (isImportKeyword(contextToken) && isSourceFile(parent2)) { + keywordCompletion = 156 /* TypeKeyword */ ; + return contextToken; } - } - function getParameterDeclarationTypeDisplayString(symbol) { - const valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || !isParameter(valueDeclaration)) return void 0; - const signatureParamType = checker.getTypeOfSymbolAtLocation(symbol, valueDeclaration); - if (isModuleReferenceType(signatureParamType)) return void 0; - return printTypeInSingleLine(signatureParamType); - } - function truncation(text, maxLength2) { - if (text.length > maxLength2) return text.substr(0, maxLength2 - 3) + "..."; - return text; - } - function printTypeInSingleLine(type) { - const flags = 71286784 /* UseAliasDefinedOutsideCurrentScope */ ; - const printer = createPrinterWithRemoveComments(); - return usingSingleLineStringWriter((writer)=>{ - const typeNode = checker.typeToTypeNode(type, /*enclosingDeclaration*/ void 0, flags); - Debug.assertIsDefined(typeNode, "should always get typenode"); - printer.writeNode(4 /* Unspecified */ , typeNode, /*sourceFile*/ file, writer); - }); - } - function isUndefined(name) { - return name === "undefined"; - } - function isHintableDeclaration(node) { - if ((isParameterDeclaration(node) || isVariableDeclaration(node) && isVarConst(node)) && node.initializer) { - const initializer = skipParentheses(node.initializer); - return !(isHintableLiteral(initializer) || isNewExpression(initializer) || isObjectLiteralExpression(initializer) || isAssertionExpression(initializer)); + if (isImportKeyword(contextToken) && isImportDeclaration(parent2)) { + keywordCompletion = 156 /* TypeKeyword */ ; + return isModuleSpecifierMissingOrEmpty(parent2.moduleSpecifier) ? parent2 : void 0; } - return true; + return void 0; } } - var maxHintsLength, leadingParameterNameCommentRegexFactory; - var init_inlayHints = __esm({ - "src/services/inlayHints.ts" () { - "use strict"; - init_ts4(); - maxHintsLength = 30; - leadingParameterNameCommentRegexFactory = (name)=>{ - return new RegExp(`^\\s?/\\*\\*?\\s?${name}\\s?\\*\\/\\s?$`); - }; - } - }); - // src/services/_namespaces/ts.InlayHints.ts - var ts_InlayHints_exports = {}; - __export(ts_InlayHints_exports, { - provideInlayHints: ()=>provideInlayHints - }); - var init_ts_InlayHints = __esm({ - "src/services/_namespaces/ts.InlayHints.ts" () { - "use strict"; - init_inlayHints(); - } - }); - // src/services/jsDoc.ts - function getJsDocCommentsFromDeclarations(declarations, checker) { - const parts = []; - forEachUnique(declarations, (declaration)=>{ - for (const jsdoc of getCommentHavingNodes(declaration)){ - const inheritDoc = isJSDoc(jsdoc) && jsdoc.tags && find(jsdoc.tags, (t)=>t.kind === 330 /* JSDocTag */ && (t.tagName.escapedText === "inheritDoc" || t.tagName.escapedText === "inheritdoc")); - if (jsdoc.comment === void 0 && !inheritDoc || isJSDoc(jsdoc) && declaration.kind !== 349 /* JSDocTypedefTag */ && declaration.kind !== 341 /* JSDocCallbackTag */ && jsdoc.tags && jsdoc.tags.some((t)=>t.kind === 349 /* JSDocTypedefTag */ || t.kind === 341 /* JSDocCallbackTag */ ) && !jsdoc.tags.some((t)=>t.kind === 344 /* JSDocParameterTag */ || t.kind === 345 /* JSDocReturnTag */ )) continue; - let newparts = jsdoc.comment ? getDisplayPartsFromComment(jsdoc.comment, checker) : []; - if (inheritDoc && inheritDoc.comment) newparts = newparts.concat(getDisplayPartsFromComment(inheritDoc.comment, checker)); - if (!contains(parts, newparts, isIdenticalListOfDisplayParts)) parts.push(newparts); - } + function getSingleLineReplacementSpanForImportCompletionNode(node) { + var _a; + if (!node) return void 0; + const top = findAncestor(node, or(isImportDeclaration, isImportEqualsDeclaration)) ?? node; + const sourceFile = top.getSourceFile(); + if (rangeIsOnSingleLine(top, sourceFile)) return createTextSpanFromNode(top, sourceFile); + Debug.assert(top.kind !== 102 /* ImportKeyword */ && top.kind !== 276 /* ImportSpecifier */ ); + const potentialSplitPoint = top.kind === 272 /* ImportDeclaration */ ? getPotentiallyInvalidImportSpecifier((_a = top.importClause) == null ? void 0 : _a.namedBindings) ?? top.moduleSpecifier : top.moduleReference; + const withoutModuleSpecifier = { + pos: top.getFirstToken().getStart(), + end: potentialSplitPoint.pos + }; + if (rangeIsOnSingleLine(withoutModuleSpecifier, sourceFile)) return createTextSpanFromRange(withoutModuleSpecifier); + } + function getPotentiallyInvalidImportSpecifier(namedBindings) { + var _a; + return find((_a = tryCast(namedBindings, isNamedImports)) == null ? void 0 : _a.elements, (e)=>{ + var _a2; + return !e.propertyName && isStringANonContextualKeyword(e.name.text) && ((_a2 = findPrecedingToken(e.name.pos, namedBindings.getSourceFile(), namedBindings)) == null ? void 0 : _a2.kind) !== 28 /* CommaToken */ ; }); - return flatten(intersperse(parts, [ - lineBreakPart() - ])); } - function isIdenticalListOfDisplayParts(parts1, parts2) { - return arraysEqual(parts1, parts2, (p1, p2)=>p1.kind === p2.kind && p1.text === p2.text); + function couldBeTypeOnlyImportSpecifier(importSpecifier, contextToken) { + return isImportSpecifier(importSpecifier) && (importSpecifier.isTypeOnly || contextToken === importSpecifier.name && isTypeKeywordTokenOrIdentifier(contextToken)); } - function getCommentHavingNodes(declaration) { - switch(declaration.kind){ - case 344 /* JSDocParameterTag */ : - case 351 /* JSDocPropertyTag */ : - return [ - declaration - ]; - case 341 /* JSDocCallbackTag */ : - case 349 /* JSDocTypedefTag */ : - return [ - declaration, - declaration.parent - ]; - default: - return getJSDocCommentsAndTags(declaration); + function canCompleteFromNamedBindings(namedBindings) { + if (!isModuleSpecifierMissingOrEmpty(namedBindings.parent.parent.moduleSpecifier) || namedBindings.parent.name) return false; + if (isNamedImports(namedBindings)) { + const invalidNamedImport = getPotentiallyInvalidImportSpecifier(namedBindings); + const validImports = invalidNamedImport ? namedBindings.elements.indexOf(invalidNamedImport) : namedBindings.elements.length; + return validImports < 2; } + return true; } - function getJsDocTagsFromDeclarations(declarations, checker) { - const infos = []; - forEachUnique(declarations, (declaration)=>{ - const tags = getJSDocTags(declaration); - if (tags.some((t)=>t.kind === 349 /* JSDocTypedefTag */ || t.kind === 341 /* JSDocCallbackTag */ ) && !tags.some((t)=>t.kind === 344 /* JSDocParameterTag */ || t.kind === 345 /* JSDocReturnTag */ )) return; - for (const tag of tags)infos.push({ - name: tag.tagName.text, - text: getCommentDisplayParts(tag, checker) - }); - }); - return infos; + function isModuleSpecifierMissingOrEmpty(specifier) { + var _a; + if (nodeIsMissing(specifier)) return true; + return !((_a = tryCast(isExternalModuleReference(specifier) ? specifier.expression : specifier, isStringLiteralLike)) == null ? void 0 : _a.text); } - function getDisplayPartsFromComment(comment, checker) { - if (typeof comment === "string") return [ - textPart(comment) - ]; - return flatMap(comment, (node)=>node.kind === 324 /* JSDocText */ ? [ - textPart(node.text) - ] : buildLinkParts(node, checker)); + function getVariableOrParameterDeclaration(contextToken, location) { + if (!contextToken) return; + const possiblyParameterDeclaration = findAncestor(contextToken, (node)=>isFunctionBlock(node) || isArrowFunctionBody(node) || isBindingPattern(node) ? "quit" : (isParameter(node) || isTypeParameterDeclaration(node)) && !isIndexSignatureDeclaration(node.parent)); + const possiblyVariableDeclaration = findAncestor(location, (node)=>isFunctionBlock(node) || isArrowFunctionBody(node) || isBindingPattern(node) ? "quit" : isVariableDeclaration(node)); + return possiblyParameterDeclaration || possiblyVariableDeclaration; } - function getCommentDisplayParts(tag, checker) { - const { comment: comment , kind: kind } = tag; - const namePart = getTagNameDisplayPart(kind); - switch(kind){ - case 352 /* JSDocThrowsTag */ : - const typeExpression = tag.typeExpression; - return typeExpression ? withNode(typeExpression) : comment === void 0 ? void 0 : getDisplayPartsFromComment(comment, checker); - case 332 /* JSDocImplementsTag */ : - return withNode(tag.class); - case 331 /* JSDocAugmentsTag */ : - return withNode(tag.class); - case 348 /* JSDocTemplateTag */ : - const templateTag = tag; - const displayParts = []; - if (templateTag.constraint) displayParts.push(textPart(templateTag.constraint.getText())); - if (length(templateTag.typeParameters)) { - if (length(displayParts)) displayParts.push(spacePart()); - const lastTypeParameter = templateTag.typeParameters[templateTag.typeParameters.length - 1]; - forEach(templateTag.typeParameters, (tp)=>{ - displayParts.push(namePart(tp.getText())); - if (lastTypeParameter !== tp) displayParts.push(...[ - punctuationPart(27 /* CommaToken */ ), - spacePart() - ]); - }); - } - if (comment) displayParts.push(...[ - spacePart(), - ...getDisplayPartsFromComment(comment, checker) - ]); - return displayParts; - case 347 /* JSDocTypeTag */ : - case 353 /* JSDocSatisfiesTag */ : - return withNode(tag.typeExpression); - case 349 /* JSDocTypedefTag */ : - case 341 /* JSDocCallbackTag */ : - case 351 /* JSDocPropertyTag */ : - case 344 /* JSDocParameterTag */ : - case 350 /* JSDocSeeTag */ : - const { name: name } = tag; - return name ? withNode(name) : comment === void 0 ? void 0 : getDisplayPartsFromComment(comment, checker); - default: - return comment === void 0 ? void 0 : getDisplayPartsFromComment(comment, checker); - } - function withNode(node) { - return addComment(node.getText()); - } - function addComment(s) { - if (comment) { - if (s.match(/^https?$/)) return [ - textPart(s), - ...getDisplayPartsFromComment(comment, checker) - ]; - else return [ - namePart(s), - spacePart(), - ...getDisplayPartsFromComment(comment, checker) - ]; - } else return [ - textPart(s) - ]; - } + function isArrowFunctionBody(node) { + return node.parent && isArrowFunction(node.parent) && (node.parent.body === node || // const a = () => /**/; + node.kind === 39 /* EqualsGreaterThanToken */ ); } - function getTagNameDisplayPart(kind) { - switch(kind){ - case 344 /* JSDocParameterTag */ : - return parameterNamePart; - case 351 /* JSDocPropertyTag */ : - return propertyNamePart; - case 348 /* JSDocTemplateTag */ : - return typeParameterNamePart; - case 349 /* JSDocTypedefTag */ : - case 341 /* JSDocCallbackTag */ : - return typeAliasNamePart; - default: - return textPart; + function symbolCanBeReferencedAtTypeLocation(symbol, checker, seenModules = /* @__PURE__ */ new Map()) { + return nonAliasCanBeReferencedAtTypeLocation(symbol) || nonAliasCanBeReferencedAtTypeLocation(skipAlias(symbol.exportSymbol || symbol, checker)); + function nonAliasCanBeReferencedAtTypeLocation(symbol2) { + return !!(symbol2.flags & 788968 /* Type */ ) || checker.isUnknownSymbol(symbol2) || !!(symbol2.flags & 1536 /* Module */ ) && addToSeen(seenModules, getSymbolId(symbol2)) && checker.getExportsOfModule(symbol2).some((e)=>symbolCanBeReferencedAtTypeLocation(e, checker, seenModules)); } } - function getJSDocTagNameCompletions() { - return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = map(jsDocTagNames, (tagName)=>{ - return { - name: tagName, - kind: "keyword" /* keyword */ , - kindModifiers: "", - sortText: ts_Completions_exports.SortText.LocationPriority - }; - })); + function isDeprecated(symbol, checker) { + const declarations = skipAlias(symbol, checker).declarations; + return !!length(declarations) && every(declarations, isDeprecatedDeclaration); } - function getJSDocTagCompletions() { - return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = map(jsDocTagNames, (tagName)=>{ - return { - name: `@${tagName}`, - kind: "keyword" /* keyword */ , - kindModifiers: "", - sortText: ts_Completions_exports.SortText.LocationPriority - }; - })); + function charactersFuzzyMatchInString(identifierString, lowercaseCharacters) { + if (lowercaseCharacters.length === 0) return true; + let matchedFirstCharacter = false; + let prevChar; + let characterIndex = 0; + const len = identifierString.length; + for(let strIndex = 0; strIndex < len; strIndex++){ + const strChar = identifierString.charCodeAt(strIndex); + const testChar = lowercaseCharacters.charCodeAt(characterIndex); + if (strChar === testChar || strChar === toUpperCharCode(testChar)) { + matchedFirstCharacter || (matchedFirstCharacter = prevChar === void 0 || // Beginning of word + 97 /* a */ <= prevChar && prevChar <= 122 /* z */ && 65 /* A */ <= strChar && strChar <= 90 /* Z */ || // camelCase transition + prevChar === 95 /* _ */ && strChar !== 95 /* _ */ ); + if (matchedFirstCharacter) characterIndex++; + if (characterIndex === lowercaseCharacters.length) return true; + } + prevChar = strChar; + } + return false; } - function getJSDocTagCompletionDetails(name) { - return { - name: name, - kind: "" /* unknown */ , - // TODO: should have its own kind? - kindModifiers: "", - displayParts: [ - textPart(name) - ], - documentation: emptyArray, - tags: void 0, - codeActions: void 0 - }; + function toUpperCharCode(charCode) { + if (97 /* a */ <= charCode && charCode <= 122 /* z */ ) return charCode - 32; + return charCode; } - function getJSDocParameterNameCompletions(tag) { - if (!isIdentifier(tag.name)) return emptyArray; - const nameThusFar = tag.name.text; - const jsdoc = tag.parent; - const fn = jsdoc.parent; - if (!isFunctionLike(fn)) return []; - return mapDefined(fn.parameters, (param)=>{ - if (!isIdentifier(param.name)) return void 0; - const name = param.name.text; - if (jsdoc.tags.some((t)=>t !== tag && isJSDocParameterTag(t) && isIdentifier(t.name) && t.name.escapedText === name) || nameThusFar !== void 0 && !startsWith(name, nameThusFar)) return void 0; - return { - name: name, - kind: "parameter" /* parameterElement */ , - kindModifiers: "", - sortText: ts_Completions_exports.SortText.LocationPriority + var moduleSpecifierResolutionLimit, moduleSpecifierResolutionCacheAttemptLimit, SortText, CompletionSource, SymbolOriginInfoKind, CompletionKind, _keywordCompletions, allKeywordsCompletions; + var init_completions = __esm({ + "src/services/completions.ts" () { + "use strict"; + init_ts4(); + init_ts_Completions(); + moduleSpecifierResolutionLimit = 100; + moduleSpecifierResolutionCacheAttemptLimit = 1e3; + SortText = { + // Presets + LocalDeclarationPriority: "10", + LocationPriority: "11", + OptionalMember: "12", + MemberDeclaredBySpreadAssignment: "13", + SuggestedClassMembers: "14", + GlobalsOrKeywords: "15", + AutoImportSuggestions: "16", + ClassMemberSnippets: "17", + JavascriptIdentifiers: "18", + // Transformations + Deprecated (sortText) { + return "z" + sortText; + }, + ObjectLiteralProperty (presetSortText, symbolDisplayName) { + return `${presetSortText}\0${symbolDisplayName}\0`; + }, + SortBelow (sortText) { + return sortText + "1"; + } }; - }); - } - function getJSDocParameterNameCompletionDetails(name) { + CompletionSource = /* @__PURE__ */ ((CompletionSource2)=>{ + CompletionSource2["ThisProperty"] = "ThisProperty/"; + CompletionSource2["ClassMemberSnippet"] = "ClassMemberSnippet/"; + CompletionSource2["TypeOnlyAlias"] = "TypeOnlyAlias/"; + CompletionSource2["ObjectLiteralMethodSnippet"] = "ObjectLiteralMethodSnippet/"; + CompletionSource2["SwitchCases"] = "SwitchCases/"; + CompletionSource2["ObjectLiteralMemberWithComma"] = "ObjectLiteralMemberWithComma/"; + return CompletionSource2; + })(CompletionSource || {}); + SymbolOriginInfoKind = /* @__PURE__ */ ((SymbolOriginInfoKind2)=>{ + SymbolOriginInfoKind2[SymbolOriginInfoKind2["ThisType"] = 1] = "ThisType"; + SymbolOriginInfoKind2[SymbolOriginInfoKind2["SymbolMember"] = 2] = "SymbolMember"; + SymbolOriginInfoKind2[SymbolOriginInfoKind2["Export"] = 4] = "Export"; + SymbolOriginInfoKind2[SymbolOriginInfoKind2["Promise"] = 8] = "Promise"; + SymbolOriginInfoKind2[SymbolOriginInfoKind2["Nullable"] = 16] = "Nullable"; + SymbolOriginInfoKind2[SymbolOriginInfoKind2["ResolvedExport"] = 32] = "ResolvedExport"; + SymbolOriginInfoKind2[SymbolOriginInfoKind2["TypeOnlyAlias"] = 64] = "TypeOnlyAlias"; + SymbolOriginInfoKind2[SymbolOriginInfoKind2["ObjectLiteralMethod"] = 128] = "ObjectLiteralMethod"; + SymbolOriginInfoKind2[SymbolOriginInfoKind2["Ignore"] = 256] = "Ignore"; + SymbolOriginInfoKind2[SymbolOriginInfoKind2["ComputedPropertyName"] = 512] = "ComputedPropertyName"; + SymbolOriginInfoKind2[SymbolOriginInfoKind2["SymbolMemberNoExport"] = 2 /* SymbolMember */ ] = "SymbolMemberNoExport"; + SymbolOriginInfoKind2[SymbolOriginInfoKind2["SymbolMemberExport"] = 6] = "SymbolMemberExport"; + return SymbolOriginInfoKind2; + })(SymbolOriginInfoKind || {}); + CompletionKind = /* @__PURE__ */ ((CompletionKind2)=>{ + CompletionKind2[CompletionKind2["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration"; + CompletionKind2[CompletionKind2["Global"] = 1] = "Global"; + CompletionKind2[CompletionKind2["PropertyAccess"] = 2] = "PropertyAccess"; + CompletionKind2[CompletionKind2["MemberLike"] = 3] = "MemberLike"; + CompletionKind2[CompletionKind2["String"] = 4] = "String"; + CompletionKind2[CompletionKind2["None"] = 5] = "None"; + return CompletionKind2; + })(CompletionKind || {}); + _keywordCompletions = []; + allKeywordsCompletions = memoize(()=>{ + const res = []; + for(let i = 83 /* FirstKeyword */ ; i <= 165 /* LastKeyword */ ; i++)res.push({ + name: tokenToString(i), + kind: "keyword" /* keyword */ , + kindModifiers: "" /* none */ , + sortText: SortText.GlobalsOrKeywords + }); + return res; + }); + } + }); + // src/services/stringCompletions.ts + function createNameAndKindSet() { + const map2 = /* @__PURE__ */ new Map(); + function add(value1) { + const existing = map2.get(value1.name); + if (!existing || kindPrecedence[existing.kind] < kindPrecedence[value1.kind]) map2.set(value1.name, value1); + } return { - name: name, - kind: "parameter" /* parameterElement */ , - kindModifiers: "", - displayParts: [ - textPart(name) - ], - documentation: emptyArray, - tags: void 0, - codeActions: void 0 + add: add, + has: map2.has.bind(map2), + values: map2.values.bind(map2) }; } - function getDocCommentTemplateAtPosition(newLine, sourceFile, position, options) { - const tokenAtPos = getTokenAtPosition(sourceFile, position); - const existingDocComment = findAncestor(tokenAtPos, isJSDoc); - if (existingDocComment && (existingDocComment.comment !== void 0 || length(existingDocComment.tags))) return void 0; - const tokenStart = tokenAtPos.getStart(sourceFile); - if (!existingDocComment && tokenStart < position) return void 0; - const commentOwnerInfo = getCommentOwnerInfo(tokenAtPos, options); - if (!commentOwnerInfo) return void 0; - const { commentOwner: commentOwner , parameters: parameters , hasReturn: hasReturn2 } = commentOwnerInfo; - const commentOwnerJsDoc = hasJSDocNodes(commentOwner) && commentOwner.jsDoc ? commentOwner.jsDoc : void 0; - const lastJsDoc = lastOrUndefined(commentOwnerJsDoc); - if (commentOwner.getStart(sourceFile) < position || lastJsDoc && existingDocComment && lastJsDoc !== existingDocComment) return void 0; - const indentationStr = getIndentationStringAtPosition(sourceFile, position); - const isJavaScriptFile = hasJSFileExtension(sourceFile.fileName); - const tags = (parameters ? parameterDocComments(parameters || [], isJavaScriptFile, indentationStr, newLine) : "") + (hasReturn2 ? returnsDocComment(indentationStr, newLine) : ""); - const openComment = "/**"; - const closeComment = " */"; - const hasTag = (commentOwnerJsDoc || []).some((jsDoc)=>!!jsDoc.tags); - if (tags && !hasTag) { - const preamble = openComment + newLine + indentationStr + " * "; - const endLine = tokenStart === position ? newLine + indentationStr : ""; - const result = preamble + newLine + tags + indentationStr + closeComment + endLine; - return { - newText: result, - caretOffset: preamble.length - }; + function getStringLiteralCompletions(sourceFile, position, contextToken, options, host, program, log, preferences, includeSymbol) { + if (isInReferenceComment(sourceFile, position)) { + const entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); + return entries && convertPathCompletions(entries); + } + if (isInString(sourceFile, position, contextToken)) { + if (!contextToken || !isStringLiteralLike(contextToken)) return void 0; + const entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, program.getTypeChecker(), options, host, preferences); + return convertStringLiteralCompletions(entries, contextToken, sourceFile, host, program, log, options, preferences, position, includeSymbol); } - return { - newText: openComment + closeComment, - caretOffset: 3 - }; } - function getIndentationStringAtPosition(sourceFile, position) { - const { text: text } = sourceFile; - const lineStart = getLineStartPositionForPosition(position, sourceFile); - let pos = lineStart; - for(; pos <= position && isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++); - return text.slice(lineStart, pos); + function convertStringLiteralCompletions(completion, contextToken, sourceFile, host, program, log, options, preferences, position, includeSymbol) { + if (completion === void 0) return void 0; + const optionalReplacementSpan = createTextSpanFromStringLiteralLikeContent(contextToken); + switch(completion.kind){ + case 0 /* Paths */ : + return convertPathCompletions(completion.paths); + case 1 /* Properties */ : + { + const entries = createSortedArray(); + getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, contextToken, sourceFile, position, sourceFile, host, program, 99 /* ESNext */ , log, 4 /* String */ , preferences, options, /*formatContext*/ void 0, /*isTypeOnlyLocation*/ void 0, /*propertyAccessToConvert*/ void 0, /*jsxIdentifierExpected*/ void 0, /*isJsxInitializer*/ void 0, /*importStatementCompletion*/ void 0, /*recommendedCompletion*/ void 0, /*symbolToOriginInfoMap*/ void 0, /*symbolToSortTextMap*/ void 0, /*isJsxIdentifierExpected*/ void 0, /*isRightOfOpenTag*/ void 0, includeSymbol); + return { + isGlobalCompletion: false, + isMemberCompletion: true, + isNewIdentifierLocation: completion.hasIndexSignature, + optionalReplacementSpan: optionalReplacementSpan, + entries: entries + }; + } + case 2 /* Types */ : + { + const entries = completion.types.map((type)=>({ + name: type.value, + kindModifiers: "" /* none */ , + kind: "string" /* string */ , + sortText: SortText.LocationPriority, + replacementSpan: getReplacementSpanForContextToken(contextToken) + })); + return { + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: completion.isNewIdentifier, + optionalReplacementSpan: optionalReplacementSpan, + entries: entries + }; + } + default: + return Debug.assertNever(completion); + } } - function parameterDocComments(parameters, isJavaScriptFile, indentationStr, newLine) { - return parameters.map(({ name: name , dotDotDotToken: dotDotDotToken }, i)=>{ - const paramName = name.kind === 79 /* Identifier */ ? name.text : "param" + i; - const type = isJavaScriptFile ? dotDotDotToken ? "{...any} " : "{any} " : ""; - return `${indentationStr} * @param ${type}${paramName}${newLine}`; - }).join(""); + function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken, preferences) { + if (!contextToken || !isStringLiteralLike(contextToken)) return void 0; + const completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host, preferences); + return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken); } - function returnsDocComment(indentationStr, newLine) { - return `${indentationStr} * @returns${newLine}`; + function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) { + switch(completion.kind){ + case 0 /* Paths */ : + { + const match = find(completion.paths, (p)=>p.name === name); + return match && createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [ + textPart(name) + ]); + } + case 1 /* Properties */ : + { + const match = find(completion.symbols, (s)=>s.name === name); + return match && createCompletionDetailsForSymbol(match, match.name, checker, sourceFile, location, cancellationToken); + } + case 2 /* Types */ : + return find(completion.types, (t)=>t.value === name) ? createCompletionDetails(name, "" /* none */ , "string" /* string */ , [ + textPart(name) + ]) : void 0; + default: + return Debug.assertNever(completion); + } } - function getCommentOwnerInfo(tokenAtPos, options) { - return forEachAncestor(tokenAtPos, (n)=>getCommentOwnerInfoWorker(n, options)); + function convertPathCompletions(pathCompletions) { + const isGlobalCompletion = false; + const isNewIdentifierLocation = true; + const entries = pathCompletions.map(({ name: name, kind: kind, span: span, extension: extension })=>({ + name: name, + kind: kind, + kindModifiers: kindModifiersFromExtension(extension), + sortText: SortText.LocationPriority, + replacementSpan: span + })); + return { + isGlobalCompletion: isGlobalCompletion, + isMemberCompletion: false, + isNewIdentifierLocation: isNewIdentifierLocation, + entries: entries + }; } - function getCommentOwnerInfoWorker(commentOwner, options) { - switch(commentOwner.kind){ - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 171 /* MethodDeclaration */ : - case 173 /* Constructor */ : - case 170 /* MethodSignature */ : - case 216 /* ArrowFunction */ : - const host = commentOwner; - return { - commentOwner: commentOwner, - parameters: host.parameters, - hasReturn: hasReturn(host, options) - }; - case 299 /* PropertyAssignment */ : - return getCommentOwnerInfoWorker(commentOwner.initializer, options); - case 260 /* ClassDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 263 /* EnumDeclaration */ : - case 302 /* EnumMember */ : - case 262 /* TypeAliasDeclaration */ : - return { - commentOwner: commentOwner - }; - case 168 /* PropertySignature */ : + function kindModifiersFromExtension(extension) { + switch(extension){ + case ".d.ts" /* Dts */ : + return ".d.ts" /* dtsModifier */ ; + case ".js" /* Js */ : + return ".js" /* jsModifier */ ; + case ".json" /* Json */ : + return ".json" /* jsonModifier */ ; + case ".jsx" /* Jsx */ : + return ".jsx" /* jsxModifier */ ; + case ".ts" /* Ts */ : + return ".ts" /* tsModifier */ ; + case ".tsx" /* Tsx */ : + return ".tsx" /* tsxModifier */ ; + case ".d.mts" /* Dmts */ : + return ".d.mts" /* dmtsModifier */ ; + case ".mjs" /* Mjs */ : + return ".mjs" /* mjsModifier */ ; + case ".mts" /* Mts */ : + return ".mts" /* mtsModifier */ ; + case ".d.cts" /* Dcts */ : + return ".d.cts" /* dctsModifier */ ; + case ".cjs" /* Cjs */ : + return ".cjs" /* cjsModifier */ ; + case ".cts" /* Cts */ : + return ".cts" /* ctsModifier */ ; + case ".tsbuildinfo" /* TsBuildInfo */ : + return Debug.fail(`Extension ${".tsbuildinfo" /* TsBuildInfo */ } is unsupported.`); + case void 0: + return "" /* none */ ; + default: + return Debug.assertNever(extension); + } + } + function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host, preferences) { + const parent2 = walkUpParentheses(node.parent); + switch(parent2.kind){ + case 201 /* LiteralType */ : { - const host2 = commentOwner; - return host2.type && isFunctionTypeNode(host2.type) ? { - commentOwner: commentOwner, - parameters: host2.type.parameters, - hasReturn: hasReturn(host2.type, options) - } : { - commentOwner: commentOwner + const grandParent = walkUpParentheses(parent2.parent); + if (grandParent.kind === 205 /* ImportType */ ) return { + kind: 0 /* Paths */ , + paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) }; + return fromUnionableLiteralType(grandParent); } - case 240 /* VariableStatement */ : + case 303 /* PropertyAssignment */ : + if (isObjectLiteralExpression(parent2.parent) && parent2.name === node) return stringLiteralCompletionsForObjectLiteral(typeChecker, parent2.parent); + return fromContextualType() || fromContextualType(0 /* None */ ); + case 212 /* ElementAccessExpression */ : { - const varStatement = commentOwner; - const varDeclarations = varStatement.declarationList.declarations; - const host2 = varDeclarations.length === 1 && varDeclarations[0].initializer ? getRightHandSideOfAssignment(varDeclarations[0].initializer) : void 0; - return host2 ? { - commentOwner: commentOwner, - parameters: host2.parameters, - hasReturn: hasReturn(host2, options) - } : { - commentOwner: commentOwner - }; + const { expression: expression, argumentExpression: argumentExpression } = parent2; + if (node === skipParentheses(argumentExpression)) return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); + return void 0; } - case 308 /* SourceFile */ : - return "quit"; - case 264 /* ModuleDeclaration */ : - return commentOwner.parent.kind === 264 /* ModuleDeclaration */ ? void 0 : { - commentOwner: commentOwner - }; - case 241 /* ExpressionStatement */ : - return getCommentOwnerInfoWorker(commentOwner.expression, options); - case 223 /* BinaryExpression */ : - { - const be = commentOwner; - if (getAssignmentDeclarationKind(be) === 0 /* None */ ) return "quit"; - return isFunctionLike(be.right) ? { - commentOwner: commentOwner, - parameters: be.right.parameters, - hasReturn: hasReturn(be.right, options) - } : { - commentOwner: commentOwner - }; + case 213 /* CallExpression */ : + case 214 /* NewExpression */ : + case 291 /* JsxAttribute */ : + if (!isRequireCallArgument(node) && !isImportCall(parent2)) { + const argumentInfo = ts_SignatureHelp_exports.getArgumentInfoForCompletions(parent2.kind === 291 /* JsxAttribute */ ? parent2.parent : node, position, sourceFile); + return argumentInfo && (getStringLiteralCompletionsFromSignature(argumentInfo.invocation, node, argumentInfo, typeChecker) || getStringLiteralCompletionsFromSignature(argumentInfo.invocation, node, argumentInfo, typeChecker, 0 /* Normal */ )) || fromContextualType(0 /* None */ ); } - case 169 /* PropertyDeclaration */ : - const init = commentOwner.initializer; - if (init && (isFunctionExpression(init) || isArrowFunction(init))) return { - commentOwner: commentOwner, - parameters: init.parameters, - hasReturn: hasReturn(init, options) + case 272 /* ImportDeclaration */ : + case 278 /* ExportDeclaration */ : + case 283 /* ExternalModuleReference */ : + return { + kind: 0 /* Paths */ , + paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) + }; + case 296 /* CaseClause */ : + const tracker = newCaseClauseTracker(typeChecker, parent2.parent.clauses); + const contextualTypes = fromContextualType(); + if (!contextualTypes) return; + const literals = contextualTypes.types.filter((literal)=>!tracker.hasValue(literal.value)); + return { + kind: 2 /* Types */ , + types: literals, + isNewIdentifier: false }; + default: + return fromContextualType() || fromContextualType(0 /* None */ ); + } + function fromUnionableLiteralType(grandParent) { + switch(grandParent.kind){ + case 233 /* ExpressionWithTypeArguments */ : + case 183 /* TypeReference */ : + { + const typeArgument = findAncestor(parent2, (n)=>n.parent === grandParent); + if (typeArgument) return { + kind: 2 /* Types */ , + types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(typeArgument)), + isNewIdentifier: false + }; + return void 0; + } + case 199 /* IndexedAccessType */ : + const { indexType: indexType, objectType: objectType } = grandParent; + if (!rangeContainsPosition(indexType, position)) return void 0; + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(objectType)); + case 192 /* UnionType */ : + { + const result = fromUnionableLiteralType(walkUpParentheses(grandParent.parent)); + if (!result) return void 0; + const alreadyUsedTypes = getAlreadyUsedTypesInStringLiteralUnion(grandParent, parent2); + if (result.kind === 1 /* Properties */ ) return { + kind: 1 /* Properties */ , + symbols: result.symbols.filter((sym)=>!contains(alreadyUsedTypes, sym.name)), + hasIndexSignature: result.hasIndexSignature + }; + return { + kind: 2 /* Types */ , + types: result.types.filter((t)=>!contains(alreadyUsedTypes, t.value)), + isNewIdentifier: false + }; + } + default: + return void 0; + } + } + function fromContextualType(contextFlags = 4 /* Completions */ ) { + const types = getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker, contextFlags)); + if (!types.length) return; + return { + kind: 2 /* Types */ , + types: types, + isNewIdentifier: false + }; } } - function hasReturn(node, options) { - return !!(options == null ? void 0 : options.generateReturnInDocTemplate) && (isFunctionTypeNode(node) || isArrowFunction(node) && isExpression(node.body) || isFunctionLikeDeclaration(node) && node.body && isBlock(node.body) && !!forEachReturnStatement(node.body, (n)=>n)); - } - function getRightHandSideOfAssignment(rightHandSide) { - while(rightHandSide.kind === 214 /* ParenthesizedExpression */ )rightHandSide = rightHandSide.expression; - switch(rightHandSide.kind){ - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - return rightHandSide; - case 228 /* ClassExpression */ : - return find(rightHandSide.members, isConstructorDeclaration); + function walkUpParentheses(node) { + switch(node.kind){ + case 196 /* ParenthesizedType */ : + return walkUpParenthesizedTypes(node); + case 217 /* ParenthesizedExpression */ : + return walkUpParenthesizedExpressions(node); + default: + return node; } } - var jsDocTagNames, jsDocTagNameCompletionEntries, jsDocTagCompletionEntries, getJSDocTagNameCompletionDetails; - var init_jsDoc = __esm({ - "src/services/jsDoc.ts" () { - "use strict"; - init_ts4(); - jsDocTagNames = [ - "abstract", - "access", - "alias", - "argument", - "async", - "augments", - "author", - "borrows", - "callback", - "class", - "classdesc", - "constant", - "constructor", - "constructs", - "copyright", - "default", - "deprecated", - "description", - "emits", - "enum", - "event", - "example", - "exports", - "extends", - "external", - "field", - "file", - "fileoverview", - "fires", - "function", - "generator", - "global", - "hideconstructor", - "host", - "ignore", - "implements", - "inheritdoc", - "inner", - "instance", - "interface", - "kind", - "lends", - "license", - "link", - "linkcode", - "linkplain", - "listens", - "member", - "memberof", - "method", - "mixes", - "module", - "name", - "namespace", - "overload", - "override", - "package", - "param", - "private", - "prop", - "property", - "protected", - "public", - "readonly", - "requires", - "returns", - "satisfies", - "see", - "since", - "static", - "summary", - "template", - "this", - "throws", - "todo", - "tutorial", - "type", - "typedef", - "var", - "variation", - "version", - "virtual", - "yields" - ]; - getJSDocTagNameCompletionDetails = getJSDocTagCompletionDetails; - } - }); - // src/services/_namespaces/ts.JsDoc.ts - var ts_JsDoc_exports = {}; - __export(ts_JsDoc_exports, { - getDocCommentTemplateAtPosition: ()=>getDocCommentTemplateAtPosition, - getJSDocParameterNameCompletionDetails: ()=>getJSDocParameterNameCompletionDetails, - getJSDocParameterNameCompletions: ()=>getJSDocParameterNameCompletions, - getJSDocTagCompletionDetails: ()=>getJSDocTagCompletionDetails, - getJSDocTagCompletions: ()=>getJSDocTagCompletions, - getJSDocTagNameCompletionDetails: ()=>getJSDocTagNameCompletionDetails, - getJSDocTagNameCompletions: ()=>getJSDocTagNameCompletions, - getJsDocCommentsFromDeclarations: ()=>getJsDocCommentsFromDeclarations, - getJsDocTagsFromDeclarations: ()=>getJsDocTagsFromDeclarations - }); - var init_ts_JsDoc = __esm({ - "src/services/_namespaces/ts.JsDoc.ts" () { - "use strict"; - init_jsDoc(); - } - }); - // src/services/organizeImports.ts - function organizeImports(sourceFile, formatContext, host, program, preferences, mode) { - const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext({ - host: host, - formatContext: formatContext, - preferences: preferences - }); - const shouldSort = mode === "SortAndCombine" /* SortAndCombine */ || mode === "All" /* All */ ; - const shouldCombine = shouldSort; - const shouldRemove = mode === "RemoveUnused" /* RemoveUnused */ || mode === "All" /* All */ ; - const topLevelImportGroupDecls = groupImportsByNewlineContiguous(sourceFile, sourceFile.statements.filter(isImportDeclaration)); - const comparer = getOrganizeImportsComparerWithDetection(preferences, shouldSort ? ()=>detectSortingWorker(topLevelImportGroupDecls, preferences) === 2 /* CaseInsensitive */ : void 0); - const processImportsOfSameModuleSpecifier = (importGroup)=>{ - if (shouldRemove) importGroup = removeUnusedImports(importGroup, sourceFile, program); - if (shouldCombine) importGroup = coalesceImportsWorker(importGroup, comparer, sourceFile); - if (shouldSort) importGroup = stableSort(importGroup, (s1, s2)=>compareImportsOrRequireStatements(s1, s2, comparer)); - return importGroup; - }; - topLevelImportGroupDecls.forEach((importGroupDecl)=>organizeImportsWorker(importGroupDecl, processImportsOfSameModuleSpecifier)); - if (mode !== "RemoveUnused" /* RemoveUnused */ ) { - const topLevelExportDecls = sourceFile.statements.filter(isExportDeclaration); - organizeImportsWorker(topLevelExportDecls, (group2)=>coalesceExportsWorker(group2, comparer)); - } - for (const ambientModule of sourceFile.statements.filter(isAmbientModule)){ - if (!ambientModule.body) continue; - const ambientModuleImportGroupDecls = groupImportsByNewlineContiguous(sourceFile, ambientModule.body.statements.filter(isImportDeclaration)); - ambientModuleImportGroupDecls.forEach((importGroupDecl)=>organizeImportsWorker(importGroupDecl, processImportsOfSameModuleSpecifier)); - if (mode !== "RemoveUnused" /* RemoveUnused */ ) { - const ambientModuleExportDecls = ambientModule.body.statements.filter(isExportDeclaration); - organizeImportsWorker(ambientModuleExportDecls, (group2)=>coalesceExportsWorker(group2, comparer)); - } - } - return changeTracker.getChanges(); - function organizeImportsWorker(oldImportDecls, coalesce) { - if (length(oldImportDecls) === 0) return; - suppressLeadingTrivia(oldImportDecls[0]); - const oldImportGroups = shouldCombine ? group(oldImportDecls, (importDecl)=>getExternalModuleName2(importDecl.moduleSpecifier)) : [ - oldImportDecls - ]; - const sortedImportGroups = shouldSort ? stableSort(oldImportGroups, (group1, group2)=>compareModuleSpecifiersWorker(group1[0].moduleSpecifier, group2[0].moduleSpecifier, comparer)) : oldImportGroups; - const newImportDecls = flatMap(sortedImportGroups, (importGroup)=>getExternalModuleName2(importGroup[0].moduleSpecifier) ? coalesce(importGroup) : importGroup); - if (newImportDecls.length === 0) changeTracker.deleteNodes(sourceFile, oldImportDecls, { - leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, - trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include - }, /*hasTrailingComment*/ true); - else { - const replaceOptions = { - leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, - // Leave header comment in place - trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include, - suffix: getNewLineOrDefaultFromHost(host, formatContext.options) - }; - changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, replaceOptions); - const hasTrailingComment = changeTracker.nodeHasTrailingComment(sourceFile, oldImportDecls[0], replaceOptions); - changeTracker.deleteNodes(sourceFile, oldImportDecls.slice(1), { - trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include - }, hasTrailingComment); - } - } - } - function groupImportsByNewlineContiguous(sourceFile, importDecls) { - const scanner2 = createScanner(sourceFile.languageVersion, /*skipTrivia*/ false, sourceFile.languageVariant); - const groupImports = []; - let groupIndex = 0; - for (const topLevelImportDecl of importDecls){ - if (groupImports[groupIndex] && isNewGroup(sourceFile, topLevelImportDecl, scanner2)) groupIndex++; - if (!groupImports[groupIndex]) groupImports[groupIndex] = []; - groupImports[groupIndex].push(topLevelImportDecl); - } - return groupImports; - } - function isNewGroup(sourceFile, topLevelImportDecl, scanner2) { - const startPos = topLevelImportDecl.getFullStart(); - const endPos = topLevelImportDecl.getStart(); - scanner2.setText(sourceFile.text, startPos, endPos - startPos); - let numberOfNewLines = 0; - while(scanner2.getTokenPos() < endPos){ - const tokenKind = scanner2.scan(); - if (tokenKind === 4 /* NewLineTrivia */ ) { - numberOfNewLines++; - if (numberOfNewLines >= 2) return true; - } - } - return false; + function getAlreadyUsedTypesInStringLiteralUnion(union, current) { + return mapDefined(union.types, (type)=>type !== current && isLiteralTypeNode(type) && isStringLiteral(type.literal) ? type.literal.text : void 0); } - function removeUnusedImports(oldImports, sourceFile, program) { - const typeChecker = program.getTypeChecker(); - const compilerOptions = program.getCompilerOptions(); - const jsxNamespace = typeChecker.getJsxNamespace(sourceFile); - const jsxFragmentFactory = typeChecker.getJsxFragmentFactory(sourceFile); - const jsxElementsPresent = !!(sourceFile.transformFlags & 2 /* ContainsJsx */ ); - const usedImports = []; - for (const importDecl of oldImports){ - const { importClause: importClause , moduleSpecifier: moduleSpecifier } = importDecl; - if (!importClause) { - usedImports.push(importDecl); - continue; - } - let { name: name , namedBindings: namedBindings } = importClause; - if (name && !isDeclarationUsed(name)) name = void 0; - if (namedBindings) { - if (isNamespaceImport(namedBindings)) { - if (!isDeclarationUsed(namedBindings.name)) namedBindings = void 0; - } else { - const newElements = namedBindings.elements.filter((e)=>isDeclarationUsed(e.name)); - if (newElements.length < namedBindings.elements.length) namedBindings = newElements.length ? factory.updateNamedImports(namedBindings, newElements) : void 0; - } - } - if (name || namedBindings) usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings)); - else if (hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier)) { - if (sourceFile.isDeclarationFile) usedImports.push(factory.createImportDeclaration(importDecl.modifiers, /*importClause*/ void 0, moduleSpecifier, /*assertClause*/ void 0)); - else usedImports.push(importDecl); + function getStringLiteralCompletionsFromSignature(call, arg, argumentInfo, checker, checkMode = 32 /* IsForStringLiteralArgumentCompletions */ ) { + let isNewIdentifier = false; + const uniques = /* @__PURE__ */ new Map(); + const candidates = []; + const editingArgument = isJsxOpeningLikeElement(call) ? Debug.checkDefined(findAncestor(arg.parent, isJsxAttribute)) : arg; + checker.getResolvedSignatureForStringLiteralCompletions(call, editingArgument, candidates, checkMode); + const types = flatMap(candidates, (candidate)=>{ + if (!signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length) return; + let type = candidate.getTypeParameterAtPosition(argumentInfo.argumentIndex); + if (isJsxOpeningLikeElement(call)) { + const propType = checker.getTypeOfPropertyOfType(type, getTextOfJsxAttributeName(editingArgument.name)); + if (propType) type = propType; } - } - return usedImports; - function isDeclarationUsed(identifier) { - return jsxElementsPresent && (identifier.text === jsxNamespace || jsxFragmentFactory && identifier.text === jsxFragmentFactory) && jsxModeNeedsExplicitImport(compilerOptions.jsx) || ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); - } - } - function hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier) { - const moduleSpecifierText = isStringLiteral(moduleSpecifier) && moduleSpecifier.text; - return isString(moduleSpecifierText) && some(sourceFile.moduleAugmentations, (moduleName)=>isStringLiteral(moduleName) && moduleName.text === moduleSpecifierText); + isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */ ); + return getStringLiteralTypes(type, uniques); + }); + return length(types) ? { + kind: 2 /* Types */ , + types: types, + isNewIdentifier: isNewIdentifier + } : void 0; } - function getExternalModuleName2(specifier) { - return specifier !== void 0 && isStringLiteralLike(specifier) ? specifier.text : void 0; + function stringLiteralCompletionsFromProperties(type) { + return type && { + kind: 1 /* Properties */ , + symbols: filter(type.getApparentProperties(), (prop)=>!(prop.valueDeclaration && isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration))), + hasIndexSignature: hasIndexSignature(type) + }; } - function coalesceImports(importGroup, ignoreCase, sourceFile) { - const comparer = getOrganizeImportsOrdinalStringComparer(ignoreCase); - return coalesceImportsWorker(importGroup, comparer, sourceFile); + function stringLiteralCompletionsForObjectLiteral(checker, objectLiteralExpression) { + const contextualType = checker.getContextualType(objectLiteralExpression); + if (!contextualType) return void 0; + const completionsType = checker.getContextualType(objectLiteralExpression, 4 /* Completions */ ); + const symbols = getPropertiesForObjectExpression(contextualType, completionsType, objectLiteralExpression, checker); + return { + kind: 1 /* Properties */ , + symbols: symbols, + hasIndexSignature: hasIndexSignature(contextualType) + }; } - function coalesceImportsWorker(importGroup, comparer, sourceFile) { - if (importGroup.length === 0) return importGroup; - const { importWithoutClause: importWithoutClause , typeOnlyImports: typeOnlyImports , regularImports: regularImports } = getCategorizedImports(importGroup); - const coalescedImports = []; - if (importWithoutClause) coalescedImports.push(importWithoutClause); - for (const group2 of [ - regularImports, - typeOnlyImports - ]){ - const isTypeOnly = group2 === typeOnlyImports; - const { defaultImports: defaultImports , namespaceImports: namespaceImports , namedImports: namedImports } = group2; - if (!isTypeOnly && defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) { - const defaultImport = defaultImports[0]; - coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); - continue; - } - const sortedNamespaceImports = stableSort(namespaceImports, (i1, i2)=>comparer(i1.importClause.namedBindings.name.text, i2.importClause.namedBindings.name.text)); - for (const namespaceImport of sortedNamespaceImports)coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ void 0, namespaceImport.importClause.namedBindings)); - const firstDefaultImport = firstOrUndefined(defaultImports); - const firstNamedImport = firstOrUndefined(namedImports); - const importDecl = firstDefaultImport != null ? firstDefaultImport : firstNamedImport; - if (!importDecl) continue; - let newDefaultImport; - const newImportSpecifiers = []; - if (defaultImports.length === 1) newDefaultImport = defaultImports[0].importClause.name; - else for (const defaultImport of defaultImports)newImportSpecifiers.push(factory.createImportSpecifier(/*isTypeOnly*/ false, factory.createIdentifier("default"), defaultImport.importClause.name)); - newImportSpecifiers.push(...getNewImportSpecifiers(namedImports)); - const sortedImportSpecifiers = factory.createNodeArray(sortSpecifiers(newImportSpecifiers, comparer), firstNamedImport == null ? void 0 : firstNamedImport.importClause.namedBindings.elements.hasTrailingComma); - const newNamedImports = sortedImportSpecifiers.length === 0 ? newDefaultImport ? void 0 : factory.createNamedImports(emptyArray) : firstNamedImport ? factory.updateNamedImports(firstNamedImport.importClause.namedBindings, sortedImportSpecifiers) : factory.createNamedImports(sortedImportSpecifiers); - if (sourceFile && newNamedImports && (firstNamedImport == null ? void 0 : firstNamedImport.importClause.namedBindings) && !rangeIsOnSingleLine(firstNamedImport.importClause.namedBindings, sourceFile)) setEmitFlags(newNamedImports, 2 /* MultiLine */ ); - if (isTypeOnly && newDefaultImport && newNamedImports) { - coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, /*namedBindings*/ void 0)); - coalescedImports.push(updateImportDeclarationAndClause(firstNamedImport != null ? firstNamedImport : importDecl, /*name*/ void 0, newNamedImports)); - } else coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports)); - } - return coalescedImports; + function getStringLiteralTypes(type, uniques = /* @__PURE__ */ new Map()) { + if (!type) return emptyArray; + type = skipConstraint(type); + return type.isUnion() ? flatMap(type.types, (t)=>getStringLiteralTypes(t, uniques)) : type.isStringLiteral() && !(type.flags & 1024 /* EnumLiteral */ ) && addToSeen(uniques, type.value) ? [ + type + ] : emptyArray; } - function getCategorizedImports(importGroup) { - let importWithoutClause; - const typeOnlyImports = { - defaultImports: [], - namespaceImports: [], - namedImports: [] - }; - const regularImports = { - defaultImports: [], - namespaceImports: [], - namedImports: [] - }; - for (const importDeclaration of importGroup){ - if (importDeclaration.importClause === void 0) { - importWithoutClause = importWithoutClause || importDeclaration; - continue; - } - const group2 = importDeclaration.importClause.isTypeOnly ? typeOnlyImports : regularImports; - const { name: name , namedBindings: namedBindings } = importDeclaration.importClause; - if (name) group2.defaultImports.push(importDeclaration); - if (namedBindings) { - if (isNamespaceImport(namedBindings)) group2.namespaceImports.push(importDeclaration); - else group2.namedImports.push(importDeclaration); - } - } + function nameAndKind(name, kind, extension) { return { - importWithoutClause: importWithoutClause, - typeOnlyImports: typeOnlyImports, - regularImports: regularImports + name: name, + kind: kind, + extension: extension }; } - function coalesceExports(exportGroup, ignoreCase) { - const comparer = getOrganizeImportsOrdinalStringComparer(ignoreCase); - return coalesceExportsWorker(exportGroup, comparer); + function directoryResult(name) { + return nameAndKind(name, "directory" /* directory */ , /*extension*/ void 0); } - function coalesceExportsWorker(exportGroup, comparer) { - if (exportGroup.length === 0) return exportGroup; - const { exportWithoutClause: exportWithoutClause , namedExports: namedExports , typeOnlyExports: typeOnlyExports } = getCategorizedExports(exportGroup); - const coalescedExports = []; - if (exportWithoutClause) coalescedExports.push(exportWithoutClause); - for (const exportGroup2 of [ - namedExports, - typeOnlyExports - ]){ - if (exportGroup2.length === 0) continue; - const newExportSpecifiers = []; - newExportSpecifiers.push(...flatMap(exportGroup2, (i)=>i.exportClause && isNamedExports(i.exportClause) ? i.exportClause.elements : emptyArray)); - const sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers, comparer); - const exportDecl = exportGroup2[0]; - coalescedExports.push(factory.updateExportDeclaration(exportDecl, exportDecl.modifiers, exportDecl.isTypeOnly, exportDecl.exportClause && (isNamedExports(exportDecl.exportClause) ? factory.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers) : factory.updateNamespaceExport(exportDecl.exportClause, exportDecl.exportClause.name)), exportDecl.moduleSpecifier, exportDecl.assertClause)); - } - return coalescedExports; - function getCategorizedExports(exportGroup2) { - let exportWithoutClause2; - const namedExports2 = []; - const typeOnlyExports2 = []; - for (const exportDeclaration of exportGroup2){ - if (exportDeclaration.exportClause === void 0) exportWithoutClause2 = exportWithoutClause2 || exportDeclaration; - else if (exportDeclaration.isTypeOnly) typeOnlyExports2.push(exportDeclaration); - else namedExports2.push(exportDeclaration); - } - return { - exportWithoutClause: exportWithoutClause2, - namedExports: namedExports2, - typeOnlyExports: typeOnlyExports2 - }; - } + function addReplacementSpans(text, textStart, names) { + const span = getDirectoryFragmentTextSpan(text, textStart); + const wholeSpan = text.length === 0 ? void 0 : createTextSpan(textStart, text.length); + return names.map(({ name: name, kind: kind, extension: extension })=>Math.max(name.indexOf(directorySeparator), name.indexOf(altDirectorySeparator)) !== -1 ? { + name: name, + kind: kind, + extension: extension, + span: wholeSpan + } : { + name: name, + kind: kind, + extension: extension, + span: span + }); } - function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { - return factory.updateImportDeclaration(importDeclaration, importDeclaration.modifiers, factory.updateImportClause(importDeclaration.importClause, importDeclaration.importClause.isTypeOnly, name, namedBindings), // TODO: GH#18217 - importDeclaration.moduleSpecifier, importDeclaration.assertClause); + function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) { + return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker, preferences)); } - function sortSpecifiers(specifiers, comparer) { - return stableSort(specifiers, (s1, s2)=>compareImportOrExportSpecifiers(s1, s2, comparer)); + function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker, preferences) { + const literalValue = normalizeSlashes(node.text); + const mode = isStringLiteralLike(node) ? getModeForUsageLocation(sourceFile, node) : void 0; + const scriptPath = sourceFile.path; + const scriptDirectory = getDirectoryPath(scriptPath); + const extensionOptions = getExtensionOptions(compilerOptions, 1 /* ModuleSpecifier */ , sourceFile, typeChecker, preferences, mode); + return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && !compilerOptions.paths && (isRootedDiskPath(literalValue) || isUrl(literalValue)) ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, extensionOptions) : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, mode, compilerOptions, host, extensionOptions, typeChecker); } - function compareImportOrExportSpecifiers(s1, s2, comparer) { - return compareBooleans(s1.isTypeOnly, s2.isTypeOnly) || comparer(s1.name.text, s2.name.text); + function getExtensionOptions(compilerOptions, referenceKind, importingSourceFile, typeChecker, preferences, resolutionMode) { + return { + extensionsToSearch: flatten(getSupportedExtensionsForModuleResolution(compilerOptions, typeChecker)), + referenceKind: referenceKind, + importingSourceFile: importingSourceFile, + endingPreference: preferences == null ? void 0 : preferences.importModuleSpecifierEnding, + resolutionMode: resolutionMode + }; } - function compareModuleSpecifiers2(m1, m2, ignoreCase) { - const comparer = getOrganizeImportsOrdinalStringComparer(!!ignoreCase); - return compareModuleSpecifiersWorker(m1, m2, comparer); + function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, extensionOptions) { + if (compilerOptions.rootDirs) return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); + else return arrayFrom(getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, /*moduleSpecifierIsRelative*/ true, scriptPath).values()); } - function compareModuleSpecifiersWorker(m1, m2, comparer) { - const name1 = m1 === void 0 ? void 0 : getExternalModuleName2(m1); - const name2 = m2 === void 0 ? void 0 : getExternalModuleName2(m2); - return compareBooleans(name1 === void 0, name2 === void 0) || compareBooleans(isExternalModuleNameRelative(name1), isExternalModuleNameRelative(name2)) || // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion - comparer(name1, name2); + function getSupportedExtensionsForModuleResolution(compilerOptions, typeChecker) { + const ambientModulesExtensions = !typeChecker ? [] : mapDefined(typeChecker.getAmbientModules(), (module2)=>{ + const name = module2.name.slice(1, -1); + if (!name.startsWith("*.") || name.includes("/")) return; + return name.slice(1); + }); + const extensions = [ + ...getSupportedExtensions(compilerOptions), + ambientModulesExtensions + ]; + const moduleResolution = getEmitModuleResolutionKind(compilerOptions); + return moduleResolutionUsesNodeModules(moduleResolution) ? getSupportedExtensionsWithJsonIfResolveJsonModule(compilerOptions, extensions) : extensions; } - function getModuleSpecifierExpression(declaration) { - var _a2; - switch(declaration.kind){ - case 268 /* ImportEqualsDeclaration */ : - return (_a2 = tryCast(declaration.moduleReference, isExternalModuleReference)) == null ? void 0 : _a2.expression; - case 269 /* ImportDeclaration */ : - return declaration.moduleSpecifier; - case 240 /* VariableStatement */ : - return declaration.declarationList.declarations[0].initializer.arguments[0]; - } + function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase) { + rootDirs = rootDirs.map((rootDirectory)=>normalizePath(isRootedDiskPath(rootDirectory) ? rootDirectory : combinePaths(basePath, rootDirectory))); + const relativeDirectory = firstDefined(rootDirs, (rootDirectory)=>containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : void 0); + return deduplicate([ + ...rootDirs.map((rootDirectory)=>combinePaths(rootDirectory, relativeDirectory)), + scriptDirectory + ], equateStringsCaseSensitive, compareStringsCaseSensitive); } - function detectSorting(sourceFile, preferences) { - return detectSortingWorker(groupImportsByNewlineContiguous(sourceFile, sourceFile.statements.filter(isImportDeclaration)), preferences); + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, compilerOptions, host, exclude) { + const basePath = compilerOptions.project || host.getCurrentDirectory(); + const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + const baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase); + return flatMap(baseDirectories, (baseDirectory)=>arrayFrom(getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, /*moduleSpecifierIsRelative*/ true, exclude).values())); } - function detectSortingWorker(importGroups, preferences) { - const collateCaseSensitive = getOrganizeImportsComparer(preferences, /*ignoreCase*/ false); - const collateCaseInsensitive = getOrganizeImportsComparer(preferences, /*ignoreCase*/ true); - let sortState = 3 /* Both */ ; - let seenUnsortedGroup = false; - for (const importGroup of importGroups){ - if (importGroup.length > 1) { - const moduleSpecifierSort = detectSortCaseSensitivity(importGroup, (i)=>{ - var _a2, _b; - return (_b = (_a2 = tryCast(i.moduleSpecifier, isStringLiteral)) == null ? void 0 : _a2.text) != null ? _b : ""; - }, collateCaseSensitive, collateCaseInsensitive); - if (moduleSpecifierSort) { - sortState &= moduleSpecifierSort; - seenUnsortedGroup = true; - } - if (!sortState) return sortState; - } - const declarationWithNamedImports = find(importGroup, (i)=>{ - var _a2, _b; - return ((_b = tryCast((_a2 = i.importClause) == null ? void 0 : _a2.namedBindings, isNamedImports)) == null ? void 0 : _b.elements.length) > 1; - }); - if (declarationWithNamedImports) { - const namedImportSort = detectImportSpecifierSorting(declarationWithNamedImports.importClause.namedBindings.elements, preferences); - if (namedImportSort) { - sortState &= namedImportSort; - seenUnsortedGroup = true; + function getCompletionEntriesForDirectoryFragment(fragment, scriptDirectory, extensionOptions, host, moduleSpecifierIsRelative, exclude, result = createNameAndKindSet()) { + var _a; + if (fragment === void 0) fragment = ""; + fragment = normalizeSlashes(fragment); + if (!hasTrailingDirectorySeparator(fragment)) fragment = getDirectoryPath(fragment); + if (fragment === "") fragment = "." + directorySeparator; + fragment = ensureTrailingDirectorySeparator(fragment); + const absolutePath = resolvePath(scriptDirectory, fragment); + const baseDirectory = hasTrailingDirectorySeparator(absolutePath) ? absolutePath : getDirectoryPath(absolutePath); + if (!moduleSpecifierIsRelative) { + const packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + const packageJson = readJson(packageJsonPath, host); + const typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + const versionPaths = (_a = getPackageJsonTypesVersionsPaths(typesVersions)) == null ? void 0 : _a.paths; + if (versionPaths) { + const packageDirectory = getDirectoryPath(packageJsonPath); + const pathInPackage = absolutePath.slice(ensureTrailingDirectorySeparator(packageDirectory).length); + if (addCompletionEntriesFromPaths(result, pathInPackage, packageDirectory, extensionOptions, host, versionPaths)) return result; + } } - if (!sortState) return sortState; } - if (sortState !== 3 /* Both */ ) return sortState; } - return seenUnsortedGroup ? 0 /* None */ : sortState; - } - function detectImportDeclarationSorting(imports, preferences) { - const collateCaseSensitive = getOrganizeImportsComparer(preferences, /*ignoreCase*/ false); - const collateCaseInsensitive = getOrganizeImportsComparer(preferences, /*ignoreCase*/ true); - return detectSortCaseSensitivity(imports, (s)=>getExternalModuleName2(getModuleSpecifierExpression(s)) || "", collateCaseSensitive, collateCaseInsensitive); - } - function getImportDeclarationInsertionIndex(sortedImports, newImport, comparer) { - const index = binarySearch(sortedImports, newImport, identity, (a, b)=>compareImportsOrRequireStatements(a, b, comparer)); - return index < 0 ? ~index : index; - } - function getImportSpecifierInsertionIndex(sortedImports, newImport, comparer) { - const index = binarySearch(sortedImports, newImport, identity, (s1, s2)=>compareImportOrExportSpecifiers(s1, s2, comparer)); - return index < 0 ? ~index : index; - } - function compareImportsOrRequireStatements(s1, s2, comparer) { - return compareModuleSpecifiersWorker(getModuleSpecifierExpression(s1), getModuleSpecifierExpression(s2), comparer) || compareImportKind(s1, s2); - } - function compareImportKind(s1, s2) { - return compareValues(getImportKindOrder(s1), getImportKindOrder(s2)); - } - function getImportKindOrder(s1) { - var _a2; - switch(s1.kind){ - case 269 /* ImportDeclaration */ : - if (!s1.importClause) return 0; - if (s1.importClause.isTypeOnly) return 1; - if (((_a2 = s1.importClause.namedBindings) == null ? void 0 : _a2.kind) === 271 /* NamespaceImport */ ) return 2; - if (s1.importClause.name) return 3; - return 4; - case 268 /* ImportEqualsDeclaration */ : - return 5; - case 240 /* VariableStatement */ : - return 6; + const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + if (!tryDirectoryExists(host, baseDirectory)) return result; + const files = tryReadDirectory(host, baseDirectory, extensionOptions.extensionsToSearch, /*exclude*/ void 0, /*include*/ [ + "./*" + ]); + if (files) for (let filePath of files){ + filePath = normalizePath(filePath); + if (exclude && comparePaths(filePath, exclude, scriptDirectory, ignoreCase) === 0 /* EqualTo */ ) continue; + const { name: name, extension: extension } = getFilenameWithExtensionOption(getBaseFileName(filePath), host.getCompilationSettings(), extensionOptions); + result.add(nameAndKind(name, "script" /* scriptElement */ , extension)); } + const directories = tryGetDirectories(host, baseDirectory); + if (directories) for (const directory of directories){ + const directoryName = getBaseFileName(normalizePath(directory)); + if (directoryName !== "@types") result.add(directoryResult(directoryName)); + } + return result; } - function getNewImportSpecifiers(namedImports) { - return flatMap(namedImports, (namedImport)=>map(tryGetNamedBindingElements(namedImport), (importSpecifier)=>importSpecifier.name && importSpecifier.propertyName && importSpecifier.name.escapedText === importSpecifier.propertyName.escapedText ? factory.updateImportSpecifier(importSpecifier, importSpecifier.isTypeOnly, /*propertyName*/ void 0, importSpecifier.name) : importSpecifier)); - } - function tryGetNamedBindingElements(namedImport) { - var _a2; - return ((_a2 = namedImport.importClause) == null ? void 0 : _a2.namedBindings) && isNamedImports(namedImport.importClause.namedBindings) ? namedImport.importClause.namedBindings.elements : void 0; - } - function getOrganizeImportsOrdinalStringComparer(ignoreCase) { - return ignoreCase ? compareStringsCaseInsensitiveEslintCompatible : compareStringsCaseSensitive; - } - function getOrganizeImportsUnicodeStringComparer(ignoreCase, preferences) { - var _a2, _b, _c; - const resolvedLocale = getOrganizeImportsLocale(preferences); - const caseFirst = (_a2 = preferences.organizeImportsCaseFirst) != null ? _a2 : false; - const numeric = (_b = preferences.organizeImportsNumericCollation) != null ? _b : false; - const accents = (_c = preferences.organizeImportsAccentCollation) != null ? _c : true; - const sensitivity = ignoreCase ? accents ? "accent" : "base" : accents ? "variant" : "case"; - const collator = new Intl.Collator(resolvedLocale, { - usage: "sort", - caseFirst: caseFirst || "false", - sensitivity: sensitivity, - numeric: numeric - }); - return collator.compare; - } - function getOrganizeImportsLocale(preferences) { - let locale = preferences.organizeImportsLocale; - if (locale === "auto") locale = getUILocale(); - if (locale === void 0) locale = "en"; - const supportedLocales = Intl.Collator.supportedLocalesOf(locale); - const resolvedLocale = supportedLocales.length ? supportedLocales[0] : "en"; - return resolvedLocale; - } - function getOrganizeImportsComparer(preferences, ignoreCase) { - var _a2; - const collation = (_a2 = preferences.organizeImportsCollation) != null ? _a2 : "ordinal"; - return collation === "unicode" ? getOrganizeImportsUnicodeStringComparer(ignoreCase, preferences) : getOrganizeImportsOrdinalStringComparer(ignoreCase); + function getFilenameWithExtensionOption(name, compilerOptions, extensionOptions) { + const nonJsResult = ts_moduleSpecifiers_exports.tryGetRealFileNameForNonJsDeclarationFileName(name); + if (nonJsResult) return { + name: nonJsResult, + extension: tryGetExtensionFromPath2(nonJsResult) + }; + if (extensionOptions.referenceKind === 0 /* Filename */ ) return { + name: name, + extension: tryGetExtensionFromPath2(name) + }; + const endingPreference = getModuleSpecifierEndingPreference(extensionOptions.endingPreference, extensionOptions.resolutionMode, compilerOptions, extensionOptions.importingSourceFile); + if (endingPreference === 3 /* TsExtension */ ) { + if (fileExtensionIsOneOf(name, supportedTSImplementationExtensions)) return { + name: name, + extension: tryGetExtensionFromPath2(name) + }; + const outputExtension2 = ts_moduleSpecifiers_exports.tryGetJSExtensionForFile(name, compilerOptions); + return outputExtension2 ? { + name: changeExtension(name, outputExtension2), + extension: outputExtension2 + } : { + name: name, + extension: tryGetExtensionFromPath2(name) + }; + } + if ((endingPreference === 0 /* Minimal */ || endingPreference === 1 /* Index */ ) && fileExtensionIsOneOf(name, [ + ".js" /* Js */ , + ".jsx" /* Jsx */ , + ".ts" /* Ts */ , + ".tsx" /* Tsx */ , + ".d.ts" /* Dts */ + ])) return { + name: removeFileExtension(name), + extension: tryGetExtensionFromPath2(name) + }; + const outputExtension = ts_moduleSpecifiers_exports.tryGetJSExtensionForFile(name, compilerOptions); + return outputExtension ? { + name: changeExtension(name, outputExtension), + extension: outputExtension + } : { + name: name, + extension: tryGetExtensionFromPath2(name) + }; } - function getOrganizeImportsComparerWithDetection(preferences, detectIgnoreCase) { - var _a2; - const ignoreCase = typeof preferences.organizeImportsIgnoreCase === "boolean" ? preferences.organizeImportsIgnoreCase : (_a2 = detectIgnoreCase == null ? void 0 : detectIgnoreCase()) != null ? _a2 : false; - return getOrganizeImportsComparer(preferences, ignoreCase); + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, extensionOptions, host, paths) { + const getPatternsForKey = (key)=>paths[key]; + const comparePaths2 = (a, b)=>{ + const patternA = tryParsePattern(a); + const patternB = tryParsePattern(b); + const lengthA = typeof patternA === "object" ? patternA.prefix.length : a.length; + const lengthB = typeof patternB === "object" ? patternB.prefix.length : b.length; + return compareValues(lengthB, lengthA); + }; + return addCompletionEntriesFromPathsOrExports(result, fragment, baseDirectory, extensionOptions, host, getOwnKeys(paths), getPatternsForKey, comparePaths2); } - var ImportSpecifierSortingCache, detectImportSpecifierSorting; - var init_organizeImports = __esm({ - "src/services/organizeImports.ts" () { - "use strict"; - init_ts4(); - ImportSpecifierSortingCache = class { - has([specifiers, preferences]) { - if (this._lastPreferences !== preferences || !this._cache) return false; - return this._cache.has(specifiers); + function addCompletionEntriesFromPathsOrExports(result, fragment, baseDirectory, extensionOptions, host, keys, getPatternsForKey, comparePaths2) { + let pathResults = []; + let matchedPath; + for (const key of keys){ + if (key === ".") continue; + const keyWithoutLeadingDotSlash = key.replace(/^\.\//, ""); + const patterns = getPatternsForKey(key); + if (patterns) { + const pathPattern = tryParsePattern(keyWithoutLeadingDotSlash); + if (!pathPattern) continue; + const isMatch = typeof pathPattern === "object" && isPatternMatch(pathPattern, fragment); + const isLongestMatch = isMatch && (matchedPath === void 0 || comparePaths2(key, matchedPath) === -1 /* LessThan */ ); + if (isLongestMatch) { + matchedPath = key; + pathResults = pathResults.filter((r)=>!r.matchedPattern); } - get([specifiers, preferences]) { - if (this._lastPreferences !== preferences || !this._cache) return void 0; - return this._cache.get(specifiers); + if (typeof pathPattern === "string" || matchedPath === void 0 || comparePaths2(key, matchedPath) !== 1 /* GreaterThan */ ) pathResults.push({ + matchedPattern: isMatch, + results: getCompletionsForPathMapping(keyWithoutLeadingDotSlash, patterns, fragment, baseDirectory, extensionOptions, host).map(({ name: name, kind: kind, extension: extension })=>nameAndKind(name, kind, extension)) + }); + } + } + pathResults.forEach((pathResult)=>pathResult.results.forEach((r)=>result.add(r))); + return matchedPath !== void 0; + } + function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, compilerOptions, host, extensionOptions, typeChecker) { + const { baseUrl: baseUrl, paths: paths } = compilerOptions; + const result = createNameAndKindSet(); + const moduleResolution = getEmitModuleResolutionKind(compilerOptions); + if (baseUrl) { + const absolute = normalizePath(combinePaths(host.getCurrentDirectory(), baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, host, /*moduleSpecifierIsRelative*/ false, /*exclude*/ void 0, result); + } + if (paths) { + const absolute = getPathsBasePath(compilerOptions, host); + addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions, host, paths); + } + const fragmentDirectory = getFragmentDirectory(fragment); + for (const ambientName of getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker))result.add(nameAndKind(ambientName, "external module name" /* externalModuleName */ , /*extension*/ void 0)); + getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result); + if (moduleResolutionUsesNodeModules(moduleResolution)) { + let foundGlobal = false; + if (fragmentDirectory === void 0) for (const moduleName of enumerateNodeModulesVisibleToScript(host, scriptPath)){ + const moduleResult = nameAndKind(moduleName, "external module name" /* externalModuleName */ , /*extension*/ void 0); + if (!result.has(moduleResult.name)) { + foundGlobal = true; + result.add(moduleResult); } - set([specifiers, preferences], value1) { - var _a2; - if (this._lastPreferences !== preferences) { - this._lastPreferences = preferences; - this._cache = void 0; - } - (_a2 = this._cache) != null ? _a2 : this._cache = /* @__PURE__ */ new WeakMap(); - this._cache.set(specifiers, value1); + } + if (!foundGlobal) { + let ancestorLookup = (ancestor)=>{ + const nodeModules = combinePaths(ancestor, "node_modules"); + if (tryDirectoryExists(host, nodeModules)) getCompletionEntriesForDirectoryFragment(fragment, nodeModules, extensionOptions, host, /*moduleSpecifierIsRelative*/ false, /*exclude*/ void 0, result); + }; + if (fragmentDirectory && getResolvePackageJsonExports(compilerOptions)) { + const nodeModulesDirectoryLookup = ancestorLookup; + ancestorLookup = (ancestor)=>{ + const components = getPathComponents(fragment); + components.shift(); + let packagePath = components.shift(); + if (!packagePath) return nodeModulesDirectoryLookup(ancestor); + if (startsWith(packagePath, "@")) { + const subName = components.shift(); + if (!subName) return nodeModulesDirectoryLookup(ancestor); + packagePath = combinePaths(packagePath, subName); + } + const packageDirectory = combinePaths(ancestor, "node_modules", packagePath); + const packageFile = combinePaths(packageDirectory, "package.json"); + if (tryFileExists(host, packageFile)) { + const packageJson = readJson(packageFile, host); + const exports = packageJson.exports; + if (exports) { + if (typeof exports !== "object" || exports === null) return; + const keys = getOwnKeys(exports); + const fragmentSubpath = components.join("/") + (components.length && hasTrailingDirectorySeparator(fragment) ? "/" : ""); + const conditions = getConditions(compilerOptions, mode === 99 /* ESNext */ ); + addCompletionEntriesFromPathsOrExports(result, fragmentSubpath, packageDirectory, extensionOptions, host, keys, (key)=>singleElementArray(getPatternFromFirstMatchingCondition(exports[key], conditions)), comparePatternKeys); + return; + } + } + return nodeModulesDirectoryLookup(ancestor); + }; } - }; - detectImportSpecifierSorting = memoizeCached((specifiers, preferences)=>{ - if (!arrayIsSorted(specifiers, (s1, s2)=>compareBooleans(s1.isTypeOnly, s2.isTypeOnly))) return 0 /* None */ ; - const collateCaseSensitive = getOrganizeImportsComparer(preferences, /*ignoreCase*/ false); - const collateCaseInsensitive = getOrganizeImportsComparer(preferences, /*ignoreCase*/ true); - return detectSortCaseSensitivity(specifiers, (specifier)=>specifier.name.text, collateCaseSensitive, collateCaseInsensitive); - }, new ImportSpecifierSortingCache()); + forEachAncestorDirectory(scriptPath, ancestorLookup); + } } - }); - // src/services/_namespaces/ts.OrganizeImports.ts - var ts_OrganizeImports_exports = {}; - __export(ts_OrganizeImports_exports, { - coalesceExports: ()=>coalesceExports, - coalesceImports: ()=>coalesceImports, - compareImportOrExportSpecifiers: ()=>compareImportOrExportSpecifiers, - compareImportsOrRequireStatements: ()=>compareImportsOrRequireStatements, - compareModuleSpecifiers: ()=>compareModuleSpecifiers2, - detectImportDeclarationSorting: ()=>detectImportDeclarationSorting, - detectImportSpecifierSorting: ()=>detectImportSpecifierSorting, - detectSorting: ()=>detectSorting, - getImportDeclarationInsertionIndex: ()=>getImportDeclarationInsertionIndex, - getImportSpecifierInsertionIndex: ()=>getImportSpecifierInsertionIndex, - getOrganizeImportsComparer: ()=>getOrganizeImportsComparer, - organizeImports: ()=>organizeImports - }); - var init_ts_OrganizeImports = __esm({ - "src/services/_namespaces/ts.OrganizeImports.ts" () { - "use strict"; - init_organizeImports(); + return arrayFrom(result.values()); + } + function getPatternFromFirstMatchingCondition(target, conditions) { + if (typeof target === "string") return target; + if (target && typeof target === "object" && !isArray(target)) { + for(const condition in target)if (condition === "default" || conditions.indexOf(condition) > -1 || isApplicableVersionedTypesKey(conditions, condition)) { + const pattern = target[condition]; + return getPatternFromFirstMatchingCondition(pattern, conditions); + } } - }); - // src/services/outliningElementsCollector.ts - function collectElements(sourceFile, cancellationToken) { - const res = []; - addNodeOutliningSpans(sourceFile, cancellationToken, res); - addRegionOutliningSpans(sourceFile, res); - return res.sort((span1, span2)=>span1.textSpan.start - span2.textSpan.start); } - function addNodeOutliningSpans(sourceFile, cancellationToken, out) { - let depthRemaining = 40; - let current = 0; - const statements = [ - ...sourceFile.statements, - sourceFile.endOfFileToken + function getFragmentDirectory(fragment) { + return containsSlash(fragment) ? hasTrailingDirectorySeparator(fragment) ? fragment : getDirectoryPath(fragment) : void 0; + } + function getCompletionsForPathMapping(path, patterns, fragment, packageDirectory, extensionOptions, host) { + if (!endsWith(path, "*")) return !stringContains(path, "*") ? justPathMappingName(path, "script" /* scriptElement */ ) : emptyArray; + const pathPrefix = path.slice(0, path.length - 1); + const remainingFragment = tryRemovePrefix(fragment, pathPrefix); + if (remainingFragment === void 0) { + const starIsFullPathComponent = path[path.length - 2] === "/"; + return starIsFullPathComponent ? justPathMappingName(pathPrefix, "directory" /* directory */ ) : flatMap(patterns, (pattern)=>{ + var _a; + return (_a = getModulesForPathsPattern("", packageDirectory, pattern, extensionOptions, host)) == null ? void 0 : _a.map(({ name: name, ...rest })=>({ + name: pathPrefix + name, + ...rest + })); + }); + } + return flatMap(patterns, (pattern)=>getModulesForPathsPattern(remainingFragment, packageDirectory, pattern, extensionOptions, host)); + function justPathMappingName(name, kind) { + return startsWith(name, fragment) ? [ + { + name: removeTrailingDirectorySeparator(name), + kind: kind, + extension: void 0 + } + ] : emptyArray; + } + } + function getModulesForPathsPattern(fragment, packageDirectory, pattern, extensionOptions, host) { + if (!host.readDirectory) return void 0; + const parsed = tryParsePattern(pattern); + if (parsed === void 0 || isString(parsed)) return void 0; + const normalizedPrefix = resolvePath(parsed.prefix); + const normalizedPrefixDirectory = hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : getDirectoryPath(normalizedPrefix); + const normalizedPrefixBase = hasTrailingDirectorySeparator(parsed.prefix) ? "" : getBaseFileName(normalizedPrefix); + const fragmentHasPath = containsSlash(fragment); + const fragmentDirectory = fragmentHasPath ? hasTrailingDirectorySeparator(fragment) ? fragment : getDirectoryPath(fragment) : void 0; + const expandedPrefixDirectory = fragmentHasPath ? combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; + const normalizedSuffix = normalizePath(parsed.suffix); + const declarationExtension = normalizedSuffix && getDeclarationEmitExtensionForPath("_" + normalizedSuffix); + const matchingSuffixes = declarationExtension ? [ + changeExtension(normalizedSuffix, declarationExtension), + normalizedSuffix + ] : [ + normalizedSuffix ]; - const n = statements.length; - while(current < n){ - while(current < n && !isAnyImportSyntax(statements[current])){ - visitNode3(statements[current]); - current++; - } - if (current === n) break; - const firstImport = current; - while(current < n && isAnyImportSyntax(statements[current])){ - visitNode3(statements[current]); - current++; + const baseDirectory = normalizePath(combinePaths(packageDirectory, expandedPrefixDirectory)); + const completePrefix = fragmentHasPath ? baseDirectory : ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; + const includeGlobs = normalizedSuffix ? matchingSuffixes.map((suffix)=>"**/*" + suffix) : [ + "./*" + ]; + const matches = mapDefined(tryReadDirectory(host, baseDirectory, extensionOptions.extensionsToSearch, /*exclude*/ void 0, includeGlobs), (match)=>{ + const trimmedWithPattern = trimPrefixAndSuffix(match); + if (trimmedWithPattern) { + if (containsSlash(trimmedWithPattern)) return directoryResult(getPathComponents(removeLeadingDirectorySeparator(trimmedWithPattern))[1]); + const { name: name, extension: extension } = getFilenameWithExtensionOption(trimmedWithPattern, host.getCompilationSettings(), extensionOptions); + return nameAndKind(name, "script" /* scriptElement */ , extension); } - const lastImport = current - 1; - if (lastImport !== firstImport) out.push(createOutliningSpanFromBounds(findChildOfKind(statements[firstImport], 100 /* ImportKeyword */ , sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */ )); + }); + const directories = normalizedSuffix ? emptyArray : mapDefined(tryGetDirectories(host, baseDirectory), (dir)=>dir === "node_modules" ? void 0 : directoryResult(dir)); + return [ + ...matches, + ...directories + ]; + function trimPrefixAndSuffix(path) { + return firstDefined(matchingSuffixes, (suffix)=>{ + const inner = withoutStartAndEnd(normalizePath(path), completePrefix, suffix); + return inner === void 0 ? void 0 : removeLeadingDirectorySeparator(inner); + }); } - function visitNode3(n2) { - var _a2; - if (depthRemaining === 0) return; - cancellationToken.throwIfCancellationRequested(); - if (isDeclaration(n2) || isVariableStatement(n2) || isReturnStatement(n2) || isCallOrNewExpression(n2) || n2.kind === 1 /* EndOfFileToken */ ) addOutliningForLeadingCommentsForNode(n2, sourceFile, cancellationToken, out); - if (isFunctionLike(n2) && isBinaryExpression(n2.parent) && isPropertyAccessExpression(n2.parent.left)) addOutliningForLeadingCommentsForNode(n2.parent.left, sourceFile, cancellationToken, out); - if (isBlock(n2) || isModuleBlock(n2)) addOutliningForLeadingCommentsForPos(n2.statements.end, sourceFile, cancellationToken, out); - if (isClassLike(n2) || isInterfaceDeclaration(n2)) addOutliningForLeadingCommentsForPos(n2.members.end, sourceFile, cancellationToken, out); - const span = getOutliningSpanForNode(n2, sourceFile); - if (span) out.push(span); - depthRemaining--; - if (isCallExpression(n2)) { - depthRemaining++; - visitNode3(n2.expression); - depthRemaining--; - n2.arguments.forEach(visitNode3); - (_a2 = n2.typeArguments) == null || _a2.forEach(visitNode3); - } else if (isIfStatement(n2) && n2.elseStatement && isIfStatement(n2.elseStatement)) { - visitNode3(n2.expression); - visitNode3(n2.thenStatement); - depthRemaining++; - visitNode3(n2.elseStatement); - depthRemaining--; - } else n2.forEachChild(visitNode3); - depthRemaining++; + } + function withoutStartAndEnd(s, start, end) { + return startsWith(s, start) && endsWith(s, end) ? s.slice(start.length, s.length - end.length) : void 0; + } + function removeLeadingDirectorySeparator(path) { + return path[0] === directorySeparator ? path.slice(1) : path; + } + function getAmbientModuleCompletions(fragment, fragmentDirectory, checker) { + const ambientModules = checker.getAmbientModules().map((sym)=>stripQuotes(sym.name)); + const nonRelativeModuleNames = ambientModules.filter((moduleName)=>startsWith(moduleName, fragment) && moduleName.indexOf("*") < 0); + if (fragmentDirectory !== void 0) { + const moduleNameWithSeparator = ensureTrailingDirectorySeparator(fragmentDirectory); + return nonRelativeModuleNames.map((nonRelativeModuleName)=>removePrefix(nonRelativeModuleName, moduleNameWithSeparator)); } + return nonRelativeModuleNames; } - function addRegionOutliningSpans(sourceFile, out) { - const regions = []; - const lineStarts = sourceFile.getLineStarts(); - for (const currentLineStart of lineStarts){ - const lineEnd = sourceFile.getLineEndOfPosition(currentLineStart); - const lineText = sourceFile.text.substring(currentLineStart, lineEnd); - const result = isRegionDelimiter(lineText); - if (!result || isInComment(sourceFile, currentLineStart)) continue; - if (!result[1]) { - const span = createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); - regions.push(createOutliningSpan(span, "region" /* Region */ , span, /*autoCollapse*/ false, result[2] || "#region")); - } else { - const region = regions.pop(); - if (region) { - region.textSpan.length = lineEnd - region.textSpan.start; - region.hintSpan.length = lineEnd - region.textSpan.start; - out.push(region); + function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { + const token = getTokenAtPosition(sourceFile, position); + const commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos); + const range = commentRanges && find(commentRanges, (commentRange)=>position >= commentRange.pos && position <= commentRange.end); + if (!range) return void 0; + const text = sourceFile.text.slice(range.pos, position); + const match = tripleSlashDirectiveFragmentRegex.exec(text); + if (!match) return void 0; + const [, prefix, kind, toComplete] = match; + const scriptPath = getDirectoryPath(sourceFile.path); + const names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getExtensionOptions(compilerOptions, 0 /* Filename */ , sourceFile), host, /*moduleSpecifierIsRelative*/ true, sourceFile.path) : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions, 1 /* ModuleSpecifier */ , sourceFile)) : Debug.fail(); + return addReplacementSpans(toComplete, range.pos + prefix.length, arrayFrom(names.values())); + } + function getCompletionEntriesFromTypings(host, options, scriptPath, fragmentDirectory, extensionOptions, result = createNameAndKindSet()) { + const seen = /* @__PURE__ */ new Map(); + const typeRoots = tryAndIgnoreErrors(()=>getEffectiveTypeRoots(options, host)) || emptyArray; + for (const root of typeRoots)getCompletionEntriesFromDirectories(root); + for (const packageJson of findPackageJsons(scriptPath, host)){ + const typesDir = combinePaths(getDirectoryPath(packageJson), "node_modules/@types"); + getCompletionEntriesFromDirectories(typesDir); + } + return result; + function getCompletionEntriesFromDirectories(directory) { + if (!tryDirectoryExists(host, directory)) return; + for (const typeDirectoryName of tryGetDirectories(host, directory)){ + const packageName = unmangleScopedPackageName(typeDirectoryName); + if (options.types && !contains(options.types, packageName)) continue; + if (fragmentDirectory === void 0) { + if (!seen.has(packageName)) { + result.add(nameAndKind(packageName, "external module name" /* externalModuleName */ , /*extension*/ void 0)); + seen.set(packageName, true); + } + } else { + const baseDirectory = combinePaths(directory, typeDirectoryName); + const remainingFragment = tryRemoveDirectoryPrefix(fragmentDirectory, packageName, hostGetCanonicalFileName(host)); + if (remainingFragment !== void 0) getCompletionEntriesForDirectoryFragment(remainingFragment, baseDirectory, extensionOptions, host, /*moduleSpecifierIsRelative*/ false, /*exclude*/ void 0, result); } } } } - function isRegionDelimiter(lineText) { - lineText = trimStringStart(lineText); - if (!startsWith(lineText, "//")) return null; - lineText = trimString(lineText.slice(2)); - return regionDelimiterRegExp.exec(lineText); - } - function addOutliningForLeadingCommentsForPos(pos, sourceFile, cancellationToken, out) { - const comments = getLeadingCommentRanges(sourceFile.text, pos); - if (!comments) return; - let firstSingleLineCommentStart = -1; - let lastSingleLineCommentEnd = -1; - let singleLineCommentCount = 0; - const sourceText = sourceFile.getFullText(); - for (const { kind: kind , pos: pos2 , end: end } of comments){ - cancellationToken.throwIfCancellationRequested(); - switch(kind){ - case 2 /* SingleLineCommentTrivia */ : - const commentText = sourceText.slice(pos2, end); - if (isRegionDelimiter(commentText)) { - combineAndAddMultipleSingleLineComments(); - singleLineCommentCount = 0; - break; - } - if (singleLineCommentCount === 0) firstSingleLineCommentStart = pos2; - lastSingleLineCommentEnd = end; - singleLineCommentCount++; - break; - case 3 /* MultiLineCommentTrivia */ : - combineAndAddMultipleSingleLineComments(); - out.push(createOutliningSpanFromBounds(pos2, end, "comment" /* Comment */ )); - singleLineCommentCount = 0; - break; - default: - Debug.assertNever(kind); + function enumerateNodeModulesVisibleToScript(host, scriptPath) { + if (!host.readFile || !host.fileExists) return emptyArray; + const result = []; + for (const packageJson of findPackageJsons(scriptPath, host)){ + const contents = readJson(packageJson, host); + for (const key of nodeModulesDependencyKeys){ + const dependencies = contents[key]; + if (!dependencies) continue; + for(const dep in dependencies)if (hasProperty(dependencies, dep) && !startsWith(dep, "@types/")) result.push(dep); } } - combineAndAddMultipleSingleLineComments(); - function combineAndAddMultipleSingleLineComments() { - if (singleLineCommentCount > 1) out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */ )); + return result; + } + function getDirectoryFragmentTextSpan(text, textStart) { + const index = Math.max(text.lastIndexOf(directorySeparator), text.lastIndexOf(altDirectorySeparator)); + const offset = index !== -1 ? index + 1 : 0; + const length2 = text.length - offset; + return length2 === 0 || isIdentifierText(text.substr(offset, length2), 99 /* ESNext */ ) ? void 0 : createTextSpan(textStart + offset, length2); + } + function isPathRelativeToScript(path) { + if (path && path.length >= 2 && path.charCodeAt(0) === 46 /* dot */ ) { + const slashIndex = path.length >= 3 && path.charCodeAt(1) === 46 /* dot */ ? 2 : 1; + const slashCharCode = path.charCodeAt(slashIndex); + return slashCharCode === 47 /* slash */ || slashCharCode === 92 /* backslash */ ; } + return false; } - function addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out) { - if (isJsxText(n)) return; - addOutliningForLeadingCommentsForPos(n.pos, sourceFile, cancellationToken, out); + function containsSlash(fragment) { + return stringContains(fragment, directorySeparator); } - function createOutliningSpanFromBounds(pos, end, kind) { - return createOutliningSpan(createTextSpanFromBounds(pos, end), kind); + function isRequireCallArgument(node) { + return isCallExpression(node.parent) && firstOrUndefined(node.parent.arguments) === node && isIdentifier(node.parent.expression) && node.parent.expression.escapedText === "require"; } - function getOutliningSpanForNode(n, sourceFile) { - switch(n.kind){ - case 238 /* Block */ : - if (isFunctionLike(n.parent)) return functionSpan(n.parent, n, sourceFile); - switch(n.parent.kind){ - case 243 /* DoStatement */ : - case 246 /* ForInStatement */ : - case 247 /* ForOfStatement */ : - case 245 /* ForStatement */ : - case 242 /* IfStatement */ : - case 244 /* WhileStatement */ : - case 251 /* WithStatement */ : - case 295 /* CatchClause */ : - return spanForNode(n.parent); - case 255 /* TryStatement */ : - const tryStatement = n.parent; - if (tryStatement.tryBlock === n) return spanForNode(n.parent); - else if (tryStatement.finallyBlock === n) { - const node = findChildOfKind(tryStatement, 96 /* FinallyKeyword */ , sourceFile); - if (node) return spanForNode(node); - } - default: - return createOutliningSpan(createTextSpanFromNode(n, sourceFile), "code" /* Code */ ); - } - case 265 /* ModuleBlock */ : - return spanForNode(n.parent); - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : - case 261 /* InterfaceDeclaration */ : - case 263 /* EnumDeclaration */ : - case 266 /* CaseBlock */ : - case 184 /* TypeLiteral */ : - case 203 /* ObjectBindingPattern */ : - return spanForNode(n); - case 186 /* TupleType */ : - return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !isTupleTypeNode(n.parent), 22 /* OpenBracketToken */ ); - case 292 /* CaseClause */ : - case 293 /* DefaultClause */ : - return spanForNodeArray(n.statements); - case 207 /* ObjectLiteralExpression */ : - return spanForObjectOrArrayLiteral(n); - case 206 /* ArrayLiteralExpression */ : - return spanForObjectOrArrayLiteral(n, 22 /* OpenBracketToken */ ); - case 281 /* JsxElement */ : - return spanForJSXElement(n); - case 285 /* JsxFragment */ : - return spanForJSXFragment(n); - case 282 /* JsxSelfClosingElement */ : - case 283 /* JsxOpeningElement */ : - return spanForJSXAttributes(n.attributes); - case 225 /* TemplateExpression */ : - case 14 /* NoSubstitutionTemplateLiteral */ : - return spanForTemplateLiteral(n); - case 204 /* ArrayBindingPattern */ : - return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !isBindingElement(n.parent), 22 /* OpenBracketToken */ ); - case 216 /* ArrowFunction */ : - return spanForArrowFunction(n); - case 210 /* CallExpression */ : - return spanForCallExpression(n); - case 214 /* ParenthesizedExpression */ : - return spanForParenthesizedExpression(n); - case 272 /* NamedImports */ : - case 276 /* NamedExports */ : - case 296 /* AssertClause */ : - return spanForNamedImportsOrExportsOrAssertClause(n); - } - function spanForNamedImportsOrExportsOrAssertClause(node) { - if (!node.elements.length) return void 0; - const openToken = findChildOfKind(node, 18 /* OpenBraceToken */ , sourceFile); - const closeToken = findChildOfKind(node, 19 /* CloseBraceToken */ , sourceFile); - if (!openToken || !closeToken || positionsAreOnSameLine(openToken.pos, closeToken.pos, sourceFile)) return void 0; - return spanBetweenTokens(openToken, closeToken, node, sourceFile, /*autoCollapse*/ false, /*useFullStart*/ false); - } - function spanForCallExpression(node) { - if (!node.arguments.length) return void 0; - const openToken = findChildOfKind(node, 20 /* OpenParenToken */ , sourceFile); - const closeToken = findChildOfKind(node, 21 /* CloseParenToken */ , sourceFile); - if (!openToken || !closeToken || positionsAreOnSameLine(openToken.pos, closeToken.pos, sourceFile)) return void 0; - return spanBetweenTokens(openToken, closeToken, node, sourceFile, /*autoCollapse*/ false, /*useFullStart*/ true); + var kindPrecedence, tripleSlashDirectiveFragmentRegex, nodeModulesDependencyKeys; + var init_stringCompletions = __esm({ + "src/services/stringCompletions.ts" () { + "use strict"; + init_ts4(); + init_ts_Completions(); + kindPrecedence = { + ["directory" /* directory */ ]: 0, + ["script" /* scriptElement */ ]: 1, + ["external module name" /* externalModuleName */ ]: 2 + }; + tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s*getStringLiteralCompletionDetails, + getStringLiteralCompletions: ()=>getStringLiteralCompletions + }); + var init_ts_Completions_StringCompletions = __esm({ + "src/services/_namespaces/ts.Completions.StringCompletions.ts" () { + "use strict"; + init_stringCompletions(); } - function spanForJSXElement(node) { - const textSpan = createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd()); - const tagName = node.openingElement.tagName.getText(sourceFile); - const bannerText = "<" + tagName + ">..."; - return createOutliningSpan(textSpan, "code" /* Code */ , textSpan, /*autoCollapse*/ false, bannerText); + }); + // src/services/_namespaces/ts.Completions.ts + var ts_Completions_exports = {}; + __export(ts_Completions_exports, { + CompletionKind: ()=>CompletionKind, + CompletionSource: ()=>CompletionSource, + SortText: ()=>SortText, + StringCompletions: ()=>ts_Completions_StringCompletions_exports, + SymbolOriginInfoKind: ()=>SymbolOriginInfoKind, + createCompletionDetails: ()=>createCompletionDetails, + createCompletionDetailsForSymbol: ()=>createCompletionDetailsForSymbol, + getCompletionEntriesFromSymbols: ()=>getCompletionEntriesFromSymbols, + getCompletionEntryDetails: ()=>getCompletionEntryDetails, + getCompletionEntrySymbol: ()=>getCompletionEntrySymbol, + getCompletionsAtPosition: ()=>getCompletionsAtPosition, + getPropertiesForObjectExpression: ()=>getPropertiesForObjectExpression, + moduleSpecifierResolutionCacheAttemptLimit: ()=>moduleSpecifierResolutionCacheAttemptLimit, + moduleSpecifierResolutionLimit: ()=>moduleSpecifierResolutionLimit + }); + var init_ts_Completions = __esm({ + "src/services/_namespaces/ts.Completions.ts" () { + "use strict"; + init_completions(); + init_ts_Completions_StringCompletions(); } - function spanForJSXFragment(node) { - const textSpan = createTextSpanFromBounds(node.openingFragment.getStart(sourceFile), node.closingFragment.getEnd()); - const bannerText = "<>..."; - return createOutliningSpan(textSpan, "code" /* Code */ , textSpan, /*autoCollapse*/ false, bannerText); + }); + // src/services/importTracker.ts + function createImportTracker(sourceFiles, sourceFilesSet, checker, cancellationToken) { + const allDirectImports = getDirectImportsMap(sourceFiles, checker, cancellationToken); + return (exportSymbol, exportInfo, isForRename)=>{ + const { directImports: directImports, indirectUsers: indirectUsers } = getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, exportInfo, checker, cancellationToken); + return { + indirectUsers: indirectUsers, + ...getSearchesFromDirectImports(directImports, exportSymbol, exportInfo.exportKind, checker, isForRename) + }; + }; + } + function getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind }, checker, cancellationToken) { + const markSeenDirectImport = nodeSeenTracker(); + const markSeenIndirectUser = nodeSeenTracker(); + const directImports = []; + const isAvailableThroughGlobal = !!exportingModuleSymbol.globalExports; + const indirectUserDeclarations = isAvailableThroughGlobal ? void 0 : []; + handleDirectImports(exportingModuleSymbol); + return { + directImports: directImports, + indirectUsers: getIndirectUsers() + }; + function getIndirectUsers() { + if (isAvailableThroughGlobal) return sourceFiles; + if (exportingModuleSymbol.declarations) { + for (const decl of exportingModuleSymbol.declarations)if (isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) addIndirectUser(decl); + } + return indirectUserDeclarations.map(getSourceFileOfNode); } - function spanForJSXAttributes(node) { - if (node.properties.length === 0) return void 0; - return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */ ); + function handleDirectImports(exportingModuleSymbol2) { + const theseDirectImports = getDirectImports(exportingModuleSymbol2); + if (theseDirectImports) for (const direct of theseDirectImports){ + if (!markSeenDirectImport(direct)) continue; + if (cancellationToken) cancellationToken.throwIfCancellationRequested(); + switch(direct.kind){ + case 213 /* CallExpression */ : + if (isImportCall(direct)) { + handleImportCall(direct); + break; + } + if (!isAvailableThroughGlobal) { + const parent2 = direct.parent; + if (exportKind === 2 /* ExportEquals */ && parent2.kind === 260 /* VariableDeclaration */ ) { + const { name: name } = parent2; + if (name.kind === 80 /* Identifier */ ) { + directImports.push(name); + break; + } + } + } + break; + case 80 /* Identifier */ : + break; + case 271 /* ImportEqualsDeclaration */ : + handleNamespaceImport(direct, direct.name, hasSyntacticModifier(direct, 1 /* Export */ ), /*alreadyAddedDirect*/ false); + break; + case 272 /* ImportDeclaration */ : + directImports.push(direct); + const namedBindings = direct.importClause && direct.importClause.namedBindings; + if (namedBindings && namedBindings.kind === 274 /* NamespaceImport */ ) handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true); + else if (!isAvailableThroughGlobal && isDefaultImport(direct)) addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); + break; + case 278 /* ExportDeclaration */ : + if (!direct.exportClause) handleDirectImports(getContainingModuleSymbol(direct, checker)); + else if (direct.exportClause.kind === 280 /* NamespaceExport */ ) addIndirectUser(getSourceFileLikeForImportDeclaration(direct), /*addTransitiveDependencies*/ true); + else directImports.push(direct); + break; + case 205 /* ImportType */ : + if (!isAvailableThroughGlobal && direct.isTypeOf && !direct.qualifier && isExported2(direct)) addIndirectUser(direct.getSourceFile(), /*addTransitiveDependencies*/ true); + directImports.push(direct); + break; + default: + Debug.failBadSyntaxKind(direct, "Unexpected import kind."); + } + } } - function spanForTemplateLiteral(node) { - if (node.kind === 14 /* NoSubstitutionTemplateLiteral */ && node.text.length === 0) return void 0; - return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */ ); + function handleImportCall(importCall) { + const top = findAncestor(importCall, isAmbientModuleDeclaration) || importCall.getSourceFile(); + addIndirectUser(top, /** addTransitiveDependencies */ !!isExported2(importCall, /*stopAtAmbientModule*/ true)); } - function spanForObjectOrArrayLiteral(node, open = 18 /* OpenBraceToken */ ) { - return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !isArrayLiteralExpression(node.parent) && !isCallExpression(node.parent), open); + function isExported2(node, stopAtAmbientModule = false) { + return findAncestor(node, (node2)=>{ + if (stopAtAmbientModule && isAmbientModuleDeclaration(node2)) return "quit"; + return canHaveModifiers(node2) && some(node2.modifiers, isExportModifier); + }); } - function spanForNode(hintSpanNode, autoCollapse = false, useFullStart = true, open = 18 /* OpenBraceToken */ , close = open === 18 /* OpenBraceToken */ ? 19 /* CloseBraceToken */ : 23 /* CloseBracketToken */ ) { - const openToken = findChildOfKind(n, open, sourceFile); - const closeToken = findChildOfKind(n, close, sourceFile); - return openToken && closeToken && spanBetweenTokens(openToken, closeToken, hintSpanNode, sourceFile, autoCollapse, useFullStart); + function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) { + if (exportKind === 2 /* ExportEquals */ ) { + if (!alreadyAddedDirect) directImports.push(importDeclaration); + } else if (!isAvailableThroughGlobal) { + const sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); + Debug.assert(sourceFileLike.kind === 312 /* SourceFile */ || sourceFileLike.kind === 267 /* ModuleDeclaration */ ); + if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) addIndirectUser(sourceFileLike, /*addTransitiveDependencies*/ true); + else addIndirectUser(sourceFileLike); + } } - function spanForNodeArray(nodeArray) { - return nodeArray.length ? createOutliningSpan(createTextSpanFromRange(nodeArray), "code" /* Code */ ) : void 0; + function addIndirectUser(sourceFileLike, addTransitiveDependencies = false) { + Debug.assert(!isAvailableThroughGlobal); + const isNew = markSeenIndirectUser(sourceFileLike); + if (!isNew) return; + indirectUserDeclarations.push(sourceFileLike); + if (!addTransitiveDependencies) return; + const moduleSymbol = checker.getMergedSymbol(sourceFileLike.symbol); + if (!moduleSymbol) return; + Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */ )); + const directImports2 = getDirectImports(moduleSymbol); + if (directImports2) { + for (const directImport of directImports2)if (!isImportTypeNode(directImport)) addIndirectUser(getSourceFileLikeForImportDeclaration(directImport), /*addTransitiveDependencies*/ true); + } } - function spanForParenthesizedExpression(node) { - if (positionsAreOnSameLine(node.getStart(), node.getEnd(), sourceFile)) return void 0; - const textSpan = createTextSpanFromBounds(node.getStart(), node.getEnd()); - return createOutliningSpan(textSpan, "code" /* Code */ , createTextSpanFromNode(node)); + function getDirectImports(moduleSymbol) { + return allDirectImports.get(getSymbolId(moduleSymbol).toString()); } } - function functionSpan(node, body, sourceFile) { - const openToken = tryGetFunctionOpenToken(node, body, sourceFile); - const closeToken = findChildOfKind(body, 19 /* CloseBraceToken */ , sourceFile); - return openToken && closeToken && spanBetweenTokens(openToken, closeToken, node, sourceFile, /*autoCollapse*/ node.kind !== 216 /* ArrowFunction */ ); - } - function spanBetweenTokens(openToken, closeToken, hintSpanNode, sourceFile, autoCollapse = false, useFullStart = true) { - const textSpan = createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd()); - return createOutliningSpan(textSpan, "code" /* Code */ , createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); - } - function createOutliningSpan(textSpan, kind, hintSpan = textSpan, autoCollapse = false, bannerText = "...") { + function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, checker, isForRename) { + const importSearches = []; + const singleReferences = []; + function addSearch(location, symbol) { + importSearches.push([ + location, + symbol + ]); + } + if (directImports) for (const decl of directImports)handleImport(decl); return { - textSpan: textSpan, - kind: kind, - hintSpan: hintSpan, - bannerText: bannerText, - autoCollapse: autoCollapse + importSearches: importSearches, + singleReferences: singleReferences }; - } - function tryGetFunctionOpenToken(node, body, sourceFile) { - if (isNodeArrayMultiLine(node.parameters, sourceFile)) { - const openParenToken = findChildOfKind(node, 20 /* OpenParenToken */ , sourceFile); - if (openParenToken) return openParenToken; + function handleImport(decl) { + if (decl.kind === 271 /* ImportEqualsDeclaration */ ) { + if (isExternalModuleImportEquals(decl)) handleNamespaceImportLike(decl.name); + return; + } + if (decl.kind === 80 /* Identifier */ ) { + handleNamespaceImportLike(decl); + return; + } + if (decl.kind === 205 /* ImportType */ ) { + if (decl.qualifier) { + const firstIdentifier = getFirstIdentifier(decl.qualifier); + if (firstIdentifier.escapedText === symbolName(exportSymbol)) singleReferences.push(firstIdentifier); + } else if (exportKind === 2 /* ExportEquals */ ) singleReferences.push(decl.argument.literal); + return; + } + if (decl.moduleSpecifier.kind !== 11 /* StringLiteral */ ) return; + if (decl.kind === 278 /* ExportDeclaration */ ) { + if (decl.exportClause && isNamedExports(decl.exportClause)) searchForNamedImport(decl.exportClause); + return; + } + const { name: name, namedBindings: namedBindings } = decl.importClause || { + name: void 0, + namedBindings: void 0 + }; + if (namedBindings) switch(namedBindings.kind){ + case 274 /* NamespaceImport */ : + handleNamespaceImportLike(namedBindings.name); + break; + case 275 /* NamedImports */ : + if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */ ) searchForNamedImport(namedBindings); + break; + default: + Debug.assertNever(namedBindings); + } + if (name && (exportKind === 1 /* Default */ || exportKind === 2 /* ExportEquals */ ) && (!isForRename || name.escapedText === symbolEscapedNameNoDefault(exportSymbol))) { + const defaultImportAlias = checker.getSymbolAtLocation(name); + addSearch(name, defaultImportAlias); + } } - return findChildOfKind(body, 18 /* OpenBraceToken */ , sourceFile); - } - var regionDelimiterRegExp; - var init_outliningElementsCollector = __esm({ - "src/services/outliningElementsCollector.ts" () { - "use strict"; - init_ts4(); - regionDelimiterRegExp = /^#(end)?region(?:\s+(.*))?(?:\r)?$/; + function handleNamespaceImportLike(importName) { + if (exportKind === 2 /* ExportEquals */ && (!isForRename || isNameMatch(importName.escapedText))) addSearch(importName, checker.getSymbolAtLocation(importName)); } - }); - // src/services/_namespaces/ts.OutliningElementsCollector.ts - var ts_OutliningElementsCollector_exports = {}; - __export(ts_OutliningElementsCollector_exports, { - collectElements: ()=>collectElements - }); - var init_ts_OutliningElementsCollector = __esm({ - "src/services/_namespaces/ts.OutliningElementsCollector.ts" () { - "use strict"; - init_outliningElementsCollector(); + function searchForNamedImport(namedBindings) { + if (!namedBindings) return; + for (const element of namedBindings.elements){ + const { name: name, propertyName: propertyName } = element; + if (!isNameMatch((propertyName || name).escapedText)) continue; + if (propertyName) { + singleReferences.push(propertyName); + if (!isForRename || name.escapedText === exportSymbol.escapedName) addSearch(name, checker.getSymbolAtLocation(name)); + } else { + const localSymbol = element.kind === 281 /* ExportSpecifier */ && element.propertyName ? checker.getExportSpecifierLocalTargetSymbol(element) : checker.getSymbolAtLocation(name); + addSearch(name, localSymbol); + } + } + } + function isNameMatch(name) { + return name === exportSymbol.escapedName || exportKind !== 0 /* Named */ && name === "default" /* Default */ ; } - }); - // src/services/refactorProvider.ts - function registerRefactor(name, refactor) { - refactors.set(name, refactor); - } - function getApplicableRefactors(context) { - return arrayFrom(flatMapIterator(refactors.values(), (refactor)=>{ - var _a2; - return context.cancellationToken && context.cancellationToken.isCancellationRequested() || !((_a2 = refactor.kinds) == null ? void 0 : _a2.some((kind)=>refactorKindBeginsWith(kind, context.kind))) ? void 0 : refactor.getAvailableActions(context); - })); } - function getEditsForRefactor(context, refactorName13, actionName2) { - const refactor = refactors.get(refactorName13); - return refactor && refactor.getEditsForAction(context, actionName2); + function findNamespaceReExports(sourceFileLike, name, checker) { + const namespaceImportSymbol = checker.getSymbolAtLocation(name); + return !!forEachPossibleImportOrExportStatement(sourceFileLike, (statement)=>{ + if (!isExportDeclaration(statement)) return; + const { exportClause: exportClause, moduleSpecifier: moduleSpecifier } = statement; + return !moduleSpecifier && exportClause && isNamedExports(exportClause) && exportClause.elements.some((element)=>checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol); + }); } - var refactors; - var init_refactorProvider = __esm({ - "src/services/refactorProvider.ts" () { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactors = /* @__PURE__ */ new Map(); - } - }); - // src/services/refactors/convertExport.ts - function getInfo19(context, considerPartialSpans = true) { - const { file: file , program: program } = context; - const span = getRefactorContextSpan(context); - const token = getTokenAtPosition(file, span.start); - const exportNode = !!(token.parent && getSyntacticModifierFlags(token.parent) & 1 /* Export */ ) && considerPartialSpans ? token.parent : getParentNodeInSpan(token, file, span); - if (!exportNode || !isSourceFile(exportNode.parent) && !(isModuleBlock(exportNode.parent) && isAmbientModule(exportNode.parent.parent))) return { - error: getLocaleSpecificMessage(Diagnostics.Could_not_find_export_statement) - }; + function findModuleReferences(program, sourceFiles, searchModuleSymbol) { + var _a; + const refs = []; const checker = program.getTypeChecker(); - const exportingModuleSymbol = getExportingModuleSymbol(exportNode.parent, checker); - const flags = getSyntacticModifierFlags(exportNode) || (isExportAssignment(exportNode) && !exportNode.isExportEquals ? 1025 /* ExportDefault */ : 0 /* None */ ); - const wasDefault = !!(flags & 1024 /* Default */ ); - if (!(flags & 1 /* Export */ ) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */ )) return { - error: getLocaleSpecificMessage(Diagnostics.This_file_already_has_a_default_export) - }; - const noSymbolError = (id)=>isIdentifier(id) && checker.getSymbolAtLocation(id) ? void 0 : { - error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_named_export) - }; - switch(exportNode.kind){ - case 259 /* FunctionDeclaration */ : - case 260 /* ClassDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 263 /* EnumDeclaration */ : - case 262 /* TypeAliasDeclaration */ : - case 264 /* ModuleDeclaration */ : - { - const node = exportNode; - if (!node.name) return void 0; - return noSymbolError(node.name) || { - exportNode: node, - exportName: node.name, - wasDefault: wasDefault, - exportingModuleSymbol: exportingModuleSymbol - }; - } - case 240 /* VariableStatement */ : - { - const vs = exportNode; - if (!(vs.declarationList.flags & 2 /* Const */ ) || vs.declarationList.declarations.length !== 1) return void 0; - const decl = first(vs.declarationList.declarations); - if (!decl.initializer) return void 0; - Debug.assert(!wasDefault, "Can't have a default flag here"); - return noSymbolError(decl.name) || { - exportNode: vs, - exportName: decl.name, - wasDefault: wasDefault, - exportingModuleSymbol: exportingModuleSymbol - }; + for (const referencingFile of sourceFiles){ + const searchSourceFile = searchModuleSymbol.valueDeclaration; + if ((searchSourceFile == null ? void 0 : searchSourceFile.kind) === 312 /* SourceFile */ ) { + for (const ref of referencingFile.referencedFiles)if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) refs.push({ + kind: "reference", + referencingFile: referencingFile, + ref: ref + }); + for (const ref of referencingFile.typeReferenceDirectives){ + const referenced = (_a = program.getResolvedTypeReferenceDirectives().get(ref.fileName, ref.resolutionMode || referencingFile.impliedNodeFormat)) == null ? void 0 : _a.resolvedTypeReferenceDirective; + if (referenced !== void 0 && referenced.resolvedFileName === searchSourceFile.fileName) refs.push({ + kind: "reference", + referencingFile: referencingFile, + ref: ref + }); } - case 274 /* ExportAssignment */ : - { - const node = exportNode; - if (node.isExportEquals) return void 0; - return noSymbolError(node.expression) || { - exportNode: node, - exportName: node.expression, - wasDefault: wasDefault, - exportingModuleSymbol: exportingModuleSymbol - }; + } + forEachImport(referencingFile, (importDecl, moduleSpecifier)=>{ + const moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol === searchModuleSymbol) refs.push(nodeIsSynthesized(importDecl) ? { + kind: "implicit", + literal: moduleSpecifier, + referencingFile: referencingFile + } : { + kind: "import", + literal: moduleSpecifier + }); + }); + } + return refs; + } + function getDirectImportsMap(sourceFiles, checker, cancellationToken) { + const map2 = /* @__PURE__ */ new Map(); + for (const sourceFile of sourceFiles){ + if (cancellationToken) cancellationToken.throwIfCancellationRequested(); + forEachImport(sourceFile, (importDecl, moduleSpecifier)=>{ + const moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol) { + const id = getSymbolId(moduleSymbol).toString(); + let imports = map2.get(id); + if (!imports) map2.set(id, imports = []); + imports.push(importDecl); } - default: - return void 0; + }); } + return map2; } - function doChange33(exportingSourceFile, program, info, changes, cancellationToken) { - changeExport(exportingSourceFile, info, changes, program.getTypeChecker()); - changeImports(program, info, changes, cancellationToken); + function forEachPossibleImportOrExportStatement(sourceFileLike, action) { + return forEach(sourceFileLike.kind === 312 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, (statement)=>// TODO: GH#18217 + action(statement) || isAmbientModuleDeclaration(statement) && forEach(statement.body && statement.body.statements, action)); } - function changeExport(exportingSourceFile, { wasDefault: wasDefault , exportNode: exportNode , exportName: exportName }, changes, checker) { - if (wasDefault) { - if (isExportAssignment(exportNode) && !exportNode.isExportEquals) { - const exp = exportNode.expression; - const spec = makeExportSpecifier(exp.text, exp.text); - changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, factory.createNamedExports([ - spec - ]))); - } else changes.delete(exportingSourceFile, Debug.checkDefined(findModifier(exportNode, 88 /* DefaultKeyword */ ), "Should find a default keyword in modifier list")); - } else { - const exportKeyword = Debug.checkDefined(findModifier(exportNode, 93 /* ExportKeyword */ ), "Should find an export keyword in modifier list"); - switch(exportNode.kind){ - case 259 /* FunctionDeclaration */ : - case 260 /* ClassDeclaration */ : - case 261 /* InterfaceDeclaration */ : - changes.insertNodeAfter(exportingSourceFile, exportKeyword, factory.createToken(88 /* DefaultKeyword */ )); - break; - case 240 /* VariableStatement */ : - const decl = first(exportNode.declarationList.declarations); - if (!ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile) && !decl.type) { - changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDefault(Debug.checkDefined(decl.initializer, "Initializer was previously known to be present"))); + function forEachImport(sourceFile, action) { + if (sourceFile.externalModuleIndicator || sourceFile.imports !== void 0) for (const i of sourceFile.imports)action(importFromModuleSpecifier(i), i); + else forEachPossibleImportOrExportStatement(sourceFile, (statement)=>{ + switch(statement.kind){ + case 278 /* ExportDeclaration */ : + case 272 /* ImportDeclaration */ : + { + const decl = statement; + if (decl.moduleSpecifier && isStringLiteral(decl.moduleSpecifier)) action(decl, decl.moduleSpecifier); + break; + } + case 271 /* ImportEqualsDeclaration */ : + { + const decl = statement; + if (isExternalModuleImportEquals(decl)) action(decl, decl.moduleReference.expression); break; } - case 263 /* EnumDeclaration */ : - case 262 /* TypeAliasDeclaration */ : - case 264 /* ModuleDeclaration */ : - changes.deleteModifier(exportingSourceFile, exportKeyword); - changes.insertNodeAfter(exportingSourceFile, exportNode, factory.createExportDefault(factory.createIdentifier(exportName.text))); - break; - default: - Debug.fail(`Unexpected exportNode kind ${exportNode.kind}`); } - } - } - function changeImports(program, { wasDefault: wasDefault , exportName: exportName , exportingModuleSymbol: exportingModuleSymbol }, changes, cancellationToken) { - const checker = program.getTypeChecker(); - const exportSymbol = Debug.checkDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol"); - ts_FindAllReferences_exports.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, (ref)=>{ - if (exportName === ref) return; - const importingSourceFile = ref.getSourceFile(); - if (wasDefault) changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text); - else changeNamedToDefaultImport(importingSourceFile, ref, changes); }); } - function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { - const { parent: parent2 } = ref; - switch(parent2.kind){ - case 208 /* PropertyAccessExpression */ : - changes.replaceNode(importingSourceFile, ref, factory.createIdentifier(exportName)); - break; - case 273 /* ImportSpecifier */ : - case 278 /* ExportSpecifier */ : - { - const spec = parent2; - changes.replaceNode(importingSourceFile, spec, makeImportSpecifier2(exportName, spec.name.text)); - break; - } - case 270 /* ImportClause */ : - { - const clause = parent2; - Debug.assert(clause.name === ref, "Import clause name should match provided ref"); - const spec = makeImportSpecifier2(exportName, ref.text); - const { namedBindings: namedBindings } = clause; - if (!namedBindings) changes.replaceNode(importingSourceFile, ref, factory.createNamedImports([ - spec - ])); - else if (namedBindings.kind === 271 /* NamespaceImport */ ) { - changes.deleteRange(importingSourceFile, { - pos: ref.getStart(importingSourceFile), - end: namedBindings.getStart(importingSourceFile) - }); - const quotePreference = isStringLiteral(clause.parent.moduleSpecifier) ? quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */ ; - const newImport = makeImport(/*default*/ void 0, [ - makeImportSpecifier2(exportName, ref.text) - ], clause.parent.moduleSpecifier, quotePreference); - changes.insertNodeAfter(importingSourceFile, clause.parent, newImport); - } else { - changes.delete(importingSourceFile, ref); - changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec); + function getImportOrExportSymbol(node, symbol, checker, comingFromExport) { + return comingFromExport ? getExport() : getExport() || getImport(); + function getExport() { + var _a; + const { parent: parent2 } = node; + const grandparent = parent2.parent; + if (symbol.exportSymbol) { + if (parent2.kind === 211 /* PropertyAccessExpression */ ) return ((_a = symbol.declarations) == null ? void 0 : _a.some((d)=>d === parent2)) && isBinaryExpression(grandparent) ? getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ false) : void 0; + else return exportInfo(symbol.exportSymbol, getExportKindForDeclaration(parent2)); + } else { + const exportNode = getExportNode(parent2, node); + if (exportNode && hasSyntacticModifier(exportNode, 1 /* Export */ )) { + if (isImportEqualsDeclaration(exportNode) && exportNode.moduleReference === node) { + if (comingFromExport) return void 0; + const lhsSymbol = checker.getSymbolAtLocation(exportNode.name); + return { + kind: 0 /* Import */ , + symbol: lhsSymbol + }; + } else return exportInfo(symbol, getExportKindForDeclaration(exportNode)); + } else if (isNamespaceExport(parent2)) return exportInfo(symbol, 0 /* Named */ ); + else if (isExportAssignment(parent2)) return getExportAssignmentExport(parent2); + else if (isExportAssignment(grandparent)) return getExportAssignmentExport(grandparent); + else if (isBinaryExpression(parent2)) return getSpecialPropertyExport(parent2, /*useLhsSymbol*/ true); + else if (isBinaryExpression(grandparent)) return getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ true); + else if (isJSDocTypedefTag(parent2) || isJSDocCallbackTag(parent2)) return exportInfo(symbol, 0 /* Named */ ); + } + function getExportAssignmentExport(ex) { + if (!ex.symbol.parent) return void 0; + const exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */ ; + return { + kind: 1 /* Export */ , + symbol: symbol, + exportInfo: { + exportingModuleSymbol: ex.symbol.parent, + exportKind: exportKind } - break; + }; + } + function getSpecialPropertyExport(node2, useLhsSymbol) { + let kind; + switch(getAssignmentDeclarationKind(node2)){ + case 1 /* ExportsProperty */ : + kind = 0 /* Named */ ; + break; + case 2 /* ModuleExports */ : + kind = 2 /* ExportEquals */ ; + break; + default: + return void 0; } - case 202 /* ImportType */ : - const importTypeNode = parent2; - changes.replaceNode(importingSourceFile, parent2, factory.createImportTypeNode(importTypeNode.argument, importTypeNode.assertions, factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf)); - break; - default: - Debug.failBadSyntaxKind(parent2); + const sym = useLhsSymbol ? checker.getSymbolAtLocation(getNameOfAccessExpression(cast(node2.left, isAccessExpression))) : symbol; + return sym && exportInfo(sym, kind); + } } - } - function changeNamedToDefaultImport(importingSourceFile, ref, changes) { - const parent2 = ref.parent; - switch(parent2.kind){ - case 208 /* PropertyAccessExpression */ : - changes.replaceNode(importingSourceFile, ref, factory.createIdentifier("default")); - break; - case 273 /* ImportSpecifier */ : - { - const defaultImport = factory.createIdentifier(parent2.name.text); - if (parent2.parent.elements.length === 1) changes.replaceNode(importingSourceFile, parent2.parent, defaultImport); - else { - changes.delete(importingSourceFile, parent2); - changes.insertNodeBefore(importingSourceFile, parent2.parent, defaultImport); - } - break; - } - case 278 /* ExportSpecifier */ : - changes.replaceNode(importingSourceFile, parent2, makeExportSpecifier("default", parent2.name.text)); - break; - default: - Debug.assertNever(parent2, `Unexpected parent kind ${parent2.kind}`); + function getImport() { + const isImport3 = isNodeImport(node); + if (!isImport3) return void 0; + let importedSymbol = checker.getImmediateAliasedSymbol(symbol); + if (!importedSymbol) return void 0; + importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker); + if (importedSymbol.escapedName === "export=") { + importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker); + if (importedSymbol === void 0) return void 0; + } + const importedName = symbolEscapedNameNoDefault(importedSymbol); + if (importedName === void 0 || importedName === "default" /* Default */ || importedName === symbol.escapedName) return { + kind: 0 /* Import */ , + symbol: importedSymbol + }; + } + function exportInfo(symbol2, kind) { + const exportInfo2 = getExportInfo(symbol2, kind, checker); + return exportInfo2 && { + kind: 1 /* Export */ , + symbol: symbol2, + exportInfo: exportInfo2 + }; + } + function getExportKindForDeclaration(node2) { + return hasSyntacticModifier(node2, 1024 /* Default */ ) ? 1 /* Default */ : 0 /* Named */ ; } } - function makeImportSpecifier2(propertyName, name) { - return factory.createImportSpecifier(/*isTypeOnly*/ false, propertyName === name ? void 0 : factory.createIdentifier(propertyName), factory.createIdentifier(name)); - } - function makeExportSpecifier(propertyName, name) { - return factory.createExportSpecifier(/*isTypeOnly*/ false, propertyName === name ? void 0 : factory.createIdentifier(propertyName), factory.createIdentifier(name)); - } - function getExportingModuleSymbol(parent2, checker) { - if (isSourceFile(parent2)) return parent2.symbol; - const symbol = parent2.parent.symbol; - if (symbol.valueDeclaration && isExternalModuleAugmentation(symbol.valueDeclaration)) return checker.getMergedSymbol(symbol); + function getExportEqualsLocalSymbol(importedSymbol, checker) { + var _a, _b; + if (importedSymbol.flags & 2097152 /* Alias */ ) return checker.getImmediateAliasedSymbol(importedSymbol); + const decl = Debug.checkDefined(importedSymbol.valueDeclaration); + if (isExportAssignment(decl)) return (_a = tryCast(decl.expression, canHaveSymbol)) == null ? void 0 : _a.symbol; + else if (isBinaryExpression(decl)) return (_b = tryCast(decl.right, canHaveSymbol)) == null ? void 0 : _b.symbol; + else if (isSourceFile(decl)) return decl.symbol; + return void 0; + } + function getExportNode(parent2, node) { + const declaration = isVariableDeclaration(parent2) ? parent2 : isBindingElement(parent2) ? walkUpBindingElementsAndPatterns(parent2) : void 0; + if (declaration) return parent2.name !== node ? void 0 : isCatchClause(declaration.parent) ? void 0 : isVariableStatement(declaration.parent.parent) ? declaration.parent.parent : void 0; + else return parent2; + } + function isNodeImport(node) { + const { parent: parent2 } = node; + switch(parent2.kind){ + case 271 /* ImportEqualsDeclaration */ : + return parent2.name === node && isExternalModuleImportEquals(parent2); + case 276 /* ImportSpecifier */ : + return !parent2.propertyName; + case 273 /* ImportClause */ : + case 274 /* NamespaceImport */ : + Debug.assert(parent2.name === node); + return true; + case 208 /* BindingElement */ : + return isInJSFile(node) && isVariableDeclarationInitializedToBareOrAccessedRequire(parent2.parent.parent); + default: + return false; + } + } + function getExportInfo(exportSymbol, exportKind, checker) { + const moduleSymbol = exportSymbol.parent; + if (!moduleSymbol) return void 0; + const exportingModuleSymbol = checker.getMergedSymbol(moduleSymbol); + return isExternalModuleSymbol(exportingModuleSymbol) ? { + exportingModuleSymbol: exportingModuleSymbol, + exportKind: exportKind + } : void 0; + } + function skipExportSpecifierSymbol(symbol, checker) { + if (symbol.declarations) for (const declaration of symbol.declarations){ + if (isExportSpecifier(declaration) && !declaration.propertyName && !declaration.parent.parent.moduleSpecifier) return checker.getExportSpecifierLocalTargetSymbol(declaration) || symbol; + else if (isPropertyAccessExpression(declaration) && isModuleExportsAccessExpression(declaration.expression) && !isPrivateIdentifier(declaration.name)) return checker.getSymbolAtLocation(declaration); + else if (isShorthandPropertyAssignment(declaration) && isBinaryExpression(declaration.parent.parent) && getAssignmentDeclarationKind(declaration.parent.parent) === 2 /* ModuleExports */ ) return checker.getExportSpecifierLocalTargetSymbol(declaration.name); + } return symbol; } - var refactorName, defaultToNamedAction, namedToDefaultAction; - var init_convertExport = __esm({ - "src/services/refactors/convertExport.ts" () { + function getContainingModuleSymbol(importer, checker) { + return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol); + } + function getSourceFileLikeForImportDeclaration(node) { + if (node.kind === 213 /* CallExpression */ ) return node.getSourceFile(); + const { parent: parent2 } = node; + if (parent2.kind === 312 /* SourceFile */ ) return parent2; + Debug.assert(parent2.kind === 268 /* ModuleBlock */ ); + return cast(parent2.parent, isAmbientModuleDeclaration); + } + function isAmbientModuleDeclaration(node) { + return node.kind === 267 /* ModuleDeclaration */ && node.name.kind === 11 /* StringLiteral */ ; + } + function isExternalModuleImportEquals(eq) { + return eq.moduleReference.kind === 283 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 11 /* StringLiteral */ ; + } + var ExportKind2, ImportExport; + var init_importTracker = __esm({ + "src/services/importTracker.ts" () { "use strict"; init_ts4(); - init_ts_refactor(); - refactorName = "Convert export"; - defaultToNamedAction = { - name: "Convert default export to named export", - description: Diagnostics.Convert_default_export_to_named_export.message, - kind: "refactor.rewrite.export.named" - }; - namedToDefaultAction = { - name: "Convert named export to default export", - description: Diagnostics.Convert_named_export_to_default_export.message, - kind: "refactor.rewrite.export.default" - }; - registerRefactor(refactorName, { - kinds: [ - defaultToNamedAction.kind, - namedToDefaultAction.kind - ], - getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndDefaultExports(context) { - const info = getInfo19(context, context.triggerReason === "invoked"); - if (!info) return emptyArray; - if (!isRefactorErrorInfo(info)) { - const action = info.wasDefault ? defaultToNamedAction : namedToDefaultAction; - return [ - { - name: refactorName, - description: action.description, - actions: [ - action - ] - } - ]; - } - if (context.preferences.provideRefactorNotApplicableReason) return [ - { - name: refactorName, - description: Diagnostics.Convert_default_export_to_named_export.message, - actions: [ - { - ...defaultToNamedAction, - notApplicableReason: info.error - }, - { - ...namedToDefaultAction, - notApplicableReason: info.error - } - ] - } - ]; - return emptyArray; - }, - getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndDefaultExports(context, actionName2) { - Debug.assert(actionName2 === defaultToNamedAction.name || actionName2 === namedToDefaultAction.name, "Unexpected action name"); - const info = getInfo19(context); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange33(context.file, context.program, info, t, context.cancellationToken)); - return { - edits: edits, - renameFilename: void 0, - renameLocation: void 0 - }; - } - }); + ExportKind2 = /* @__PURE__ */ ((ExportKind3)=>{ + ExportKind3[ExportKind3["Named"] = 0] = "Named"; + ExportKind3[ExportKind3["Default"] = 1] = "Default"; + ExportKind3[ExportKind3["ExportEquals"] = 2] = "ExportEquals"; + return ExportKind3; + })(ExportKind2 || {}); + ImportExport = /* @__PURE__ */ ((ImportExport2)=>{ + ImportExport2[ImportExport2["Import"] = 0] = "Import"; + ImportExport2[ImportExport2["Export"] = 1] = "Export"; + return ImportExport2; + })(ImportExport || {}); } }); - // src/services/refactors/convertImport.ts - function getImportConversionInfo(context, considerPartialSpans = true) { - const { file: file } = context; - const span = getRefactorContextSpan(context); - const token = getTokenAtPosition(file, span.start); - const importDecl = considerPartialSpans ? findAncestor(token, isImportDeclaration) : getParentNodeInSpan(token, file, span); - if (!importDecl || !isImportDeclaration(importDecl)) return { - error: "Selection is not an import declaration." - }; - const end = span.start + span.length; - const nextToken = findNextToken(importDecl, importDecl.parent, file); - if (nextToken && end > nextToken.getStart()) return void 0; - const { importClause: importClause } = importDecl; - if (!importClause) return { - error: getLocaleSpecificMessage(Diagnostics.Could_not_find_import_clause) - }; - if (!importClause.namedBindings) return { - error: getLocaleSpecificMessage(Diagnostics.Could_not_find_namespace_import_or_named_imports) - }; - if (importClause.namedBindings.kind === 271 /* NamespaceImport */ ) return { - convertTo: 0 /* Named */ , - import: importClause.namedBindings - }; - const shouldUseDefault = getShouldUseDefault(context.program, importClause); - return shouldUseDefault ? { - convertTo: 1 /* Default */ , - import: importClause.namedBindings - } : { - convertTo: 2 /* Namespace */ , - import: importClause.namedBindings + // src/services/findAllReferences.ts + function nodeEntry(node, kind = 1 /* Node */ ) { + return { + kind: kind, + node: node.name || node, + context: getContextNodeForNodeEntry(node) }; } - function getShouldUseDefault(program, importClause) { - return getAllowSyntheticDefaultImports(program.getCompilerOptions()) && isExportEqualsModule(importClause.parent.moduleSpecifier, program.getTypeChecker()); - } - function doChange34(sourceFile, program, changes, info) { - const checker = program.getTypeChecker(); - if (info.convertTo === 0 /* Named */ ) doChangeNamespaceToNamed(sourceFile, checker, changes, info.import, getAllowSyntheticDefaultImports(program.getCompilerOptions())); - else doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, info.import, info.convertTo === 1 /* Default */ ); + function isContextWithStartAndEndNode(node) { + return node && node.kind === void 0; } - function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) { - let usedAsNamespaceOrDefault = false; - const nodesToReplace = []; - const conflictingNames = /* @__PURE__ */ new Map(); - ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, (id)=>{ - if (!isPropertyAccessOrQualifiedName(id.parent)) usedAsNamespaceOrDefault = true; - else { - const exportName = getRightOfPropertyAccessOrQualifiedName(id.parent).text; - if (checker.resolveName(exportName, id, 67108863 /* All */ , /*excludeGlobals*/ true)) conflictingNames.set(exportName, true); - Debug.assert(getLeftOfPropertyAccessOrQualifiedName(id.parent) === id, "Parent expression should match id"); - nodesToReplace.push(id.parent); + function getContextNodeForNodeEntry(node) { + if (isDeclaration(node)) return getContextNode(node); + if (!node.parent) return void 0; + if (!isDeclaration(node.parent) && !isExportAssignment(node.parent)) { + if (isInJSFile(node)) { + const binaryExpression = isBinaryExpression(node.parent) ? node.parent : isAccessExpression(node.parent) && isBinaryExpression(node.parent.parent) && node.parent.parent.left === node.parent ? node.parent.parent : void 0; + if (binaryExpression && getAssignmentDeclarationKind(binaryExpression) !== 0 /* None */ ) return getContextNode(binaryExpression); } - }); - const exportNameToImportName = /* @__PURE__ */ new Map(); - for (const propertyAccessOrQualifiedName of nodesToReplace){ - const exportName = getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName).text; - let importName = exportNameToImportName.get(exportName); - if (importName === void 0) exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? getUniqueName(exportName, sourceFile) : exportName); - changes.replaceNode(sourceFile, propertyAccessOrQualifiedName, factory.createIdentifier(importName)); + if (isJsxOpeningElement(node.parent) || isJsxClosingElement(node.parent)) return node.parent.parent; + else if (isJsxSelfClosingElement(node.parent) || isLabeledStatement(node.parent) || isBreakOrContinueStatement(node.parent)) return node.parent; + else if (isStringLiteralLike(node)) { + const validImport = tryGetImportFromModuleSpecifier(node); + if (validImport) { + const declOrStatement = findAncestor(validImport, (node2)=>isDeclaration(node2) || isStatement(node2) || isJSDocTag(node2)); + return isDeclaration(declOrStatement) ? getContextNode(declOrStatement) : declOrStatement; + } + } + const propertyName = findAncestor(node, isComputedPropertyName); + return propertyName ? getContextNode(propertyName.parent) : void 0; } - const importSpecifiers = []; - exportNameToImportName.forEach((name, propertyName)=>{ - importSpecifiers.push(factory.createImportSpecifier(/*isTypeOnly*/ false, name === propertyName ? void 0 : factory.createIdentifier(propertyName), factory.createIdentifier(name))); - }); - const importDecl = toConvert.parent.parent; - if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) changes.insertNodeAfter(sourceFile, importDecl, updateImport(importDecl, /*defaultImportName*/ void 0, importSpecifiers)); - else changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? factory.createIdentifier(toConvert.name.text) : void 0, importSpecifiers)); + if (node.parent.name === node || // node is name of declaration, use parent + isConstructorDeclaration(node.parent) || isExportAssignment(node.parent) || // Property name of the import export specifier or binding pattern, use parent + (isImportOrExportSpecifier(node.parent) || isBindingElement(node.parent)) && node.parent.propertyName === node || // Is default export + node.kind === 90 /* DefaultKeyword */ && hasSyntacticModifier(node.parent, 1025 /* ExportDefault */ )) return getContextNode(node.parent); + return void 0; } - function getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) { - return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.name : propertyAccessOrQualifiedName.right; + function getContextNode(node) { + if (!node) return void 0; + switch(node.kind){ + case 260 /* VariableDeclaration */ : + return !isVariableDeclarationList(node.parent) || node.parent.declarations.length !== 1 ? node : isVariableStatement(node.parent.parent) ? node.parent.parent : isForInOrOfStatement(node.parent.parent) ? getContextNode(node.parent.parent) : node.parent; + case 208 /* BindingElement */ : + return getContextNode(node.parent.parent); + case 276 /* ImportSpecifier */ : + return node.parent.parent.parent; + case 281 /* ExportSpecifier */ : + case 274 /* NamespaceImport */ : + return node.parent.parent; + case 273 /* ImportClause */ : + case 280 /* NamespaceExport */ : + return node.parent; + case 226 /* BinaryExpression */ : + return isExpressionStatement(node.parent) ? node.parent : node; + case 250 /* ForOfStatement */ : + case 249 /* ForInStatement */ : + return { + start: node.initializer, + end: node.expression + }; + case 303 /* PropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : + return isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent) ? getContextNode(findAncestor(node.parent, (node2)=>isBinaryExpression(node2) || isForInOrOfStatement(node2))) : node; + default: + return node; + } } - function getLeftOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) { - return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.expression : propertyAccessOrQualifiedName.left; + function toContextSpan(textSpan, sourceFile, context) { + if (!context) return void 0; + const contextSpan = isContextWithStartAndEndNode(context) ? getTextSpan(context.start, sourceFile, context.end) : getTextSpan(context, sourceFile); + return contextSpan.start !== textSpan.start || contextSpan.length !== textSpan.length ? { + contextSpan: contextSpan + } : void 0; } - function doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, toConvert, shouldUseDefault = getShouldUseDefault(program, toConvert.parent)) { + function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { + const node = getTouchingPropertyName(sourceFile, position); + const options = { + use: 1 /* References */ + }; + const referencedSymbols = Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options); const checker = program.getTypeChecker(); - const importDecl = toConvert.parent.parent; - const { moduleSpecifier: moduleSpecifier } = importDecl; - const toConvertSymbols = /* @__PURE__ */ new Set(); - toConvert.elements.forEach((namedImport)=>{ - const symbol = checker.getSymbolAtLocation(namedImport.name); - if (symbol) toConvertSymbols.add(symbol); - }); - const preferredName = moduleSpecifier && isStringLiteral(moduleSpecifier) ? ts_codefix_exports.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 99 /* ESNext */ ) : "module"; - function hasNamespaceNameConflict(namedImport) { - return !!ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(namedImport.name, checker, sourceFile, (id)=>{ - const symbol = checker.resolveName(preferredName, id, 67108863 /* All */ , /*excludeGlobals*/ true); - if (symbol) { - if (toConvertSymbols.has(symbol)) return isExportSpecifier(id.parent); - return true; - } - return false; - }); - } - const namespaceNameConflicts = toConvert.elements.some(hasNamespaceNameConflict); - const namespaceImportName = namespaceNameConflicts ? getUniqueName(preferredName, sourceFile) : preferredName; - const neededNamedImports = /* @__PURE__ */ new Set(); - for (const element of toConvert.elements){ - const propertyName = (element.propertyName || element.name).text; - ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, (id)=>{ - const access = factory.createPropertyAccessExpression(factory.createIdentifier(namespaceImportName), propertyName); - if (isShorthandPropertyAssignment(id.parent)) changes.replaceNode(sourceFile, id.parent, factory.createPropertyAssignment(id.text, access)); - else if (isExportSpecifier(id.parent)) neededNamedImports.add(element); - else changes.replaceNode(sourceFile, id, access); + const adjustedNode = Core.getAdjustedNode(node, options); + const symbol = isDefinitionForReference(adjustedNode) ? checker.getSymbolAtLocation(adjustedNode) : void 0; + return !referencedSymbols || !referencedSymbols.length ? void 0 : mapDefined(referencedSymbols, ({ definition: definition, references: references })=>// Only include referenced symbols that have a valid definition. + definition && { + definition: checker.runWithCancellationToken(cancellationToken, (checker2)=>definitionToReferencedSymbolDefinitionInfo(definition, checker2, node)), + references: references.map((r)=>toReferencedSymbolEntry(r, symbol)) }); + } + function isDefinitionForReference(node) { + return node.kind === 90 /* DefaultKeyword */ || !!getDeclarationFromName(node) || isLiteralComputedPropertyDeclarationName(node) || node.kind === 137 /* ConstructorKeyword */ && isConstructorDeclaration(node.parent); + } + function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { + const node = getTouchingPropertyName(sourceFile, position); + let referenceEntries; + const entries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); + if (node.parent.kind === 211 /* PropertyAccessExpression */ || node.parent.kind === 208 /* BindingElement */ || node.parent.kind === 212 /* ElementAccessExpression */ || node.kind === 108 /* SuperKeyword */ ) referenceEntries = entries && [ + ...entries + ]; + else if (entries) { + const queue = createQueue(entries); + const seenNodes = /* @__PURE__ */ new Map(); + while(!queue.isEmpty()){ + const entry = queue.dequeue(); + if (!addToSeen(seenNodes, getNodeId(entry.node))) continue; + referenceEntries = append(referenceEntries, entry); + const entries2 = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, entry.node, entry.node.pos); + if (entries2) queue.enqueue(...entries2); + } } - changes.replaceNode(sourceFile, toConvert, shouldUseDefault ? factory.createIdentifier(namespaceImportName) : factory.createNamespaceImport(factory.createIdentifier(namespaceImportName))); - if (neededNamedImports.size) { - const newNamedImports = arrayFrom(neededNamedImports.values(), (element)=>factory.createImportSpecifier(element.isTypeOnly, element.propertyName && factory.createIdentifier(element.propertyName.text), factory.createIdentifier(element.name.text))); - changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport(importDecl, /*defaultImportName*/ void 0, newNamedImports)); - } + const checker = program.getTypeChecker(); + return map(referenceEntries, (entry)=>toImplementationLocation(entry, checker)); } - function isExportEqualsModule(moduleSpecifier, checker) { - const externalModule = checker.resolveExternalModuleName(moduleSpecifier); - if (!externalModule) return false; - const exportEquals = checker.resolveExternalModuleSymbol(externalModule); - return externalModule !== exportEquals; + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { + if (node.kind === 312 /* SourceFile */ ) return void 0; + const checker = program.getTypeChecker(); + if (node.parent.kind === 304 /* ShorthandPropertyAssignment */ ) { + const result = []; + Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, (node2)=>result.push(nodeEntry(node2))); + return result; + } else if (node.kind === 108 /* SuperKeyword */ || isSuperProperty(node.parent)) { + const symbol = checker.getSymbolAtLocation(node); + return symbol.valueDeclaration && [ + nodeEntry(symbol.valueDeclaration) + ]; + } else return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { + implementations: true, + use: 1 /* References */ + }); } - function updateImport(old, defaultImportName, elements) { - return factory.createImportDeclaration(/*modifiers*/ void 0, factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, elements && elements.length ? factory.createNamedImports(elements) : void 0), old.moduleSpecifier, /*assertClause*/ void 0); + function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) { + return map(flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), (entry)=>convertEntry(entry, node, program.getTypeChecker())); } - var refactorName2, actions; - var init_convertImport = __esm({ - "src/services/refactors/convertImport.ts" () { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName2 = "Convert import"; - actions = { - [0 /* Named */ ]: { - name: "Convert namespace import to named imports", - description: Diagnostics.Convert_namespace_import_to_named_imports.message, - kind: "refactor.rewrite.import.named" - }, - [2 /* Namespace */ ]: { - name: "Convert named imports to namespace import", - description: Diagnostics.Convert_named_imports_to_namespace_import.message, - kind: "refactor.rewrite.import.namespace" - }, - [1 /* Default */ ]: { - name: "Convert named imports to default import", - description: Diagnostics.Convert_named_imports_to_default_import.message, - kind: "refactor.rewrite.import.default" - } - }; - registerRefactor(refactorName2, { - kinds: getOwnValues(actions).map((a)=>a.kind), - getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndNamespacedImports(context) { - const info = getImportConversionInfo(context, context.triggerReason === "invoked"); - if (!info) return emptyArray; - if (!isRefactorErrorInfo(info)) { - const action = actions[info.convertTo]; - return [ - { - name: refactorName2, - description: action.description, - actions: [ - action - ] - } - ]; + function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options = {}, sourceFilesSet = new Set(sourceFiles.map((f)=>f.fileName))) { + return flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet)); + } + function flattenEntries(referenceSymbols) { + return referenceSymbols && flatMap(referenceSymbols, (r)=>r.references); + } + function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { + const info = (()=>{ + switch(def.type){ + case 0 /* Symbol */ : + { + const { symbol: symbol } = def; + const { displayParts: displayParts2, kind: kind2 } = getDefinitionKindAndDisplayParts(symbol, checker, originalNode); + const name2 = displayParts2.map((p)=>p.text).join(""); + const declaration = symbol.declarations && firstOrUndefined(symbol.declarations); + const node = declaration ? getNameOfDeclaration(declaration) || declaration : originalNode; + return { + ...getFileAndTextSpanFromNode(node), + name: name2, + kind: kind2, + displayParts: displayParts2, + context: getContextNode(declaration) + }; } - if (context.preferences.provideRefactorNotApplicableReason) return getOwnValues(actions).map((action)=>({ - name: refactorName2, - description: action.description, - actions: [ + case 1 /* Label */ : + { + const { node: node } = def; + return { + ...getFileAndTextSpanFromNode(node), + name: node.text, + kind: "label" /* label */ , + displayParts: [ + displayPart(node.text, 17 /* text */ ) + ] + }; + } + case 2 /* Keyword */ : + { + const { node: node } = def; + const name2 = tokenToString(node.kind); + return { + ...getFileAndTextSpanFromNode(node), + name: name2, + kind: "keyword" /* keyword */ , + displayParts: [ { - ...action, - notApplicableReason: info.error + text: name2, + kind: "keyword" /* keyword */ } ] - })); - return emptyArray; - }, - getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndNamespacedImports(context, actionName2) { - Debug.assert(some(getOwnValues(actions), (action)=>action.name === actionName2), "Unexpected action name"); - const info = getImportConversionInfo(context); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange34(context.file, context.program, t, info)); + }; + } + case 3 /* This */ : + { + const { node: node } = def; + const symbol = checker.getSymbolAtLocation(node); + const displayParts2 = symbol && ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node.getSourceFile(), getContainerNode(node), node).displayParts || [ + textPart("this") + ]; + return { + ...getFileAndTextSpanFromNode(node), + name: "this", + kind: "var" /* variableElement */ , + displayParts: displayParts2 + }; + } + case 4 /* String */ : + { + const { node: node } = def; + return { + ...getFileAndTextSpanFromNode(node), + name: node.text, + kind: "var" /* variableElement */ , + displayParts: [ + displayPart(getTextOfNode(node), 8 /* stringLiteral */ ) + ] + }; + } + case 5 /* TripleSlashReference */ : return { - edits: edits, - renameFilename: void 0, - renameLocation: void 0 + textSpan: createTextSpanFromRange(def.reference), + sourceFile: def.file, + name: def.reference.fileName, + kind: "string" /* string */ , + displayParts: [ + displayPart(`"${def.reference.fileName}"`, 8 /* stringLiteral */ ) + ] }; - } - }); - } - }); - // src/services/refactors/extractType.ts - function getRangeToExtract(context, considerEmptySpans = true) { - const { file: file , startPosition: startPosition } = context; - const isJS = isSourceFileJS(file); - const current = getTokenAtPosition(file, startPosition); - const range = createTextRangeFromSpan(getRefactorContextSpan(context)); - const cursorRequest = range.pos === range.end && considerEmptySpans; - const selection = findAncestor(current, (node)=>node.parent && isTypeNode(node) && !rangeContainsSkipTrivia(range, node.parent, file) && (cursorRequest || nodeOverlapsWithStartEnd(current, file, range.pos, range.end))); - if (!selection || !isTypeNode(selection)) return { - error: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_type_node) + default: + return Debug.assertNever(def); + } + })(); + const { sourceFile: sourceFile, textSpan: textSpan, name: name, kind: kind, displayParts: displayParts, context: context } = info; + return { + containerKind: "" /* unknown */ , + containerName: "", + fileName: sourceFile.fileName, + kind: kind, + name: name, + textSpan: textSpan, + displayParts: displayParts, + ...toContextSpan(textSpan, sourceFile, context) }; - const checker = context.program.getTypeChecker(); - const enclosingNode = getEnclosingNode(selection, isJS); - if (enclosingNode === void 0) return { - error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) + } + function getFileAndTextSpanFromNode(node) { + const sourceFile = node.getSourceFile(); + return { + sourceFile: sourceFile, + textSpan: getTextSpan(isComputedPropertyName(node) ? node.expression : node, sourceFile) }; - const typeParameters = collectTypeParameters(checker, selection, enclosingNode, file); - if (!typeParameters) return { - error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) + } + function getDefinitionKindAndDisplayParts(symbol, checker, node) { + const meaning = Core.getIntersectingMeaningFromDeclarations(node, symbol); + const enclosingDeclaration = symbol.declarations && firstOrUndefined(symbol.declarations) || node; + const { displayParts: displayParts, symbolKind: symbolKind } = ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning); + return { + displayParts: displayParts, + kind: symbolKind }; - const typeElements = flattenTypeLiteralNodeReference(checker, selection); + } + function toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixText, quotePreference) { return { - isJS: isJS, - selection: selection, - enclosingNode: enclosingNode, - typeParameters: typeParameters, - typeElements: typeElements + ...entryToDocumentSpan(entry), + ...providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker, quotePreference) }; } - function flattenTypeLiteralNodeReference(checker, node) { - if (!node) return void 0; - if (isIntersectionTypeNode(node)) { - const result = []; - const seen = /* @__PURE__ */ new Map(); - for (const type of node.types){ - const flattenedTypeMembers = flattenTypeLiteralNodeReference(checker, type); - if (!flattenedTypeMembers || !flattenedTypeMembers.every((type2)=>type2.name && addToSeen(seen, getNameFromPropertyName(type2.name)))) return void 0; - addRange(result, flattenedTypeMembers); - } - return result; - } else if (isParenthesizedTypeNode(node)) return flattenTypeLiteralNodeReference(checker, node.type); - else if (isTypeLiteralNode(node)) return node.members; - return void 0; - } - function rangeContainsSkipTrivia(r1, node, file) { - return rangeContainsStartEnd(r1, skipTrivia(file.text, node.pos), node.end); - } - function collectTypeParameters(checker, selection, enclosingNode, file) { - const result = []; - return visitor(selection) ? void 0 : result; - function visitor(node) { - if (isTypeReferenceNode(node)) { - if (isIdentifier(node.typeName)) { - const typeName = node.typeName; - const symbol = checker.resolveName(typeName.text, typeName, 262144 /* TypeParameter */ , /* excludeGlobals */ true); - for (const decl of (symbol == null ? void 0 : symbol.declarations) || emptyArray)if (isTypeParameterDeclaration(decl) && decl.getSourceFile() === file) { - if (decl.name.escapedText === typeName.escapedText && rangeContainsSkipTrivia(decl, selection, file)) return true; - if (rangeContainsSkipTrivia(enclosingNode, decl, file) && !rangeContainsSkipTrivia(selection, decl, file)) { - pushIfUnique(result, decl); - break; - } - } - } - } else if (isInferTypeNode(node)) { - const conditionalTypeNode = findAncestor(node, (n)=>isConditionalTypeNode(n) && rangeContainsSkipTrivia(n.extendsType, node, file)); - if (!conditionalTypeNode || !rangeContainsSkipTrivia(selection, conditionalTypeNode, file)) return true; - } else if (isTypePredicateNode(node) || isThisTypeNode(node)) { - const functionLikeNode = findAncestor(node.parent, isFunctionLike); - if (functionLikeNode && functionLikeNode.type && rangeContainsSkipTrivia(functionLikeNode.type, node, file) && !rangeContainsSkipTrivia(selection, functionLikeNode, file)) return true; - } else if (isTypeQueryNode(node)) { - if (isIdentifier(node.exprName)) { - const symbol = checker.resolveName(node.exprName.text, node.exprName, 111551 /* Value */ , /* excludeGlobals */ false); - if ((symbol == null ? void 0 : symbol.valueDeclaration) && rangeContainsSkipTrivia(enclosingNode, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) return true; - } else { - if (isThisIdentifier(node.exprName.left) && !rangeContainsSkipTrivia(selection, node.parent, file)) return true; - } - } - if (file && isTupleTypeNode(node) && getLineAndCharacterOfPosition(file, node.pos).line === getLineAndCharacterOfPosition(file, node.end).line) setEmitFlags(node, 1 /* SingleLine */ ); - return forEachChild(node, visitor); - } - } - function doTypeAliasChange(changes, file, name, info) { - const { enclosingNode: enclosingNode , selection: selection , typeParameters: typeParameters } = info; - const newTypeNode = factory.createTypeAliasDeclaration(/* modifiers */ void 0, name, typeParameters.map((id)=>factory.updateTypeParameterDeclaration(id, id.modifiers, id.name, id.constraint, /* defaultType */ void 0)), selection); - changes.insertNodeBefore(file, enclosingNode, ignoreSourceNewlines(newTypeNode), /* blankLineBetween */ true); - changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id)=>factory.createTypeReferenceNode(id.name, /* typeArguments */ void 0))), { - leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, - trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace - }); - } - function doInterfaceChange(changes, file, name, info) { - var _a2; - const { enclosingNode: enclosingNode , selection: selection , typeParameters: typeParameters , typeElements: typeElements } = info; - const newTypeNode = factory.createInterfaceDeclaration(/* modifiers */ void 0, name, typeParameters, /* heritageClauses */ void 0, typeElements); - setTextRange(newTypeNode, (_a2 = typeElements[0]) == null ? void 0 : _a2.parent); - changes.insertNodeBefore(file, enclosingNode, ignoreSourceNewlines(newTypeNode), /* blankLineBetween */ true); - changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id)=>factory.createTypeReferenceNode(id.name, /* typeArguments */ void 0))), { - leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, - trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace - }); - } - function doTypedefChange(changes, context, file, name, info) { - var _a2; - const { enclosingNode: enclosingNode , selection: selection , typeParameters: typeParameters } = info; - setEmitFlags(selection, 7168 /* NoNestedComments */ ); - const node = factory.createJSDocTypedefTag(factory.createIdentifier("typedef"), factory.createJSDocTypeExpression(selection), factory.createIdentifier(name)); - const templates = []; - forEach(typeParameters, (typeParameter)=>{ - const constraint = getEffectiveConstraintOfTypeParameter(typeParameter); - const parameter = factory.createTypeParameterDeclaration(/*modifiers*/ void 0, typeParameter.name); - const template = factory.createJSDocTemplateTag(factory.createIdentifier("template"), constraint && cast(constraint, isJSDocTypeExpression), [ - parameter - ]); - templates.push(template); - }); - const jsDoc = factory.createJSDocComment(/* comment */ void 0, factory.createNodeArray(concatenate(templates, [ - node - ]))); - if (isJSDoc(enclosingNode)) { - const pos = enclosingNode.getStart(file); - const newLineCharacter = getNewLineOrDefaultFromHost(context.host, (_a2 = context.formatContext) == null ? void 0 : _a2.options); - changes.insertNodeAt(file, enclosingNode.getStart(file), jsDoc, { - suffix: newLineCharacter + newLineCharacter + file.text.slice(getPrecedingNonSpaceCharacterPosition(file.text, pos - 1), pos) - }); - } else changes.insertNodeBefore(file, enclosingNode, jsDoc, /* blankLineBetween */ true); - changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id)=>factory.createTypeReferenceNode(id.name, /* typeArguments */ void 0)))); - } - function getEnclosingNode(node, isJS) { - return findAncestor(node, isStatement) || (isJS ? findAncestor(node, isJSDoc) : void 0); - } - var refactorName3, extractToTypeAliasAction, extractToInterfaceAction, extractToTypeDefAction; - var init_extractType = __esm({ - "src/services/refactors/extractType.ts" () { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName3 = "Extract type"; - extractToTypeAliasAction = { - name: "Extract to type alias", - description: getLocaleSpecificMessage(Diagnostics.Extract_to_type_alias), - kind: "refactor.extract.type" - }; - extractToInterfaceAction = { - name: "Extract to interface", - description: getLocaleSpecificMessage(Diagnostics.Extract_to_interface), - kind: "refactor.extract.interface" - }; - extractToTypeDefAction = { - name: "Extract to typedef", - description: getLocaleSpecificMessage(Diagnostics.Extract_to_typedef), - kind: "refactor.extract.typedef" - }; - registerRefactor(refactorName3, { - kinds: [ - extractToTypeAliasAction.kind, - extractToInterfaceAction.kind, - extractToTypeDefAction.kind - ], - getAvailableActions: function getRefactorActionsToExtractType(context) { - const info = getRangeToExtract(context, context.triggerReason === "invoked"); - if (!info) return emptyArray; - if (!isRefactorErrorInfo(info)) return [ - { - name: refactorName3, - description: getLocaleSpecificMessage(Diagnostics.Extract_type), - actions: info.isJS ? [ - extractToTypeDefAction - ] : append([ - extractToTypeAliasAction - ], info.typeElements && extractToInterfaceAction) - } - ]; - if (context.preferences.provideRefactorNotApplicableReason) return [ - { - name: refactorName3, - description: getLocaleSpecificMessage(Diagnostics.Extract_type), - actions: [ - { - ...extractToTypeDefAction, - notApplicableReason: info.error - }, - { - ...extractToTypeAliasAction, - notApplicableReason: info.error - }, - { - ...extractToInterfaceAction, - notApplicableReason: info.error - } - ] - } - ]; - return emptyArray; - }, - getEditsForAction: function getRefactorEditsToExtractType(context, actionName2) { - const { file: file } = context; - const info = getRangeToExtract(context); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected to find a range to extract"); - const name = getUniqueName("NewType", file); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (changes)=>{ - switch(actionName2){ - case extractToTypeAliasAction.name: - Debug.assert(!info.isJS, "Invalid actionName/JS combo"); - return doTypeAliasChange(changes, file, name, info); - case extractToTypeDefAction.name: - Debug.assert(info.isJS, "Invalid actionName/JS combo"); - return doTypedefChange(changes, context, file, name, info); - case extractToInterfaceAction.name: - Debug.assert(!info.isJS && !!info.typeElements, "Invalid actionName/JS combo"); - return doInterfaceChange(changes, file, name, info); - default: - Debug.fail("Unexpected action name"); - } - }); - const renameFilename = file.fileName; - const renameLocation = getRenameLocation(edits, renameFilename, name, /*preferLastLocation*/ false); - return { - edits: edits, - renameFilename: renameFilename, - renameLocation: renameLocation - }; - } - }); - } - }); - // src/services/refactors/helpers.ts - function isRefactorErrorInfo(info) { - return info.error !== void 0; - } - function refactorKindBeginsWith(known, requested) { - if (!requested) return true; - return known.substr(0, requested.length) === requested; + function toReferencedSymbolEntry(entry, symbol) { + const referenceEntry = toReferenceEntry(entry); + if (!symbol) return referenceEntry; + return { + ...referenceEntry, + isDefinition: entry.kind !== 0 /* Span */ && isDeclarationOfSymbol(entry.node, symbol) + }; } - var init_helpers2 = __esm({ - "src/services/refactors/helpers.ts" () { - "use strict"; - } - }); - // src/services/refactors/moveToNewFile.ts - function getRangeToMove(context) { - const { file: file } = context; - const range = createTextRangeFromSpan(getRefactorContextSpan(context)); - const { statements: statements } = file; - const startNodeIndex = findIndex(statements, (s)=>s.end > range.pos); - if (startNodeIndex === -1) return void 0; - const startStatement = statements[startNodeIndex]; - if (isNamedDeclaration(startStatement) && startStatement.name && rangeContainsRange(startStatement.name, range)) return { - toMove: [ - statements[startNodeIndex] - ], - afterLast: statements[startNodeIndex + 1] + function toReferenceEntry(entry) { + const documentSpan = entryToDocumentSpan(entry); + if (entry.kind === 0 /* Span */ ) return { + ...documentSpan, + isWriteAccess: false }; - if (range.pos > startStatement.getStart(file)) return void 0; - const afterEndNodeIndex = findIndex(statements, (s)=>s.end > range.end, startNodeIndex); - if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) return void 0; + const { kind: kind, node: node } = entry; return { - toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex), - afterLast: afterEndNodeIndex === -1 ? void 0 : statements[afterEndNodeIndex] + ...documentSpan, + isWriteAccess: isWriteAccessForReference(node), + isInString: kind === 2 /* StringLiteral */ ? true : void 0 }; } - function doChange35(oldFile, program, toMove, changes, host, preferences) { - const checker = program.getTypeChecker(); - const usage = getUsageInfo(oldFile, toMove.all, checker); - const currentDirectory = getDirectoryPath(oldFile.fileName); - const extension = extensionFromPath(oldFile.fileName); - const newFilename = combinePaths(// new file is always placed in the same directory as the old file - currentDirectory, // ensures the filename computed below isn't already taken - makeUniqueFilename(// infers a name for the new file from the symbols being moved - inferNewFilename(usage.oldFileImportsFromNewFile, usage.movedSymbols), extension, currentDirectory, host)) + extension; - changes.createNewFile(oldFile, newFilename, getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, host, newFilename, preferences)); - addNewFileToTsconfig(program, changes, oldFile.fileName, newFilename, hostGetCanonicalFileName(host)); - } - function getStatementsToMove(context) { - const rangeToMove = getRangeToMove(context); - if (rangeToMove === void 0) return void 0; - const all = []; - const ranges = []; - const { toMove: toMove , afterLast: afterLast } = rangeToMove; - getRangesWhere(toMove, isAllowedStatementToMove, (start, afterEndIndex)=>{ - for(let i = start; i < afterEndIndex; i++)all.push(toMove[i]); - ranges.push({ - first: toMove[start], - afterLast: afterLast - }); - }); - return all.length === 0 ? void 0 : { - all: all, - ranges: ranges + function entryToDocumentSpan(entry) { + if (entry.kind === 0 /* Span */ ) return { + textSpan: entry.textSpan, + fileName: entry.fileName }; - } - function isAllowedStatementToMove(statement) { - return !isPureImport(statement) && !isPrologueDirective(statement); - } - function isPureImport(node) { - switch(node.kind){ - case 269 /* ImportDeclaration */ : - return true; - case 268 /* ImportEqualsDeclaration */ : - return !hasSyntacticModifier(node, 1 /* Export */ ); - case 240 /* VariableStatement */ : - return node.declarationList.declarations.every((d)=>!!d.initializer && isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true)); - default: - return false; - } - } - function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) { - const cfg = program.getCompilerOptions().configFile; - if (!cfg) return; - const newFileAbsolutePath = normalizePath(combinePaths(oldFileName, "..", newFileNameWithExtension)); - const newFilePath = getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName); - const cfgObject = cfg.statements[0] && tryCast(cfg.statements[0].expression, isObjectLiteralExpression); - const filesProp = cfgObject && find(cfgObject.properties, (prop)=>isPropertyAssignment(prop) && isStringLiteral(prop.name) && prop.name.text === "files"); - if (filesProp && isArrayLiteralExpression(filesProp.initializer)) changes.insertNodeInListAfter(cfg, last(filesProp.initializer.elements), factory.createStringLiteral(newFilePath), filesProp.initializer.elements); - } - function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, host, newFilename, preferences) { - const checker = program.getTypeChecker(); - const prologueDirectives = takeWhile(oldFile.statements, isPrologueDirective); - if (oldFile.externalModuleIndicator === void 0 && oldFile.commonJsModuleIndicator === void 0 && usage.oldImportsNeededByNewFile.size() === 0) { - deleteMovedStatements(oldFile, toMove.ranges, changes); - return [ - ...prologueDirectives, - ...toMove.all - ]; - } - const useEsModuleSyntax = !!oldFile.externalModuleIndicator; - const quotePreference = getQuotePreference(oldFile, preferences); - const importsFromNewFile = createOldFileImportsFromNewFile(oldFile, usage.oldFileImportsFromNewFile, newFilename, program, host, useEsModuleSyntax, quotePreference); - if (importsFromNewFile) insertImports(changes, oldFile, importsFromNewFile, /*blankLineBetween*/ true, preferences); - deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); - deleteMovedStatements(oldFile, toMove.ranges, changes); - updateImportsInOtherFiles(changes, program, host, oldFile, usage.movedSymbols, newFilename); - const imports = getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference); - const body = addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEsModuleSyntax); - if (imports.length && body.length) return [ - ...prologueDirectives, - ...imports, - 4 /* NewLineTrivia */ , - ...body - ]; - return [ - ...prologueDirectives, - ...imports, - ...body - ]; - } - function deleteMovedStatements(sourceFile, moved, changes) { - for (const { first: first2 , afterLast: afterLast } of moved)changes.deleteNodeRangeExcludingEnd(sourceFile, first2, afterLast); - } - function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { - for (const statement of oldFile.statements){ - if (contains(toMove, statement)) continue; - forEachImportInStatement(statement, (i)=>deleteUnusedImports(oldFile, i, changes, (name)=>toDelete.has(checker.getSymbolAtLocation(name)))); + else { + const sourceFile = entry.node.getSourceFile(); + const textSpan = getTextSpan(entry.node, sourceFile); + return { + textSpan: textSpan, + fileName: sourceFile.fileName, + ...toContextSpan(textSpan, sourceFile, entry.context) + }; } } - function updateImportsInOtherFiles(changes, program, host, oldFile, movedSymbols, newFilename) { - const checker = program.getTypeChecker(); - for (const sourceFile of program.getSourceFiles()){ - if (sourceFile === oldFile) continue; - for (const statement of sourceFile.statements)forEachImportInStatement(statement, (importNode)=>{ - if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; - const shouldMove = (name)=>{ - const symbol = isBindingElement(name.parent) ? getPropertySymbolFromBindingElement(checker, name.parent) : skipAlias(checker.getSymbolAtLocation(name), checker); - return !!symbol && movedSymbols.has(symbol); + function getPrefixAndSuffixText(entry, originalNode, checker, quotePreference) { + if (entry.kind !== 0 /* Span */ && isIdentifier(originalNode)) { + const { node: node, kind: kind } = entry; + const parent2 = node.parent; + const name = originalNode.text; + const isShorthandAssignment = isShorthandPropertyAssignment(parent2); + if (isShorthandAssignment || isObjectBindingElementWithoutPropertyName(parent2) && parent2.name === node && parent2.dotDotDotToken === void 0) { + const prefixColon = { + prefixText: name + ": " }; - deleteUnusedImports(sourceFile, importNode, changes, shouldMove); - const pathToNewFileWithExtension = resolvePath(getDirectoryPath(oldFile.path), newFilename); - const newModuleSpecifier = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.path, pathToNewFileWithExtension, createModuleSpecifierResolutionHost(program, host)); - const newImportDeclaration = filterImport(importNode, factory.createStringLiteral(newModuleSpecifier), shouldMove); - if (newImportDeclaration) changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); - const ns = getNamespaceLikeImport(importNode); - if (ns) updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, ns, importNode); - }); - } - } - function getNamespaceLikeImport(node) { - switch(node.kind){ - case 269 /* ImportDeclaration */ : - return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 271 /* NamespaceImport */ ? node.importClause.namedBindings.name : void 0; - case 268 /* ImportEqualsDeclaration */ : - return node.name; - case 257 /* VariableDeclaration */ : - return tryCast(node.name, isIdentifier); - default: - return Debug.assertNever(node, `Unexpected node kind ${node.kind}`); - } - } - function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, oldImportId, oldImportNode) { - const preferredNewNamespaceName = ts_codefix_exports.moduleSpecifierToValidIdentifier(newModuleSpecifier, 99 /* ESNext */ ); - let needUniqueName = false; - const toChange = []; - ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, (ref)=>{ - if (!isPropertyAccessExpression(ref.parent)) return; - needUniqueName = needUniqueName || !!checker.resolveName(preferredNewNamespaceName, ref, 67108863 /* All */ , /*excludeGlobals*/ true); - if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) toChange.push(ref); - }); - if (toChange.length) { - const newNamespaceName = needUniqueName ? getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName; - for (const ref of toChange)changes.replaceNode(sourceFile, ref, factory.createIdentifier(newNamespaceName)); - changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, preferredNewNamespaceName, newModuleSpecifier)); + const suffixColon = { + suffixText: ": " + name + }; + if (kind === 3 /* SearchedLocalFoundProperty */ ) return prefixColon; + if (kind === 4 /* SearchedPropertyFoundLocal */ ) return suffixColon; + if (isShorthandAssignment) { + const grandParent = parent2.parent; + if (isObjectLiteralExpression(grandParent) && isBinaryExpression(grandParent.parent) && isModuleExportsAccessExpression(grandParent.parent.left)) return prefixColon; + return suffixColon; + } else return prefixColon; + } else if (isImportSpecifier(parent2) && !parent2.propertyName) { + const originalSymbol = isExportSpecifier(originalNode.parent) ? checker.getExportSpecifierLocalTargetSymbol(originalNode.parent) : checker.getSymbolAtLocation(originalNode); + return contains(originalSymbol.declarations, parent2) ? { + prefixText: name + " as " + } : emptyOptions; + } else if (isExportSpecifier(parent2) && !parent2.propertyName) return originalNode === entry.node || checker.getSymbolAtLocation(originalNode) === checker.getSymbolAtLocation(entry.node) ? { + prefixText: name + " as " + } : { + suffixText: " as " + name + }; } - } - function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier) { - const newNamespaceId = factory.createIdentifier(newNamespaceName); - const newModuleString = factory.createStringLiteral(newModuleSpecifier); - switch(node.kind){ - case 269 /* ImportDeclaration */ : - return factory.createImportDeclaration(/*modifiers*/ void 0, factory.createImportClause(/*isTypeOnly*/ false, /*name*/ void 0, factory.createNamespaceImport(newNamespaceId)), newModuleString, /*assertClause*/ void 0); - case 268 /* ImportEqualsDeclaration */ : - return factory.createImportEqualsDeclaration(/*modifiers*/ void 0, /*isTypeOnly*/ false, newNamespaceId, factory.createExternalModuleReference(newModuleString)); - case 257 /* VariableDeclaration */ : - return factory.createVariableDeclaration(newNamespaceId, /*exclamationToken*/ void 0, /*type*/ void 0, createRequireCall(newModuleString)); - default: - return Debug.assertNever(node, `Unexpected node kind ${node.kind}`); + if (entry.kind !== 0 /* Span */ && isNumericLiteral(entry.node) && isAccessExpression(entry.node.parent)) { + const quote2 = getQuoteFromPreference(quotePreference); + return { + prefixText: quote2, + suffixText: quote2 + }; } + return emptyOptions; } - function moduleSpecifierFromImport(i) { - return i.kind === 269 /* ImportDeclaration */ ? i.moduleSpecifier : i.kind === 268 /* ImportEqualsDeclaration */ ? i.moduleReference.expression : i.initializer.arguments[0]; + function toImplementationLocation(entry, checker) { + const documentSpan = entryToDocumentSpan(entry); + if (entry.kind !== 0 /* Span */ ) { + const { node: node } = entry; + return { + ...documentSpan, + ...implementationKindDisplayParts(node, checker) + }; + } else return { + ...documentSpan, + kind: "" /* unknown */ , + displayParts: [] + }; } - function forEachImportInStatement(statement, cb) { - if (isImportDeclaration(statement)) { - if (isStringLiteral(statement.moduleSpecifier)) cb(statement); - } else if (isImportEqualsDeclaration(statement)) { - if (isExternalModuleReference(statement.moduleReference) && isStringLiteralLike(statement.moduleReference.expression)) cb(statement); - } else if (isVariableStatement(statement)) { - for (const decl of statement.declarationList.declarations)if (decl.initializer && isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true)) cb(decl); - } + function implementationKindDisplayParts(node, checker) { + const symbol = checker.getSymbolAtLocation(isDeclaration(node) && node.name ? node.name : node); + if (symbol) return getDefinitionKindAndDisplayParts(symbol, checker, node); + else if (node.kind === 210 /* ObjectLiteralExpression */ ) return { + kind: "interface" /* interfaceElement */ , + displayParts: [ + punctuationPart(21 /* OpenParenToken */ ), + textPart("object literal"), + punctuationPart(22 /* CloseParenToken */ ) + ] + }; + else if (node.kind === 231 /* ClassExpression */ ) return { + kind: "local class" /* localClassElement */ , + displayParts: [ + punctuationPart(21 /* OpenParenToken */ ), + textPart("anonymous local class"), + punctuationPart(22 /* CloseParenToken */ ) + ] + }; + else return { + kind: getNodeKind(node), + displayParts: [] + }; } - function createOldFileImportsFromNewFile(sourceFile, newFileNeedExport, newFileNameWithExtension, program, host, useEs6Imports, quotePreference) { - let defaultImport; - const imports = []; - newFileNeedExport.forEach((symbol)=>{ - if (symbol.escapedName === "default" /* Default */ ) defaultImport = factory.createIdentifier(symbolNameNoDefault(symbol)); - else imports.push(symbol.name); - }); - return makeImportOrRequire(sourceFile, defaultImport, imports, newFileNameWithExtension, program, host, useEs6Imports, quotePreference); + function toHighlightSpan(entry) { + const documentSpan = entryToDocumentSpan(entry); + if (entry.kind === 0 /* Span */ ) return { + fileName: documentSpan.fileName, + span: { + textSpan: documentSpan.textSpan, + kind: "reference" /* reference */ + } + }; + const writeAccess = isWriteAccessForReference(entry.node); + const span = { + textSpan: documentSpan.textSpan, + kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */ , + isInString: entry.kind === 2 /* StringLiteral */ ? true : void 0, + ...documentSpan.contextSpan && { + contextSpan: documentSpan.contextSpan + } + }; + return { + fileName: documentSpan.fileName, + span: span + }; } - function makeImportOrRequire(sourceFile, defaultImport, imports, newFileNameWithExtension, program, host, useEs6Imports, quotePreference) { - const pathToNewFile = resolvePath(getDirectoryPath(sourceFile.path), newFileNameWithExtension); - const pathToNewFileWithCorrectExtension = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.path, pathToNewFile, createModuleSpecifierResolutionHost(program, host)); - if (useEs6Imports) { - const specifiers = imports.map((i)=>factory.createImportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ void 0, factory.createIdentifier(i))); - return makeImportIfNecessary(defaultImport, specifiers, pathToNewFileWithCorrectExtension, quotePreference); - } else { - Debug.assert(!defaultImport, "No default import should exist"); - const bindingElements = imports.map((i)=>factory.createBindingElement(/*dotDotDotToken*/ void 0, /*propertyName*/ void 0, i)); - return bindingElements.length ? makeVariableStatement(factory.createObjectBindingPattern(bindingElements), /*type*/ void 0, createRequireCall(factory.createStringLiteral(pathToNewFileWithCorrectExtension))) : void 0; + function getTextSpan(node, sourceFile, endNode2) { + let start = node.getStart(sourceFile); + let end = (endNode2 || node).getEnd(); + if (isStringLiteralLike(node) && end - start > 2) { + Debug.assert(endNode2 === void 0); + start += 1; + end -= 1; } + return createTextSpanFromBounds(start, end); } - function makeVariableStatement(name, type, initializer, flags = 2 /* Const */ ) { - return factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ - factory.createVariableDeclaration(name, /*exclamationToken*/ void 0, type, initializer) - ], flags)); + function getTextSpanOfEntry(entry) { + return entry.kind === 0 /* Span */ ? entry.textSpan : getTextSpan(entry.node, entry.node.getSourceFile()); } - function createRequireCall(moduleSpecifier) { - return factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ void 0, [ - moduleSpecifier - ]); + function isWriteAccessForReference(node) { + const decl = getDeclarationFromName(node); + return !!decl && declarationIsWriteAccess(decl) || node.kind === 90 /* DefaultKeyword */ || isWriteAccess(node); } - function addExports(sourceFile, toMove, needExport, useEs6Exports) { - return flatMap(toMove, (statement)=>{ - if (isTopLevelDeclarationStatement(statement) && !isExported(sourceFile, statement, useEs6Exports) && forEachTopLevelDeclaration(statement, (d)=>{ - var _a2; - return needExport.has(Debug.checkDefined((_a2 = tryCast(d, canHaveSymbol)) == null ? void 0 : _a2.symbol)); - })) { - const exports = addExport(statement, useEs6Exports); - if (exports) return exports; - } - return statement; - }); + function isDeclarationOfSymbol(node, target) { + var _a; + if (!target) return false; + const source = getDeclarationFromName(node) || (node.kind === 90 /* DefaultKeyword */ ? node.parent : isLiteralComputedPropertyDeclarationName(node) ? node.parent.parent : node.kind === 137 /* ConstructorKeyword */ && isConstructorDeclaration(node.parent) ? node.parent.parent : void 0); + const commonjsSource = source && isBinaryExpression(source) ? source.left : void 0; + return !!(source && ((_a = target.declarations) == null ? void 0 : _a.some((d)=>d === source || d === commonjsSource))); } - function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { - switch(importDecl.kind){ - case 269 /* ImportDeclaration */ : - deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); - break; - case 268 /* ImportEqualsDeclaration */ : - if (isUnused(importDecl.name)) changes.delete(sourceFile, importDecl); - break; - case 257 /* VariableDeclaration */ : - deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); - break; + function declarationIsWriteAccess(decl) { + if (!!(decl.flags & 33554432 /* Ambient */ )) return true; + switch(decl.kind){ + case 226 /* BinaryExpression */ : + case 208 /* BindingElement */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 90 /* DefaultKeyword */ : + case 266 /* EnumDeclaration */ : + case 306 /* EnumMember */ : + case 281 /* ExportSpecifier */ : + case 273 /* ImportClause */ : + case 271 /* ImportEqualsDeclaration */ : + case 276 /* ImportSpecifier */ : + case 264 /* InterfaceDeclaration */ : + case 345 /* JSDocCallbackTag */ : + case 353 /* JSDocTypedefTag */ : + case 291 /* JsxAttribute */ : + case 267 /* ModuleDeclaration */ : + case 270 /* NamespaceExportDeclaration */ : + case 274 /* NamespaceImport */ : + case 280 /* NamespaceExport */ : + case 169 /* Parameter */ : + case 304 /* ShorthandPropertyAssignment */ : + case 265 /* TypeAliasDeclaration */ : + case 168 /* TypeParameter */ : + return true; + case 303 /* PropertyAssignment */ : + return !isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 176 /* Constructor */ : + case 174 /* MethodDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + return !!decl.body; + case 260 /* VariableDeclaration */ : + case 172 /* PropertyDeclaration */ : + return !!decl.initializer || isCatchClause(decl.parent); + case 173 /* MethodSignature */ : + case 171 /* PropertySignature */ : + case 355 /* JSDocPropertyTag */ : + case 348 /* JSDocParameterTag */ : + return false; default: - Debug.assertNever(importDecl, `Unexpected import decl kind ${importDecl.kind}`); - } - } - function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) { - if (!importDecl.importClause) return; - const { name: name , namedBindings: namedBindings } = importDecl.importClause; - const defaultUnused = !name || isUnused(name); - const namedBindingsUnused = !namedBindings || (namedBindings.kind === 271 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every((e)=>isUnused(e.name))); - if (defaultUnused && namedBindingsUnused) changes.delete(sourceFile, importDecl); - else { - if (name && defaultUnused) changes.delete(sourceFile, name); - if (namedBindings) { - if (namedBindingsUnused) changes.replaceNode(sourceFile, importDecl.importClause, factory.updateImportClause(importDecl.importClause, importDecl.importClause.isTypeOnly, name, /*namedBindings*/ void 0)); - else if (namedBindings.kind === 272 /* NamedImports */ ) { - for (const element of namedBindings.elements)if (isUnused(element.name)) changes.delete(sourceFile, element); - } - } - } - } - function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { - const { name: name } = varDecl; - switch(name.kind){ - case 79 /* Identifier */ : - if (isUnused(name)) { - if (varDecl.initializer && isRequireCall(varDecl.initializer, /*requireStringLiteralLikeArgument*/ true)) changes.delete(sourceFile, isVariableDeclarationList(varDecl.parent) && length(varDecl.parent.declarations) === 1 ? varDecl.parent.parent : varDecl); - else changes.delete(sourceFile, name); - } - break; - case 204 /* ArrayBindingPattern */ : - break; - case 203 /* ObjectBindingPattern */ : - if (name.elements.every((e)=>isIdentifier(e.name) && isUnused(e.name))) changes.delete(sourceFile, isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); - else { - for (const element of name.elements)if (isIdentifier(element.name) && isUnused(element.name)) changes.delete(sourceFile, element.name); - } - break; + return Debug.failBadSyntaxKind(decl); } } - function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference) { - const copiedOldImports = []; - for (const oldStatement of oldFile.statements)forEachImportInStatement(oldStatement, (i)=>{ - append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), (name)=>importsToCopy.has(checker.getSymbolAtLocation(name)))); - }); - let oldFileDefault; - const oldFileNamedImports = []; - const markSeenTop = nodeSeenTracker(); - newFileImportsFromOldFile.forEach((symbol)=>{ - if (!symbol.declarations) return; - for (const decl of symbol.declarations){ - if (!isTopLevelDeclaration(decl)) continue; - const name = nameOfTopLevelDeclaration(decl); - if (!name) continue; - const top = getTopLevelDeclarationStatement(decl); - if (markSeenTop(top)) addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); - if (hasSyntacticModifier(decl, 1024 /* Default */ )) oldFileDefault = name; - else oldFileNamedImports.push(name.text); - } - }); - append(copiedOldImports, makeImportOrRequire(oldFile, oldFileDefault, oldFileNamedImports, getBaseFileName(oldFile.fileName), program, host, useEsModuleSyntax, quotePreference)); - return copiedOldImports; - } - function makeUniqueFilename(proposedFilename, extension, inDirectory, host) { - let newFilename = proposedFilename; - for(let i = 1;; i++){ - const name = combinePaths(inDirectory, newFilename + extension); - if (!host.fileExists(name)) return newFilename; - newFilename = `${proposedFilename}.${i}`; - } - } - function inferNewFilename(importsFromNewFile, movedSymbols) { - return importsFromNewFile.forEachEntry(symbolNameNoDefault) || movedSymbols.forEachEntry(symbolNameNoDefault) || "newFile"; - } - function getUsageInfo(oldFile, toMove, checker) { - const movedSymbols = new SymbolSet(); - const oldImportsNeededByNewFile = new SymbolSet(); - const newFileImportsFromOldFile = new SymbolSet(); - const containsJsx = find(toMove, (statement)=>!!(statement.transformFlags & 2 /* ContainsJsx */ )); - const jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx); - if (jsxNamespaceSymbol) oldImportsNeededByNewFile.add(jsxNamespaceSymbol); - for (const statement of toMove)forEachTopLevelDeclaration(statement, (decl)=>{ - movedSymbols.add(Debug.checkDefined(isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol, "Need a symbol here")); - }); - for (const statement of toMove)forEachReference(statement, checker, (symbol)=>{ - if (!symbol.declarations) return; - for (const decl of symbol.declarations){ - if (isInImport(decl)) oldImportsNeededByNewFile.add(symbol); - else if (isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile && !movedSymbols.has(symbol)) newFileImportsFromOldFile.add(symbol); - } - }); - const unusedImportsFromOldFile = oldImportsNeededByNewFile.clone(); - const oldFileImportsFromNewFile = new SymbolSet(); - for (const statement of oldFile.statements){ - if (contains(toMove, statement)) continue; - if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */ )) unusedImportsFromOldFile.delete(jsxNamespaceSymbol); - forEachReference(statement, checker, (symbol)=>{ - if (movedSymbols.has(symbol)) oldFileImportsFromNewFile.add(symbol); - unusedImportsFromOldFile.delete(symbol); - }); - } - return { - movedSymbols: movedSymbols, - newFileImportsFromOldFile: newFileImportsFromOldFile, - oldFileImportsFromNewFile: oldFileImportsFromNewFile, - oldImportsNeededByNewFile: oldImportsNeededByNewFile, - unusedImportsFromOldFile: unusedImportsFromOldFile - }; - function getJsxNamespaceSymbol(containsJsx2) { - if (containsJsx2 === void 0) return void 0; - const jsxNamespace = checker.getJsxNamespace(containsJsx2); - const jsxNamespaceSymbol2 = checker.resolveName(jsxNamespace, containsJsx2, 1920 /* Namespace */ , /*excludeGlobals*/ true); - return !!jsxNamespaceSymbol2 && some(jsxNamespaceSymbol2.declarations, isInImport) ? jsxNamespaceSymbol2 : void 0; - } - } - function isInImport(decl) { - switch(decl.kind){ - case 268 /* ImportEqualsDeclaration */ : - case 273 /* ImportSpecifier */ : - case 270 /* ImportClause */ : - case 271 /* NamespaceImport */ : - return true; - case 257 /* VariableDeclaration */ : - return isVariableDeclarationInImport(decl); - case 205 /* BindingElement */ : - return isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); - default: - return false; - } - } - function isVariableDeclarationInImport(decl) { - return isSourceFile(decl.parent.parent.parent) && !!decl.initializer && isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true); - } - function filterImport(i, moduleSpecifier, keep) { - switch(i.kind){ - case 269 /* ImportDeclaration */ : - { - const clause = i.importClause; - if (!clause) return void 0; - const defaultImport = clause.name && keep(clause.name) ? clause.name : void 0; - const namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); - return defaultImport || namedBindings ? factory.createImportDeclaration(/*modifiers*/ void 0, factory.createImportClause(clause.isTypeOnly, defaultImport, namedBindings), moduleSpecifier, /*assertClause*/ void 0) : void 0; + var DefinitionKind, EntryKind, FindReferencesUse, Core; + var init_findAllReferences = __esm({ + "src/services/findAllReferences.ts" () { + "use strict"; + init_ts4(); + init_ts_FindAllReferences(); + DefinitionKind = /* @__PURE__ */ ((DefinitionKind2)=>{ + DefinitionKind2[DefinitionKind2["Symbol"] = 0] = "Symbol"; + DefinitionKind2[DefinitionKind2["Label"] = 1] = "Label"; + DefinitionKind2[DefinitionKind2["Keyword"] = 2] = "Keyword"; + DefinitionKind2[DefinitionKind2["This"] = 3] = "This"; + DefinitionKind2[DefinitionKind2["String"] = 4] = "String"; + DefinitionKind2[DefinitionKind2["TripleSlashReference"] = 5] = "TripleSlashReference"; + return DefinitionKind2; + })(DefinitionKind || {}); + EntryKind = /* @__PURE__ */ ((EntryKind2)=>{ + EntryKind2[EntryKind2["Span"] = 0] = "Span"; + EntryKind2[EntryKind2["Node"] = 1] = "Node"; + EntryKind2[EntryKind2["StringLiteral"] = 2] = "StringLiteral"; + EntryKind2[EntryKind2["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty"; + EntryKind2[EntryKind2["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal"; + return EntryKind2; + })(EntryKind || {}); + FindReferencesUse = /* @__PURE__ */ ((FindReferencesUse2)=>{ + FindReferencesUse2[FindReferencesUse2["Other"] = 0] = "Other"; + FindReferencesUse2[FindReferencesUse2["References"] = 1] = "References"; + FindReferencesUse2[FindReferencesUse2["Rename"] = 2] = "Rename"; + return FindReferencesUse2; + })(FindReferencesUse || {}); + ((Core2)=>{ + function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options = {}, sourceFilesSet = new Set(sourceFiles.map((f)=>f.fileName))) { + var _a, _b, _c; + node = getAdjustedNode2(node, options); + if (isSourceFile(node)) { + const resolvedRef = ts_GoToDefinition_exports.getReferenceAtPosition(node, position, program); + if (!(resolvedRef == null ? void 0 : resolvedRef.file)) return void 0; + const moduleSymbol = program.getTypeChecker().getMergedSymbol(resolvedRef.file.symbol); + if (moduleSymbol) return getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); + const fileIncludeReasons = program.getFileIncludeReasons(); + if (!fileIncludeReasons) return void 0; + return [ + { + definition: { + type: 5 /* TripleSlashReference */ , + reference: resolvedRef.reference, + file: node + }, + references: getReferencesForNonModule(resolvedRef.file, fileIncludeReasons, program) || emptyArray + } + ]; + } + if (!options.implementations) { + const special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); + if (special) return special; + } + const checker = program.getTypeChecker(); + const symbol = checker.getSymbolAtLocation(isConstructorDeclaration(node) && node.parent.name || node); + if (!symbol) { + if (!options.implementations && isStringLiteralLike(node)) { + if (isModuleSpecifierLike(node)) { + const fileIncludeReasons = program.getFileIncludeReasons(); + const referencedFileName = (_c = (_b = (_a = node.getSourceFile().resolvedModules) == null ? void 0 : _a.get(node.text, getModeForUsageLocation(node.getSourceFile(), node))) == null ? void 0 : _b.resolvedModule) == null ? void 0 : _c.resolvedFileName; + const referencedFile = referencedFileName ? program.getSourceFile(referencedFileName) : void 0; + if (referencedFile) return [ + { + definition: { + type: 4 /* String */ , + node: node + }, + references: getReferencesForNonModule(referencedFile, fileIncludeReasons, program) || emptyArray + } + ]; + } + return getReferencesForStringLiteral(node, sourceFiles, checker, cancellationToken); + } + return void 0; + } + if (symbol.escapedName === "export=" /* ExportEquals */ ) return getReferencedSymbolsForModule(program, symbol.parent, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); + const moduleReferences = getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol, program, sourceFiles, cancellationToken, options, sourceFilesSet); + if (moduleReferences && !(symbol.flags & 33554432 /* Transient */ )) return moduleReferences; + const aliasedSymbol = getMergedAliasedSymbolOfNamespaceExportDeclaration(node, symbol, checker); + const moduleReferencesOfExportTarget = aliasedSymbol && getReferencedSymbolsForModuleIfDeclaredBySourceFile(aliasedSymbol, program, sourceFiles, cancellationToken, options, sourceFilesSet); + const references = getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options); + return mergeReferences(program, moduleReferences, references, moduleReferencesOfExportTarget); } - case 268 /* ImportEqualsDeclaration */ : - return keep(i.name) ? i : void 0; - case 257 /* VariableDeclaration */ : - { - const name = filterBindingName(i.name, keep); - return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : void 0; + Core2.getReferencedSymbolsForNode = getReferencedSymbolsForNode; + function getAdjustedNode2(node, options) { + if (options.use === 1 /* References */ ) node = getAdjustedReferenceLocation(node); + else if (options.use === 2 /* Rename */ ) node = getAdjustedRenameLocation(node); + return node; } - default: - return Debug.assertNever(i, `Unexpected import kind ${i.kind}`); - } - } - function filterNamedBindings(namedBindings, keep) { - if (namedBindings.kind === 271 /* NamespaceImport */ ) return keep(namedBindings.name) ? namedBindings : void 0; - else { - const newElements = namedBindings.elements.filter((e)=>keep(e.name)); - return newElements.length ? factory.createNamedImports(newElements) : void 0; - } - } - function filterBindingName(name, keep) { - switch(name.kind){ - case 79 /* Identifier */ : - return keep(name) ? name : void 0; - case 204 /* ArrayBindingPattern */ : - return name; - case 203 /* ObjectBindingPattern */ : - { - const newElements = name.elements.filter((prop)=>prop.propertyName || !isIdentifier(prop.name) || keep(prop.name)); - return newElements.length ? factory.createObjectBindingPattern(newElements) : void 0; + Core2.getAdjustedNode = getAdjustedNode2; + function getReferencesForFileName(fileName, program, sourceFiles, sourceFilesSet = new Set(sourceFiles.map((f)=>f.fileName))) { + var _a, _b; + const moduleSymbol = (_a = program.getSourceFile(fileName)) == null ? void 0 : _a.symbol; + if (moduleSymbol) return ((_b = getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet)[0]) == null ? void 0 : _b.references) || emptyArray; + const fileIncludeReasons = program.getFileIncludeReasons(); + const referencedFile = program.getSourceFile(fileName); + return referencedFile && fileIncludeReasons && getReferencesForNonModule(referencedFile, fileIncludeReasons, program) || emptyArray; } - } - } - function forEachReference(node, checker, onReference) { - node.forEachChild(function cb(node2) { - if (isIdentifier(node2) && !isDeclarationName(node2)) { - const sym = checker.getSymbolAtLocation(node2); - if (sym) onReference(sym); - } else node2.forEachChild(cb); - }); - } - function isTopLevelDeclaration(node) { - return isNonVariableTopLevelDeclaration(node) && isSourceFile(node.parent) || isVariableDeclaration(node) && isSourceFile(node.parent.parent.parent); - } - function sourceFileOfTopLevelDeclaration(node) { - return isVariableDeclaration(node) ? node.parent.parent.parent : node.parent; - } - function isTopLevelDeclarationStatement(node) { - Debug.assert(isSourceFile(node.parent), "Node parent should be a SourceFile"); - return isNonVariableTopLevelDeclaration(node) || isVariableStatement(node); - } - function isNonVariableTopLevelDeclaration(node) { - switch(node.kind){ - case 259 /* FunctionDeclaration */ : - case 260 /* ClassDeclaration */ : - case 264 /* ModuleDeclaration */ : - case 263 /* EnumDeclaration */ : - case 262 /* TypeAliasDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 268 /* ImportEqualsDeclaration */ : - return true; - default: - return false; - } - } - function forEachTopLevelDeclaration(statement, cb) { - switch(statement.kind){ - case 259 /* FunctionDeclaration */ : - case 260 /* ClassDeclaration */ : - case 264 /* ModuleDeclaration */ : - case 263 /* EnumDeclaration */ : - case 262 /* TypeAliasDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 268 /* ImportEqualsDeclaration */ : - return cb(statement); - case 240 /* VariableStatement */ : - return firstDefined(statement.declarationList.declarations, (decl)=>forEachTopLevelDeclarationInBindingName(decl.name, cb)); - case 241 /* ExpressionStatement */ : - { - const { expression: expression } = statement; - return isBinaryExpression(expression) && getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : void 0; + Core2.getReferencesForFileName = getReferencesForFileName; + function getReferencesForNonModule(referencedFile, refFileMap, program) { + let entries; + const references = refFileMap.get(referencedFile.path) || emptyArray; + for (const ref of references)if (isReferencedFile(ref)) { + const referencingFile = program.getSourceFileByPath(ref.file); + const location = getReferencedFileLocation(program.getSourceFileByPath, ref); + if (isReferenceFileLocation(location)) entries = append(entries, { + kind: 0 /* Span */ , + fileName: referencingFile.fileName, + textSpan: createTextSpanFromRange(location) + }); + } + return entries; } - } - } - function forEachTopLevelDeclarationInBindingName(name, cb) { - switch(name.kind){ - case 79 /* Identifier */ : - return cb(cast(name.parent, (x)=>isVariableDeclaration(x) || isBindingElement(x))); - case 204 /* ArrayBindingPattern */ : - case 203 /* ObjectBindingPattern */ : - return firstDefined(name.elements, (em)=>isOmittedExpression(em) ? void 0 : forEachTopLevelDeclarationInBindingName(em.name, cb)); - default: - return Debug.assertNever(name, `Unexpected name kind ${name.kind}`); - } - } - function nameOfTopLevelDeclaration(d) { - return isExpressionStatement(d) ? tryCast(d.expression.left.name, isIdentifier) : tryCast(d.name, isIdentifier); - } - function getTopLevelDeclarationStatement(d) { - switch(d.kind){ - case 257 /* VariableDeclaration */ : - return d.parent.parent; - case 205 /* BindingElement */ : - return getTopLevelDeclarationStatement(cast(d.parent.parent, (p)=>isVariableDeclaration(p) || isBindingElement(p))); - default: - return d; - } - } - function addExportToChanges(sourceFile, decl, name, changes, useEs6Exports) { - if (isExported(sourceFile, decl, useEs6Exports, name)) return; - if (useEs6Exports) { - if (!isExpressionStatement(decl)) changes.insertExportModifier(sourceFile, decl); - } else { - const names = getNamesToExportInCommonJS(decl); - if (names.length !== 0) changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment)); - } - } - function isExported(sourceFile, decl, useEs6Exports, name) { - var _a2; - if (useEs6Exports) return !isExpressionStatement(decl) && hasSyntacticModifier(decl, 1 /* Export */ ) || !!(name && ((_a2 = sourceFile.symbol.exports) == null ? void 0 : _a2.has(name.escapedText))); - return !!sourceFile.symbol && !!sourceFile.symbol.exports && getNamesToExportInCommonJS(decl).some((name2)=>sourceFile.symbol.exports.has(escapeLeadingUnderscores(name2))); - } - function addExport(decl, useEs6Exports) { - return useEs6Exports ? [ - addEs6Export(decl) - ] : addCommonjsExport(decl); - } - function addEs6Export(d) { - const modifiers = canHaveModifiers(d) ? concatenate([ - factory.createModifier(93 /* ExportKeyword */ ) - ], getModifiers(d)) : void 0; - switch(d.kind){ - case 259 /* FunctionDeclaration */ : - return factory.updateFunctionDeclaration(d, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); - case 260 /* ClassDeclaration */ : - const decorators = canHaveDecorators(d) ? getDecorators(d) : void 0; - return factory.updateClassDeclaration(d, concatenate(decorators, modifiers), d.name, d.typeParameters, d.heritageClauses, d.members); - case 240 /* VariableStatement */ : - return factory.updateVariableStatement(d, modifiers, d.declarationList); - case 264 /* ModuleDeclaration */ : - return factory.updateModuleDeclaration(d, modifiers, d.name, d.body); - case 263 /* EnumDeclaration */ : - return factory.updateEnumDeclaration(d, modifiers, d.name, d.members); - case 262 /* TypeAliasDeclaration */ : - return factory.updateTypeAliasDeclaration(d, modifiers, d.name, d.typeParameters, d.type); - case 261 /* InterfaceDeclaration */ : - return factory.updateInterfaceDeclaration(d, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 268 /* ImportEqualsDeclaration */ : - return factory.updateImportEqualsDeclaration(d, modifiers, d.isTypeOnly, d.name, d.moduleReference); - case 241 /* ExpressionStatement */ : - return Debug.fail(); - default: - return Debug.assertNever(d, `Unexpected declaration kind ${d.kind}`); - } - } - function addCommonjsExport(decl) { - return [ - decl, - ...getNamesToExportInCommonJS(decl).map(createExportAssignment) - ]; - } - function getNamesToExportInCommonJS(decl) { - switch(decl.kind){ - case 259 /* FunctionDeclaration */ : - case 260 /* ClassDeclaration */ : - return [ - decl.name.text - ]; - case 240 /* VariableStatement */ : - return mapDefined(decl.declarationList.declarations, (d)=>isIdentifier(d.name) ? d.name.text : void 0); - case 264 /* ModuleDeclaration */ : - case 263 /* EnumDeclaration */ : - case 262 /* TypeAliasDeclaration */ : - case 261 /* InterfaceDeclaration */ : - case 268 /* ImportEqualsDeclaration */ : - return emptyArray; - case 241 /* ExpressionStatement */ : - return Debug.fail("Can't export an ExpressionStatement"); - default: - return Debug.assertNever(decl, `Unexpected decl kind ${decl.kind}`); - } - } - function createExportAssignment(name) { - return factory.createExpressionStatement(factory.createBinaryExpression(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(name)), 63 /* EqualsToken */ , factory.createIdentifier(name))); - } - var refactorName4, description, moveToNewFileAction, SymbolSet; - var init_moveToNewFile = __esm({ - "src/services/refactors/moveToNewFile.ts" () { - "use strict"; - init_moduleSpecifiers(); - init_ts4(); - init_ts_refactor(); - refactorName4 = "Move to a new file"; - description = getLocaleSpecificMessage(Diagnostics.Move_to_a_new_file); - moveToNewFileAction = { - name: refactorName4, - description: description, - kind: "refactor.move.newFile" - }; - registerRefactor(refactorName4, { - kinds: [ - moveToNewFileAction.kind - ], - getAvailableActions: function getRefactorActionsToMoveToNewFile(context) { - const statements = getStatementsToMove(context); - if (context.preferences.allowTextChangesInNewFiles && statements) return [ - { - name: refactorName4, - description: description, - actions: [ - moveToNewFileAction - ] + function getMergedAliasedSymbolOfNamespaceExportDeclaration(node, symbol, checker) { + if (node.parent && isNamespaceExportDeclaration(node.parent)) { + const aliasedSymbol = checker.getAliasedSymbol(symbol); + const targetSymbol = checker.getMergedSymbol(aliasedSymbol); + if (aliasedSymbol !== targetSymbol) return targetSymbol; + } + return void 0; + } + function getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol, program, sourceFiles, cancellationToken, options, sourceFilesSet) { + const moduleSourceFile = symbol.flags & 1536 /* Module */ && symbol.declarations && find(symbol.declarations, isSourceFile); + if (!moduleSourceFile) return void 0; + const exportEquals = symbol.exports.get("export=" /* ExportEquals */ ); + const moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet); + if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName)) return moduleReferences; + const checker = program.getTypeChecker(); + symbol = skipAlias(exportEquals, checker); + return mergeReferences(program, moduleReferences, getReferencedSymbolsForSymbol(symbol, /*node*/ void 0, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); + } + function mergeReferences(program, ...referencesToMerge) { + let result; + for (const references of referencesToMerge){ + if (!references || !references.length) continue; + if (!result) { + result = references; + continue; } - ]; - if (context.preferences.provideRefactorNotApplicableReason) return [ - { - name: refactorName4, - description: description, - actions: [ - { - ...moveToNewFileAction, - notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) - } - ] + for (const entry of references){ + if (!entry.definition || entry.definition.type !== 0 /* Symbol */ ) { + result.push(entry); + continue; + } + const symbol = entry.definition.symbol; + const refIndex = findIndex(result, (ref)=>!!ref.definition && ref.definition.type === 0 /* Symbol */ && ref.definition.symbol === symbol); + if (refIndex === -1) { + result.push(entry); + continue; + } + const reference = result[refIndex]; + result[refIndex] = { + definition: reference.definition, + references: reference.references.concat(entry.references).sort((entry1, entry2)=>{ + const entry1File = getSourceFileIndexOfEntry(program, entry1); + const entry2File = getSourceFileIndexOfEntry(program, entry2); + if (entry1File !== entry2File) return compareValues(entry1File, entry2File); + const entry1Span = getTextSpanOfEntry(entry1); + const entry2Span = getTextSpanOfEntry(entry2); + return entry1Span.start !== entry2Span.start ? compareValues(entry1Span.start, entry2Span.start) : compareValues(entry1Span.length, entry2Span.length); + }) + }; } - ]; - return emptyArray; - }, - getEditsForAction: function getRefactorEditsToMoveToNewFile(context, actionName2) { - Debug.assert(actionName2 === refactorName4, "Wrong refactor invoked"); - const statements = Debug.checkDefined(getStatementsToMove(context)); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange35(context.file, context.program, statements, t, context.host, context.preferences)); - return { - edits: edits, - renameFilename: void 0, - renameLocation: void 0 - }; - } - }); - SymbolSet = class { - constructor(){ - this.map = /* @__PURE__ */ new Map(); + } + return result; } - add(symbol) { - this.map.set(String(getSymbolId(symbol)), symbol); + function getSourceFileIndexOfEntry(program, entry) { + const sourceFile = entry.kind === 0 /* Span */ ? program.getSourceFile(entry.fileName) : entry.node.getSourceFile(); + return program.getSourceFiles().indexOf(sourceFile); } - has(symbol) { - return this.map.has(String(getSymbolId(symbol))); + function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) { + Debug.assert(!!symbol.valueDeclaration); + const references = mapDefined(findModuleReferences(program, sourceFiles, symbol), (reference)=>{ + if (reference.kind === "import") { + const parent2 = reference.literal.parent; + if (isLiteralTypeNode(parent2)) { + const importType = cast(parent2.parent, isImportTypeNode); + if (excludeImportTypeOfExportEquals && !importType.qualifier) return void 0; + } + return nodeEntry(reference.literal); + } else if (reference.kind === "implicit") { + const range = reference.literal.text !== externalHelpersModuleNameText && forEachChildRecursively(reference.referencingFile, (n)=>!(n.transformFlags & 2 /* ContainsJsx */ ) ? "skip" : isJsxElement(n) || isJsxSelfClosingElement(n) || isJsxFragment(n) ? n : void 0) || reference.referencingFile.statements[0] || reference.referencingFile; + return nodeEntry(range); + } else return { + kind: 0 /* Span */ , + fileName: reference.referencingFile.fileName, + textSpan: createTextSpanFromRange(reference.ref) + }; + }); + if (symbol.declarations) for (const decl of symbol.declarations)switch(decl.kind){ + case 312 /* SourceFile */ : + break; + case 267 /* ModuleDeclaration */ : + if (sourceFilesSet.has(decl.getSourceFile().fileName)) references.push(nodeEntry(decl.name)); + break; + default: + Debug.assert(!!(symbol.flags & 33554432 /* Transient */ ), "Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); + } + const exported = symbol.exports.get("export=" /* ExportEquals */ ); + if (exported == null ? void 0 : exported.declarations) for (const decl of exported.declarations){ + const sourceFile = decl.getSourceFile(); + if (sourceFilesSet.has(sourceFile.fileName)) { + const node = isBinaryExpression(decl) && isPropertyAccessExpression(decl.left) ? decl.left.expression : isExportAssignment(decl) ? Debug.checkDefined(findChildOfKind(decl, 95 /* ExportKeyword */ , sourceFile)) : getNameOfDeclaration(decl) || decl; + references.push(nodeEntry(node)); + } + } + return references.length ? [ + { + definition: { + type: 0 /* Symbol */ , + symbol: symbol + }, + references: references + } + ] : emptyArray; } - delete(symbol) { - this.map.delete(String(getSymbolId(symbol))); + function isReadonlyTypeOperator(node) { + return node.kind === 148 /* ReadonlyKeyword */ && isTypeOperatorNode(node.parent) && node.parent.operator === 148 /* ReadonlyKeyword */ ; } - forEach(cb) { - this.map.forEach(cb); + function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { + if (isTypeKeyword(node.kind)) { + if (node.kind === 116 /* VoidKeyword */ && isVoidExpression(node.parent)) return void 0; + if (node.kind === 148 /* ReadonlyKeyword */ && !isReadonlyTypeOperator(node)) return void 0; + return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken, node.kind === 148 /* ReadonlyKeyword */ ? isReadonlyTypeOperator : void 0); + } + if (isImportMeta(node.parent) && node.parent.name === node) return getAllReferencesForImportMeta(sourceFiles, cancellationToken); + if (isStaticModifier(node) && isClassStaticBlockDeclaration(node.parent)) return [ + { + definition: { + type: 2 /* Keyword */ , + node: node + }, + references: [ + nodeEntry(node) + ] + } + ]; + if (isJumpStatementTarget(node)) { + const labelDefinition = getTargetLabel(node.parent, node.text); + return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition); + } else if (isLabelOfLabeledStatement(node)) return getLabelReferencesInNode(node.parent, node); + if (isThis(node)) return getReferencesForThisKeyword(node, sourceFiles, cancellationToken); + if (node.kind === 108 /* SuperKeyword */ ) return getReferencesForSuperKeyword(node); + return void 0; } - forEachEntry(cb) { - return forEachEntry(this.map, cb); + function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { + const symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, /*useLocalSymbolForExportSpecifier*/ !isForRenameWithPrefixAndSuffixText(options)) || originalSymbol; + const searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */ ; + const result = []; + const state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */ , checker, cancellationToken, searchMeaning, options, result); + const exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) || !symbol.declarations ? void 0 : find(symbol.declarations, isExportSpecifier); + if (exportSpecifier) getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ void 0), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); + else if (node && node.kind === 90 /* DefaultKeyword */ && symbol.escapedName === "default" /* Default */ && symbol.parent) { + addReference(node, symbol, state); + searchForImportsOfExport(node, symbol, { + exportingModuleSymbol: symbol.parent, + exportKind: 1 /* Default */ + }, state); + } else { + const search = state.createSearch(node, symbol, /*comingFrom*/ void 0, { + allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.use === 2 /* Rename */ , !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [ + symbol + ] + }); + getReferencesInContainerOrFiles(symbol, state, search); + } + return result; } - clone() { - const clone2 = new SymbolSet(); - copyEntries(this.map, clone2.map); - return clone2; + function getReferencesInContainerOrFiles(symbol, state, search) { + const scope = getSymbolScope(symbol); + if (scope) getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(isSourceFile(scope) && !contains(state.sourceFiles, scope))); + else for (const sourceFile of state.sourceFiles){ + state.cancellationToken.throwIfCancellationRequested(); + searchForName(sourceFile, search, state); + } } - size() { - return this.map.size; + function getSpecialSearchKind(node) { + switch(node.kind){ + case 176 /* Constructor */ : + case 137 /* ConstructorKeyword */ : + return 1 /* Constructor */ ; + case 80 /* Identifier */ : + if (isClassLike(node.parent)) { + Debug.assert(node.parent.name === node); + return 2 /* Class */ ; + } + default: + return 0 /* None */ ; + } } - }; - } - }); - // src/services/refactors/convertOverloadListToSingleSignature.ts - function getRefactorActionsToConvertOverloadsToOneSignature(context) { - const { file: file , startPosition: startPosition , program: program } = context; - const info = getConvertableOverloadListAtPosition(file, startPosition, program); - if (!info) return emptyArray; - return [ - { - name: refactorName5, - description: refactorDescription, - actions: [ - functionOverloadAction - ] - } - ]; - } - function getRefactorEditsToConvertOverloadsToOneSignature(context) { - const { file: file , startPosition: startPosition , program: program } = context; - const signatureDecls = getConvertableOverloadListAtPosition(file, startPosition, program); - if (!signatureDecls) return void 0; - const checker = program.getTypeChecker(); - const lastDeclaration = signatureDecls[signatureDecls.length - 1]; - let updated = lastDeclaration; - switch(lastDeclaration.kind){ - case 170 /* MethodSignature */ : - updated = factory.updateMethodSignature(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); - break; - case 171 /* MethodDeclaration */ : - updated = factory.updateMethodDeclaration(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); - break; - case 176 /* CallSignature */ : - updated = factory.updateCallSignature(lastDeclaration, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); - break; - case 173 /* Constructor */ : - updated = factory.updateConstructorDeclaration(lastDeclaration, lastDeclaration.modifiers, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.body); - break; - case 177 /* ConstructSignature */ : - updated = factory.updateConstructSignature(lastDeclaration, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); - break; - case 259 /* FunctionDeclaration */ : - updated = factory.updateFunctionDeclaration(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); - break; - default: - return Debug.failBadSyntaxKind(lastDeclaration, "Unhandled signature kind in overload list conversion refactoring"); - } - if (updated === lastDeclaration) return; - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t)=>{ - t.replaceNodeRange(file, signatureDecls[0], signatureDecls[signatureDecls.length - 1], updated); - }); - return { - renameFilename: void 0, - renameLocation: void 0, - edits: edits - }; - function getNewParametersForCombinedSignature(signatureDeclarations) { - const lastSig = signatureDeclarations[signatureDeclarations.length - 1]; - if (isFunctionLikeDeclaration(lastSig) && lastSig.body) signatureDeclarations = signatureDeclarations.slice(0, signatureDeclarations.length - 1); - return factory.createNodeArray([ - factory.createParameterDeclaration(/*modifiers*/ void 0, factory.createToken(25 /* DotDotDotToken */ ), "args", /*questionToken*/ void 0, factory.createUnionTypeNode(map(signatureDeclarations, convertSignatureParametersToTuple))) - ]); - } - function convertSignatureParametersToTuple(decl) { - const members = map(decl.parameters, convertParameterToNamedTupleMember); - return setEmitFlags(factory.createTupleTypeNode(members), some(members, (m)=>!!length(getSyntheticLeadingComments(m))) ? 0 /* None */ : 1 /* SingleLine */ ); - } - function convertParameterToNamedTupleMember(p) { - Debug.assert(isIdentifier(p.name)); - const result = setTextRange(factory.createNamedTupleMember(p.dotDotDotToken, p.name, p.questionToken, p.type || factory.createKeywordTypeNode(131 /* AnyKeyword */ )), p); - const parameterDocComment = p.symbol && p.symbol.getDocumentationComment(checker); - if (parameterDocComment) { - const newComment = displayPartsToString(parameterDocComment); - if (newComment.length) setSyntheticLeadingComments(result, [ - { - text: `* -${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} - `, - kind: 3 /* MultiLineCommentTrivia */ , - pos: -1, - end: -1, - hasTrailingNewLine: true, - hasLeadingNewline: true + function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, useLocalSymbolForExportSpecifier) { + const { parent: parent2 } = node; + if (isExportSpecifier(parent2) && useLocalSymbolForExportSpecifier) return getLocalSymbolForExportSpecifier(node, symbol, parent2, checker); + return firstDefined(symbol.declarations, (decl)=>{ + if (!decl.parent) { + if (symbol.flags & 33554432 /* Transient */ ) return void 0; + Debug.fail(`Unexpected symbol at ${Debug.formatSyntaxKind(node.kind)}: ${Debug.formatSymbol(symbol)}`); + } + return isTypeLiteralNode(decl.parent) && isUnionTypeNode(decl.parent.parent) ? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name) : void 0; + }); + } + let SpecialSearchKind; + ((SpecialSearchKind2)=>{ + SpecialSearchKind2[SpecialSearchKind2["None"] = 0] = "None"; + SpecialSearchKind2[SpecialSearchKind2["Constructor"] = 1] = "Constructor"; + SpecialSearchKind2[SpecialSearchKind2["Class"] = 2] = "Class"; + })(SpecialSearchKind || (SpecialSearchKind = {})); + function getNonModuleSymbolOfMergedModuleSymbol(symbol) { + if (!(symbol.flags & 33555968 /* Transient */ )) return void 0; + const decl = symbol.declarations && find(symbol.declarations, (d)=>!isSourceFile(d) && !isModuleDeclaration(d)); + return decl && decl.symbol; + } + class State { + constructor(sourceFiles, sourceFilesSet, specialSearchKind, checker, cancellationToken, searchMeaning, options, result){ + this.sourceFiles = sourceFiles; + this.sourceFilesSet = sourceFilesSet; + this.specialSearchKind = specialSearchKind; + this.checker = checker; + this.cancellationToken = cancellationToken; + this.searchMeaning = searchMeaning; + this.options = options; + this.result = result; + /** Cache for `explicitlyinheritsFrom`. */ this.inheritsFromCache = /* @__PURE__ */ new Map(); + /** + * Type nodes can contain multiple references to the same type. For example: + * let x: Foo & (Foo & Bar) = ... + * Because we are returning the implementation locations and not the identifier locations, + * duplicate entries would be returned here as each of the type references is part of + * the same implementation. For that reason, check before we add a new entry. + */ this.markSeenContainingTypeReference = nodeSeenTracker(); + /** + * It's possible that we will encounter the right side of `export { foo as bar } from "x";` more than once. + * For example: + * // b.ts + * export { foo as bar } from "./a"; + * import { bar } from "./b"; + * + * Normally at `foo as bar` we directly add `foo` and do not locally search for it (since it doesn't declare a local). + * But another reference to it may appear in the same source file. + * See `tests/cases/fourslash/transitiveExportImports3.ts`. + */ this.markSeenReExportRHS = nodeSeenTracker(); + this.symbolIdToReferences = []; + // Source file ID -> symbol ID -> Whether the symbol has been searched for in the source file. + this.sourceFileToSeenSymbols = []; + } + includesSourceFile(sourceFile) { + return this.sourceFilesSet.has(sourceFile.fileName); + } + /** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */ getImportSearches(exportSymbol, exportInfo) { + if (!this.importTracker) this.importTracker = createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken); + return this.importTracker(exportSymbol, exportInfo, this.options.use === 2 /* Rename */ ); + } + /** @param allSearchSymbols set of additional symbols for use by `includes`. */ createSearch(location, symbol, comingFrom, searchOptions = {}) { + const { text: text = stripQuotes(symbolName(getLocalSymbolForExportDefault(symbol) || getNonModuleSymbolOfMergedModuleSymbol(symbol) || symbol)), allSearchSymbols: allSearchSymbols = [ + symbol + ] } = searchOptions; + const escapedText = escapeLeadingUnderscores(text); + const parents = this.options.implementations && location ? getParentSymbolsOfPropertyAccess(location, symbol, this.checker) : void 0; + return { + symbol: symbol, + comingFrom: comingFrom, + text: text, + escapedText: escapedText, + parents: parents, + allSearchSymbols: allSearchSymbols, + includes: (sym)=>contains(allSearchSymbols, sym) + }; + } + /** + * Callback to add references for a particular searched symbol. + * This initializes a reference group, so only call this if you will add at least one reference. + */ referenceAdder(searchSymbol) { + const symbolId = getSymbolId(searchSymbol); + let references = this.symbolIdToReferences[symbolId]; + if (!references) { + references = this.symbolIdToReferences[symbolId] = []; + this.result.push({ + definition: { + type: 0 /* Symbol */ , + symbol: searchSymbol + }, + references: references + }); + } + return (node, kind)=>references.push(nodeEntry(node, kind)); + } + /** Add a reference with no associated definition. */ addStringOrCommentReference(fileName, textSpan) { + this.result.push({ + definition: void 0, + references: [ + { + kind: 0 /* Span */ , + fileName: fileName, + textSpan: textSpan + } + ] + }); + } + /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ markSearchedSymbols(sourceFile, symbols) { + const sourceId = getNodeId(sourceFile); + const seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = /* @__PURE__ */ new Set()); + let anyNewSymbols = false; + for (const sym of symbols)anyNewSymbols = tryAddToSet(seenSymbols, getSymbolId(sym)) || anyNewSymbols; + return anyNewSymbols; + } + } + function searchForImportsOfExport(exportLocation, exportSymbol, exportInfo, state) { + const { importSearches: importSearches, singleReferences: singleReferences, indirectUsers: indirectUsers } = state.getImportSearches(exportSymbol, exportInfo); + if (singleReferences.length) { + const addRef = state.referenceAdder(exportSymbol); + for (const singleRef of singleReferences)if (shouldAddSingleReference(singleRef, state)) addRef(singleRef); + } + for (const [importLocation, importSymbol] of importSearches)getReferencesInSourceFile(importLocation.getSourceFile(), state.createSearch(importLocation, importSymbol, 1 /* Export */ ), state); + if (indirectUsers.length) { + let indirectSearch; + switch(exportInfo.exportKind){ + case 0 /* Named */ : + indirectSearch = state.createSearch(exportLocation, exportSymbol, 1 /* Export */ ); + break; + case 1 /* Default */ : + indirectSearch = state.options.use === 2 /* Rename */ ? void 0 : state.createSearch(exportLocation, exportSymbol, 1 /* Export */ , { + text: "default" + }); + break; + case 2 /* ExportEquals */ : + break; + } + if (indirectSearch) for (const indirectUser of indirectUsers)searchForName(indirectUser, indirectSearch, state); + } + } + function eachExportReference(sourceFiles, checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName, isDefaultExport, cb) { + const importTracker = createImportTracker(sourceFiles, new Set(sourceFiles.map((f)=>f.fileName)), checker, cancellationToken); + const { importSearches: importSearches, indirectUsers: indirectUsers, singleReferences: singleReferences } = importTracker(exportSymbol, { + exportKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */ , + exportingModuleSymbol: exportingModuleSymbol + }, /*isForRename*/ false); + for (const [importLocation] of importSearches)cb(importLocation); + for (const singleReference of singleReferences)if (isIdentifier(singleReference) && isImportTypeNode(singleReference.parent)) cb(singleReference); + for (const indirectUser of indirectUsers)for (const node of getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName)){ + const symbol = checker.getSymbolAtLocation(node); + const hasExportAssignmentDeclaration = some(symbol == null ? void 0 : symbol.declarations, (d)=>tryCast(d, isExportAssignment) ? true : false); + if (isIdentifier(node) && !isImportOrExportSpecifier(node.parent) && (symbol === exportSymbol || hasExportAssignmentDeclaration)) cb(node); + } + } + Core2.eachExportReference = eachExportReference; + function shouldAddSingleReference(singleRef, state) { + if (!hasMatchingMeaning(singleRef, state)) return false; + if (state.options.use !== 2 /* Rename */ ) return true; + if (!isIdentifier(singleRef)) return false; + return !(isImportOrExportSpecifier(singleRef.parent) && singleRef.escapedText === "default" /* Default */ ); + } + function searchForImportedSymbol(symbol, state) { + if (!symbol.declarations) return; + for (const declaration of symbol.declarations){ + const exportingFile = declaration.getSourceFile(); + getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */ ), state, state.includesSourceFile(exportingFile)); + } + } + function searchForName(sourceFile, search, state) { + if (getNameTable(sourceFile).get(search.escapedText) !== void 0) getReferencesInSourceFile(sourceFile, search, state); + } + function getPropertySymbolOfDestructuringAssignment(location, checker) { + return isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) ? checker.getPropertySymbolOfDestructuringAssignment(location) : void 0; + } + function getSymbolScope(symbol) { + const { declarations: declarations, flags: flags, parent: parent2, valueDeclaration: valueDeclaration } = symbol; + if (valueDeclaration && (valueDeclaration.kind === 218 /* FunctionExpression */ || valueDeclaration.kind === 231 /* ClassExpression */ )) return valueDeclaration; + if (!declarations) return void 0; + if (flags & 8196 /* Method */ ) { + const privateDeclaration = find(declarations, (d)=>hasEffectiveModifier(d, 8 /* Private */ ) || isPrivateIdentifierClassElementDeclaration(d)); + if (privateDeclaration) return getAncestor(privateDeclaration, 263 /* ClassDeclaration */ ); + return void 0; + } + if (declarations.some(isObjectBindingElementWithoutPropertyName)) return void 0; + const exposedByParent = parent2 && !(symbol.flags & 262144 /* TypeParameter */ ); + if (exposedByParent && !(isExternalModuleSymbol(parent2) && !parent2.globalExports)) return void 0; + let scope; + for (const declaration of declarations){ + const container = getContainerNode(declaration); + if (scope && scope !== container) return void 0; + if (!container || container.kind === 312 /* SourceFile */ && !isExternalOrCommonJsModule(container)) return void 0; + scope = container; + if (isFunctionExpression(scope)) { + let next; + while(next = getNextJSDocCommentLocation(scope))scope = next; + } + } + return exposedByParent ? scope.getSourceFile() : scope; + } + function isSymbolReferencedInFile(definition, checker, sourceFile, searchContainer = sourceFile) { + return eachSymbolReferenceInFile(definition, checker, sourceFile, ()=>true, searchContainer) || false; + } + Core2.isSymbolReferencedInFile = isSymbolReferencedInFile; + function eachSymbolReferenceInFile(definition, checker, sourceFile, cb, searchContainer = sourceFile) { + const symbol = isParameterPropertyDeclaration(definition.parent, definition.parent.parent) ? first(checker.getSymbolsOfParameterPropertyDeclaration(definition.parent, definition.text)) : checker.getSymbolAtLocation(definition); + if (!symbol) return void 0; + for (const token of getPossibleSymbolReferenceNodes(sourceFile, symbol.name, searchContainer)){ + if (!isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) continue; + const referenceSymbol = checker.getSymbolAtLocation(token); + if (referenceSymbol === symbol || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol || isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) { + const res = cb(token); + if (res) return res; + } + } + } + Core2.eachSymbolReferenceInFile = eachSymbolReferenceInFile; + function getTopMostDeclarationNamesInFile(declarationName, sourceFile) { + const candidates = filter(getPossibleSymbolReferenceNodes(sourceFile, declarationName), (name)=>!!getDeclarationFromName(name)); + return candidates.reduce((topMost, decl)=>{ + const depth = getDepth(decl); + if (!some(topMost.declarationNames) || depth === topMost.depth) { + topMost.declarationNames.push(decl); + topMost.depth = depth; + } else if (depth < topMost.depth) { + topMost.declarationNames = [ + decl + ]; + topMost.depth = depth; + } + return topMost; + }, { + depth: Infinity, + declarationNames: [] + }).declarationNames; + function getDepth(declaration) { + let depth = 0; + while(declaration){ + declaration = getContainerNode(declaration); + depth++; + } + return depth; + } + } + Core2.getTopMostDeclarationNamesInFile = getTopMostDeclarationNamesInFile; + function someSignatureUsage(signature, sourceFiles, checker, cb) { + if (!signature.name || !isIdentifier(signature.name)) return false; + const symbol = Debug.checkDefined(checker.getSymbolAtLocation(signature.name)); + for (const sourceFile of sourceFiles)for (const name of getPossibleSymbolReferenceNodes(sourceFile, symbol.name)){ + if (!isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) continue; + const called = climbPastPropertyAccess(name); + const call = isCallExpression(called.parent) && called.parent.expression === called ? called.parent : void 0; + const referenceSymbol = checker.getSymbolAtLocation(name); + if (referenceSymbol && checker.getRootSymbols(referenceSymbol).some((s)=>s === symbol)) { + if (cb(name, call)) return true; + } + } + return false; + } + Core2.someSignatureUsage = someSignatureUsage; + function getPossibleSymbolReferenceNodes(sourceFile, symbolName2, container = sourceFile) { + return mapDefined(getPossibleSymbolReferencePositions(sourceFile, symbolName2, container), (pos)=>{ + const referenceLocation = getTouchingPropertyName(sourceFile, pos); + return referenceLocation === sourceFile ? void 0 : referenceLocation; + }); + } + function getPossibleSymbolReferencePositions(sourceFile, symbolName2, container = sourceFile) { + const positions = []; + if (!symbolName2 || !symbolName2.length) return positions; + const text = sourceFile.text; + const sourceLength = text.length; + const symbolNameLength = symbolName2.length; + let position = text.indexOf(symbolName2, container.pos); + while(position >= 0){ + if (position > container.end) break; + const endPosition = position + symbolNameLength; + if ((position === 0 || !isIdentifierPart(text.charCodeAt(position - 1), 99 /* Latest */ )) && (endPosition === sourceLength || !isIdentifierPart(text.charCodeAt(endPosition), 99 /* Latest */ ))) positions.push(position); + position = text.indexOf(symbolName2, position + symbolNameLength + 1); + } + return positions; + } + function getLabelReferencesInNode(container, targetLabel) { + const sourceFile = container.getSourceFile(); + const labelName = targetLabel.text; + const references = mapDefined(getPossibleSymbolReferenceNodes(sourceFile, labelName, container), (node)=>// Only pick labels that are either the target label, or have a target that is the target label + node === targetLabel || isJumpStatementTarget(node) && getTargetLabel(node, labelName) === targetLabel ? nodeEntry(node) : void 0); + return [ + { + definition: { + type: 1 /* Label */ , + node: targetLabel + }, + references: references + } + ]; + } + function isValidReferencePosition(node, searchSymbolName) { + switch(node.kind){ + case 81 /* PrivateIdentifier */ : + if (isJSDocMemberName(node.parent)) return true; + case 80 /* Identifier */ : + return node.text.length === searchSymbolName.length; + case 15 /* NoSubstitutionTemplateLiteral */ : + case 11 /* StringLiteral */ : + { + const str = node; + return (isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || isNameOfModuleDeclaration(node) || isExpressionOfExternalModuleImportEqualsDeclaration(node) || isCallExpression(node.parent) && isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node) && str.text.length === searchSymbolName.length; + } + case 9 /* NumericLiteral */ : + return isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; + case 90 /* DefaultKeyword */ : + return 7 === searchSymbolName.length; + default: + return false; + } + } + function getAllReferencesForImportMeta(sourceFiles, cancellationToken) { + const references = flatMap(sourceFiles, (sourceFile)=>{ + cancellationToken.throwIfCancellationRequested(); + return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "meta", sourceFile), (node)=>{ + const parent2 = node.parent; + if (isImportMeta(parent2)) return nodeEntry(parent2); + }); + }); + return references.length ? [ + { + definition: { + type: 2 /* Keyword */ , + node: references[0].node + }, + references: references + } + ] : void 0; + } + function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken, filter2) { + const references = flatMap(sourceFiles, (sourceFile)=>{ + cancellationToken.throwIfCancellationRequested(); + return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, tokenToString(keywordKind), sourceFile), (referenceLocation)=>{ + if (referenceLocation.kind === keywordKind && (!filter2 || filter2(referenceLocation))) return nodeEntry(referenceLocation); + }); + }); + return references.length ? [ + { + definition: { + type: 2 /* Keyword */ , + node: references[0].node + }, + references: references + } + ] : void 0; + } + function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere = true) { + state.cancellationToken.throwIfCancellationRequested(); + return getReferencesInContainer(sourceFile, sourceFile, search, state, addReferencesHere); + } + function getReferencesInContainer(container, sourceFile, search, state, addReferencesHere) { + if (!state.markSearchedSymbols(sourceFile, search.allSearchSymbols)) return; + for (const position of getPossibleSymbolReferencePositions(sourceFile, search.text, container))getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere); + } + function hasMatchingMeaning(referenceLocation, state) { + return !!(getMeaningFromLocation(referenceLocation) & state.searchMeaning); + } + function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) { + const referenceLocation = getTouchingPropertyName(sourceFile, position); + if (!isValidReferencePosition(referenceLocation, search.text)) { + if (!state.options.implementations && (state.options.findInStrings && isInString(sourceFile, position) || state.options.findInComments && isInNonReferenceComment(sourceFile, position))) state.addStringOrCommentReference(sourceFile.fileName, createTextSpan(position, search.text.length)); + return; + } + if (!hasMatchingMeaning(referenceLocation, state)) return; + let referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation); + if (!referenceSymbol) return; + const parent2 = referenceLocation.parent; + if (isImportSpecifier(parent2) && parent2.propertyName === referenceLocation) return; + if (isExportSpecifier(parent2)) { + Debug.assert(referenceLocation.kind === 80 /* Identifier */ ); + getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent2, search, state, addReferencesHere); + return; + } + const relatedSymbol = getRelatedSymbol(search, referenceSymbol, referenceLocation, state); + if (!relatedSymbol) { + getReferenceForShorthandProperty(referenceSymbol, search, state); + return; + } + switch(state.specialSearchKind){ + case 0 /* None */ : + if (addReferencesHere) addReference(referenceLocation, relatedSymbol, state); + break; + case 1 /* Constructor */ : + addConstructorReferences(referenceLocation, sourceFile, search, state); + break; + case 2 /* Class */ : + addClassStaticThisReferences(referenceLocation, search, state); + break; + default: + Debug.assertNever(state.specialSearchKind); + } + if (isInJSFile(referenceLocation) && isBindingElement(referenceLocation.parent) && isVariableDeclarationInitializedToBareOrAccessedRequire(referenceLocation.parent.parent.parent)) { + referenceSymbol = referenceLocation.parent.symbol; + if (!referenceSymbol) return; + } + getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); + } + function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { + Debug.assert(!alwaysGetReferences || !!state.options.providePrefixAndSuffixTextForRename, "If alwaysGetReferences is true, then prefix/suffix text must be enabled"); + const { parent: parent2, propertyName: propertyName, name: name } = exportSpecifier; + const exportDeclaration = parent2.parent; + const localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); + if (!alwaysGetReferences && !search.includes(localSymbol)) return; + if (!propertyName) { + if (!(state.options.use === 2 /* Rename */ && name.escapedText === "default" /* Default */ )) addRef(); + } else if (referenceLocation === propertyName) { + if (!exportDeclaration.moduleSpecifier) addRef(); + if (addReferencesHere && state.options.use !== 2 /* Rename */ && state.markSeenReExportRHS(name)) addReference(name, Debug.checkDefined(exportSpecifier.symbol), state); + } else if (state.markSeenReExportRHS(referenceLocation)) addRef(); + if (!isForRenameWithPrefixAndSuffixText(state.options) || alwaysGetReferences) { + const isDefaultExport = referenceLocation.escapedText === "default" || exportSpecifier.name.escapedText === "default"; + const exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */ ; + const exportSymbol = Debug.checkDefined(exportSpecifier.symbol); + const exportInfo = getExportInfo(exportSymbol, exportKind, state.checker); + if (exportInfo) searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + } + if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !isForRenameWithPrefixAndSuffixText(state.options)) { + const imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); + if (imported) searchForImportedSymbol(imported, state); + } + function addRef() { + if (addReferencesHere) addReference(referenceLocation, localSymbol, state); + } + } + function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) { + return isExportSpecifierAlias(referenceLocation, exportSpecifier) && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier) || referenceSymbol; + } + function isExportSpecifierAlias(referenceLocation, exportSpecifier) { + const { parent: parent2, propertyName: propertyName, name: name } = exportSpecifier; + Debug.assert(propertyName === referenceLocation || name === referenceLocation); + if (propertyName) return propertyName === referenceLocation; + else return !parent2.parent.moduleSpecifier; + } + function getImportOrExportReferences(referenceLocation, referenceSymbol, search, state) { + const importOrExport = getImportOrExportSymbol(referenceLocation, referenceSymbol, state.checker, search.comingFrom === 1 /* Export */ ); + if (!importOrExport) return; + const { symbol: symbol } = importOrExport; + if (importOrExport.kind === 0 /* Import */ ) { + if (!isForRenameWithPrefixAndSuffixText(state.options)) searchForImportedSymbol(symbol, state); + } else searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state); + } + function getReferenceForShorthandProperty({ flags: flags, valueDeclaration: valueDeclaration }, search, state) { + const shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration); + const name = valueDeclaration && getNameOfDeclaration(valueDeclaration); + if (!(flags & 33554432 /* Transient */ ) && name && search.includes(shorthandValueSymbol)) addReference(name, shorthandValueSymbol, state); + } + function addReference(referenceLocation, relatedSymbol, state) { + const { kind: kind, symbol: symbol } = "kind" in relatedSymbol ? relatedSymbol : { + kind: void 0, + symbol: relatedSymbol + }; + if (state.options.use === 2 /* Rename */ && referenceLocation.kind === 90 /* DefaultKeyword */ ) return; + const addRef = state.referenceAdder(symbol); + if (state.options.implementations) addImplementationReferences(referenceLocation, addRef, state); + else addRef(referenceLocation, kind); + } + function addConstructorReferences(referenceLocation, sourceFile, search, state) { + if (isNewExpressionTarget(referenceLocation)) addReference(referenceLocation, search.symbol, state); + const pusher = ()=>state.referenceAdder(search.symbol); + if (isClassLike(referenceLocation.parent)) { + Debug.assert(referenceLocation.kind === 90 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation); + findOwnConstructorReferences(search.symbol, sourceFile, pusher()); + } else { + const classExtending = tryGetClassByExtendingIdentifier(referenceLocation); + if (classExtending) { + findSuperConstructorAccesses(classExtending, pusher()); + findInheritedConstructorReferences(classExtending, state); + } + } + } + function addClassStaticThisReferences(referenceLocation, search, state) { + addReference(referenceLocation, search.symbol, state); + const classLike = referenceLocation.parent; + if (state.options.use === 2 /* Rename */ || !isClassLike(classLike)) return; + Debug.assert(classLike.name === referenceLocation); + const addRef = state.referenceAdder(search.symbol); + for (const member of classLike.members){ + if (!(isMethodOrAccessor(member) && isStatic(member))) continue; + if (member.body) member.body.forEachChild(function cb(node) { + if (node.kind === 110 /* ThisKeyword */ ) addRef(node); + else if (!isFunctionLike(node) && !isClassLike(node)) node.forEachChild(cb); + }); + } + } + function findOwnConstructorReferences(classSymbol, sourceFile, addNode) { + const constructorSymbol = getClassConstructorSymbol(classSymbol); + if (constructorSymbol && constructorSymbol.declarations) for (const decl of constructorSymbol.declarations){ + const ctrKeyword = findChildOfKind(decl, 137 /* ConstructorKeyword */ , sourceFile); + Debug.assert(decl.kind === 176 /* Constructor */ && !!ctrKeyword); + addNode(ctrKeyword); + } + if (classSymbol.exports) classSymbol.exports.forEach((member)=>{ + const decl = member.valueDeclaration; + if (decl && decl.kind === 174 /* MethodDeclaration */ ) { + const body = decl.body; + if (body) forEachDescendantOfKind(body, 110 /* ThisKeyword */ , (thisKeyword)=>{ + if (isNewExpressionTarget(thisKeyword)) addNode(thisKeyword); + }); + } + }); + } + function getClassConstructorSymbol(classSymbol) { + return classSymbol.members && classSymbol.members.get("__constructor" /* Constructor */ ); + } + function findSuperConstructorAccesses(classDeclaration, addNode) { + const constructor = getClassConstructorSymbol(classDeclaration.symbol); + if (!(constructor && constructor.declarations)) return; + for (const decl of constructor.declarations){ + Debug.assert(decl.kind === 176 /* Constructor */ ); + const body = decl.body; + if (body) forEachDescendantOfKind(body, 108 /* SuperKeyword */ , (node)=>{ + if (isCallExpressionTarget(node)) addNode(node); + }); + } + } + function hasOwnConstructor(classDeclaration) { + return !!getClassConstructorSymbol(classDeclaration.symbol); + } + function findInheritedConstructorReferences(classDeclaration, state) { + if (hasOwnConstructor(classDeclaration)) return; + const classSymbol = classDeclaration.symbol; + const search = state.createSearch(/*location*/ void 0, classSymbol, /*comingFrom*/ void 0); + getReferencesInContainerOrFiles(classSymbol, state, search); + } + function addImplementationReferences(refNode, addReference2, state) { + if (isDeclarationName(refNode) && isImplementation(refNode.parent)) { + addReference2(refNode); + return; + } + if (refNode.kind !== 80 /* Identifier */ ) return; + if (refNode.parent.kind === 304 /* ShorthandPropertyAssignment */ ) getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference2); + const containingNode = getContainingNodeIfInHeritageClause(refNode); + if (containingNode) { + addReference2(containingNode); + return; + } + const typeNode = findAncestor(refNode, (a)=>!isQualifiedName(a.parent) && !isTypeNode(a.parent) && !isTypeElement(a.parent)); + const typeHavingNode = typeNode.parent; + if (hasType(typeHavingNode) && typeHavingNode.type === typeNode && state.markSeenContainingTypeReference(typeHavingNode)) { + if (hasInitializer(typeHavingNode)) addIfImplementation(typeHavingNode.initializer); + else if (isFunctionLike(typeHavingNode) && typeHavingNode.body) { + const body = typeHavingNode.body; + if (body.kind === 241 /* Block */ ) forEachReturnStatement(body, (returnStatement)=>{ + if (returnStatement.expression) addIfImplementation(returnStatement.expression); + }); + else addIfImplementation(body); + } else if (isAssertionExpression(typeHavingNode)) addIfImplementation(typeHavingNode.expression); + } + function addIfImplementation(e) { + if (isImplementationExpression(e)) addReference2(e); + } + } + function getContainingNodeIfInHeritageClause(node) { + return isIdentifier(node) || isPropertyAccessExpression(node) ? getContainingNodeIfInHeritageClause(node.parent) : isExpressionWithTypeArguments(node) ? tryCast(node.parent.parent, or(isClassLike, isInterfaceDeclaration)) : void 0; + } + function isImplementationExpression(node) { + switch(node.kind){ + case 217 /* ParenthesizedExpression */ : + return isImplementationExpression(node.expression); + case 219 /* ArrowFunction */ : + case 218 /* FunctionExpression */ : + case 210 /* ObjectLiteralExpression */ : + case 231 /* ClassExpression */ : + case 209 /* ArrayLiteralExpression */ : + return true; + default: + return false; + } + } + function explicitlyInheritsFrom(symbol, parent2, cachedResults, checker) { + if (symbol === parent2) return true; + const key = getSymbolId(symbol) + "," + getSymbolId(parent2); + const cached = cachedResults.get(key); + if (cached !== void 0) return cached; + cachedResults.set(key, false); + const inherits = !!symbol.declarations && symbol.declarations.some((declaration)=>getAllSuperTypeNodes(declaration).some((typeReference)=>{ + const type = checker.getTypeAtLocation(typeReference); + return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent2, cachedResults, checker); + })); + cachedResults.set(key, inherits); + return inherits; + } + function getReferencesForSuperKeyword(superKeyword) { + let searchSpaceNode = getSuperContainer(superKeyword, /*stopOnFunctions*/ false); + if (!searchSpaceNode) return void 0; + let staticFlag = 32 /* Static */ ; + switch(searchSpaceNode.kind){ + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 176 /* Constructor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + staticFlag &= getSyntacticModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; + break; + default: + return void 0; } - ]); - } - return result; - } - } - function isConvertableSignatureDeclaration(d) { - switch(d.kind){ - case 170 /* MethodSignature */ : - case 171 /* MethodDeclaration */ : - case 176 /* CallSignature */ : - case 173 /* Constructor */ : - case 177 /* ConstructSignature */ : - case 259 /* FunctionDeclaration */ : - return true; - } - return false; - } - function getConvertableOverloadListAtPosition(file, startPosition, program) { - const node = getTokenAtPosition(file, startPosition); - const containingDecl = findAncestor(node, isConvertableSignatureDeclaration); - if (!containingDecl) return; - if (isFunctionLikeDeclaration(containingDecl) && containingDecl.body && rangeContainsPosition(containingDecl.body, startPosition)) return; - const checker = program.getTypeChecker(); - const signatureSymbol = containingDecl.symbol; - if (!signatureSymbol) return; - const decls = signatureSymbol.declarations; - if (length(decls) <= 1) return; - if (!every(decls, (d)=>getSourceFileOfNode(d) === file)) return; - if (!isConvertableSignatureDeclaration(decls[0])) return; - const kindOne = decls[0].kind; - if (!every(decls, (d)=>d.kind === kindOne)) return; - const signatureDecls = decls; - if (some(signatureDecls, (d)=>!!d.typeParameters || some(d.parameters, (p)=>!!p.modifiers || !isIdentifier(p.name)))) return; - const signatures = mapDefined(signatureDecls, (d)=>checker.getSignatureFromDeclaration(d)); - if (length(signatures) !== length(decls)) return; - const returnOne = checker.getReturnTypeOfSignature(signatures[0]); - if (!every(signatures, (s)=>checker.getReturnTypeOfSignature(s) === returnOne)) return; - return signatureDecls; - } - var refactorName5, refactorDescription, functionOverloadAction; - var init_convertOverloadListToSingleSignature = __esm({ - "src/services/refactors/convertOverloadListToSingleSignature.ts" () { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName5 = "Convert overload list to single signature"; - refactorDescription = Diagnostics.Convert_overload_list_to_single_signature.message; - functionOverloadAction = { - name: refactorName5, - description: refactorDescription, - kind: "refactor.rewrite.function.overloadList" - }; - registerRefactor(refactorName5, { - kinds: [ - functionOverloadAction.kind - ], - getEditsForAction: getRefactorEditsToConvertOverloadsToOneSignature, - getAvailableActions: getRefactorActionsToConvertOverloadsToOneSignature - }); - } - }); - // src/services/refactors/addOrRemoveBracesToArrowFunction.ts - function getRefactorActionsToRemoveFunctionBraces(context) { - const { file: file , startPosition: startPosition , triggerReason: triggerReason } = context; - const info = getConvertibleArrowFunctionAtPosition(file, startPosition, triggerReason === "invoked"); - if (!info) return emptyArray; - if (!isRefactorErrorInfo(info)) return [ - { - name: refactorName6, - description: refactorDescription2, - actions: [ - info.addBraces ? addBracesAction : removeBracesAction - ] - } - ]; - if (context.preferences.provideRefactorNotApplicableReason) return [ - { - name: refactorName6, - description: refactorDescription2, - actions: [ - { - ...addBracesAction, - notApplicableReason: info.error - }, - { - ...removeBracesAction, - notApplicableReason: info.error + const sourceFile = searchSpaceNode.getSourceFile(); + const references = mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), (node)=>{ + if (node.kind !== 108 /* SuperKeyword */ ) return; + const container = getSuperContainer(node, /*stopOnFunctions*/ false); + return container && isStatic(container) === !!staticFlag && container.parent.symbol === searchSpaceNode.symbol ? nodeEntry(node) : void 0; + }); + return [ + { + definition: { + type: 0 /* Symbol */ , + symbol: searchSpaceNode.symbol + }, + references: references + } + ]; + } + function isParameterName(node) { + return node.kind === 80 /* Identifier */ && node.parent.kind === 169 /* Parameter */ && node.parent.name === node; + } + function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { + let searchSpaceNode = getThisContainer(thisOrSuperKeyword, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false); + let staticFlag = 32 /* Static */ ; + switch(searchSpaceNode.kind){ + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + if (isObjectLiteralMethod(searchSpaceNode)) { + staticFlag &= getSyntacticModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; + break; + } + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : + case 176 /* Constructor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + staticFlag &= getSyntacticModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; + break; + case 312 /* SourceFile */ : + if (isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) return void 0; + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + break; + default: + return void 0; } - ] - } - ]; - return emptyArray; - } - function getRefactorEditsToRemoveFunctionBraces(context, actionName2) { - const { file: file , startPosition: startPosition } = context; - const info = getConvertibleArrowFunctionAtPosition(file, startPosition); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const { expression: expression , returnStatement: returnStatement , func: func } = info; - let body; - if (actionName2 === addBracesAction.name) { - const returnStatement2 = factory.createReturnStatement(expression); - body = factory.createBlock([ - returnStatement2 - ], /* multiLine */ true); - copyLeadingComments(expression, returnStatement2, file, 3 /* MultiLineCommentTrivia */ , /* hasTrailingNewLine */ true); - } else if (actionName2 === removeBracesAction.name && returnStatement) { - const actualExpression = expression || factory.createVoidZero(); - body = needsParentheses(actualExpression) ? factory.createParenthesizedExpression(actualExpression) : actualExpression; - copyTrailingAsLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */ , /* hasTrailingNewLine */ false); - copyLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */ , /* hasTrailingNewLine */ false); - copyTrailingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */ , /* hasTrailingNewLine */ false); - } else Debug.fail("invalid action"); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t)=>{ - t.replaceNode(file, func.body, body); - }); - return { - renameFilename: void 0, - renameLocation: void 0, - edits: edits - }; - } - function getConvertibleArrowFunctionAtPosition(file, startPosition, considerFunctionBodies = true, kind) { - const node = getTokenAtPosition(file, startPosition); - const func = getContainingFunction(node); - if (!func) return { - error: getLocaleSpecificMessage(Diagnostics.Could_not_find_a_containing_arrow_function) - }; - if (!isArrowFunction(func)) return { - error: getLocaleSpecificMessage(Diagnostics.Containing_function_is_not_an_arrow_function) - }; - if (!rangeContainsRange(func, node) || rangeContainsRange(func.body, node) && !considerFunctionBodies) return void 0; - if (refactorKindBeginsWith(addBracesAction.kind, kind) && isExpression(func.body)) return { - func: func, - addBraces: true, - expression: func.body - }; - else if (refactorKindBeginsWith(removeBracesAction.kind, kind) && isBlock(func.body) && func.body.statements.length === 1) { - const firstStatement = first(func.body.statements); - if (isReturnStatement(firstStatement)) return { - func: func, - addBraces: false, - expression: firstStatement.expression, - returnStatement: firstStatement - }; - } - return void 0; - } - var refactorName6, refactorDescription2, addBracesAction, removeBracesAction; - var init_addOrRemoveBracesToArrowFunction = __esm({ - "src/services/refactors/addOrRemoveBracesToArrowFunction.ts" () { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName6 = "Add or remove braces in an arrow function"; - refactorDescription2 = Diagnostics.Add_or_remove_braces_in_an_arrow_function.message; - addBracesAction = { - name: "Add braces to arrow function", - description: Diagnostics.Add_braces_to_arrow_function.message, - kind: "refactor.rewrite.arrow.braces.add" - }; - removeBracesAction = { - name: "Remove braces from arrow function", - description: Diagnostics.Remove_braces_from_arrow_function.message, - kind: "refactor.rewrite.arrow.braces.remove" - }; - registerRefactor(refactorName6, { - kinds: [ - removeBracesAction.kind - ], - getEditsForAction: getRefactorEditsToRemoveFunctionBraces, - getAvailableActions: getRefactorActionsToRemoveFunctionBraces - }); - } - }); - // src/services/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.ts - var ts_refactor_addOrRemoveBracesToArrowFunction_exports = {}; - var init_ts_refactor_addOrRemoveBracesToArrowFunction = __esm({ - "src/services/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.ts" () { - "use strict"; - init_convertOverloadListToSingleSignature(); - init_addOrRemoveBracesToArrowFunction(); - } - }); - // src/services/refactors/convertArrowFunctionOrFunctionExpression.ts - function getRefactorActionsToConvertFunctionExpressions(context) { - const { file: file , startPosition: startPosition , program: program , kind: kind } = context; - const info = getFunctionInfo(file, startPosition, program); - if (!info) return emptyArray; - const { selectedVariableDeclaration: selectedVariableDeclaration , func: func } = info; - const possibleActions = []; - const errors = []; - if (refactorKindBeginsWith(toNamedFunctionAction.kind, kind)) { - const error = selectedVariableDeclaration || isArrowFunction(func) && isVariableDeclaration(func.parent) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_named_function); - if (error) errors.push({ - ...toNamedFunctionAction, - notApplicableReason: error - }); - else possibleActions.push(toNamedFunctionAction); - } - if (refactorKindBeginsWith(toAnonymousFunctionAction.kind, kind)) { - const error = !selectedVariableDeclaration && isArrowFunction(func) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_anonymous_function); - if (error) errors.push({ - ...toAnonymousFunctionAction, - notApplicableReason: error - }); - else possibleActions.push(toAnonymousFunctionAction); - } - if (refactorKindBeginsWith(toArrowFunctionAction.kind, kind)) { - const error = isFunctionExpression(func) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_arrow_function); - if (error) errors.push({ - ...toArrowFunctionAction, - notApplicableReason: error - }); - else possibleActions.push(toArrowFunctionAction); - } - return [ - { - name: refactorName7, - description: refactorDescription3, - actions: possibleActions.length === 0 && context.preferences.provideRefactorNotApplicableReason ? errors : possibleActions - } - ]; - } - function getRefactorEditsToConvertFunctionExpressions(context, actionName2) { - const { file: file , startPosition: startPosition , program: program } = context; - const info = getFunctionInfo(file, startPosition, program); - if (!info) return void 0; - const { func: func } = info; - const edits = []; - switch(actionName2){ - case toAnonymousFunctionAction.name: - edits.push(...getEditInfoForConvertToAnonymousFunction(context, func)); - break; - case toNamedFunctionAction.name: - const variableInfo = getVariableInfo(func); - if (!variableInfo) return void 0; - edits.push(...getEditInfoForConvertToNamedFunction(context, func, variableInfo)); - break; - case toArrowFunctionAction.name: - if (!isFunctionExpression(func)) return void 0; - edits.push(...getEditInfoForConvertToArrowFunction(context, func)); - break; - default: - return Debug.fail("invalid action"); - } - return { - renameFilename: void 0, - renameLocation: void 0, - edits: edits - }; - } - function containingThis(node) { - let containsThis = false; - node.forEachChild(function checkThis(child) { - if (isThis(child)) { - containsThis = true; - return; - } - if (!isClassLike(child) && !isFunctionDeclaration(child) && !isFunctionExpression(child)) forEachChild(child, checkThis); - }); - return containsThis; - } - function getFunctionInfo(file, startPosition, program) { - const token = getTokenAtPosition(file, startPosition); - const typeChecker = program.getTypeChecker(); - const func = tryGetFunctionFromVariableDeclaration(file, typeChecker, token.parent); - if (func && !containingThis(func.body) && !typeChecker.containsArgumentsReference(func)) return { - selectedVariableDeclaration: true, - func: func - }; - const maybeFunc = getContainingFunction(token); - if (maybeFunc && (isFunctionExpression(maybeFunc) || isArrowFunction(maybeFunc)) && !rangeContainsRange(maybeFunc.body, token) && !containingThis(maybeFunc.body) && !typeChecker.containsArgumentsReference(maybeFunc)) { - if (isFunctionExpression(maybeFunc) && isFunctionReferencedInFile(file, typeChecker, maybeFunc)) return void 0; - return { - selectedVariableDeclaration: false, - func: maybeFunc - }; - } - return void 0; - } - function isSingleVariableDeclaration(parent2) { - return isVariableDeclaration(parent2) || isVariableDeclarationList(parent2) && parent2.declarations.length === 1; - } - function tryGetFunctionFromVariableDeclaration(sourceFile, typeChecker, parent2) { - if (!isSingleVariableDeclaration(parent2)) return void 0; - const variableDeclaration = isVariableDeclaration(parent2) ? parent2 : first(parent2.declarations); - const initializer = variableDeclaration.initializer; - if (initializer && (isArrowFunction(initializer) || isFunctionExpression(initializer) && !isFunctionReferencedInFile(sourceFile, typeChecker, initializer))) return initializer; - return void 0; - } - function convertToBlock(body) { - if (isExpression(body)) { - const returnStatement = factory.createReturnStatement(body); - const file = body.getSourceFile(); - setTextRange(returnStatement, body); - suppressLeadingAndTrailingTrivia(returnStatement); - copyTrailingAsLeadingComments(body, returnStatement, file, /* commentKind */ void 0, /* hasTrailingNewLine */ true); - return factory.createBlock([ - returnStatement - ], /* multiLine */ true); - } else return body; - } - function getVariableInfo(func) { - const variableDeclaration = func.parent; - if (!isVariableDeclaration(variableDeclaration) || !isVariableDeclarationInVariableStatement(variableDeclaration)) return void 0; - const variableDeclarationList = variableDeclaration.parent; - const statement = variableDeclarationList.parent; - if (!isVariableDeclarationList(variableDeclarationList) || !isVariableStatement(statement) || !isIdentifier(variableDeclaration.name)) return void 0; - return { - variableDeclaration: variableDeclaration, - variableDeclarationList: variableDeclarationList, - statement: statement, - name: variableDeclaration.name - }; - } - function getEditInfoForConvertToAnonymousFunction(context, func) { - const { file: file } = context; - const body = convertToBlock(func.body); - const newNode = factory.createFunctionExpression(func.modifiers, func.asteriskToken, /* name */ void 0, func.typeParameters, func.parameters, func.type, body); - return ts_textChanges_exports.ChangeTracker.with(context, (t)=>t.replaceNode(file, func, newNode)); - } - function getEditInfoForConvertToNamedFunction(context, func, variableInfo) { - const { file: file } = context; - const body = convertToBlock(func.body); - const { variableDeclaration: variableDeclaration , variableDeclarationList: variableDeclarationList , statement: statement , name: name } = variableInfo; - suppressLeadingTrivia(statement); - const modifiersFlags = getCombinedModifierFlags(variableDeclaration) & 1 /* Export */ | getEffectiveModifierFlags(func); - const modifiers = factory.createModifiersFromModifierFlags(modifiersFlags); - const newNode = factory.createFunctionDeclaration(length(modifiers) ? modifiers : void 0, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); - if (variableDeclarationList.declarations.length === 1) return ts_textChanges_exports.ChangeTracker.with(context, (t)=>t.replaceNode(file, statement, newNode)); - else return ts_textChanges_exports.ChangeTracker.with(context, (t)=>{ - t.delete(file, variableDeclaration); - t.insertNodeAfter(file, statement, newNode); - }); - } - function getEditInfoForConvertToArrowFunction(context, func) { - const { file: file } = context; - const statements = func.body.statements; - const head = statements[0]; - let body; - if (canBeConvertedToExpression(func.body, head)) { - body = head.expression; - suppressLeadingAndTrailingTrivia(body); - copyComments(head, body); - } else body = func.body; - const newNode = factory.createArrowFunction(func.modifiers, func.typeParameters, func.parameters, func.type, factory.createToken(38 /* EqualsGreaterThanToken */ ), body); - return ts_textChanges_exports.ChangeTracker.with(context, (t)=>t.replaceNode(file, func, newNode)); - } - function canBeConvertedToExpression(body, head) { - return body.statements.length === 1 && isReturnStatement(head) && !!head.expression; - } - function isFunctionReferencedInFile(sourceFile, typeChecker, node) { - return !!node.name && ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(node.name, typeChecker, sourceFile); - } - var refactorName7, refactorDescription3, toAnonymousFunctionAction, toNamedFunctionAction, toArrowFunctionAction; - var init_convertArrowFunctionOrFunctionExpression = __esm({ - "src/services/refactors/convertArrowFunctionOrFunctionExpression.ts" () { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName7 = "Convert arrow function or function expression"; - refactorDescription3 = getLocaleSpecificMessage(Diagnostics.Convert_arrow_function_or_function_expression); - toAnonymousFunctionAction = { - name: "Convert to anonymous function", - description: getLocaleSpecificMessage(Diagnostics.Convert_to_anonymous_function), - kind: "refactor.rewrite.function.anonymous" - }; - toNamedFunctionAction = { - name: "Convert to named function", - description: getLocaleSpecificMessage(Diagnostics.Convert_to_named_function), - kind: "refactor.rewrite.function.named" - }; - toArrowFunctionAction = { - name: "Convert to arrow function", - description: getLocaleSpecificMessage(Diagnostics.Convert_to_arrow_function), - kind: "refactor.rewrite.function.arrow" - }; - registerRefactor(refactorName7, { - kinds: [ - toAnonymousFunctionAction.kind, - toNamedFunctionAction.kind, - toArrowFunctionAction.kind - ], - getEditsForAction: getRefactorEditsToConvertFunctionExpressions, - getAvailableActions: getRefactorActionsToConvertFunctionExpressions - }); - } - }); - // src/services/_namespaces/ts.refactor.convertArrowFunctionOrFunctionExpression.ts - var ts_refactor_convertArrowFunctionOrFunctionExpression_exports = {}; - var init_ts_refactor_convertArrowFunctionOrFunctionExpression = __esm({ - "src/services/_namespaces/ts.refactor.convertArrowFunctionOrFunctionExpression.ts" () { - "use strict"; - init_convertArrowFunctionOrFunctionExpression(); - } - }); - // src/services/refactors/convertParamsToDestructuredObject.ts - function getRefactorActionsToConvertParametersToDestructuredObject(context) { - const { file: file , startPosition: startPosition } = context; - const isJSFile = isSourceFileJS(file); - if (isJSFile) return emptyArray; - const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker()); - if (!functionDeclaration) return emptyArray; - return [ - { - name: refactorName8, - description: refactorDescription4, - actions: [ - toDestructuredAction - ] - } - ]; - } - function getRefactorEditsToConvertParametersToDestructuredObject(context, actionName2) { - Debug.assert(actionName2 === refactorName8, "Unexpected action name"); - const { file: file , startPosition: startPosition , program: program , cancellationToken: cancellationToken , host: host } = context; - const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker()); - if (!functionDeclaration || !cancellationToken) return void 0; - const groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken); - if (groupedReferences.valid) { - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange36(file, program, host, t, functionDeclaration, groupedReferences)); - return { - renameFilename: void 0, - renameLocation: void 0, - edits: edits - }; - } - return { - edits: [] - }; - } - function doChange36(sourceFile, program, host, changes, functionDeclaration, groupedReferences) { - const signature = groupedReferences.signature; - const newFunctionDeclarationParams = map(createNewParameters(functionDeclaration, program, host), (param)=>getSynthesizedDeepClone(param)); - if (signature) { - const newSignatureParams = map(createNewParameters(signature, program, host), (param)=>getSynthesizedDeepClone(param)); - replaceParameters(signature, newSignatureParams); - } - replaceParameters(functionDeclaration, newFunctionDeclarationParams); - const functionCalls = sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ (a, b)=>compareValues(a.pos, b.pos)); - for (const call of functionCalls)if (call.arguments && call.arguments.length) { - const newArgument = getSynthesizedDeepClone(createNewArgument(functionDeclaration, call.arguments), /*includeTrivia*/ true); - changes.replaceNodeRange(getSourceFileOfNode(call), first(call.arguments), last(call.arguments), newArgument, { - leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, - trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include - }); - } - function replaceParameters(declarationOrSignature, parameterDeclarations) { - changes.replaceNodeRangeWithNodes(sourceFile, first(declarationOrSignature.parameters), last(declarationOrSignature.parameters), parameterDeclarations, { - joiner: ", ", - // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter - indentation: 0, - leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, - trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include - }); - } - } - function getGroupedReferences(functionDeclaration, program, cancellationToken) { - const functionNames = getFunctionNames(functionDeclaration); - const classNames = isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : []; - const names = deduplicate([ - ...functionNames, - ...classNames - ], equateValues); - const checker = program.getTypeChecker(); - const references = flatMap(names, /*mapfn*/ (name)=>ts_FindAllReferences_exports.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken)); - const groupedReferences = groupReferences(references); - if (!every(groupedReferences.declarations, /*callback*/ (decl)=>contains(names, decl))) groupedReferences.valid = false; - return groupedReferences; - function groupReferences(referenceEntries) { - const classReferences = { - accessExpressions: [], - typeUsages: [] - }; - const groupedReferences2 = { - functionCalls: [], - declarations: [], - classReferences: classReferences, - valid: true - }; - const functionSymbols = map(functionNames, getSymbolTargetAtLocation); - const classSymbols = map(classNames, getSymbolTargetAtLocation); - const isConstructor = isConstructorDeclaration(functionDeclaration); - const contextualSymbols = map(functionNames, (name)=>getSymbolForContextualType(name, checker)); - for (const entry of referenceEntries){ - if (entry.kind === ts_FindAllReferences_exports.EntryKind.Span) { - groupedReferences2.valid = false; - continue; + const references = flatMap(searchSpaceNode.kind === 312 /* SourceFile */ ? sourceFiles : [ + searchSpaceNode.getSourceFile() + ], (sourceFile)=>{ + cancellationToken.throwIfCancellationRequested(); + return getPossibleSymbolReferenceNodes(sourceFile, "this", isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter((node)=>{ + if (!isThis(node)) return false; + const container = getThisContainer(node, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false); + if (!canHaveSymbol(container)) return false; + switch(searchSpaceNode.kind){ + case 218 /* FunctionExpression */ : + case 262 /* FunctionDeclaration */ : + return searchSpaceNode.symbol === container.symbol; + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + return isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; + case 231 /* ClassExpression */ : + case 263 /* ClassDeclaration */ : + case 210 /* ObjectLiteralExpression */ : + return container.parent && canHaveSymbol(container.parent) && searchSpaceNode.symbol === container.parent.symbol && isStatic(container) === !!staticFlag; + case 312 /* SourceFile */ : + return container.kind === 312 /* SourceFile */ && !isExternalModule(container) && !isParameterName(node); + } + }); + }).map((n)=>nodeEntry(n)); + const thisParameter = firstDefined(references, (r)=>isParameter(r.node.parent) ? r.node : void 0); + return [ + { + definition: { + type: 3 /* This */ , + node: thisParameter || thisOrSuperKeyword + }, + references: references + } + ]; + } + function getReferencesForStringLiteral(node, sourceFiles, checker, cancellationToken) { + const type = getContextualTypeFromParentOrAncestorTypeNode(node, checker); + const references = flatMap(sourceFiles, (sourceFile)=>{ + cancellationToken.throwIfCancellationRequested(); + return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), (ref)=>{ + if (isStringLiteralLike(ref) && ref.text === node.text) { + if (type) { + const refType = getContextualTypeFromParentOrAncestorTypeNode(ref, checker); + if (type !== checker.getStringType() && type === refType) return nodeEntry(ref, 2 /* StringLiteral */ ); + } else return isNoSubstitutionTemplateLiteral(ref) && !rangeIsOnSingleLine(ref, sourceFile) ? void 0 : nodeEntry(ref, 2 /* StringLiteral */ ); + } + }); + }); + return [ + { + definition: { + type: 4 /* String */ , + node: node + }, + references: references + } + ]; } - if (contains(contextualSymbols, getSymbolTargetAtLocation(entry.node))) { - if (isValidMethodSignature(entry.node.parent)) { - groupedReferences2.signature = entry.node.parent; - continue; + function populateSearchSymbolSet(symbol, location, checker, isForRename, providePrefixAndSuffixText, implementations) { + const result = []; + forEachRelatedSymbol(symbol, location, checker, isForRename, !(isForRename && providePrefixAndSuffixText), (sym, root, base)=>{ + if (base) { + if (isStaticSymbol(symbol) !== isStaticSymbol(base)) base = void 0; + } + result.push(base || root || sym); + }, // when try to find implementation, implementations is true, and not allowed to find base class + /*allowBaseTypes*/ ()=>!implementations); + return result; + } + function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, onlyIncludeBindingElementAtReferenceLocation, cbSymbol, allowBaseTypes) { + const containingObjectLiteralElement = getContainingObjectLiteralElement(location); + if (containingObjectLiteralElement) { + const shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); + if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ void 0, /*baseSymbol*/ void 0, 3 /* SearchedLocalFoundProperty */ ); + const contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + const res2 = contextualType && firstDefined(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), (sym)=>fromRoot(sym, 4 /* SearchedPropertyFoundLocal */ )); + if (res2) return res2; + const propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); + const res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ void 0, /*baseSymbol*/ void 0, 4 /* SearchedPropertyFoundLocal */ ); + if (res1) return res1; + const res22 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ void 0, /*baseSymbol*/ void 0, 3 /* SearchedLocalFoundProperty */ ); + if (res22) return res22; } - const call = entryToFunctionCall(entry); - if (call) { - groupedReferences2.functionCalls.push(call); - continue; + const aliasedSymbol = getMergedAliasedSymbolOfNamespaceExportDeclaration(location, symbol, checker); + if (aliasedSymbol) { + const res2 = cbSymbol(aliasedSymbol, /*rootSymbol*/ void 0, /*baseSymbol*/ void 0, 1 /* Node */ ); + if (res2) return res2; } - } - const contextualSymbol = getSymbolForContextualType(entry.node, checker); - if (contextualSymbol && contains(contextualSymbols, contextualSymbol)) { - const decl = entryToDeclaration(entry); - if (decl) { - groupedReferences2.declarations.push(decl); - continue; + const res = fromRoot(symbol); + if (res) return res; + if (symbol.valueDeclaration && isParameterPropertyDeclaration(symbol.valueDeclaration, symbol.valueDeclaration.parent)) { + const paramProps = checker.getSymbolsOfParameterPropertyDeclaration(cast(symbol.valueDeclaration, isParameter), symbol.name); + Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */ ) && !!(paramProps[1].flags & 4 /* Property */ )); + return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); } - } - if (contains(functionSymbols, getSymbolTargetAtLocation(entry.node)) || isNewExpressionTarget(entry.node)) { - const importOrExportReference = entryToImportOrExport(entry); - if (importOrExportReference) continue; - const decl = entryToDeclaration(entry); - if (decl) { - groupedReferences2.declarations.push(decl); - continue; + const exportSpecifier = getDeclarationOfKind(symbol, 281 /* ExportSpecifier */ ); + if (!isForRenamePopulateSearchSymbolSet || exportSpecifier && !exportSpecifier.propertyName) { + const localSymbol = exportSpecifier && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); + if (localSymbol) { + const res2 = cbSymbol(localSymbol, /*rootSymbol*/ void 0, /*baseSymbol*/ void 0, 1 /* Node */ ); + if (res2) return res2; + } } - const call = entryToFunctionCall(entry); - if (call) { - groupedReferences2.functionCalls.push(call); - continue; + if (!isForRenamePopulateSearchSymbolSet) { + let bindingElementPropertySymbol; + if (onlyIncludeBindingElementAtReferenceLocation) bindingElementPropertySymbol = isObjectBindingElementWithoutPropertyName(location.parent) ? getPropertySymbolFromBindingElement(checker, location.parent) : void 0; + else bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */ ); } - } - if (isConstructor && contains(classSymbols, getSymbolTargetAtLocation(entry.node))) { - const importOrExportReference = entryToImportOrExport(entry); - if (importOrExportReference) continue; - const decl = entryToDeclaration(entry); - if (decl) { - groupedReferences2.declarations.push(decl); - continue; + Debug.assert(isForRenamePopulateSearchSymbolSet); + const includeOriginalSymbolOfBindingElement = onlyIncludeBindingElementAtReferenceLocation; + if (includeOriginalSymbolOfBindingElement) { + const bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */ ); } - const accessExpression = entryToAccessExpression(entry); - if (accessExpression) { - classReferences.accessExpressions.push(accessExpression); - continue; + function fromRoot(sym, kind) { + return firstDefined(checker.getRootSymbols(sym), (rootSymbol)=>cbSymbol(sym, rootSymbol, /*baseSymbol*/ void 0, kind) || (rootSymbol.parent && rootSymbol.parent.flags & 96 /* Interface */ && allowBaseTypes(rootSymbol) ? getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, (base)=>cbSymbol(sym, rootSymbol, base, kind)) : void 0)); } - if (isClassDeclaration(functionDeclaration.parent)) { - const type = entryToType(entry); - if (type) { - classReferences.typeUsages.push(type); - continue; - } + function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol2, checker2) { + const bindingElement = getDeclarationOfKind(symbol2, 208 /* BindingElement */ ); + if (bindingElement && isObjectBindingElementWithoutPropertyName(bindingElement)) return getPropertySymbolFromBindingElement(checker2, bindingElement); } } - groupedReferences2.valid = false; - } - return groupedReferences2; - } - function getSymbolTargetAtLocation(node) { - const symbol = checker.getSymbolAtLocation(node); - return symbol && getSymbolTarget(symbol, checker); - } - } - function getSymbolForContextualType(node, checker) { - const element = getContainingObjectLiteralElement(node); - if (element) { - const contextualType = checker.getContextualTypeForObjectLiteralElement(element); - const symbol = contextualType == null ? void 0 : contextualType.getSymbol(); - if (symbol && !(getCheckFlags(symbol) & 6 /* Synthetic */ )) return symbol; - } - } - function entryToImportOrExport(entry) { - const node = entry.node; - if (isImportSpecifier(node.parent) || isImportClause(node.parent) || isImportEqualsDeclaration(node.parent) || isNamespaceImport(node.parent)) return node; - if (isExportSpecifier(node.parent) || isExportAssignment(node.parent)) return node; - return void 0; - } - function entryToDeclaration(entry) { - if (isDeclaration(entry.node.parent)) return entry.node; - return void 0; - } - function entryToFunctionCall(entry) { - if (entry.node.parent) { - const functionReference = entry.node; - const parent2 = functionReference.parent; - switch(parent2.kind){ - case 210 /* CallExpression */ : - case 211 /* NewExpression */ : - const callOrNewExpression = tryCast(parent2, isCallOrNewExpression); - if (callOrNewExpression && callOrNewExpression.expression === functionReference) return callOrNewExpression; - break; - case 208 /* PropertyAccessExpression */ : - const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression); - if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) { - const callOrNewExpression2 = tryCast(propertyAccessExpression.parent, isCallOrNewExpression); - if (callOrNewExpression2 && callOrNewExpression2.expression === propertyAccessExpression) return callOrNewExpression2; + function getPropertySymbolsFromBaseTypes(symbol, propertyName, checker, cb) { + const seen = /* @__PURE__ */ new Map(); + return recur(symbol); + function recur(symbol2) { + if (!(symbol2.flags & 96 /* Interface */ ) || !addToSeen(seen, getSymbolId(symbol2))) return; + return firstDefined(symbol2.declarations, (declaration)=>firstDefined(getAllSuperTypeNodes(declaration), (typeReference)=>{ + const type = checker.getTypeAtLocation(typeReference); + const propertySymbol = type && type.symbol && checker.getPropertyOfType(type, propertyName); + return type && propertySymbol && (firstDefined(checker.getRootSymbols(propertySymbol), cb) || recur(type.symbol)); + })); } - break; - case 209 /* ElementAccessExpression */ : - const elementAccessExpression = tryCast(parent2, isElementAccessExpression); - if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) { - const callOrNewExpression2 = tryCast(elementAccessExpression.parent, isCallOrNewExpression); - if (callOrNewExpression2 && callOrNewExpression2.expression === elementAccessExpression) return callOrNewExpression2; + } + function isStaticSymbol(symbol) { + if (!symbol.valueDeclaration) return false; + const modifierFlags = getEffectiveModifierFlags(symbol.valueDeclaration); + return !!(modifierFlags & 32 /* Static */ ); + } + function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { + const { checker: checker } = state; + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, /*onlyIncludeBindingElementAtReferenceLocation*/ state.options.use !== 2 /* Rename */ || !!state.options.providePrefixAndSuffixTextForRename, (sym, rootSymbol, baseSymbol, kind)=>{ + if (baseSymbol) { + if (isStaticSymbol(referenceSymbol) !== isStaticSymbol(baseSymbol)) baseSymbol = void 0; + } + return search.includes(baseSymbol || rootSymbol || sym) ? { + symbol: rootSymbol && !(getCheckFlags(sym) & 6 /* Synthetic */ ) ? rootSymbol : sym, + kind: kind + } : void 0; + }, /*allowBaseTypes*/ (rootSymbol)=>!(search.parents && !search.parents.some((parent2)=>explicitlyInheritsFrom(rootSymbol.parent, parent2, state.inheritsFromCache, checker)))); + } + function getIntersectingMeaningFromDeclarations(node, symbol) { + let meaning = getMeaningFromLocation(node); + const { declarations: declarations } = symbol; + if (declarations) { + let lastIterationMeaning; + do { + lastIterationMeaning = meaning; + for (const declaration of declarations){ + const declarationMeaning = getMeaningFromDeclaration(declaration); + if (declarationMeaning & meaning) meaning |= declarationMeaning; + } + }while (meaning !== lastIterationMeaning); } - break; - } - } - return void 0; - } - function entryToAccessExpression(entry) { - if (entry.node.parent) { - const reference = entry.node; - const parent2 = reference.parent; - switch(parent2.kind){ - case 208 /* PropertyAccessExpression */ : - const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression); - if (propertyAccessExpression && propertyAccessExpression.expression === reference) return propertyAccessExpression; - break; - case 209 /* ElementAccessExpression */ : - const elementAccessExpression = tryCast(parent2, isElementAccessExpression); - if (elementAccessExpression && elementAccessExpression.expression === reference) return elementAccessExpression; - break; - } - } - return void 0; - } - function entryToType(entry) { - const reference = entry.node; - if (getMeaningFromLocation(reference) === 2 /* Type */ || isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) return reference; - return void 0; - } - function getFunctionDeclarationAtPosition(file, startPosition, checker) { - const node = getTouchingToken(file, startPosition); - const functionDeclaration = getContainingFunctionDeclaration(node); - if (isTopLevelJSDoc(node)) return void 0; - if (functionDeclaration && isValidFunctionDeclaration(functionDeclaration, checker) && rangeContainsRange(functionDeclaration, node) && !(functionDeclaration.body && rangeContainsRange(functionDeclaration.body, node))) return functionDeclaration; - return void 0; - } - function isTopLevelJSDoc(node) { - const containingJSDoc = findAncestor(node, isJSDocNode); - if (containingJSDoc) { - const containingNonJSDoc = findAncestor(containingJSDoc, (n)=>!isJSDocNode(n)); - return !!containingNonJSDoc && isFunctionLikeDeclaration(containingNonJSDoc); - } - return false; - } - function isValidMethodSignature(node) { - return isMethodSignature(node) && (isInterfaceDeclaration(node.parent) || isTypeLiteralNode(node.parent)); - } - function isValidFunctionDeclaration(functionDeclaration, checker) { - var _a2; - if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) return false; - switch(functionDeclaration.kind){ - case 259 /* FunctionDeclaration */ : - return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker); - case 171 /* MethodDeclaration */ : - if (isObjectLiteralExpression(functionDeclaration.parent)) { - const contextualSymbol = getSymbolForContextualType(functionDeclaration.name, checker); - return ((_a2 = contextualSymbol == null ? void 0 : contextualSymbol.declarations) == null ? void 0 : _a2.length) === 1 && isSingleImplementation(functionDeclaration, checker); + return meaning; } - return isSingleImplementation(functionDeclaration, checker); - case 173 /* Constructor */ : - if (isClassDeclaration(functionDeclaration.parent)) return hasNameOrDefault(functionDeclaration.parent) && isSingleImplementation(functionDeclaration, checker); - else return isValidVariableDeclaration(functionDeclaration.parent.parent) && isSingleImplementation(functionDeclaration, checker); - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - return isValidVariableDeclaration(functionDeclaration.parent); - } - return false; - } - function isSingleImplementation(functionDeclaration, checker) { - return !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); - } - function hasNameOrDefault(functionOrClassDeclaration) { - if (!functionOrClassDeclaration.name) { - const defaultKeyword = findModifier(functionOrClassDeclaration, 88 /* DefaultKeyword */ ); - return !!defaultKeyword; - } - return true; - } - function isValidParameterNodeArray(parameters, checker) { - return getRefactorableParametersLength(parameters) >= minimumParameterLength && every(parameters, /*callback*/ (paramDecl)=>isValidParameterDeclaration(paramDecl, checker)); - } - function isValidParameterDeclaration(parameterDeclaration, checker) { - if (isRestParameter(parameterDeclaration)) { - const type = checker.getTypeAtLocation(parameterDeclaration); - if (!checker.isArrayType(type) && !checker.isTupleType(type)) return false; - } - return !parameterDeclaration.modifiers && isIdentifier(parameterDeclaration.name); - } - function isValidVariableDeclaration(node) { - return isVariableDeclaration(node) && isVarConst(node) && isIdentifier(node.name) && !node.type; - } - function hasThisParameter(parameters) { - return parameters.length > 0 && isThis(parameters[0].name); - } - function getRefactorableParametersLength(parameters) { - if (hasThisParameter(parameters)) return parameters.length - 1; - return parameters.length; - } - function getRefactorableParameters(parameters) { - if (hasThisParameter(parameters)) parameters = factory.createNodeArray(parameters.slice(1), parameters.hasTrailingComma); - return parameters; - } - function createPropertyOrShorthandAssignment(name, initializer) { - if (isIdentifier(initializer) && getTextOfIdentifierOrLiteral(initializer) === name) return factory.createShorthandPropertyAssignment(name); - return factory.createPropertyAssignment(name, initializer); - } - function createNewArgument(functionDeclaration, functionArguments) { - const parameters = getRefactorableParameters(functionDeclaration.parameters); - const hasRestParameter2 = isRestParameter(last(parameters)); - const nonRestArguments = hasRestParameter2 ? functionArguments.slice(0, parameters.length - 1) : functionArguments; - const properties = map(nonRestArguments, (arg, i)=>{ - const parameterName = getParameterName(parameters[i]); - const property = createPropertyOrShorthandAssignment(parameterName, arg); - suppressLeadingAndTrailingTrivia(property.name); - if (isPropertyAssignment(property)) suppressLeadingAndTrailingTrivia(property.initializer); - copyComments(arg, property); - return property; - }); - if (hasRestParameter2 && functionArguments.length >= parameters.length) { - const restArguments = functionArguments.slice(parameters.length - 1); - const restProperty = factory.createPropertyAssignment(getParameterName(last(parameters)), factory.createArrayLiteralExpression(restArguments)); - properties.push(restProperty); - } - const objectLiteral = factory.createObjectLiteralExpression(properties, /*multiLine*/ false); - return objectLiteral; - } - function createNewParameters(functionDeclaration, program, host) { - const checker = program.getTypeChecker(); - const refactorableParameters = getRefactorableParameters(functionDeclaration.parameters); - const bindingElements = map(refactorableParameters, createBindingElementFromParameterDeclaration); - const objectParameterName = factory.createObjectBindingPattern(bindingElements); - const objectParameterType = createParameterTypeNode(refactorableParameters); - let objectInitializer; - if (every(refactorableParameters, isOptionalParameter)) objectInitializer = factory.createObjectLiteralExpression(); - const objectParameter = factory.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, objectParameterName, /*questionToken*/ void 0, objectParameterType, objectInitializer); - if (hasThisParameter(functionDeclaration.parameters)) { - const thisParameter = functionDeclaration.parameters[0]; - const newThisParameter = factory.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, thisParameter.name, /*questionToken*/ void 0, thisParameter.type); - suppressLeadingAndTrailingTrivia(newThisParameter.name); - copyComments(thisParameter.name, newThisParameter.name); - if (thisParameter.type) { - suppressLeadingAndTrailingTrivia(newThisParameter.type); - copyComments(thisParameter.type, newThisParameter.type); - } - return factory.createNodeArray([ - newThisParameter, - objectParameter - ]); - } - return factory.createNodeArray([ - objectParameter - ]); - function createBindingElementFromParameterDeclaration(parameterDeclaration) { - const element = factory.createBindingElement(/*dotDotDotToken*/ void 0, /*propertyName*/ void 0, getParameterName(parameterDeclaration), isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? factory.createArrayLiteralExpression() : parameterDeclaration.initializer); - suppressLeadingAndTrailingTrivia(element); - if (parameterDeclaration.initializer && element.initializer) copyComments(parameterDeclaration.initializer, element.initializer); - return element; - } - function createParameterTypeNode(parameters) { - const members = map(parameters, createPropertySignatureFromParameterDeclaration); - const typeNode = addEmitFlags(factory.createTypeLiteralNode(members), 1 /* SingleLine */ ); - return typeNode; - } - function createPropertySignatureFromParameterDeclaration(parameterDeclaration) { - let parameterType = parameterDeclaration.type; - if (!parameterType && (parameterDeclaration.initializer || isRestParameter(parameterDeclaration))) parameterType = getTypeNode3(parameterDeclaration); - const propertySignature = factory.createPropertySignature(/*modifiers*/ void 0, getParameterName(parameterDeclaration), isOptionalParameter(parameterDeclaration) ? factory.createToken(57 /* QuestionToken */ ) : parameterDeclaration.questionToken, parameterType); - suppressLeadingAndTrailingTrivia(propertySignature); - copyComments(parameterDeclaration.name, propertySignature.name); - if (parameterDeclaration.type && propertySignature.type) copyComments(parameterDeclaration.type, propertySignature.type); - return propertySignature; + Core2.getIntersectingMeaningFromDeclarations = getIntersectingMeaningFromDeclarations; + function isImplementation(node) { + return !!(node.flags & 33554432 /* Ambient */ ) ? !(isInterfaceDeclaration(node) || isTypeAliasDeclaration(node)) : isVariableLike(node) ? hasInitializer(node) : isFunctionLikeDeclaration(node) ? !!node.body : isClassLike(node) || isModuleOrEnumDeclaration(node); + } + function getReferenceEntriesForShorthandPropertyAssignment(node, checker, addReference2) { + const refSymbol = checker.getSymbolAtLocation(node); + const shorthandSymbol = checker.getShorthandAssignmentValueSymbol(refSymbol.valueDeclaration); + if (shorthandSymbol) { + for (const declaration of shorthandSymbol.getDeclarations())if (getMeaningFromDeclaration(declaration) & 1 /* Value */ ) addReference2(declaration); + } + } + Core2.getReferenceEntriesForShorthandPropertyAssignment = getReferenceEntriesForShorthandPropertyAssignment; + function forEachDescendantOfKind(node, kind, action) { + forEachChild(node, (child)=>{ + if (child.kind === kind) action(child); + forEachDescendantOfKind(child, kind, action); + }); + } + function tryGetClassByExtendingIdentifier(node) { + return tryGetClassExtendingExpressionWithTypeArguments(climbPastPropertyAccess(node).parent); + } + function getParentSymbolsOfPropertyAccess(location, symbol, checker) { + const propertyAccessExpression = isRightSideOfPropertyAccess(location) ? location.parent : void 0; + const lhsType = propertyAccessExpression && checker.getTypeAtLocation(propertyAccessExpression.expression); + const res = mapDefined(lhsType && (lhsType.isUnionOrIntersection() ? lhsType.types : lhsType.symbol === symbol.parent ? void 0 : [ + lhsType + ]), (t)=>t.symbol && t.symbol.flags & 96 /* Interface */ ? t.symbol : void 0); + return res.length === 0 ? void 0 : res; + } + function isForRenameWithPrefixAndSuffixText(options) { + return options.use === 2 /* Rename */ && options.providePrefixAndSuffixTextForRename; + } + })(Core || (Core = {})); } - function getTypeNode3(node) { - const type = checker.getTypeAtLocation(node); - return getTypeNodeIfAccessible(type, node, program, host); + }); + // src/services/_namespaces/ts.FindAllReferences.ts + var ts_FindAllReferences_exports = {}; + __export(ts_FindAllReferences_exports, { + Core: ()=>Core, + DefinitionKind: ()=>DefinitionKind, + EntryKind: ()=>EntryKind, + ExportKind: ()=>ExportKind2, + FindReferencesUse: ()=>FindReferencesUse, + ImportExport: ()=>ImportExport, + createImportTracker: ()=>createImportTracker, + findModuleReferences: ()=>findModuleReferences, + findReferenceOrRenameEntries: ()=>findReferenceOrRenameEntries, + findReferencedSymbols: ()=>findReferencedSymbols, + getContextNode: ()=>getContextNode, + getExportInfo: ()=>getExportInfo, + getImplementationsAtPosition: ()=>getImplementationsAtPosition, + getImportOrExportSymbol: ()=>getImportOrExportSymbol, + getReferenceEntriesForNode: ()=>getReferenceEntriesForNode, + getTextSpanOfEntry: ()=>getTextSpanOfEntry, + isContextWithStartAndEndNode: ()=>isContextWithStartAndEndNode, + isDeclarationOfSymbol: ()=>isDeclarationOfSymbol, + isWriteAccessForReference: ()=>isWriteAccessForReference, + nodeEntry: ()=>nodeEntry, + toContextSpan: ()=>toContextSpan, + toHighlightSpan: ()=>toHighlightSpan, + toReferenceEntry: ()=>toReferenceEntry, + toRenameLocation: ()=>toRenameLocation + }); + var init_ts_FindAllReferences = __esm({ + "src/services/_namespaces/ts.FindAllReferences.ts" () { + "use strict"; + init_importTracker(); + init_findAllReferences(); } - function isOptionalParameter(parameterDeclaration) { - if (isRestParameter(parameterDeclaration)) { - const type = checker.getTypeAtLocation(parameterDeclaration); - return !checker.isTupleType(type); - } - return checker.isOptionalParameter(parameterDeclaration); + }); + // src/services/goToDefinition.ts + function getDefinitionAtPosition(program, sourceFile, position, searchOtherFilesOnly, stopAtAlias) { + var _a, _b; + const resolvedRef = getReferenceAtPosition(sourceFile, position, program); + const fileReferenceDefinition = resolvedRef && [ + getDefinitionInfoForFileReference(resolvedRef.reference.fileName, resolvedRef.fileName, resolvedRef.unverified) + ] || emptyArray; + if (resolvedRef == null ? void 0 : resolvedRef.file) return fileReferenceDefinition; + const node = getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) return void 0; + const { parent: parent2 } = node; + const typeChecker = program.getTypeChecker(); + if (node.kind === 164 /* OverrideKeyword */ || isIdentifier(node) && isJSDocOverrideTag(parent2) && parent2.tagName === node) return getDefinitionFromOverriddenMember(typeChecker, node) || emptyArray; + if (isJumpStatementTarget(node)) { + const label = getTargetLabel(node.parent, node.text); + return label ? [ + createDefinitionInfoFromName(typeChecker, label, "label" /* label */ , node.text, /*containerName*/ void 0) + ] : void 0; } - } - function getParameterName(paramDeclaration) { - return getTextOfIdentifierOrLiteral(paramDeclaration.name); - } - function getClassNames(constructorDeclaration) { - switch(constructorDeclaration.parent.kind){ - case 260 /* ClassDeclaration */ : - const classDeclaration = constructorDeclaration.parent; - if (classDeclaration.name) return [ - classDeclaration.name - ]; - const defaultModifier = Debug.checkDefined(findModifier(classDeclaration, 88 /* DefaultKeyword */ ), "Nameless class declaration should be a default export"); - return [ - defaultModifier - ]; - case 228 /* ClassExpression */ : - const classExpression = constructorDeclaration.parent; - const variableDeclaration = constructorDeclaration.parent.parent; - const className = classExpression.name; - if (className) return [ - className, - variableDeclaration.name - ]; - return [ - variableDeclaration.name - ]; + if (node.kind === 107 /* ReturnKeyword */ ) { + const functionDeclaration = findAncestor(node.parent, (n)=>isClassStaticBlockDeclaration(n) ? "quit" : isFunctionLikeDeclaration(n)); + return functionDeclaration ? [ + createDefinitionFromSignatureDeclaration(typeChecker, functionDeclaration) + ] : void 0; } - } - function getFunctionNames(functionDeclaration) { - switch(functionDeclaration.kind){ - case 259 /* FunctionDeclaration */ : - if (functionDeclaration.name) return [ - functionDeclaration.name - ]; - const defaultModifier = Debug.checkDefined(findModifier(functionDeclaration, 88 /* DefaultKeyword */ ), "Nameless function declaration should be a default export"); - return [ - defaultModifier - ]; - case 171 /* MethodDeclaration */ : - return [ - functionDeclaration.name - ]; - case 173 /* Constructor */ : - const ctrKeyword = Debug.checkDefined(findChildOfKind(functionDeclaration, 135 /* ConstructorKeyword */ , functionDeclaration.getSourceFile()), "Constructor declaration should have constructor keyword"); - if (functionDeclaration.parent.kind === 228 /* ClassExpression */ ) { - const variableDeclaration = functionDeclaration.parent.parent; - return [ - variableDeclaration.name, - ctrKeyword - ]; - } - return [ - ctrKeyword - ]; - case 216 /* ArrowFunction */ : - return [ - functionDeclaration.parent.name - ]; - case 215 /* FunctionExpression */ : - if (functionDeclaration.name) return [ - functionDeclaration.name, - functionDeclaration.parent.name - ]; - return [ - functionDeclaration.parent.name - ]; - default: - return Debug.assertNever(functionDeclaration, `Unexpected function declaration kind ${functionDeclaration.kind}`); + if (node.kind === 135 /* AwaitKeyword */ ) { + const functionDeclaration = findAncestor(node, (n)=>isFunctionLikeDeclaration(n)); + const isAsyncFunction2 = functionDeclaration && some(functionDeclaration.modifiers, (node2)=>node2.kind === 134 /* AsyncKeyword */ ); + return isAsyncFunction2 ? [ + createDefinitionFromSignatureDeclaration(typeChecker, functionDeclaration) + ] : void 0; } - } - var refactorName8, minimumParameterLength, refactorDescription4, toDestructuredAction; - var init_convertParamsToDestructuredObject = __esm({ - "src/services/refactors/convertParamsToDestructuredObject.ts" () { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName8 = "Convert parameters to destructured object"; - minimumParameterLength = 1; - refactorDescription4 = getLocaleSpecificMessage(Diagnostics.Convert_parameters_to_destructured_object); - toDestructuredAction = { - name: refactorName8, - description: refactorDescription4, - kind: "refactor.rewrite.parameters.toDestructured" - }; - registerRefactor(refactorName8, { - kinds: [ - toDestructuredAction.kind - ], - getEditsForAction: getRefactorEditsToConvertParametersToDestructuredObject, - getAvailableActions: getRefactorActionsToConvertParametersToDestructuredObject + if (node.kind === 127 /* YieldKeyword */ ) { + const functionDeclaration = findAncestor(node, (n)=>isFunctionLikeDeclaration(n)); + const isGeneratorFunction = functionDeclaration && functionDeclaration.asteriskToken; + return isGeneratorFunction ? [ + createDefinitionFromSignatureDeclaration(typeChecker, functionDeclaration) + ] : void 0; + } + if (isStaticModifier(node) && isClassStaticBlockDeclaration(node.parent)) { + const classDecl = node.parent.parent; + const { symbol: symbol2, failedAliasResolution: failedAliasResolution2 } = getSymbol(classDecl, typeChecker, stopAtAlias); + const staticBlocks = filter(classDecl.members, isClassStaticBlockDeclaration); + const containerName = symbol2 ? typeChecker.symbolToString(symbol2, classDecl) : ""; + const sourceFile2 = node.getSourceFile(); + return map(staticBlocks, (staticBlock)=>{ + let { pos: pos } = moveRangePastModifiers(staticBlock); + pos = skipTrivia(sourceFile2.text, pos); + return createDefinitionInfoFromName(typeChecker, staticBlock, "constructor" /* constructorImplementationElement */ , "static {}", containerName, /*unverified*/ false, failedAliasResolution2, { + start: pos, + length: 6 + }); }); } - }); - // src/services/_namespaces/ts.refactor.convertParamsToDestructuredObject.ts - var ts_refactor_convertParamsToDestructuredObject_exports = {}; - var init_ts_refactor_convertParamsToDestructuredObject = __esm({ - "src/services/_namespaces/ts.refactor.convertParamsToDestructuredObject.ts" () { - "use strict"; - init_convertParamsToDestructuredObject(); + let { symbol: symbol, failedAliasResolution: failedAliasResolution } = getSymbol(node, typeChecker, stopAtAlias); + let fallbackNode = node; + if (searchOtherFilesOnly && failedAliasResolution) { + const importDeclaration = forEach([ + node, + ...(symbol == null ? void 0 : symbol.declarations) || emptyArray + ], (n)=>findAncestor(n, isAnyImportOrBareOrAccessedRequire)); + const moduleSpecifier = importDeclaration && tryGetModuleSpecifierFromDeclaration(importDeclaration); + if (moduleSpecifier) { + ({ symbol: symbol, failedAliasResolution: failedAliasResolution } = getSymbol(moduleSpecifier, typeChecker, stopAtAlias)); + fallbackNode = moduleSpecifier; + } } - }); - // src/services/refactors/convertStringOrTemplateLiteral.ts - function getRefactorActionsToConvertToTemplateString(context) { - const { file: file , startPosition: startPosition } = context; - const node = getNodeOrParentOfParentheses(file, startPosition); - const maybeBinary = getParentBinaryExpression(node); - const refactorInfo = { - name: refactorName9, - description: refactorDescription5, - actions: [] - }; - if (isBinaryExpression(maybeBinary) && treeToArray(maybeBinary).isValidConcatenation) { - refactorInfo.actions.push(convertStringAction); - return [ - refactorInfo + if (!symbol && isModuleSpecifierLike(fallbackNode)) { + const ref = (_b = (_a = sourceFile.resolvedModules) == null ? void 0 : _a.get(fallbackNode.text, getModeForUsageLocation(sourceFile, fallbackNode))) == null ? void 0 : _b.resolvedModule; + if (ref) return [ + { + name: fallbackNode.text, + fileName: ref.resolvedFileName, + containerName: void 0, + containerKind: void 0, + kind: "script" /* scriptElement */ , + textSpan: createTextSpan(0, 0), + failedAliasResolution: failedAliasResolution, + isAmbient: isDeclarationFileName(ref.resolvedFileName), + unverified: fallbackNode !== node + } ]; - } else if (context.preferences.provideRefactorNotApplicableReason) { - refactorInfo.actions.push({ - ...convertStringAction, - notApplicableReason: getLocaleSpecificMessage(Diagnostics.Can_only_convert_string_concatenation) - }); - return [ - refactorInfo + } + if (!symbol) return concatenate(fileReferenceDefinition, getDefinitionInfoForIndexSignatures(node, typeChecker)); + if (searchOtherFilesOnly && every(symbol.declarations, (d)=>d.getSourceFile().fileName === sourceFile.fileName)) return void 0; + const calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); + if (calledDeclaration && !(isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { + const sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration, failedAliasResolution); + if (typeChecker.getRootSymbols(symbol).some((s)=>symbolMatchesSignature(s, calledDeclaration))) return [ + sigInfo ]; + else { + const defs = getDefinitionFromSymbol(typeChecker, symbol, node, failedAliasResolution, calledDeclaration) || emptyArray; + return node.kind === 108 /* SuperKeyword */ ? [ + sigInfo, + ...defs + ] : [ + ...defs, + sigInfo + ]; + } } - return emptyArray; - } - function getNodeOrParentOfParentheses(file, startPosition) { - const node = getTokenAtPosition(file, startPosition); - const nestedBinary = getParentBinaryExpression(node); - const isNonStringBinary = !treeToArray(nestedBinary).isValidConcatenation; - if (isNonStringBinary && isParenthesizedExpression(nestedBinary.parent) && isBinaryExpression(nestedBinary.parent.parent)) return nestedBinary.parent.parent; - return node; - } - function getRefactorEditsToConvertToTemplateString(context, actionName2) { - const { file: file , startPosition: startPosition } = context; - const node = getNodeOrParentOfParentheses(file, startPosition); - switch(actionName2){ - case refactorDescription5: - return { - edits: getEditsForToTemplateLiteral(context, node) - }; - default: - return Debug.fail("invalid action"); + if (node.parent.kind === 304 /* ShorthandPropertyAssignment */ ) { + const shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); + const definitions = (shorthandSymbol == null ? void 0 : shorthandSymbol.declarations) ? shorthandSymbol.declarations.map((decl)=>createDefinitionInfo(decl, typeChecker, shorthandSymbol, node, /*unverified*/ false, failedAliasResolution)) : emptyArray; + return concatenate(definitions, getDefinitionFromObjectLiteralElement(typeChecker, node)); } - } - function getEditsForToTemplateLiteral(context, node) { - const maybeBinary = getParentBinaryExpression(node); - const file = context.file; - const templateLiteral = nodesToTemplate(treeToArray(maybeBinary), file); - const trailingCommentRanges = getTrailingCommentRanges(file.text, maybeBinary.end); - if (trailingCommentRanges) { - const lastComment = trailingCommentRanges[trailingCommentRanges.length - 1]; - const trailingRange = { - pos: trailingCommentRanges[0].pos, - end: lastComment.end - }; - return ts_textChanges_exports.ChangeTracker.with(context, (t)=>{ - t.deleteRange(file, trailingRange); - t.replaceNode(file, maybeBinary, templateLiteral); + if (isPropertyName(node) && isBindingElement(parent2) && isObjectBindingPattern(parent2.parent) && node === (parent2.propertyName || parent2.name)) { + const name = getNameFromPropertyName(node); + const type = typeChecker.getTypeAtLocation(parent2.parent); + return name === void 0 ? emptyArray : flatMap(type.isUnion() ? type.types : [ + type + ], (t)=>{ + const prop = t.getProperty(name); + return prop && getDefinitionFromSymbol(typeChecker, prop, node); }); - } else return ts_textChanges_exports.ChangeTracker.with(context, (t)=>t.replaceNode(file, maybeBinary, templateLiteral)); + } + const objectLiteralElementDefinition = getDefinitionFromObjectLiteralElement(typeChecker, node); + return concatenate(fileReferenceDefinition, objectLiteralElementDefinition.length ? objectLiteralElementDefinition : getDefinitionFromSymbol(typeChecker, symbol, node, failedAliasResolution)); } - function isNotEqualsOperator(node) { - return node.operatorToken.kind !== 63 /* EqualsToken */ ; + function symbolMatchesSignature(s, calledDeclaration) { + var _a; + return s === calledDeclaration.symbol || s === calledDeclaration.symbol.parent || isAssignmentExpression(calledDeclaration.parent) || !isCallLikeExpression(calledDeclaration.parent) && s === ((_a = tryCast(calledDeclaration.parent, canHaveSymbol)) == null ? void 0 : _a.symbol); } - function getParentBinaryExpression(expr) { - const container = findAncestor(expr.parent, (n)=>{ - switch(n.kind){ - case 208 /* PropertyAccessExpression */ : - case 209 /* ElementAccessExpression */ : - return false; - case 225 /* TemplateExpression */ : - case 223 /* BinaryExpression */ : - return !(isBinaryExpression(n.parent) && isNotEqualsOperator(n.parent)); - default: - return "quit"; - } - }); - return container || expr; + function getDefinitionFromObjectLiteralElement(typeChecker, node) { + const element = getContainingObjectLiteralElement(node); + if (element) { + const contextualType = element && typeChecker.getContextualType(element.parent); + if (contextualType) return flatMap(getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), (propertySymbol)=>getDefinitionFromSymbol(typeChecker, propertySymbol, node)); + } + return emptyArray; } - function treeToArray(current) { - const loop = (current2)=>{ - if (!isBinaryExpression(current2)) return { - nodes: [ - current2 - ], - operators: [], - validOperators: true, - hasString: isStringLiteral(current2) || isNoSubstitutionTemplateLiteral(current2) - }; - const { nodes: nodes2 , operators: operators2 , hasString: leftHasString , validOperators: leftOperatorValid } = loop(current2.left); - if (!(leftHasString || isStringLiteral(current2.right) || isTemplateExpression(current2.right))) return { - nodes: [ - current2 - ], - operators: [], - hasString: false, - validOperators: true + function getDefinitionFromOverriddenMember(typeChecker, node) { + const classElement = findAncestor(node, isClassElement); + if (!(classElement && classElement.name)) return; + const baseDeclaration = findAncestor(classElement, isClassLike); + if (!baseDeclaration) return; + const baseTypeNode = getEffectiveBaseTypeNode(baseDeclaration); + if (!baseTypeNode) return; + const expression = skipParentheses(baseTypeNode.expression); + const base = isClassExpression(expression) ? expression.symbol : typeChecker.getSymbolAtLocation(expression); + if (!base) return; + const name = unescapeLeadingUnderscores(getTextOfPropertyName(classElement.name)); + const symbol = hasStaticModifier(classElement) ? typeChecker.getPropertyOfType(typeChecker.getTypeOfSymbol(base), name) : typeChecker.getPropertyOfType(typeChecker.getDeclaredTypeOfSymbol(base), name); + if (!symbol) return; + return getDefinitionFromSymbol(typeChecker, symbol, node); + } + function getReferenceAtPosition(sourceFile, position, program) { + var _a, _b, _c, _d; + const referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); + if (referencePath) { + const file = program.getSourceFileFromReference(sourceFile, referencePath); + return file && { + reference: referencePath, + fileName: file.fileName, + file: file, + unverified: false }; - const currentOperatorValid = current2.operatorToken.kind === 39 /* PlusToken */ ; - const validOperators2 = leftOperatorValid && currentOperatorValid; - nodes2.push(current2.right); - operators2.push(current2.operatorToken); - return { - nodes: nodes2, - operators: operators2, - hasString: true, - validOperators: validOperators2 + } + const typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + if (typeReferenceDirective) { + const reference = (_a = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName, typeReferenceDirective.resolutionMode || sourceFile.impliedNodeFormat)) == null ? void 0 : _a.resolvedTypeReferenceDirective; + const file = reference && program.getSourceFile(reference.resolvedFileName); + return file && { + reference: typeReferenceDirective, + fileName: file.fileName, + file: file, + unverified: false }; - }; - const { nodes: nodes , operators: operators , validOperators: validOperators , hasString: hasString } = loop(current); - return { - nodes: nodes, - operators: operators, - isValidConcatenation: validOperators && hasString - }; - } - function escapeRawStringForTemplate(s) { - return s.replace(/\\.|[$`]/g, (m)=>m[0] === "\\" ? m : "\\" + m); - } - function getRawTextOfTemplate(node) { - const rightShaving = isTemplateHead(node) || isTemplateMiddle(node) ? -2 : -1; - return getTextOfNode(node).slice(1, rightShaving); - } - function concatConsecutiveString(index, nodes) { - const indexes = []; - let text = "", rawText = ""; - while(index < nodes.length){ - const node = nodes[index]; - if (isStringLiteralLike(node)) { - text += node.text; - rawText += escapeRawStringForTemplate(getTextOfNode(node).slice(1, -1)); - indexes.push(index); - index++; - } else if (isTemplateExpression(node)) { - text += node.head.text; - rawText += getRawTextOfTemplate(node.head); - break; - } else break; } - return [ - index, - text, - rawText, - indexes - ]; - } - function nodesToTemplate({ nodes: nodes , operators: operators }, file) { - const copyOperatorComments = copyTrailingOperatorComments(operators, file); - const copyCommentFromStringLiterals = copyCommentFromMultiNode(nodes, file, copyOperatorComments); - const [begin, headText, rawHeadText, headIndexes] = concatConsecutiveString(0, nodes); - if (begin === nodes.length) { - const noSubstitutionTemplateLiteral = factory.createNoSubstitutionTemplateLiteral(headText, rawHeadText); - copyCommentFromStringLiterals(headIndexes, noSubstitutionTemplateLiteral); - return noSubstitutionTemplateLiteral; + const libReferenceDirective = findReferenceInPosition(sourceFile.libReferenceDirectives, position); + if (libReferenceDirective) { + const file = program.getLibFileFromReference(libReferenceDirective); + return file && { + reference: libReferenceDirective, + fileName: file.fileName, + file: file, + unverified: false + }; } - const templateSpans = []; - const templateHead = factory.createTemplateHead(headText, rawHeadText); - copyCommentFromStringLiterals(headIndexes, templateHead); - for(let i = begin; i < nodes.length; i++){ - const currentNode = getExpressionFromParenthesesOrExpression(nodes[i]); - copyOperatorComments(i, currentNode); - const [newIndex, subsequentText, rawSubsequentText, stringIndexes] = concatConsecutiveString(i + 1, nodes); - i = newIndex - 1; - const isLast = i === nodes.length - 1; - if (isTemplateExpression(currentNode)) { - const spans = map(currentNode.templateSpans, (span, index)=>{ - copyExpressionComments(span); - const isLastSpan = index === currentNode.templateSpans.length - 1; - const text = span.literal.text + (isLastSpan ? subsequentText : ""); - const rawText = getRawTextOfTemplate(span.literal) + (isLastSpan ? rawSubsequentText : ""); - return factory.createTemplateSpan(span.expression, isLast && isLastSpan ? factory.createTemplateTail(text, rawText) : factory.createTemplateMiddle(text, rawText)); - }); - templateSpans.push(...spans); - } else { - const templatePart = isLast ? factory.createTemplateTail(subsequentText, rawSubsequentText) : factory.createTemplateMiddle(subsequentText, rawSubsequentText); - copyCommentFromStringLiterals(stringIndexes, templatePart); - templateSpans.push(factory.createTemplateSpan(currentNode, templatePart)); + if ((_b = sourceFile.resolvedModules) == null ? void 0 : _b.size()) { + const node = getTouchingToken(sourceFile, position); + if (isModuleSpecifierLike(node) && isExternalModuleNameRelative(node.text) && sourceFile.resolvedModules.has(node.text, getModeForUsageLocation(sourceFile, node))) { + const verifiedFileName = (_d = (_c = sourceFile.resolvedModules.get(node.text, getModeForUsageLocation(sourceFile, node))) == null ? void 0 : _c.resolvedModule) == null ? void 0 : _d.resolvedFileName; + const fileName = verifiedFileName || resolvePath(getDirectoryPath(sourceFile.fileName), node.text); + return { + file: program.getSourceFile(fileName), + fileName: fileName, + reference: { + pos: node.getStart(), + end: node.getEnd(), + fileName: node.text + }, + unverified: !verifiedFileName + }; } } - return factory.createTemplateExpression(templateHead, templateSpans); - } - function copyExpressionComments(node) { - const file = node.getSourceFile(); - copyTrailingComments(node, node.expression, file, 3 /* MultiLineCommentTrivia */ , /* hasTrailingNewLine */ false); - copyTrailingAsLeadingComments(node.expression, node.expression, file, 3 /* MultiLineCommentTrivia */ , /* hasTrailingNewLine */ false); + return void 0; } - function getExpressionFromParenthesesOrExpression(node) { - if (isParenthesizedExpression(node)) { - copyExpressionComments(node); - node = node.expression; + function shouldUnwrapFirstTypeArgumentTypeDefinitionFromTypeReference(typeChecker, type) { + const referenceName = type.symbol.name; + if (!typesWithUnwrappedTypeArguments.has(referenceName)) return false; + const globalType = typeChecker.resolveName(referenceName, /*location*/ void 0, 788968 /* Type */ , /*excludeGlobals*/ false); + return !!globalType && globalType === type.target.symbol; + } + function shouldUnwrapFirstTypeArgumentTypeDefinitionFromAlias(typeChecker, type) { + if (!type.aliasSymbol) return false; + const referenceName = type.aliasSymbol.name; + if (!typesWithUnwrappedTypeArguments.has(referenceName)) return false; + const globalType = typeChecker.resolveName(referenceName, /*location*/ void 0, 788968 /* Type */ , /*excludeGlobals*/ false); + return !!globalType && globalType === type.aliasSymbol; + } + function getFirstTypeArgumentDefinitions(typeChecker, type, node, failedAliasResolution) { + var _a, _b; + if (!!(getObjectFlags(type) & 4 /* Reference */ ) && shouldUnwrapFirstTypeArgumentTypeDefinitionFromTypeReference(typeChecker, type)) return definitionFromType(typeChecker.getTypeArguments(type)[0], typeChecker, node, failedAliasResolution); + if (shouldUnwrapFirstTypeArgumentTypeDefinitionFromAlias(typeChecker, type) && type.aliasTypeArguments) return definitionFromType(type.aliasTypeArguments[0], typeChecker, node, failedAliasResolution); + if (getObjectFlags(type) & 32 /* Mapped */ && type.target && shouldUnwrapFirstTypeArgumentTypeDefinitionFromAlias(typeChecker, type.target)) { + const declaration = (_b = (_a = type.aliasSymbol) == null ? void 0 : _a.declarations) == null ? void 0 : _b[0]; + if (declaration && isTypeAliasDeclaration(declaration) && isTypeReferenceNode(declaration.type) && declaration.type.typeArguments) return definitionFromType(typeChecker.getTypeAtLocation(declaration.type.typeArguments[0]), typeChecker, node, failedAliasResolution); } - return node; + return []; } - var refactorName9, refactorDescription5, convertStringAction, copyTrailingOperatorComments, copyCommentFromMultiNode; - var init_convertStringOrTemplateLiteral = __esm({ - "src/services/refactors/convertStringOrTemplateLiteral.ts" () { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName9 = "Convert to template string"; - refactorDescription5 = getLocaleSpecificMessage(Diagnostics.Convert_to_template_string); - convertStringAction = { - name: refactorName9, - description: refactorDescription5, - kind: "refactor.rewrite.string" - }; - registerRefactor(refactorName9, { - kinds: [ - convertStringAction.kind - ], - getEditsForAction: getRefactorEditsToConvertToTemplateString, - getAvailableActions: getRefactorActionsToConvertToTemplateString - }); - copyTrailingOperatorComments = (operators, file)=>(index, targetNode)=>{ - if (index < operators.length) copyTrailingComments(operators[index], targetNode, file, 3 /* MultiLineCommentTrivia */ , /* hasTrailingNewLine */ false); - }; - copyCommentFromMultiNode = (nodes, file, copyOperatorComments)=>(indexes, targetNode)=>{ - while(indexes.length > 0){ - const index = indexes.shift(); - copyTrailingComments(nodes[index], targetNode, file, 3 /* MultiLineCommentTrivia */ , /* hasTrailingNewLine */ false); - copyOperatorComments(index, targetNode); - } - }; - } - }); - // src/services/_namespaces/ts.refactor.convertStringOrTemplateLiteral.ts - var ts_refactor_convertStringOrTemplateLiteral_exports = {}; - var init_ts_refactor_convertStringOrTemplateLiteral = __esm({ - "src/services/_namespaces/ts.refactor.convertStringOrTemplateLiteral.ts" () { - "use strict"; - init_convertStringOrTemplateLiteral(); - } - }); - // src/services/refactors/convertToOptionalChainExpression.ts - function getRefactorActionsToConvertToOptionalChain(context) { - const info = getInfo20(context, context.triggerReason === "invoked"); - if (!info) return emptyArray; - if (!isRefactorErrorInfo(info)) return [ - { - name: refactorName10, - description: convertToOptionalChainExpressionMessage, - actions: [ - toOptionalChainAction - ] - } - ]; - if (context.preferences.provideRefactorNotApplicableReason) return [ - { - name: refactorName10, - description: convertToOptionalChainExpressionMessage, - actions: [ - { - ...toOptionalChainAction, - notApplicableReason: info.error - } - ] - } + function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { + const node = getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) return void 0; + if (isImportMeta(node.parent) && node.parent.name === node) return definitionFromType(typeChecker.getTypeAtLocation(node.parent), typeChecker, node.parent, /*failedAliasResolution*/ false); + const { symbol: symbol, failedAliasResolution: failedAliasResolution } = getSymbol(node, typeChecker, /*stopAtAlias*/ false); + if (!symbol) return void 0; + const typeAtLocation = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + const returnType = tryGetReturnTypeOfFunction(symbol, typeAtLocation, typeChecker); + const fromReturnType = returnType && definitionFromType(returnType, typeChecker, node, failedAliasResolution); + const [resolvedType, typeDefinitions] = fromReturnType && fromReturnType.length !== 0 ? [ + returnType, + fromReturnType + ] : [ + typeAtLocation, + definitionFromType(typeAtLocation, typeChecker, node, failedAliasResolution) ]; - return emptyArray; - } - function getRefactorEditsToConvertToOptionalChain(context, actionName2) { - const info = getInfo20(context); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange37(context.file, context.program.getTypeChecker(), t, info, actionName2)); - return { - edits: edits, - renameFilename: void 0, - renameLocation: void 0 - }; - } - function isValidExpression(node) { - return isBinaryExpression(node) || isConditionalExpression(node); - } - function isValidStatement(node) { - return isExpressionStatement(node) || isReturnStatement(node) || isVariableStatement(node); + return typeDefinitions.length ? [ + ...getFirstTypeArgumentDefinitions(typeChecker, resolvedType, node, failedAliasResolution), + ...typeDefinitions + ] : !(symbol.flags & 111551 /* Value */ ) && symbol.flags & 788968 /* Type */ ? getDefinitionFromSymbol(typeChecker, skipAlias(symbol, typeChecker), node, failedAliasResolution) : void 0; } - function isValidExpressionOrStatement(node) { - return isValidExpression(node) || isValidStatement(node); + function definitionFromType(type, checker, node, failedAliasResolution) { + return flatMap(type.isUnion() && !(type.flags & 32 /* Enum */ ) ? type.types : [ + type + ], (t)=>t.symbol && getDefinitionFromSymbol(checker, t.symbol, node, failedAliasResolution)); } - function getInfo20(context, considerEmptySpans = true) { - const { file: file , program: program } = context; - const span = getRefactorContextSpan(context); - const forEmptySpan = span.length === 0; - if (forEmptySpan && !considerEmptySpans) return void 0; - const startToken = getTokenAtPosition(file, span.start); - const endToken = findTokenOnLeftOfPosition(file, span.start + span.length); - const adjustedSpan = createTextSpanFromBounds(startToken.pos, endToken && endToken.end >= startToken.pos ? endToken.getEnd() : startToken.getEnd()); - const parent2 = forEmptySpan ? getValidParentNodeOfEmptySpan(startToken) : getValidParentNodeContainingSpan(startToken, adjustedSpan); - const expression = parent2 && isValidExpressionOrStatement(parent2) ? getExpression(parent2) : void 0; - if (!expression) return { - error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) - }; - const checker = program.getTypeChecker(); - return isConditionalExpression(expression) ? getConditionalInfo(expression, checker) : getBinaryInfo(expression); + function tryGetReturnTypeOfFunction(symbol, type, checker) { + if (type.symbol === symbol || // At `const f = () => {}`, the symbol is `f` and the type symbol is at `() => {}` + symbol.valueDeclaration && type.symbol && isVariableDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.initializer === type.symbol.valueDeclaration) { + const sigs = type.getCallSignatures(); + if (sigs.length === 1) return checker.getReturnTypeOfSignature(first(sigs)); + } + return void 0; } - function getConditionalInfo(expression, checker) { - const condition = expression.condition; - const finalExpression = getFinalExpressionInChain(expression.whenTrue); - if (!finalExpression || checker.isNullableType(checker.getTypeAtLocation(finalExpression))) return { - error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) + function getDefinitionAndBoundSpan(program, sourceFile, position) { + const definitions = getDefinitionAtPosition(program, sourceFile, position); + if (!definitions || definitions.length === 0) return void 0; + const comment = findReferenceInPosition(sourceFile.referencedFiles, position) || findReferenceInPosition(sourceFile.typeReferenceDirectives, position) || findReferenceInPosition(sourceFile.libReferenceDirectives, position); + if (comment) return { + definitions: definitions, + textSpan: createTextSpanFromRange(comment) }; - if ((isPropertyAccessExpression(condition) || isIdentifier(condition)) && getMatchingStart(condition, finalExpression.expression)) return { - finalExpression: finalExpression, - occurrences: [ - condition - ], - expression: expression + const node = getTouchingPropertyName(sourceFile, position); + const textSpan = createTextSpan(node.getStart(), node.getWidth()); + return { + definitions: definitions, + textSpan: textSpan }; - else if (isBinaryExpression(condition)) { - const occurrences = getOccurrencesInExpression(finalExpression.expression, condition); - return occurrences ? { - finalExpression: finalExpression, - occurrences: occurrences, - expression: expression - } : { - error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) + } + function getDefinitionInfoForIndexSignatures(node, checker) { + return mapDefined(checker.getIndexInfosAtLocation(node), (info)=>info.declaration && createDefinitionFromSignatureDeclaration(checker, info.declaration)); + } + function getSymbol(node, checker, stopAtAlias) { + const symbol = checker.getSymbolAtLocation(node); + let failedAliasResolution = false; + if ((symbol == null ? void 0 : symbol.declarations) && symbol.flags & 2097152 /* Alias */ && !stopAtAlias && shouldSkipAlias(node, symbol.declarations[0])) { + const aliased = checker.getAliasedSymbol(symbol); + if (aliased.declarations) return { + symbol: aliased }; + else failedAliasResolution = true; } - } - function getBinaryInfo(expression) { - if (expression.operatorToken.kind !== 55 /* AmpersandAmpersandToken */ ) return { - error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_logical_AND_access_chains) - }; - const finalExpression = getFinalExpressionInChain(expression.right); - if (!finalExpression) return { - error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) - }; - const occurrences = getOccurrencesInExpression(finalExpression.expression, expression.left); - return occurrences ? { - finalExpression: finalExpression, - occurrences: occurrences, - expression: expression - } : { - error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) + return { + symbol: symbol, + failedAliasResolution: failedAliasResolution }; } - function getOccurrencesInExpression(matchTo, expression) { - const occurrences = []; - while(isBinaryExpression(expression) && expression.operatorToken.kind === 55 /* AmpersandAmpersandToken */ ){ - const match = getMatchingStart(skipParentheses(matchTo), skipParentheses(expression.right)); - if (!match) break; - occurrences.push(match); - matchTo = match; - expression = expression.left; - } - const finalMatch = getMatchingStart(matchTo, expression); - if (finalMatch) occurrences.push(finalMatch); - return occurrences.length > 0 ? occurrences : void 0; + function shouldSkipAlias(node, declaration) { + if (node.kind !== 80 /* Identifier */ ) return false; + if (node.parent === declaration) return true; + if (declaration.kind === 274 /* NamespaceImport */ ) return false; + return true; } - function getMatchingStart(chain, subchain) { - if (!isIdentifier(subchain) && !isPropertyAccessExpression(subchain) && !isElementAccessExpression(subchain)) return void 0; - return chainStartsWith(chain, subchain) ? subchain : void 0; + function isExpandoDeclaration(node) { + if (!isAssignmentDeclaration(node)) return false; + const containingAssignment = findAncestor(node, (p)=>{ + if (isAssignmentExpression(p)) return true; + if (!isAssignmentDeclaration(p)) return "quit"; + return false; + }); + return !!containingAssignment && getAssignmentDeclarationKind(containingAssignment) === 5 /* Property */ ; } - function chainStartsWith(chain, subchain) { - while(isCallExpression(chain) || isPropertyAccessExpression(chain) || isElementAccessExpression(chain)){ - if (getTextOfChainNode(chain) === getTextOfChainNode(subchain)) break; - chain = chain.expression; + function getDefinitionFromSymbol(typeChecker, symbol, node, failedAliasResolution, excludeDeclaration) { + const filteredDeclarations = filter(symbol.declarations, (d)=>d !== excludeDeclaration); + const withoutExpandos = filter(filteredDeclarations, (d)=>!isExpandoDeclaration(d)); + const results = some(withoutExpandos) ? withoutExpandos : filteredDeclarations; + return getConstructSignatureDefinition() || getCallSignatureDefinition() || map(results, (declaration)=>createDefinitionInfo(declaration, typeChecker, symbol, node, /*unverified*/ false, failedAliasResolution)); + function getConstructSignatureDefinition() { + if (symbol.flags & 32 /* Class */ && !(symbol.flags & 19 /* Variable */ ) && (isNewExpressionTarget(node) || node.kind === 137 /* ConstructorKeyword */ )) { + const cls = find(filteredDeclarations, isClassLike) || Debug.fail("Expected declaration to have at least one class-like declaration"); + return getSignatureDefinition(cls.members, /*selectConstructors*/ true); + } } - while(isPropertyAccessExpression(chain) && isPropertyAccessExpression(subchain) || isElementAccessExpression(chain) && isElementAccessExpression(subchain)){ - if (getTextOfChainNode(chain) !== getTextOfChainNode(subchain)) return false; - chain = chain.expression; - subchain = subchain.expression; + function getCallSignatureDefinition() { + return isCallOrNewExpressionTarget(node) || isNameOfFunctionDeclaration(node) ? getSignatureDefinition(filteredDeclarations, /*selectConstructors*/ false) : void 0; + } + function getSignatureDefinition(signatureDeclarations, selectConstructors) { + if (!signatureDeclarations) return void 0; + const declarations = signatureDeclarations.filter(selectConstructors ? isConstructorDeclaration : isFunctionLike); + const declarationsWithBody = declarations.filter((d)=>!!d.body); + return declarations.length ? declarationsWithBody.length !== 0 ? declarationsWithBody.map((x)=>createDefinitionInfo(x, typeChecker, symbol, node)) : [ + createDefinitionInfo(last(declarations), typeChecker, symbol, node, /*unverified*/ false, failedAliasResolution) + ] : void 0; } - return isIdentifier(chain) && isIdentifier(subchain) && chain.getText() === subchain.getText(); } - function getTextOfChainNode(node) { - if (isIdentifier(node) || isStringOrNumericLiteralLike(node)) return node.getText(); - if (isPropertyAccessExpression(node)) return getTextOfChainNode(node.name); - if (isElementAccessExpression(node)) return getTextOfChainNode(node.argumentExpression); - return void 0; + function createDefinitionInfo(declaration, checker, symbol, node, unverified, failedAliasResolution) { + const symbolName2 = checker.symbolToString(symbol); + const symbolKind = ts_SymbolDisplay_exports.getSymbolKind(checker, symbol, node); + const containerName = symbol.parent ? checker.symbolToString(symbol.parent, node) : ""; + return createDefinitionInfoFromName(checker, declaration, symbolKind, symbolName2, containerName, unverified, failedAliasResolution); } - function getValidParentNodeContainingSpan(node, span) { - while(node.parent){ - if (isValidExpressionOrStatement(node) && span.length !== 0 && node.end >= span.start + span.length) return node; - node = node.parent; + function createDefinitionInfoFromName(checker, declaration, symbolKind, symbolName2, containerName, unverified, failedAliasResolution, textSpan) { + const sourceFile = declaration.getSourceFile(); + if (!textSpan) { + const name = getNameOfDeclaration(declaration) || declaration; + textSpan = createTextSpanFromNode(name, sourceFile); } - return void 0; + return { + fileName: sourceFile.fileName, + textSpan: textSpan, + kind: symbolKind, + name: symbolName2, + containerKind: void 0, + containerName: // TODO: GH#18217 + containerName, + ...ts_FindAllReferences_exports.toContextSpan(textSpan, sourceFile, ts_FindAllReferences_exports.getContextNode(declaration)), + isLocal: !isDefinitionVisible(checker, declaration), + isAmbient: !!(declaration.flags & 33554432 /* Ambient */ ), + unverified: unverified, + failedAliasResolution: failedAliasResolution + }; } - function getValidParentNodeOfEmptySpan(node) { - while(node.parent){ - if (isValidExpressionOrStatement(node) && !isValidExpressionOrStatement(node.parent)) return node; - node = node.parent; + function isDefinitionVisible(checker, declaration) { + if (checker.isDeclarationVisible(declaration)) return true; + if (!declaration.parent) return false; + if (hasInitializer(declaration.parent) && declaration.parent.initializer === declaration) return isDefinitionVisible(checker, declaration.parent); + switch(declaration.kind){ + case 172 /* PropertyDeclaration */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 174 /* MethodDeclaration */ : + if (hasEffectiveModifier(declaration, 8 /* Private */ )) return false; + case 176 /* Constructor */ : + case 303 /* PropertyAssignment */ : + case 304 /* ShorthandPropertyAssignment */ : + case 210 /* ObjectLiteralExpression */ : + case 231 /* ClassExpression */ : + case 219 /* ArrowFunction */ : + case 218 /* FunctionExpression */ : + return isDefinitionVisible(checker, declaration.parent); + default: + return false; } - return void 0; } - function getExpression(node) { - if (isValidExpression(node)) return node; - if (isVariableStatement(node)) { - const variable = getSingleVariableOfVariableStatement(node); - const initializer = variable == null ? void 0 : variable.initializer; - return initializer && isValidExpression(initializer) ? initializer : void 0; - } - return node.expression && isValidExpression(node.expression) ? node.expression : void 0; + function createDefinitionFromSignatureDeclaration(typeChecker, decl, failedAliasResolution) { + return createDefinitionInfo(decl, typeChecker, decl.symbol, decl, /*unverified*/ false, failedAliasResolution); } - function getFinalExpressionInChain(node) { - node = skipParentheses(node); - if (isBinaryExpression(node)) return getFinalExpressionInChain(node.left); - else if ((isPropertyAccessExpression(node) || isElementAccessExpression(node) || isCallExpression(node)) && !isOptionalChain(node)) return node; - return void 0; + function findReferenceInPosition(refs, pos) { + return find(refs, (ref)=>textRangeContainsPositionInclusive(ref, pos)); } - function convertOccurrences(checker, toConvert, occurrences) { - if (isPropertyAccessExpression(toConvert) || isElementAccessExpression(toConvert) || isCallExpression(toConvert)) { - const chain = convertOccurrences(checker, toConvert.expression, occurrences); - const lastOccurrence = occurrences.length > 0 ? occurrences[occurrences.length - 1] : void 0; - const isOccurrence = (lastOccurrence == null ? void 0 : lastOccurrence.getText()) === toConvert.expression.getText(); - if (isOccurrence) occurrences.pop(); - if (isCallExpression(toConvert)) return isOccurrence ? factory.createCallChain(chain, factory.createToken(28 /* QuestionDotToken */ ), toConvert.typeArguments, toConvert.arguments) : factory.createCallChain(chain, toConvert.questionDotToken, toConvert.typeArguments, toConvert.arguments); - else if (isPropertyAccessExpression(toConvert)) return isOccurrence ? factory.createPropertyAccessChain(chain, factory.createToken(28 /* QuestionDotToken */ ), toConvert.name) : factory.createPropertyAccessChain(chain, toConvert.questionDotToken, toConvert.name); - else if (isElementAccessExpression(toConvert)) return isOccurrence ? factory.createElementAccessChain(chain, factory.createToken(28 /* QuestionDotToken */ ), toConvert.argumentExpression) : factory.createElementAccessChain(chain, toConvert.questionDotToken, toConvert.argumentExpression); - } - return toConvert; + function getDefinitionInfoForFileReference(name, targetFileName, unverified) { + return { + fileName: targetFileName, + textSpan: createTextSpanFromBounds(0, 0), + kind: "script" /* scriptElement */ , + name: name, + containerName: void 0, + containerKind: void 0, + unverified: // TODO: GH#18217 + unverified + }; } - function doChange37(sourceFile, checker, changes, info, _actionName) { - const { finalExpression: finalExpression , occurrences: occurrences , expression: expression } = info; - const firstOccurrence = occurrences[occurrences.length - 1]; - const convertedChain = convertOccurrences(checker, finalExpression, occurrences); - if (convertedChain && (isPropertyAccessExpression(convertedChain) || isElementAccessExpression(convertedChain) || isCallExpression(convertedChain))) { - if (isBinaryExpression(expression)) changes.replaceNodeRange(sourceFile, firstOccurrence, finalExpression, convertedChain); - else if (isConditionalExpression(expression)) changes.replaceNode(sourceFile, expression, factory.createBinaryExpression(convertedChain, factory.createToken(60 /* QuestionQuestionToken */ ), expression.whenFalse)); + function getAncestorCallLikeExpression(node) { + const target = findAncestor(node, (n)=>!isRightSideOfPropertyAccess(n)); + const callLike = target == null ? void 0 : target.parent; + return callLike && isCallLikeExpression(callLike) && getInvokedExpression(callLike) === target ? callLike : void 0; + } + function tryGetSignatureDeclaration(typeChecker, node) { + const callLike = getAncestorCallLikeExpression(node); + const signature = callLike && typeChecker.getResolvedSignature(callLike); + return tryCast(signature && signature.declaration, (d)=>isFunctionLike(d) && !isFunctionTypeNode(d)); + } + function isConstructorLike(node) { + switch(node.kind){ + case 176 /* Constructor */ : + case 185 /* ConstructorType */ : + case 180 /* ConstructSignature */ : + return true; + default: + return false; } } - var refactorName10, convertToOptionalChainExpressionMessage, toOptionalChainAction; - var init_convertToOptionalChainExpression = __esm({ - "src/services/refactors/convertToOptionalChainExpression.ts" () { + var typesWithUnwrappedTypeArguments; + var init_goToDefinition = __esm({ + "src/services/goToDefinition.ts" () { "use strict"; init_ts4(); - init_ts_refactor(); - refactorName10 = "Convert to optional chain expression"; - convertToOptionalChainExpressionMessage = getLocaleSpecificMessage(Diagnostics.Convert_to_optional_chain_expression); - toOptionalChainAction = { - name: refactorName10, - description: convertToOptionalChainExpressionMessage, - kind: "refactor.rewrite.expression.optionalChain" - }; - registerRefactor(refactorName10, { - kinds: [ - toOptionalChainAction.kind - ], - getEditsForAction: getRefactorEditsToConvertToOptionalChain, - getAvailableActions: getRefactorActionsToConvertToOptionalChain - }); + typesWithUnwrappedTypeArguments = /* @__PURE__ */ new Set([ + "Array", + "ArrayLike", + "ReadonlyArray", + "Promise", + "PromiseLike", + "Iterable", + "IterableIterator", + "AsyncIterable", + "Set", + "WeakSet", + "ReadonlySet", + "Map", + "WeakMap", + "ReadonlyMap", + "Partial", + "Required", + "Readonly", + "Pick", + "Omit" + ]); } }); - // src/services/_namespaces/ts.refactor.convertToOptionalChainExpression.ts - var ts_refactor_convertToOptionalChainExpression_exports = {}; - var init_ts_refactor_convertToOptionalChainExpression = __esm({ - "src/services/_namespaces/ts.refactor.convertToOptionalChainExpression.ts" () { + // src/services/_namespaces/ts.GoToDefinition.ts + var ts_GoToDefinition_exports = {}; + __export(ts_GoToDefinition_exports, { + createDefinitionInfo: ()=>createDefinitionInfo, + findReferenceInPosition: ()=>findReferenceInPosition, + getDefinitionAndBoundSpan: ()=>getDefinitionAndBoundSpan, + getDefinitionAtPosition: ()=>getDefinitionAtPosition, + getReferenceAtPosition: ()=>getReferenceAtPosition, + getTypeDefinitionAtPosition: ()=>getTypeDefinitionAtPosition + }); + var init_ts_GoToDefinition = __esm({ + "src/services/_namespaces/ts.GoToDefinition.ts" () { "use strict"; - init_convertToOptionalChainExpression(); + init_goToDefinition(); } }); - // src/services/refactors/extractSymbol.ts - function getRefactorActionsToExtractSymbol(context) { - const requestedRefactor = context.kind; - const rangeToExtract = getRangeToExtract2(context.file, getRefactorContextSpan(context), context.triggerReason === "invoked"); - const targetRange = rangeToExtract.targetRange; - if (targetRange === void 0) { - if (!rangeToExtract.errors || rangeToExtract.errors.length === 0 || !context.preferences.provideRefactorNotApplicableReason) return emptyArray; - const errors = []; - if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) errors.push({ - name: refactorName11, - description: extractFunctionAction.description, - actions: [ + // src/services/inlayHints.ts + function shouldShowParameterNameHints(preferences) { + return preferences.includeInlayParameterNameHints === "literals" || preferences.includeInlayParameterNameHints === "all"; + } + function shouldShowLiteralParameterNameHintsOnly(preferences) { + return preferences.includeInlayParameterNameHints === "literals"; + } + function shouldUseInteractiveInlayHints(preferences) { + return preferences.interactiveInlayHints === true; + } + function provideInlayHints(context) { + const { file: file, program: program, span: span, cancellationToken: cancellationToken, preferences: preferences } = context; + const sourceFileText = file.text; + const compilerOptions = program.getCompilerOptions(); + const checker = program.getTypeChecker(); + const result = []; + visitor(file); + return result; + function visitor(node) { + if (!node || node.getFullWidth() === 0) return; + switch(node.kind){ + case 267 /* ModuleDeclaration */ : + case 263 /* ClassDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 262 /* FunctionDeclaration */ : + case 231 /* ClassExpression */ : + case 218 /* FunctionExpression */ : + case 174 /* MethodDeclaration */ : + case 219 /* ArrowFunction */ : + cancellationToken.throwIfCancellationRequested(); + } + if (!textSpanIntersectsWith(span, node.pos, node.getFullWidth())) return; + if (isTypeNode(node) && !isExpressionWithTypeArguments(node)) return; + if (preferences.includeInlayVariableTypeHints && isVariableDeclaration(node)) visitVariableLikeDeclaration(node); + else if (preferences.includeInlayPropertyDeclarationTypeHints && isPropertyDeclaration(node)) visitVariableLikeDeclaration(node); + else if (preferences.includeInlayEnumMemberValueHints && isEnumMember(node)) visitEnumMember(node); + else if (shouldShowParameterNameHints(preferences) && (isCallExpression(node) || isNewExpression(node))) visitCallOrNewExpression(node); + else { + if (preferences.includeInlayFunctionParameterTypeHints && isFunctionLikeDeclaration(node) && hasContextSensitiveParameters(node)) visitFunctionLikeForParameterType(node); + if (preferences.includeInlayFunctionLikeReturnTypeHints && isSignatureSupportingReturnAnnotation(node)) visitFunctionDeclarationLikeForReturnType(node); + } + return forEachChild(node, visitor); + } + function isSignatureSupportingReturnAnnotation(node) { + return isArrowFunction(node) || isFunctionExpression(node) || isFunctionDeclaration(node) || isMethodDeclaration(node) || isGetAccessorDeclaration(node); + } + function addParameterHints(text, parameter, position, isFirstVariadicArgument) { + let hintText = `${isFirstVariadicArgument ? "..." : ""}${text}`; + let displayParts; + if (shouldUseInteractiveInlayHints(preferences)) { + displayParts = [ + getNodeDisplayPart(hintText, parameter), { - ...extractFunctionAction, - notApplicableReason: getStringError(rangeToExtract.errors) + text: ":" } - ] + ]; + hintText = ""; + } else hintText += ":"; + result.push({ + text: hintText, + position: position, + kind: "Parameter" /* Parameter */ , + whitespaceAfter: true, + displayParts: displayParts }); - if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) errors.push({ - name: refactorName11, - description: extractConstantAction.description, - actions: [ + } + function addTypeHints(text, position) { + result.push({ + text: `: ${text.length > maxTypeHintLength ? text.substr(0, maxTypeHintLength - 3) + "..." : text}`, + position: position, + kind: "Type" /* Type */ , + whitespaceBefore: true + }); + } + function addEnumMemberValueHints(text, position) { + result.push({ + text: `= ${text}`, + position: position, + kind: "Enum" /* Enum */ , + whitespaceBefore: true + }); + } + function visitEnumMember(member) { + if (member.initializer) return; + const enumValue = checker.getConstantValue(member); + if (enumValue !== void 0) addEnumMemberValueHints(enumValue.toString(), member.end); + } + function isModuleReferenceType(type) { + return type.symbol && type.symbol.flags & 1536 /* Module */ ; + } + function visitVariableLikeDeclaration(decl) { + if (!decl.initializer || isBindingPattern(decl.name) || isVariableDeclaration(decl) && !isHintableDeclaration(decl)) return; + const effectiveTypeAnnotation = getEffectiveTypeAnnotationNode(decl); + if (effectiveTypeAnnotation) return; + const declarationType = checker.getTypeAtLocation(decl); + if (isModuleReferenceType(declarationType)) return; + const typeDisplayString = printTypeInSingleLine(declarationType); + if (typeDisplayString) { + const isVariableNameMatchesType = preferences.includeInlayVariableTypeHintsWhenTypeMatchesName === false && equateStringsCaseInsensitive(decl.name.getText(), typeDisplayString); + if (isVariableNameMatchesType) return; + addTypeHints(typeDisplayString, decl.name.end); + } + } + function visitCallOrNewExpression(expr) { + const args = expr.arguments; + if (!args || !args.length) return; + const candidates = []; + const signature = checker.getResolvedSignatureForSignatureHelp(expr, candidates); + if (!signature || !candidates.length) return; + let signatureParamPos = 0; + for (const originalArg of args){ + const arg = skipParentheses(originalArg); + if (shouldShowLiteralParameterNameHintsOnly(preferences) && !isHintableLiteral(arg)) continue; + let spreadArgs = 0; + if (isSpreadElement(arg)) { + const spreadType = checker.getTypeAtLocation(arg.expression); + if (checker.isTupleType(spreadType)) { + const { elementFlags: elementFlags, fixedLength: fixedLength } = spreadType.target; + if (fixedLength === 0) continue; + const firstOptionalIndex = findIndex(elementFlags, (f)=>!(f & 1 /* Required */ )); + const requiredArgs = firstOptionalIndex < 0 ? fixedLength : firstOptionalIndex; + if (requiredArgs > 0) spreadArgs = firstOptionalIndex < 0 ? fixedLength : firstOptionalIndex; + } + } + const identifierInfo = checker.getParameterIdentifierInfoAtPosition(signature, signatureParamPos); + signatureParamPos = signatureParamPos + (spreadArgs || 1); + if (identifierInfo) { + const { parameter: parameter, parameterName: parameterName, isRestParameter: isFirstVariadicArgument } = identifierInfo; + const isParameterNameNotSameAsArgument = preferences.includeInlayParameterNameHintsWhenArgumentMatchesName || !identifierOrAccessExpressionPostfixMatchesParameterName(arg, parameterName); + if (!isParameterNameNotSameAsArgument && !isFirstVariadicArgument) continue; + const name = unescapeLeadingUnderscores(parameterName); + if (leadingCommentsContainsParameterName(arg, name)) continue; + addParameterHints(name, parameter, originalArg.getStart(), isFirstVariadicArgument); + } + } + } + function identifierOrAccessExpressionPostfixMatchesParameterName(expr, parameterName) { + if (isIdentifier(expr)) return expr.text === parameterName; + if (isPropertyAccessExpression(expr)) return expr.name.text === parameterName; + return false; + } + function leadingCommentsContainsParameterName(node, name) { + if (!isIdentifierText(name, compilerOptions.target, getLanguageVariant(file.scriptKind))) return false; + const ranges = getLeadingCommentRanges(sourceFileText, node.pos); + if (!(ranges == null ? void 0 : ranges.length)) return false; + const regex = leadingParameterNameCommentRegexFactory(name); + return some(ranges, (range)=>regex.test(sourceFileText.substring(range.pos, range.end))); + } + function isHintableLiteral(node) { + switch(node.kind){ + case 224 /* PrefixUnaryExpression */ : { - ...extractConstantAction, - notApplicableReason: getStringError(rangeToExtract.errors) + const operand = node.operand; + return isLiteralExpression(operand) || isIdentifier(operand) && isInfinityOrNaNString(operand.escapedText); } - ] + case 112 /* TrueKeyword */ : + case 97 /* FalseKeyword */ : + case 106 /* NullKeyword */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + case 228 /* TemplateExpression */ : + return true; + case 80 /* Identifier */ : + { + const name = node.escapedText; + return isUndefined(name) || isInfinityOrNaNString(name); + } + } + return isLiteralExpression(node); + } + function visitFunctionDeclarationLikeForReturnType(decl) { + if (isArrowFunction(decl)) { + if (!findChildOfKind(decl, 21 /* OpenParenToken */ , file)) return; + } + const effectiveTypeAnnotation = getEffectiveReturnTypeNode(decl); + if (effectiveTypeAnnotation || !decl.body) return; + const signature = checker.getSignatureFromDeclaration(decl); + if (!signature) return; + const returnType = checker.getReturnTypeOfSignature(signature); + if (isModuleReferenceType(returnType)) return; + const typeDisplayString = printTypeInSingleLine(returnType); + if (!typeDisplayString) return; + addTypeHints(typeDisplayString, getTypeAnnotationPosition(decl)); + } + function getTypeAnnotationPosition(decl) { + const closeParenToken = findChildOfKind(decl, 22 /* CloseParenToken */ , file); + if (closeParenToken) return closeParenToken.end; + return decl.parameters.end; + } + function visitFunctionLikeForParameterType(node) { + const signature = checker.getSignatureFromDeclaration(node); + if (!signature) return; + for(let i = 0; i < node.parameters.length && i < signature.parameters.length; ++i){ + const param = node.parameters[i]; + if (!isHintableDeclaration(param)) continue; + const effectiveTypeAnnotation = getEffectiveTypeAnnotationNode(param); + if (effectiveTypeAnnotation) continue; + const typeDisplayString = getParameterDeclarationTypeDisplayString(signature.parameters[i]); + if (!typeDisplayString) continue; + addTypeHints(typeDisplayString, param.questionToken ? param.questionToken.end : param.name.end); + } + } + function getParameterDeclarationTypeDisplayString(symbol) { + const valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || !isParameter(valueDeclaration)) return void 0; + const signatureParamType = checker.getTypeOfSymbolAtLocation(symbol, valueDeclaration); + if (isModuleReferenceType(signatureParamType)) return void 0; + return printTypeInSingleLine(signatureParamType); + } + function printTypeInSingleLine(type) { + const flags = 71286784 /* UseAliasDefinedOutsideCurrentScope */ ; + const printer = createPrinterWithRemoveComments(); + return usingSingleLineStringWriter((writer)=>{ + const typeNode = checker.typeToTypeNode(type, /*enclosingDeclaration*/ void 0, flags); + Debug.assertIsDefined(typeNode, "should always get typenode"); + printer.writeNode(4 /* Unspecified */ , typeNode, /*sourceFile*/ file, writer); }); - return errors; } - const extractions = getPossibleExtractions(targetRange, context); - if (extractions === void 0) return emptyArray; - const functionActions = []; - const usedFunctionNames = /* @__PURE__ */ new Map(); - let innermostErrorFunctionAction; - const constantActions = []; - const usedConstantNames = /* @__PURE__ */ new Map(); - let innermostErrorConstantAction; - let i = 0; - for (const { functionExtraction: functionExtraction , constantExtraction: constantExtraction } of extractions){ - if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) { - const description2 = functionExtraction.description; - if (functionExtraction.errors.length === 0) { - if (!usedFunctionNames.has(description2)) { - usedFunctionNames.set(description2, true); - functionActions.push({ - description: description2, - name: `function_scope_${i}`, - kind: extractFunctionAction.kind - }); - } - } else if (!innermostErrorFunctionAction) innermostErrorFunctionAction = { - description: description2, - name: `function_scope_${i}`, - notApplicableReason: getStringError(functionExtraction.errors), - kind: extractFunctionAction.kind - }; + function isUndefined(name) { + return name === "undefined"; + } + function isHintableDeclaration(node) { + if ((isParameterDeclaration(node) || isVariableDeclaration(node) && isVarConst(node)) && node.initializer) { + const initializer = skipParentheses(node.initializer); + return !(isHintableLiteral(initializer) || isNewExpression(initializer) || isObjectLiteralExpression(initializer) || isAssertionExpression(initializer)); } - if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { - const description2 = constantExtraction.description; - if (constantExtraction.errors.length === 0) { - if (!usedConstantNames.has(description2)) { - usedConstantNames.set(description2, true); - constantActions.push({ - description: description2, - name: `constant_scope_${i}`, - kind: extractConstantAction.kind - }); - } - } else if (!innermostErrorConstantAction) innermostErrorConstantAction = { - description: description2, - name: `constant_scope_${i}`, - notApplicableReason: getStringError(constantExtraction.errors), - kind: extractConstantAction.kind - }; + return true; + } + function getNodeDisplayPart(text, node) { + const sourceFile = node.getSourceFile(); + return { + text: text, + span: createTextSpanFromNode(node, sourceFile), + file: sourceFile.fileName + }; + } + } + var maxTypeHintLength, leadingParameterNameCommentRegexFactory; + var init_inlayHints = __esm({ + "src/services/inlayHints.ts" () { + "use strict"; + init_ts4(); + maxTypeHintLength = 30; + leadingParameterNameCommentRegexFactory = (name)=>{ + return new RegExp(`^\\s?/\\*\\*?\\s?${name}\\s?\\*\\/\\s?$`); + }; + } + }); + // src/services/_namespaces/ts.InlayHints.ts + var ts_InlayHints_exports = {}; + __export(ts_InlayHints_exports, { + provideInlayHints: ()=>provideInlayHints + }); + var init_ts_InlayHints = __esm({ + "src/services/_namespaces/ts.InlayHints.ts" () { + "use strict"; + init_inlayHints(); + } + }); + // src/services/jsDoc.ts + function getJsDocCommentsFromDeclarations(declarations, checker) { + const parts = []; + forEachUnique(declarations, (declaration)=>{ + for (const jsdoc of getCommentHavingNodes(declaration)){ + const inheritDoc = isJSDoc(jsdoc) && jsdoc.tags && find(jsdoc.tags, (t)=>t.kind === 334 /* JSDocTag */ && (t.tagName.escapedText === "inheritDoc" || t.tagName.escapedText === "inheritdoc")); + if (jsdoc.comment === void 0 && !inheritDoc || isJSDoc(jsdoc) && declaration.kind !== 353 /* JSDocTypedefTag */ && declaration.kind !== 345 /* JSDocCallbackTag */ && jsdoc.tags && jsdoc.tags.some((t)=>t.kind === 353 /* JSDocTypedefTag */ || t.kind === 345 /* JSDocCallbackTag */ ) && !jsdoc.tags.some((t)=>t.kind === 348 /* JSDocParameterTag */ || t.kind === 349 /* JSDocReturnTag */ )) continue; + let newparts = jsdoc.comment ? getDisplayPartsFromComment(jsdoc.comment, checker) : []; + if (inheritDoc && inheritDoc.comment) newparts = newparts.concat(getDisplayPartsFromComment(inheritDoc.comment, checker)); + if (!contains(parts, newparts, isIdenticalListOfDisplayParts)) parts.push(newparts); } - i++; + }); + return flatten(intersperse(parts, [ + lineBreakPart() + ])); + } + function isIdenticalListOfDisplayParts(parts1, parts2) { + return arraysEqual(parts1, parts2, (p1, p2)=>p1.kind === p2.kind && p1.text === p2.text); + } + function getCommentHavingNodes(declaration) { + switch(declaration.kind){ + case 348 /* JSDocParameterTag */ : + case 355 /* JSDocPropertyTag */ : + return [ + declaration + ]; + case 345 /* JSDocCallbackTag */ : + case 353 /* JSDocTypedefTag */ : + return [ + declaration, + declaration.parent + ]; + default: + return getJSDocCommentsAndTags(declaration); } + } + function getJsDocTagsFromDeclarations(declarations, checker) { const infos = []; - if (functionActions.length) infos.push({ - name: refactorName11, - description: getLocaleSpecificMessage(Diagnostics.Extract_function), - actions: functionActions - }); - else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorFunctionAction) infos.push({ - name: refactorName11, - description: getLocaleSpecificMessage(Diagnostics.Extract_function), - actions: [ - innermostErrorFunctionAction - ] - }); - if (constantActions.length) infos.push({ - name: refactorName11, - description: getLocaleSpecificMessage(Diagnostics.Extract_constant), - actions: constantActions - }); - else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorConstantAction) infos.push({ - name: refactorName11, - description: getLocaleSpecificMessage(Diagnostics.Extract_constant), - actions: [ - innermostErrorConstantAction - ] + forEachUnique(declarations, (declaration)=>{ + const tags = getJSDocTags(declaration); + if (tags.some((t)=>t.kind === 353 /* JSDocTypedefTag */ || t.kind === 345 /* JSDocCallbackTag */ ) && !tags.some((t)=>t.kind === 348 /* JSDocParameterTag */ || t.kind === 349 /* JSDocReturnTag */ )) return; + for (const tag of tags)infos.push({ + name: tag.tagName.text, + text: getCommentDisplayParts(tag, checker) + }); }); - return infos.length ? infos : emptyArray; - function getStringError(errors) { - let error = errors[0].messageText; - if (typeof error !== "string") error = error.messageText; - return error; + return infos; + } + function getDisplayPartsFromComment(comment, checker) { + if (typeof comment === "string") return [ + textPart(comment) + ]; + return flatMap(comment, (node)=>node.kind === 328 /* JSDocText */ ? [ + textPart(node.text) + ] : buildLinkParts(node, checker)); + } + function getCommentDisplayParts(tag, checker) { + const { comment: comment, kind: kind } = tag; + const namePart = getTagNameDisplayPart(kind); + switch(kind){ + case 356 /* JSDocThrowsTag */ : + const typeExpression = tag.typeExpression; + return typeExpression ? withNode(typeExpression) : comment === void 0 ? void 0 : getDisplayPartsFromComment(comment, checker); + case 336 /* JSDocImplementsTag */ : + return withNode(tag.class); + case 335 /* JSDocAugmentsTag */ : + return withNode(tag.class); + case 352 /* JSDocTemplateTag */ : + const templateTag = tag; + const displayParts = []; + if (templateTag.constraint) displayParts.push(textPart(templateTag.constraint.getText())); + if (length(templateTag.typeParameters)) { + if (length(displayParts)) displayParts.push(spacePart()); + const lastTypeParameter = templateTag.typeParameters[templateTag.typeParameters.length - 1]; + forEach(templateTag.typeParameters, (tp)=>{ + displayParts.push(namePart(tp.getText())); + if (lastTypeParameter !== tp) displayParts.push(...[ + punctuationPart(28 /* CommaToken */ ), + spacePart() + ]); + }); + } + if (comment) displayParts.push(...[ + spacePart(), + ...getDisplayPartsFromComment(comment, checker) + ]); + return displayParts; + case 351 /* JSDocTypeTag */ : + case 357 /* JSDocSatisfiesTag */ : + return withNode(tag.typeExpression); + case 353 /* JSDocTypedefTag */ : + case 345 /* JSDocCallbackTag */ : + case 355 /* JSDocPropertyTag */ : + case 348 /* JSDocParameterTag */ : + case 354 /* JSDocSeeTag */ : + const { name: name } = tag; + return name ? withNode(name) : comment === void 0 ? void 0 : getDisplayPartsFromComment(comment, checker); + default: + return comment === void 0 ? void 0 : getDisplayPartsFromComment(comment, checker); } - } - function getRefactorEditsToExtractSymbol(context, actionName2) { - const rangeToExtract = getRangeToExtract2(context.file, getRefactorContextSpan(context)); - const targetRange = rangeToExtract.targetRange; - const parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName2); - if (parsedFunctionIndexMatch) { - const index = +parsedFunctionIndexMatch[1]; - Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index"); - return getFunctionExtractionAtIndex(targetRange, context, index); + function withNode(node) { + return addComment(node.getText()); } - const parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName2); - if (parsedConstantIndexMatch) { - const index = +parsedConstantIndexMatch[1]; - Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index"); - return getConstantExtractionAtIndex(targetRange, context, index); + function addComment(s) { + if (comment) { + if (s.match(/^https?$/)) return [ + textPart(s), + ...getDisplayPartsFromComment(comment, checker) + ]; + else return [ + namePart(s), + spacePart(), + ...getDisplayPartsFromComment(comment, checker) + ]; + } else return [ + textPart(s) + ]; } - Debug.fail("Unrecognized action name"); } - function getRangeToExtract2(sourceFile, span, invoked = true) { - const { length: length2 } = span; - if (length2 === 0 && !invoked) return { - errors: [ - createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractEmpty) - ] - }; - const cursorRequest = length2 === 0 && invoked; - const startToken = findFirstNonJsxWhitespaceToken(sourceFile, span.start); - const endToken = findTokenOnLeftOfPosition(sourceFile, textSpanEnd(span)); - const adjustedSpan = startToken && endToken && invoked ? getAdjustedSpanFromNodes(startToken, endToken, sourceFile) : span; - const start = cursorRequest ? getExtractableParent(startToken) : getParentNodeInSpan(startToken, sourceFile, adjustedSpan); - const end = cursorRequest ? start : getParentNodeInSpan(endToken, sourceFile, adjustedSpan); - let rangeFacts = 0 /* None */ ; - let thisNode; - if (!start || !end) return { - errors: [ - createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange) - ] - }; - if (start.flags & 8388608 /* JSDoc */ ) return { - errors: [ - createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractJSDoc) - ] - }; - if (start.parent !== end.parent) return { - errors: [ - createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange) - ] - }; - if (start !== end) { - if (!isBlockLike(start.parent)) return { - errors: [ - createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange) - ] - }; - const statements = []; - for (const statement of start.parent.statements){ - if (statement === start || statements.length) { - const errors2 = checkNode(statement); - if (errors2) return { - errors: errors2 - }; - statements.push(statement); - } - if (statement === end) break; - } - if (!statements.length) return { - errors: [ - createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange) - ] + function getTagNameDisplayPart(kind) { + switch(kind){ + case 348 /* JSDocParameterTag */ : + return parameterNamePart; + case 355 /* JSDocPropertyTag */ : + return propertyNamePart; + case 352 /* JSDocTemplateTag */ : + return typeParameterNamePart; + case 353 /* JSDocTypedefTag */ : + case 345 /* JSDocCallbackTag */ : + return typeAliasNamePart; + default: + return textPart; + } + } + function getJSDocTagNameCompletions() { + return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = map(jsDocTagNames, (tagName)=>{ + return { + name: tagName, + kind: "keyword" /* keyword */ , + kindModifiers: "", + sortText: ts_Completions_exports.SortText.LocationPriority }; + })); + } + function getJSDocTagCompletions() { + return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = map(jsDocTagNames, (tagName)=>{ return { - targetRange: { - range: statements, - facts: rangeFacts, - thisNode: thisNode - } + name: `@${tagName}`, + kind: "keyword" /* keyword */ , + kindModifiers: "", + sortText: ts_Completions_exports.SortText.LocationPriority }; - } - if (isReturnStatement(start) && !start.expression) return { - errors: [ - createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange) - ] + })); + } + function getJSDocTagCompletionDetails(name) { + return { + name: name, + kind: "" /* unknown */ , + // TODO: should have its own kind? + kindModifiers: "", + displayParts: [ + textPart(name) + ], + documentation: emptyArray, + tags: void 0, + codeActions: void 0 }; - const node = refineNode(start); - const errors = checkRootNode(node) || checkNode(node); - if (errors) return { - errors: errors + } + function getJSDocParameterNameCompletions(tag) { + if (!isIdentifier(tag.name)) return emptyArray; + const nameThusFar = tag.name.text; + const jsdoc = tag.parent; + const fn = jsdoc.parent; + if (!isFunctionLike(fn)) return []; + return mapDefined(fn.parameters, (param)=>{ + if (!isIdentifier(param.name)) return void 0; + const name = param.name.text; + if (jsdoc.tags.some((t)=>t !== tag && isJSDocParameterTag(t) && isIdentifier(t.name) && t.name.escapedText === name) || nameThusFar !== void 0 && !startsWith(name, nameThusFar)) return void 0; + return { + name: name, + kind: "parameter" /* parameterElement */ , + kindModifiers: "", + sortText: ts_Completions_exports.SortText.LocationPriority + }; + }); + } + function getJSDocParameterNameCompletionDetails(name) { + return { + name: name, + kind: "parameter" /* parameterElement */ , + kindModifiers: "", + displayParts: [ + textPart(name) + ], + documentation: emptyArray, + tags: void 0, + codeActions: void 0 }; + } + function getDocCommentTemplateAtPosition(newLine, sourceFile, position, options) { + const tokenAtPos = getTokenAtPosition(sourceFile, position); + const existingDocComment = findAncestor(tokenAtPos, isJSDoc); + if (existingDocComment && (existingDocComment.comment !== void 0 || length(existingDocComment.tags))) return void 0; + const tokenStart = tokenAtPos.getStart(sourceFile); + if (!existingDocComment && tokenStart < position) return void 0; + const commentOwnerInfo = getCommentOwnerInfo(tokenAtPos, options); + if (!commentOwnerInfo) return void 0; + const { commentOwner: commentOwner, parameters: parameters, hasReturn: hasReturn2 } = commentOwnerInfo; + const commentOwnerJsDoc = hasJSDocNodes(commentOwner) && commentOwner.jsDoc ? commentOwner.jsDoc : void 0; + const lastJsDoc = lastOrUndefined(commentOwnerJsDoc); + if (commentOwner.getStart(sourceFile) < position || lastJsDoc && existingDocComment && lastJsDoc !== existingDocComment) return void 0; + const indentationStr = getIndentationStringAtPosition(sourceFile, position); + const isJavaScriptFile = hasJSFileExtension(sourceFile.fileName); + const tags = (parameters ? parameterDocComments(parameters || [], isJavaScriptFile, indentationStr, newLine) : "") + (hasReturn2 ? returnsDocComment(indentationStr, newLine) : ""); + const openComment = "/**"; + const closeComment = " */"; + const hasTag = length(getJSDocTags(commentOwner)) > 0; + if (tags && !hasTag) { + const preamble = openComment + newLine + indentationStr + " * "; + const endLine = tokenStart === position ? newLine + indentationStr : ""; + const result = preamble + newLine + tags + indentationStr + closeComment + endLine; + return { + newText: result, + caretOffset: preamble.length + }; + } return { - targetRange: { - range: getStatementOrExpressionRange(node), - facts: rangeFacts, - thisNode: thisNode - } + newText: openComment + closeComment, + caretOffset: 3 }; - function refineNode(node2) { - if (isReturnStatement(node2)) { - if (node2.expression) return node2.expression; - } else if (isVariableStatement(node2) || isVariableDeclarationList(node2)) { - const declarations = isVariableStatement(node2) ? node2.declarationList.declarations : node2.declarations; - let numInitializers = 0; - let lastInitializer; - for (const declaration of declarations)if (declaration.initializer) { - numInitializers++; - lastInitializer = declaration.initializer; + } + function getIndentationStringAtPosition(sourceFile, position) { + const { text: text } = sourceFile; + const lineStart = getLineStartPositionForPosition(position, sourceFile); + let pos = lineStart; + for(; pos <= position && isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++); + return text.slice(lineStart, pos); + } + function parameterDocComments(parameters, isJavaScriptFile, indentationStr, newLine) { + return parameters.map(({ name: name, dotDotDotToken: dotDotDotToken }, i)=>{ + const paramName = name.kind === 80 /* Identifier */ ? name.text : "param" + i; + const type = isJavaScriptFile ? dotDotDotToken ? "{...any} " : "{any} " : ""; + return `${indentationStr} * @param ${type}${paramName}${newLine}`; + }).join(""); + } + function returnsDocComment(indentationStr, newLine) { + return `${indentationStr} * @returns${newLine}`; + } + function getCommentOwnerInfo(tokenAtPos, options) { + return forEachAncestor(tokenAtPos, (n)=>getCommentOwnerInfoWorker(n, options)); + } + function getCommentOwnerInfoWorker(commentOwner, options) { + switch(commentOwner.kind){ + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 174 /* MethodDeclaration */ : + case 176 /* Constructor */ : + case 173 /* MethodSignature */ : + case 219 /* ArrowFunction */ : + const host = commentOwner; + return { + commentOwner: commentOwner, + parameters: host.parameters, + hasReturn: hasReturn(host, options) + }; + case 303 /* PropertyAssignment */ : + return getCommentOwnerInfoWorker(commentOwner.initializer, options); + case 263 /* ClassDeclaration */ : + case 264 /* InterfaceDeclaration */ : + case 266 /* EnumDeclaration */ : + case 306 /* EnumMember */ : + case 265 /* TypeAliasDeclaration */ : + return { + commentOwner: commentOwner + }; + case 171 /* PropertySignature */ : + { + const host2 = commentOwner; + return host2.type && isFunctionTypeNode(host2.type) ? { + commentOwner: commentOwner, + parameters: host2.type.parameters, + hasReturn: hasReturn(host2.type, options) + } : { + commentOwner: commentOwner + }; } - if (numInitializers === 1) return lastInitializer; - } else if (isVariableDeclaration(node2)) { - if (node2.initializer) return node2.initializer; - } - return node2; - } - function checkRootNode(node2) { - if (isIdentifier(isExpressionStatement(node2) ? node2.expression : node2)) return [ - createDiagnosticForNode(node2, Messages.cannotExtractIdentifier) - ]; - return void 0; - } - function checkForStaticContext(nodeToCheck, containingClass) { - let current = nodeToCheck; - while(current !== containingClass){ - if (current.kind === 169 /* PropertyDeclaration */ ) { - if (isStatic(current)) rangeFacts |= 32 /* InStaticRegion */ ; - break; - } else if (current.kind === 166 /* Parameter */ ) { - const ctorOrMethod = getContainingFunction(current); - if (ctorOrMethod.kind === 173 /* Constructor */ ) rangeFacts |= 32 /* InStaticRegion */ ; - break; - } else if (current.kind === 171 /* MethodDeclaration */ ) { - if (isStatic(current)) rangeFacts |= 32 /* InStaticRegion */ ; + case 243 /* VariableStatement */ : + { + const varStatement = commentOwner; + const varDeclarations = varStatement.declarationList.declarations; + const host2 = varDeclarations.length === 1 && varDeclarations[0].initializer ? getRightHandSideOfAssignment(varDeclarations[0].initializer) : void 0; + return host2 ? { + commentOwner: commentOwner, + parameters: host2.parameters, + hasReturn: hasReturn(host2, options) + } : { + commentOwner: commentOwner + }; } - current = current.parent; - } + case 312 /* SourceFile */ : + return "quit"; + case 267 /* ModuleDeclaration */ : + return commentOwner.parent.kind === 267 /* ModuleDeclaration */ ? void 0 : { + commentOwner: commentOwner + }; + case 244 /* ExpressionStatement */ : + return getCommentOwnerInfoWorker(commentOwner.expression, options); + case 226 /* BinaryExpression */ : + { + const be = commentOwner; + if (getAssignmentDeclarationKind(be) === 0 /* None */ ) return "quit"; + return isFunctionLike(be.right) ? { + commentOwner: commentOwner, + parameters: be.right.parameters, + hasReturn: hasReturn(be.right, options) + } : { + commentOwner: commentOwner + }; + } + case 172 /* PropertyDeclaration */ : + const init = commentOwner.initializer; + if (init && (isFunctionExpression(init) || isArrowFunction(init))) return { + commentOwner: commentOwner, + parameters: init.parameters, + hasReturn: hasReturn(init, options) + }; } - function checkNode(nodeToCheck) { - let PermittedJumps; - ((PermittedJumps2)=>{ - PermittedJumps2[PermittedJumps2["None"] = 0] = "None"; - PermittedJumps2[PermittedJumps2["Break"] = 1] = "Break"; - PermittedJumps2[PermittedJumps2["Continue"] = 2] = "Continue"; - PermittedJumps2[PermittedJumps2["Return"] = 4] = "Return"; - })(PermittedJumps || (PermittedJumps = {})); - Debug.assert(nodeToCheck.pos <= nodeToCheck.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (1)"); - Debug.assert(!positionIsSynthesized(nodeToCheck.pos), "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (2)"); - if (!isStatement(nodeToCheck) && !(isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck)) && !isStringLiteralJsxAttribute(nodeToCheck)) return [ - createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected) - ]; - if (nodeToCheck.flags & 16777216 /* Ambient */ ) return [ - createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock) + } + function hasReturn(node, options) { + return !!(options == null ? void 0 : options.generateReturnInDocTemplate) && (isFunctionTypeNode(node) || isArrowFunction(node) && isExpression(node.body) || isFunctionLikeDeclaration(node) && node.body && isBlock(node.body) && !!forEachReturnStatement(node.body, (n)=>n)); + } + function getRightHandSideOfAssignment(rightHandSide) { + while(rightHandSide.kind === 217 /* ParenthesizedExpression */ )rightHandSide = rightHandSide.expression; + switch(rightHandSide.kind){ + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + return rightHandSide; + case 231 /* ClassExpression */ : + return find(rightHandSide.members, isConstructorDeclaration); + } + } + var jsDocTagNames, jsDocTagNameCompletionEntries, jsDocTagCompletionEntries, getJSDocTagNameCompletionDetails; + var init_jsDoc = __esm({ + "src/services/jsDoc.ts" () { + "use strict"; + init_ts4(); + jsDocTagNames = [ + "abstract", + "access", + "alias", + "argument", + "async", + "augments", + "author", + "borrows", + "callback", + "class", + "classdesc", + "constant", + "constructor", + "constructs", + "copyright", + "default", + "deprecated", + "description", + "emits", + "enum", + "event", + "example", + "exports", + "extends", + "external", + "field", + "file", + "fileoverview", + "fires", + "function", + "generator", + "global", + "hideconstructor", + "host", + "ignore", + "implements", + "inheritdoc", + "inner", + "instance", + "interface", + "kind", + "lends", + "license", + "link", + "linkcode", + "linkplain", + "listens", + "member", + "memberof", + "method", + "mixes", + "module", + "name", + "namespace", + "overload", + "override", + "package", + "param", + "private", + "prop", + "property", + "protected", + "public", + "readonly", + "requires", + "returns", + "satisfies", + "see", + "since", + "static", + "summary", + "template", + "this", + "throws", + "todo", + "tutorial", + "type", + "typedef", + "var", + "variation", + "version", + "virtual", + "yields" ]; - const containingClass = getContainingClass(nodeToCheck); - if (containingClass) checkForStaticContext(nodeToCheck, containingClass); - let errors2; - let permittedJumps = 4 /* Return */ ; - let seenLabels; - visit(nodeToCheck); - if (rangeFacts & 8 /* UsesThis */ ) { - const container = getThisContainer(nodeToCheck, /** includeArrowFunctions */ false, /*includeClassComputedPropertyName*/ false); - if (container.kind === 259 /* FunctionDeclaration */ || container.kind === 171 /* MethodDeclaration */ && container.parent.kind === 207 /* ObjectLiteralExpression */ || container.kind === 215 /* FunctionExpression */ ) rangeFacts |= 16 /* UsesThisInFunction */ ; - } - return errors2; - function visit(node2) { - if (errors2) return true; - if (isDeclaration(node2)) { - const declaringNode = node2.kind === 257 /* VariableDeclaration */ ? node2.parent.parent : node2; - if (hasSyntacticModifier(declaringNode, 1 /* Export */ )) { - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractExportedEntity)); - return true; - } - } - switch(node2.kind){ - case 269 /* ImportDeclaration */ : - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractImport)); - return true; - case 274 /* ExportAssignment */ : - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractExportedEntity)); - return true; - case 106 /* SuperKeyword */ : - if (node2.parent.kind === 210 /* CallExpression */ ) { - const containingClass2 = getContainingClass(node2); - if (containingClass2 === void 0 || containingClass2.pos < span.start || containingClass2.end >= span.start + span.length) { - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractSuper)); - return true; - } - } else { - rangeFacts |= 8 /* UsesThis */ ; - thisNode = node2; - } - break; - case 216 /* ArrowFunction */ : - forEachChild(node2, function check(n) { - if (isThis(n)) { - rangeFacts |= 8 /* UsesThis */ ; - thisNode = node2; - } else if (isClassLike(n) || isFunctionLike(n) && !isArrowFunction(n)) return false; - else forEachChild(n, check); - }); - case 260 /* ClassDeclaration */ : - case 259 /* FunctionDeclaration */ : - if (isSourceFile(node2.parent) && node2.parent.externalModuleIndicator === void 0) (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.functionWillNotBeVisibleInTheNewScope)); - case 228 /* ClassExpression */ : - case 215 /* FunctionExpression */ : - case 171 /* MethodDeclaration */ : - case 173 /* Constructor */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - return false; - } - const savedPermittedJumps = permittedJumps; - switch(node2.kind){ - case 242 /* IfStatement */ : - permittedJumps &= -5 /* Return */ ; - break; - case 255 /* TryStatement */ : - permittedJumps = 0 /* None */ ; - break; - case 238 /* Block */ : - if (node2.parent && node2.parent.kind === 255 /* TryStatement */ && node2.parent.finallyBlock === node2) permittedJumps = 4 /* Return */ ; - break; - case 293 /* DefaultClause */ : - case 292 /* CaseClause */ : - permittedJumps |= 1 /* Break */ ; - break; - default: - if (isIterationStatement(node2, /*lookInLabeledStatements*/ false)) permittedJumps |= 3 /* Continue */ ; - break; - } - switch(node2.kind){ - case 194 /* ThisType */ : - case 108 /* ThisKeyword */ : - rangeFacts |= 8 /* UsesThis */ ; - thisNode = node2; - break; - case 253 /* LabeledStatement */ : - { - const label = node2.label; - (seenLabels || (seenLabels = [])).push(label.escapedText); - forEachChild(node2, visit); - seenLabels.pop(); - break; - } - case 249 /* BreakStatement */ : - case 248 /* ContinueStatement */ : - { - const label = node2.label; - if (label) { - if (!contains(seenLabels, label.escapedText)) (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); - } else if (!(permittedJumps & (node2.kind === 249 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */ ))) (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); - break; - } - case 220 /* AwaitExpression */ : - rangeFacts |= 4 /* IsAsyncFunction */ ; - break; - case 226 /* YieldExpression */ : - rangeFacts |= 2 /* IsGenerator */ ; - break; - case 250 /* ReturnStatement */ : - if (permittedJumps & 4 /* Return */ ) rangeFacts |= 1 /* HasReturn */ ; - else (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingConditionalReturnStatement)); - break; - default: - forEachChild(node2, visit); - break; - } - permittedJumps = savedPermittedJumps; - } + getJSDocTagNameCompletionDetails = getJSDocTagCompletionDetails; + } + }); + // src/services/_namespaces/ts.JsDoc.ts + var ts_JsDoc_exports = {}; + __export(ts_JsDoc_exports, { + getDocCommentTemplateAtPosition: ()=>getDocCommentTemplateAtPosition, + getJSDocParameterNameCompletionDetails: ()=>getJSDocParameterNameCompletionDetails, + getJSDocParameterNameCompletions: ()=>getJSDocParameterNameCompletions, + getJSDocTagCompletionDetails: ()=>getJSDocTagCompletionDetails, + getJSDocTagCompletions: ()=>getJSDocTagCompletions, + getJSDocTagNameCompletionDetails: ()=>getJSDocTagNameCompletionDetails, + getJSDocTagNameCompletions: ()=>getJSDocTagNameCompletions, + getJsDocCommentsFromDeclarations: ()=>getJsDocCommentsFromDeclarations, + getJsDocTagsFromDeclarations: ()=>getJsDocTagsFromDeclarations + }); + var init_ts_JsDoc = __esm({ + "src/services/_namespaces/ts.JsDoc.ts" () { + "use strict"; + init_jsDoc(); } - } - function getAdjustedSpanFromNodes(startNode2, endNode2, sourceFile) { - const start = startNode2.getStart(sourceFile); - let end = endNode2.getEnd(); - if (sourceFile.text.charCodeAt(end) === 59 /* semicolon */ ) end++; - return { - start: start, - length: end - start + }); + // src/services/organizeImports.ts + function organizeImports(sourceFile, formatContext, host, program, preferences, mode) { + const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext({ + host: host, + formatContext: formatContext, + preferences: preferences + }); + const shouldSort = mode === "SortAndCombine" /* SortAndCombine */ || mode === "All" /* All */ ; + const shouldCombine = shouldSort; + const shouldRemove = mode === "RemoveUnused" /* RemoveUnused */ || mode === "All" /* All */ ; + const topLevelImportGroupDecls = groupByNewlineContiguous(sourceFile, sourceFile.statements.filter(isImportDeclaration)); + const comparer = getOrganizeImportsComparerWithDetection(preferences, shouldSort ? ()=>detectSortingWorker(topLevelImportGroupDecls, preferences) === 2 /* CaseInsensitive */ : void 0); + const processImportsOfSameModuleSpecifier = (importGroup)=>{ + if (shouldRemove) importGroup = removeUnusedImports(importGroup, sourceFile, program); + if (shouldCombine) importGroup = coalesceImportsWorker(importGroup, comparer, sourceFile); + if (shouldSort) importGroup = stableSort(importGroup, (s1, s2)=>compareImportsOrRequireStatements(s1, s2, comparer)); + return importGroup; }; - } - function getStatementOrExpressionRange(node) { - if (isStatement(node)) return [ - node - ]; - if (isExpressionNode(node)) return isExpressionStatement(node.parent) ? [ - node.parent - ] : node; - if (isStringLiteralJsxAttribute(node)) return node; - return void 0; - } - function isScope(node) { - return isArrowFunction(node) ? isFunctionBody(node.body) : isFunctionLikeDeclaration(node) || isSourceFile(node) || isModuleBlock(node) || isClassLike(node); - } - function collectEnclosingScopes(range) { - let current = isReadonlyArray(range.range) ? first(range.range) : range.range; - if (range.facts & 8 /* UsesThis */ && !(range.facts & 16 /* UsesThisInFunction */ )) { - const containingClass = getContainingClass(current); - if (containingClass) { - const containingFunction = findAncestor(current, isFunctionLikeDeclaration); - return containingFunction ? [ - containingFunction, - containingClass - ] : [ - containingClass - ]; + topLevelImportGroupDecls.forEach((importGroupDecl)=>organizeImportsWorker(importGroupDecl, processImportsOfSameModuleSpecifier)); + if (mode !== "RemoveUnused" /* RemoveUnused */ ) getTopLevelExportGroups(sourceFile).forEach((exportGroupDecl)=>organizeImportsWorker(exportGroupDecl, (group2)=>coalesceExportsWorker(group2, comparer))); + for (const ambientModule of sourceFile.statements.filter(isAmbientModule)){ + if (!ambientModule.body) continue; + const ambientModuleImportGroupDecls = groupByNewlineContiguous(sourceFile, ambientModule.body.statements.filter(isImportDeclaration)); + ambientModuleImportGroupDecls.forEach((importGroupDecl)=>organizeImportsWorker(importGroupDecl, processImportsOfSameModuleSpecifier)); + if (mode !== "RemoveUnused" /* RemoveUnused */ ) { + const ambientModuleExportDecls = ambientModule.body.statements.filter(isExportDeclaration); + organizeImportsWorker(ambientModuleExportDecls, (group2)=>coalesceExportsWorker(group2, comparer)); } } - const scopes = []; - while(true){ - current = current.parent; - if (current.kind === 166 /* Parameter */ ) current = findAncestor(current, (parent2)=>isFunctionLikeDeclaration(parent2)).parent; - if (isScope(current)) { - scopes.push(current); - if (current.kind === 308 /* SourceFile */ ) return scopes; + return changeTracker.getChanges(); + function organizeImportsWorker(oldImportDecls, coalesce) { + if (length(oldImportDecls) === 0) return; + setEmitFlags(oldImportDecls[0], 1024 /* NoLeadingComments */ ); + const oldImportGroups = shouldCombine ? group(oldImportDecls, (importDecl)=>getExternalModuleName2(importDecl.moduleSpecifier)) : [ + oldImportDecls + ]; + const sortedImportGroups = shouldSort ? stableSort(oldImportGroups, (group1, group2)=>compareModuleSpecifiersWorker(group1[0].moduleSpecifier, group2[0].moduleSpecifier, comparer)) : oldImportGroups; + const newImportDecls = flatMap(sortedImportGroups, (importGroup)=>getExternalModuleName2(importGroup[0].moduleSpecifier) || importGroup[0].moduleSpecifier === void 0 ? coalesce(importGroup) : importGroup); + if (newImportDecls.length === 0) changeTracker.deleteNodes(sourceFile, oldImportDecls, { + leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, + trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include + }, /*hasTrailingComment*/ true); + else { + const replaceOptions = { + leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, + // Leave header comment in place + trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include, + suffix: getNewLineOrDefaultFromHost(host, formatContext.options) + }; + changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, replaceOptions); + const hasTrailingComment = changeTracker.nodeHasTrailingComment(sourceFile, oldImportDecls[0], replaceOptions); + changeTracker.deleteNodes(sourceFile, oldImportDecls.slice(1), { + trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include + }, hasTrailingComment); } } } - function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { - const { scopes: scopes , readsAndWrites: { target: target , usagesPerScope: usagesPerScope , functionErrorsPerScope: functionErrorsPerScope , exposedVariableDeclarations: exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context); - Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); - context.cancellationToken.throwIfCancellationRequested(); - return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); + function groupByNewlineContiguous(sourceFile, decls) { + const scanner2 = createScanner(sourceFile.languageVersion, /*skipTrivia*/ false, sourceFile.languageVariant); + const group2 = []; + let groupIndex = 0; + for (const decl of decls){ + if (group2[groupIndex] && isNewGroup(sourceFile, decl, scanner2)) groupIndex++; + if (!group2[groupIndex]) group2[groupIndex] = []; + group2[groupIndex].push(decl); + } + return group2; } - function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { - const { scopes: scopes , readsAndWrites: { target: target , usagesPerScope: usagesPerScope , constantErrorsPerScope: constantErrorsPerScope , exposedVariableDeclarations: exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context); - Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); - Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?"); - context.cancellationToken.throwIfCancellationRequested(); - const expression = isExpression(target) ? target : target.statements[0].expression; - return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context); + function isNewGroup(sourceFile, decl, scanner2) { + const startPos = decl.getFullStart(); + const endPos = decl.getStart(); + scanner2.setText(sourceFile.text, startPos, endPos - startPos); + let numberOfNewLines = 0; + while(scanner2.getTokenStart() < endPos){ + const tokenKind = scanner2.scan(); + if (tokenKind === 4 /* NewLineTrivia */ ) { + numberOfNewLines++; + if (numberOfNewLines >= 2) return true; + } + } + return false; } - function getPossibleExtractions(targetRange, context) { - const { scopes: scopes , readsAndWrites: { functionErrorsPerScope: functionErrorsPerScope , constantErrorsPerScope: constantErrorsPerScope } } = getPossibleExtractionsWorker(targetRange, context); - const extractions = scopes.map((scope, i)=>{ - const functionDescriptionPart = getDescriptionForFunctionInScope(scope); - const constantDescriptionPart = getDescriptionForConstantInScope(scope); - const scopeDescription = isFunctionLikeDeclaration(scope) ? getDescriptionForFunctionLikeDeclaration(scope) : isClassLike(scope) ? getDescriptionForClassLikeDeclaration(scope) : getDescriptionForModuleLikeDeclaration(scope); - let functionDescription; - let constantDescription; - if (scopeDescription === 1 /* Global */ ) { - functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [ - functionDescriptionPart, - "global" - ]); - constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [ - constantDescriptionPart, - "global" - ]); - } else if (scopeDescription === 0 /* Module */ ) { - functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [ - functionDescriptionPart, - "module" - ]); - constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [ - constantDescriptionPart, - "module" - ]); - } else { - functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1), [ - functionDescriptionPart, - scopeDescription - ]); - constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1), [ - constantDescriptionPart, - scopeDescription - ]); + function removeUnusedImports(oldImports, sourceFile, program) { + const typeChecker = program.getTypeChecker(); + const compilerOptions = program.getCompilerOptions(); + const jsxNamespace = typeChecker.getJsxNamespace(sourceFile); + const jsxFragmentFactory = typeChecker.getJsxFragmentFactory(sourceFile); + const jsxElementsPresent = !!(sourceFile.transformFlags & 2 /* ContainsJsx */ ); + const usedImports = []; + for (const importDecl of oldImports){ + const { importClause: importClause, moduleSpecifier: moduleSpecifier } = importDecl; + if (!importClause) { + usedImports.push(importDecl); + continue; } - if (i === 0 && !isClassLike(scope)) constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_enclosing_scope), [ - constantDescriptionPart - ]); - return { - functionExtraction: { - description: functionDescription, - errors: functionErrorsPerScope[i] - }, - constantExtraction: { - description: constantDescription, - errors: constantErrorsPerScope[i] + let { name: name, namedBindings: namedBindings } = importClause; + if (name && !isDeclarationUsed(name)) name = void 0; + if (namedBindings) { + if (isNamespaceImport(namedBindings)) { + if (!isDeclarationUsed(namedBindings.name)) namedBindings = void 0; + } else { + const newElements = namedBindings.elements.filter((e)=>isDeclarationUsed(e.name)); + if (newElements.length < namedBindings.elements.length) namedBindings = newElements.length ? factory.updateNamedImports(namedBindings, newElements) : void 0; } - }; - }); - return extractions; - } - function getPossibleExtractionsWorker(targetRange, context) { - const { file: sourceFile } = context; - const scopes = collectEnclosingScopes(targetRange); - const enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); - const readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken); - return { - scopes: scopes, - readsAndWrites: readsAndWrites - }; - } - function getDescriptionForFunctionInScope(scope) { - return isFunctionLikeDeclaration(scope) ? "inner function" : isClassLike(scope) ? "method" : "function"; - } - function getDescriptionForConstantInScope(scope) { - return isClassLike(scope) ? "readonly field" : "constant"; - } - function getDescriptionForFunctionLikeDeclaration(scope) { - switch(scope.kind){ - case 173 /* Constructor */ : - return "constructor"; - case 215 /* FunctionExpression */ : - case 259 /* FunctionDeclaration */ : - return scope.name ? `function '${scope.name.text}'` : ANONYMOUS; - case 216 /* ArrowFunction */ : - return "arrow function"; - case 171 /* MethodDeclaration */ : - return `method '${scope.name.getText()}'`; - case 174 /* GetAccessor */ : - return `'get ${scope.name.getText()}'`; - case 175 /* SetAccessor */ : - return `'set ${scope.name.getText()}'`; - default: - throw Debug.assertNever(scope, `Unexpected scope kind ${scope.kind}`); + } + if (name || namedBindings) usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings)); + else if (hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier)) { + if (sourceFile.isDeclarationFile) usedImports.push(factory.createImportDeclaration(importDecl.modifiers, /*importClause*/ void 0, moduleSpecifier, /*assertClause*/ void 0)); + else usedImports.push(importDecl); + } + } + return usedImports; + function isDeclarationUsed(identifier) { + return jsxElementsPresent && (identifier.text === jsxNamespace || jsxFragmentFactory && identifier.text === jsxFragmentFactory) && jsxModeNeedsExplicitImport(compilerOptions.jsx) || ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); } } - function getDescriptionForClassLikeDeclaration(scope) { - return scope.kind === 260 /* ClassDeclaration */ ? scope.name ? `class '${scope.name.text}'` : "anonymous class declaration" : scope.name ? `class expression '${scope.name.text}'` : "anonymous class expression"; + function hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier) { + const moduleSpecifierText = isStringLiteral(moduleSpecifier) && moduleSpecifier.text; + return isString(moduleSpecifierText) && some(sourceFile.moduleAugmentations, (moduleName)=>isStringLiteral(moduleName) && moduleName.text === moduleSpecifierText); } - function getDescriptionForModuleLikeDeclaration(scope) { - return scope.kind === 265 /* ModuleBlock */ ? `namespace '${scope.parent.name.getText()}'` : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */ ; + function getExternalModuleName2(specifier) { + return specifier !== void 0 && isStringLiteralLike(specifier) ? specifier.text : void 0; } - function extractFunctionInScope(node, scope, { usages: usagesInScope , typeParameterUsages: typeParameterUsages , substitutions: substitutions }, exposedVariableDeclarations, range, context) { - const checker = context.program.getTypeChecker(); - const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions()); - const importAdder = ts_codefix_exports.createImportAdder(context.file, context.program, context.preferences, context.host); - const file = scope.getSourceFile(); - const functionNameText = getUniqueName(isClassLike(scope) ? "newMethod" : "newFunction", file); - const isJS = isInJSFile(scope); - const functionName = factory.createIdentifier(functionNameText); - let returnType; - const parameters = []; - const callArguments = []; - let writes; - usagesInScope.forEach((usage, name)=>{ - let typeNode; - if (!isJS) { - let type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); - type = checker.getBaseTypeOfLiteralType(type); - typeNode = ts_codefix_exports.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NoTruncation */ ); + function coalesceImports(importGroup, ignoreCase, sourceFile) { + const comparer = getOrganizeImportsOrdinalStringComparer(ignoreCase); + return coalesceImportsWorker(importGroup, comparer, sourceFile); + } + function coalesceImportsWorker(importGroup, comparer, sourceFile) { + if (importGroup.length === 0) return importGroup; + const { importWithoutClause: importWithoutClause, typeOnlyImports: typeOnlyImports, regularImports: regularImports } = getCategorizedImports(importGroup); + const coalescedImports = []; + if (importWithoutClause) coalescedImports.push(importWithoutClause); + for (const group2 of [ + regularImports, + typeOnlyImports + ]){ + const isTypeOnly = group2 === typeOnlyImports; + const { defaultImports: defaultImports, namespaceImports: namespaceImports, namedImports: namedImports } = group2; + if (!isTypeOnly && defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) { + const defaultImport = defaultImports[0]; + coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); + continue; } - const paramDecl = factory.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, /*name*/ name, /*questionToken*/ void 0, typeNode); - parameters.push(paramDecl); - if (usage.usage === 2 /* Write */ ) (writes || (writes = [])).push(usage); - callArguments.push(factory.createIdentifier(name)); - }); - const typeParametersAndDeclarations = arrayFrom(typeParameterUsages.values(), (type)=>({ - type: type, - declaration: getFirstDeclaration(type) - })); - const sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); - const typeParameters = sortedTypeParametersAndDeclarations.length === 0 ? void 0 : sortedTypeParametersAndDeclarations.map((t)=>t.declaration); - const callTypeArguments = typeParameters !== void 0 ? typeParameters.map((decl)=>factory.createTypeReferenceNode(decl.name, /*typeArguments*/ void 0)) : void 0; - if (isExpression(node) && !isJS) { - const contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */ ); - } - const { body: body , returnValueProperty: returnValueProperty } = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & 1 /* HasReturn */ )); - suppressLeadingAndTrailingTrivia(body); - let newFunction; - const callThis = !!(range.facts & 16 /* UsesThisInFunction */ ); - if (isClassLike(scope)) { - const modifiers = isJS ? [] : [ - factory.createModifier(121 /* PrivateKeyword */ ) - ]; - if (range.facts & 32 /* InStaticRegion */ ) modifiers.push(factory.createModifier(124 /* StaticKeyword */ )); - if (range.facts & 4 /* IsAsyncFunction */ ) modifiers.push(factory.createModifier(132 /* AsyncKeyword */ )); - newFunction = factory.createMethodDeclaration(modifiers.length ? modifiers : void 0, range.facts & 2 /* IsGenerator */ ? factory.createToken(41 /* AsteriskToken */ ) : void 0, functionName, /*questionToken*/ void 0, typeParameters, parameters, returnType, body); - } else { - if (callThis) parameters.unshift(factory.createParameterDeclaration(/*modifiers*/ void 0, /*dotDotDotToken*/ void 0, /*name*/ "this", /*questionToken*/ void 0, checker.typeToTypeNode(checker.getTypeAtLocation(range.thisNode), scope, 1 /* NoTruncation */ ), /*initializer*/ void 0)); - newFunction = factory.createFunctionDeclaration(range.facts & 4 /* IsAsyncFunction */ ? [ - factory.createToken(132 /* AsyncKeyword */ ) - ] : void 0, range.facts & 2 /* IsGenerator */ ? factory.createToken(41 /* AsteriskToken */ ) : void 0, functionName, typeParameters, parameters, returnType, body); + const sortedNamespaceImports = stableSort(namespaceImports, (i1, i2)=>comparer(i1.importClause.namedBindings.name.text, i2.importClause.namedBindings.name.text)); + for (const namespaceImport of sortedNamespaceImports)coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ void 0, namespaceImport.importClause.namedBindings)); + const firstDefaultImport = firstOrUndefined(defaultImports); + const firstNamedImport = firstOrUndefined(namedImports); + const importDecl = firstDefaultImport ?? firstNamedImport; + if (!importDecl) continue; + let newDefaultImport; + const newImportSpecifiers = []; + if (defaultImports.length === 1) newDefaultImport = defaultImports[0].importClause.name; + else for (const defaultImport of defaultImports)newImportSpecifiers.push(factory.createImportSpecifier(/*isTypeOnly*/ false, factory.createIdentifier("default"), defaultImport.importClause.name)); + newImportSpecifiers.push(...getNewImportSpecifiers(namedImports)); + const sortedImportSpecifiers = factory.createNodeArray(sortSpecifiers(newImportSpecifiers, comparer), firstNamedImport == null ? void 0 : firstNamedImport.importClause.namedBindings.elements.hasTrailingComma); + const newNamedImports = sortedImportSpecifiers.length === 0 ? newDefaultImport ? void 0 : factory.createNamedImports(emptyArray) : firstNamedImport ? factory.updateNamedImports(firstNamedImport.importClause.namedBindings, sortedImportSpecifiers) : factory.createNamedImports(sortedImportSpecifiers); + if (sourceFile && newNamedImports && (firstNamedImport == null ? void 0 : firstNamedImport.importClause.namedBindings) && !rangeIsOnSingleLine(firstNamedImport.importClause.namedBindings, sourceFile)) setEmitFlags(newNamedImports, 2 /* MultiLine */ ); + if (isTypeOnly && newDefaultImport && newNamedImports) { + coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, /*namedBindings*/ void 0)); + coalescedImports.push(updateImportDeclarationAndClause(firstNamedImport ?? importDecl, /*name*/ void 0, newNamedImports)); + } else coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports)); } - const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context); - const minInsertionPos = (isReadonlyArray(range.range) ? last(range.range) : range.range).end; - const nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope); - if (nodeToInsertBefore) changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, /*blankLineBetween*/ true); - else changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); - importAdder.writeFixes(changeTracker); - const newNodes = []; - const called = getCalledExpression(scope, range, functionNameText); - if (callThis) callArguments.unshift(factory.createIdentifier("this")); - let call = factory.createCallExpression(callThis ? factory.createPropertyAccessExpression(called, "call") : called, callTypeArguments, // Note that no attempt is made to take advantage of type argument inference - callArguments); - if (range.facts & 2 /* IsGenerator */ ) call = factory.createYieldExpression(factory.createToken(41 /* AsteriskToken */ ), call); - if (range.facts & 4 /* IsAsyncFunction */ ) call = factory.createAwaitExpression(call); - if (isInJSXContent(node)) call = factory.createJsxExpression(/*dotDotDotToken*/ void 0, call); - if (exposedVariableDeclarations.length && !writes) { - Debug.assert(!returnValueProperty, "Expected no returnValueProperty"); - Debug.assert(!(range.facts & 1 /* HasReturn */ ), "Expected RangeFacts.HasReturn flag to be unset"); - if (exposedVariableDeclarations.length === 1) { - const variableDeclaration = exposedVariableDeclarations[0]; - newNodes.push(factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ - factory.createVariableDeclaration(getSynthesizedDeepClone(variableDeclaration.name), /*exclamationToken*/ void 0, /*type*/ getSynthesizedDeepClone(variableDeclaration.type), /*initializer*/ call) - ], variableDeclaration.parent.flags))); - } else { - const bindingElements = []; - const typeElements = []; - let commonNodeFlags = exposedVariableDeclarations[0].parent.flags; - let sawExplicitType = false; - for (const variableDeclaration of exposedVariableDeclarations){ - bindingElements.push(factory.createBindingElement(/*dotDotDotToken*/ void 0, /*propertyName*/ void 0, /*name*/ getSynthesizedDeepClone(variableDeclaration.name))); - const variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */ ); - typeElements.push(factory.createPropertySignature(/*modifiers*/ void 0, /*name*/ variableDeclaration.symbol.name, /*questionToken*/ void 0, /*type*/ variableType)); - sawExplicitType = sawExplicitType || variableDeclaration.type !== void 0; - commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; - } - const typeLiteral = sawExplicitType ? factory.createTypeLiteralNode(typeElements) : void 0; - if (typeLiteral) setEmitFlags(typeLiteral, 1 /* SingleLine */ ); - newNodes.push(factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ - factory.createVariableDeclaration(factory.createObjectBindingPattern(bindingElements), /*exclamationToken*/ void 0, /*type*/ typeLiteral, /*initializer*/ call) - ], commonNodeFlags))); - } - } else if (exposedVariableDeclarations.length || writes) { - if (exposedVariableDeclarations.length) for (const variableDeclaration of exposedVariableDeclarations){ - let flags = variableDeclaration.parent.flags; - if (flags & 2 /* Const */ ) flags = flags & -3 /* Const */ | 1 /* Let */ ; - newNodes.push(factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ - factory.createVariableDeclaration(variableDeclaration.symbol.name, /*exclamationToken*/ void 0, getTypeDeepCloneUnionUndefined(variableDeclaration.type)) - ], flags))); + return coalescedImports; + } + function getCategorizedImports(importGroup) { + let importWithoutClause; + const typeOnlyImports = { + defaultImports: [], + namespaceImports: [], + namedImports: [] + }; + const regularImports = { + defaultImports: [], + namespaceImports: [], + namedImports: [] + }; + for (const importDeclaration of importGroup){ + if (importDeclaration.importClause === void 0) { + importWithoutClause = importWithoutClause || importDeclaration; + continue; } - if (returnValueProperty) newNodes.push(factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ - factory.createVariableDeclaration(returnValueProperty, /*exclamationToken*/ void 0, getTypeDeepCloneUnionUndefined(returnType)) - ], 1 /* Let */ ))); - const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); - if (returnValueProperty) assignments.unshift(factory.createShorthandPropertyAssignment(returnValueProperty)); - if (assignments.length === 1) { - Debug.assert(!returnValueProperty, "Shouldn't have returnValueProperty here"); - newNodes.push(factory.createExpressionStatement(factory.createAssignment(assignments[0].name, call))); - if (range.facts & 1 /* HasReturn */ ) newNodes.push(factory.createReturnStatement()); - } else { - newNodes.push(factory.createExpressionStatement(factory.createAssignment(factory.createObjectLiteralExpression(assignments), call))); - if (returnValueProperty) newNodes.push(factory.createReturnStatement(factory.createIdentifier(returnValueProperty))); + const group2 = importDeclaration.importClause.isTypeOnly ? typeOnlyImports : regularImports; + const { name: name, namedBindings: namedBindings } = importDeclaration.importClause; + if (name) group2.defaultImports.push(importDeclaration); + if (namedBindings) { + if (isNamespaceImport(namedBindings)) group2.namespaceImports.push(importDeclaration); + else group2.namedImports.push(importDeclaration); } - } else { - if (range.facts & 1 /* HasReturn */ ) newNodes.push(factory.createReturnStatement(call)); - else if (isReadonlyArray(range.range)) newNodes.push(factory.createExpressionStatement(call)); - else newNodes.push(call); } - if (isReadonlyArray(range.range)) changeTracker.replaceNodeRangeWithNodes(context.file, first(range.range), last(range.range), newNodes); - else changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes); - const edits = changeTracker.getChanges(); - const renameRange = isReadonlyArray(range.range) ? first(range.range) : range.range; - const renameFilename = renameRange.getSourceFile().fileName; - const renameLocation = getRenameLocation(edits, renameFilename, functionNameText, /*isDeclaredBeforeUse*/ false); return { - renameFilename: renameFilename, - renameLocation: renameLocation, - edits: edits + importWithoutClause: importWithoutClause, + typeOnlyImports: typeOnlyImports, + regularImports: regularImports }; - function getTypeDeepCloneUnionUndefined(typeNode) { - if (typeNode === void 0) return void 0; - const clone2 = getSynthesizedDeepClone(typeNode); - let withoutParens = clone2; - while(isParenthesizedTypeNode(withoutParens))withoutParens = withoutParens.type; - return isUnionTypeNode(withoutParens) && find(withoutParens.types, (t)=>t.kind === 155 /* UndefinedKeyword */ ) ? clone2 : factory.createUnionTypeNode([ - clone2, - factory.createKeywordTypeNode(155 /* UndefinedKeyword */ ) - ]); - } } - function extractConstantInScope(node, scope, { substitutions: substitutions }, rangeFacts, context) { - const checker = context.program.getTypeChecker(); - const file = scope.getSourceFile(); - const localNameText = isPropertyAccessExpression(node) && !isClassLike(scope) && !checker.resolveName(node.name.text, node, 111551 /* Value */ , /*excludeGlobals*/ false) && !isPrivateIdentifier(node.name) && !identifierToKeywordKind(node.name) ? node.name.text : getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file); - const isJS = isInJSFile(scope); - let variableType = isJS || !checker.isContextSensitive(node) ? void 0 : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */ ); - let initializer = transformConstantInitializer(skipParentheses(node), substitutions); - ({ variableType: variableType , initializer: initializer } = transformFunctionInitializerAndType(variableType, initializer)); - suppressLeadingAndTrailingTrivia(initializer); - const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context); - if (isClassLike(scope)) { - Debug.assert(!isJS, "Cannot extract to a JS class"); - const modifiers = []; - modifiers.push(factory.createModifier(121 /* PrivateKeyword */ )); - if (rangeFacts & 32 /* InStaticRegion */ ) modifiers.push(factory.createModifier(124 /* StaticKeyword */ )); - modifiers.push(factory.createModifier(146 /* ReadonlyKeyword */ )); - const newVariable = factory.createPropertyDeclaration(modifiers, localNameText, /*questionToken*/ void 0, variableType, initializer); - let localReference = factory.createPropertyAccessExpression(rangeFacts & 32 /* InStaticRegion */ ? factory.createIdentifier(scope.name.getText()) : factory.createThis(), factory.createIdentifier(localNameText)); - if (isInJSXContent(node)) localReference = factory.createJsxExpression(/*dotDotDotToken*/ void 0, localReference); - const maxInsertionPos = node.pos; - const nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); - changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, /*blankLineBetween*/ true); - changeTracker.replaceNode(context.file, node, localReference); - } else { - const newVariableDeclaration = factory.createVariableDeclaration(localNameText, /*exclamationToken*/ void 0, variableType, initializer); - const oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope); - if (oldVariableDeclaration) { - changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); - const localReference = factory.createIdentifier(localNameText); - changeTracker.replaceNode(context.file, node, localReference); - } else if (node.parent.kind === 241 /* ExpressionStatement */ && scope === findAncestor(node, isScope)) { - const newVariableStatement = factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ - newVariableDeclaration - ], 2 /* Const */ )); - changeTracker.replaceNode(context.file, node.parent, newVariableStatement); - } else { - const newVariableStatement = factory.createVariableStatement(/*modifiers*/ void 0, factory.createVariableDeclarationList([ - newVariableDeclaration - ], 2 /* Const */ )); - const nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); - if (nodeToInsertBefore.pos === 0) changeTracker.insertNodeAtTopOfFile(context.file, newVariableStatement, /*blankLineBetween*/ false); - else changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false); - if (node.parent.kind === 241 /* ExpressionStatement */ ) changeTracker.delete(context.file, node.parent); - else { - let localReference = factory.createIdentifier(localNameText); - if (isInJSXContent(node)) localReference = factory.createJsxExpression(/*dotDotDotToken*/ void 0, localReference); - changeTracker.replaceNode(context.file, node, localReference); - } - } + function coalesceExports(exportGroup, ignoreCase) { + const comparer = getOrganizeImportsOrdinalStringComparer(ignoreCase); + return coalesceExportsWorker(exportGroup, comparer); + } + function coalesceExportsWorker(exportGroup, comparer) { + if (exportGroup.length === 0) return exportGroup; + const { exportWithoutClause: exportWithoutClause, namedExports: namedExports, typeOnlyExports: typeOnlyExports } = getCategorizedExports(exportGroup); + const coalescedExports = []; + if (exportWithoutClause) coalescedExports.push(exportWithoutClause); + for (const exportGroup2 of [ + namedExports, + typeOnlyExports + ]){ + if (exportGroup2.length === 0) continue; + const newExportSpecifiers = []; + newExportSpecifiers.push(...flatMap(exportGroup2, (i)=>i.exportClause && isNamedExports(i.exportClause) ? i.exportClause.elements : emptyArray)); + const sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers, comparer); + const exportDecl = exportGroup2[0]; + coalescedExports.push(factory.updateExportDeclaration(exportDecl, exportDecl.modifiers, exportDecl.isTypeOnly, exportDecl.exportClause && (isNamedExports(exportDecl.exportClause) ? factory.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers) : factory.updateNamespaceExport(exportDecl.exportClause, exportDecl.exportClause.name)), exportDecl.moduleSpecifier, exportDecl.assertClause)); } - const edits = changeTracker.getChanges(); - const renameFilename = node.getSourceFile().fileName; - const renameLocation = getRenameLocation(edits, renameFilename, localNameText, /*isDeclaredBeforeUse*/ true); - return { - renameFilename: renameFilename, - renameLocation: renameLocation, - edits: edits - }; - function transformFunctionInitializerAndType(variableType2, initializer2) { - if (variableType2 === void 0) return { - variableType: variableType2, - initializer: initializer2 - }; - if (!isFunctionExpression(initializer2) && !isArrowFunction(initializer2) || !!initializer2.typeParameters) return { - variableType: variableType2, - initializer: initializer2 - }; - const functionType = checker.getTypeAtLocation(node); - const functionSignature = singleOrUndefined(checker.getSignaturesOfType(functionType, 0 /* Call */ )); - if (!functionSignature) return { - variableType: variableType2, - initializer: initializer2 - }; - if (!!functionSignature.getTypeParameters()) return { - variableType: variableType2, - initializer: initializer2 - }; - const parameters = []; - let hasAny = false; - for (const p of initializer2.parameters)if (p.type) parameters.push(p); - else { - const paramType = checker.getTypeAtLocation(p); - if (paramType === checker.getAnyType()) hasAny = true; - parameters.push(factory.updateParameterDeclaration(p, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, p.type || checker.typeToTypeNode(paramType, scope, 1 /* NoTruncation */ ), p.initializer)); - } - if (hasAny) return { - variableType: variableType2, - initializer: initializer2 - }; - variableType2 = void 0; - if (isArrowFunction(initializer2)) initializer2 = factory.updateArrowFunction(initializer2, canHaveModifiers(node) ? getModifiers(node) : void 0, initializer2.typeParameters, parameters, initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */ ), initializer2.equalsGreaterThanToken, initializer2.body); - else { - if (functionSignature && !!functionSignature.thisParameter) { - const firstParameter = firstOrUndefined(parameters); - if (!firstParameter || isIdentifier(firstParameter.name) && firstParameter.name.escapedText !== "this") { - const thisType = checker.getTypeOfSymbolAtLocation(functionSignature.thisParameter, node); - parameters.splice(0, 0, factory.createParameterDeclaration(/* modifiers */ void 0, /* dotDotDotToken */ void 0, "this", /* questionToken */ void 0, checker.typeToTypeNode(thisType, scope, 1 /* NoTruncation */ ))); - } - } - initializer2 = factory.updateFunctionExpression(initializer2, canHaveModifiers(node) ? getModifiers(node) : void 0, initializer2.asteriskToken, initializer2.name, initializer2.typeParameters, parameters, initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */ ), initializer2.body); + return coalescedExports; + function getCategorizedExports(exportGroup2) { + let exportWithoutClause2; + const namedExports2 = []; + const typeOnlyExports2 = []; + for (const exportDeclaration of exportGroup2){ + if (exportDeclaration.exportClause === void 0) exportWithoutClause2 = exportWithoutClause2 || exportDeclaration; + else if (exportDeclaration.isTypeOnly) typeOnlyExports2.push(exportDeclaration); + else namedExports2.push(exportDeclaration); } return { - variableType: variableType2, - initializer: initializer2 + exportWithoutClause: exportWithoutClause2, + namedExports: namedExports2, + typeOnlyExports: typeOnlyExports2 }; } } - function getContainingVariableDeclarationIfInList(node, scope) { - let prevNode; - while(node !== void 0 && node !== scope){ - if (isVariableDeclaration(node) && node.initializer === prevNode && isVariableDeclarationList(node.parent) && node.parent.declarations.length > 1) return node; - prevNode = node; - node = node.parent; - } + function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { + return factory.updateImportDeclaration(importDeclaration, importDeclaration.modifiers, factory.updateImportClause(importDeclaration.importClause, importDeclaration.importClause.isTypeOnly, name, namedBindings), // TODO: GH#18217 + importDeclaration.moduleSpecifier, importDeclaration.assertClause); } - function getFirstDeclaration(type) { - let firstDeclaration; - const symbol = type.symbol; - if (symbol && symbol.declarations) { - for (const declaration of symbol.declarations)if (firstDeclaration === void 0 || declaration.pos < firstDeclaration.pos) firstDeclaration = declaration; - } - return firstDeclaration; + function sortSpecifiers(specifiers, comparer) { + return stableSort(specifiers, (s1, s2)=>compareImportOrExportSpecifiers(s1, s2, comparer)); } - function compareTypesByDeclarationOrder({ type: type1 , declaration: declaration1 }, { type: type2 , declaration: declaration2 }) { - return compareProperties(declaration1, declaration2, "pos", compareValues) || compareStringsCaseSensitive(type1.symbol ? type1.symbol.getName() : "", type2.symbol ? type2.symbol.getName() : "") || compareValues(type1.id, type2.id); + function compareImportOrExportSpecifiers(s1, s2, comparer) { + return compareBooleans(s1.isTypeOnly, s2.isTypeOnly) || comparer(s1.name.text, s2.name.text); } - function getCalledExpression(scope, range, functionNameText) { - const functionReference = factory.createIdentifier(functionNameText); - if (isClassLike(scope)) { - const lhs = range.facts & 32 /* InStaticRegion */ ? factory.createIdentifier(scope.name.text) : factory.createThis(); - return factory.createPropertyAccessExpression(lhs, functionReference); - } else return functionReference; + function compareModuleSpecifiers2(m1, m2, ignoreCase) { + const comparer = getOrganizeImportsOrdinalStringComparer(!!ignoreCase); + return compareModuleSpecifiersWorker(m1, m2, comparer); } - function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn2) { - const hasWritesOrVariableDeclarations = writes !== void 0 || exposedVariableDeclarations.length > 0; - if (isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) return { - body: factory.createBlock(body.statements, /*multLine*/ true), - returnValueProperty: void 0 - }; - let returnValueProperty; - let ignoreReturns = false; - const statements = factory.createNodeArray(isBlock(body) ? body.statements.slice(0) : [ - isStatement(body) ? body : factory.createReturnStatement(skipParentheses(body)) - ]); - if (hasWritesOrVariableDeclarations || substitutions.size) { - const rewrittenStatements = visitNodes2(statements, visitor, isStatement).slice(); - if (hasWritesOrVariableDeclarations && !hasReturn2 && isStatement(body)) { - const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); - if (assignments.length === 1) rewrittenStatements.push(factory.createReturnStatement(assignments[0].name)); - else rewrittenStatements.push(factory.createReturnStatement(factory.createObjectLiteralExpression(assignments))); + function compareModuleSpecifiersWorker(m1, m2, comparer) { + const name1 = m1 === void 0 ? void 0 : getExternalModuleName2(m1); + const name2 = m2 === void 0 ? void 0 : getExternalModuleName2(m2); + return compareBooleans(name1 === void 0, name2 === void 0) || compareBooleans(isExternalModuleNameRelative(name1), isExternalModuleNameRelative(name2)) || comparer(name1, name2); + } + function getModuleSpecifierExpression(declaration) { + var _a; + switch(declaration.kind){ + case 271 /* ImportEqualsDeclaration */ : + return (_a = tryCast(declaration.moduleReference, isExternalModuleReference)) == null ? void 0 : _a.expression; + case 272 /* ImportDeclaration */ : + return declaration.moduleSpecifier; + case 243 /* VariableStatement */ : + return declaration.declarationList.declarations[0].initializer.arguments[0]; + } + } + function detectSorting(sourceFile, preferences) { + return detectSortingWorker(groupByNewlineContiguous(sourceFile, sourceFile.statements.filter(isImportDeclaration)), preferences); + } + function detectSortingWorker(importGroups, preferences) { + const collateCaseSensitive = getOrganizeImportsComparer(preferences, /*ignoreCase*/ false); + const collateCaseInsensitive = getOrganizeImportsComparer(preferences, /*ignoreCase*/ true); + let sortState = 3 /* Both */ ; + let seenUnsortedGroup = false; + for (const importGroup of importGroups){ + if (importGroup.length > 1) { + const moduleSpecifierSort = detectSortCaseSensitivity(importGroup, (i)=>{ + var _a; + return ((_a = tryCast(i.moduleSpecifier, isStringLiteral)) == null ? void 0 : _a.text) ?? ""; + }, collateCaseSensitive, collateCaseInsensitive); + if (moduleSpecifierSort) { + sortState &= moduleSpecifierSort; + seenUnsortedGroup = true; + } + if (!sortState) return sortState; } - return { - body: factory.createBlock(rewrittenStatements, /*multiLine*/ true), - returnValueProperty: returnValueProperty - }; - } else return { - body: factory.createBlock(statements, /*multiLine*/ true), - returnValueProperty: void 0 - }; - function visitor(node) { - if (!ignoreReturns && isReturnStatement(node) && hasWritesOrVariableDeclarations) { - const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); - if (node.expression) { - if (!returnValueProperty) returnValueProperty = "__return"; - assignments.unshift(factory.createPropertyAssignment(returnValueProperty, visitNode(node.expression, visitor, isExpression))); + const declarationWithNamedImports = find(importGroup, (i)=>{ + var _a, _b; + return ((_b = tryCast((_a = i.importClause) == null ? void 0 : _a.namedBindings, isNamedImports)) == null ? void 0 : _b.elements.length) > 1; + }); + if (declarationWithNamedImports) { + const namedImportSort = detectImportSpecifierSorting(declarationWithNamedImports.importClause.namedBindings.elements, preferences); + if (namedImportSort) { + sortState &= namedImportSort; + seenUnsortedGroup = true; } - if (assignments.length === 1) return factory.createReturnStatement(assignments[0].name); - else return factory.createReturnStatement(factory.createObjectLiteralExpression(assignments)); - } else { - const oldIgnoreReturns = ignoreReturns; - ignoreReturns = ignoreReturns || isFunctionLikeDeclaration(node) || isClassLike(node); - const substitution = substitutions.get(getNodeId(node).toString()); - const result = substitution ? getSynthesizedDeepClone(substitution) : visitEachChild(node, visitor, nullTransformationContext); - ignoreReturns = oldIgnoreReturns; - return result; + if (!sortState) return sortState; } + if (sortState !== 3 /* Both */ ) return sortState; } + return seenUnsortedGroup ? 0 /* None */ : sortState; } - function transformConstantInitializer(initializer, substitutions) { - return substitutions.size ? visitor(initializer) : initializer; - function visitor(node) { - const substitution = substitutions.get(getNodeId(node).toString()); - return substitution ? getSynthesizedDeepClone(substitution) : visitEachChild(node, visitor, nullTransformationContext); - } + function detectImportDeclarationSorting(imports, preferences) { + const collateCaseSensitive = getOrganizeImportsComparer(preferences, /*ignoreCase*/ false); + const collateCaseInsensitive = getOrganizeImportsComparer(preferences, /*ignoreCase*/ true); + return detectSortCaseSensitivity(imports, (s)=>getExternalModuleName2(getModuleSpecifierExpression(s)) || "", collateCaseSensitive, collateCaseInsensitive); } - function getStatementsOrClassElements(scope) { - if (isFunctionLikeDeclaration(scope)) { - const body = scope.body; - if (isBlock(body)) return body.statements; - } else if (isModuleBlock(scope) || isSourceFile(scope)) return scope.statements; - else if (isClassLike(scope)) return scope.members; - else assertType(scope); - return emptyArray; + function getImportDeclarationInsertionIndex(sortedImports, newImport, comparer) { + const index = binarySearch(sortedImports, newImport, identity, (a, b)=>compareImportsOrRequireStatements(a, b, comparer)); + return index < 0 ? ~index : index; } - function getNodeToInsertFunctionBefore(minPos, scope) { - return find(getStatementsOrClassElements(scope), (child)=>child.pos >= minPos && isFunctionLikeDeclaration(child) && !isConstructorDeclaration(child)); + function getImportSpecifierInsertionIndex(sortedImports, newImport, comparer) { + const index = binarySearch(sortedImports, newImport, identity, (s1, s2)=>compareImportOrExportSpecifiers(s1, s2, comparer)); + return index < 0 ? ~index : index; } - function getNodeToInsertPropertyBefore(maxPos, scope) { - const members = scope.members; - Debug.assert(members.length > 0, "Found no members"); - let prevMember; - let allProperties = true; - for (const member of members){ - if (member.pos > maxPos) return prevMember || members[0]; - if (allProperties && !isPropertyDeclaration(member)) { - if (prevMember !== void 0) return member; - allProperties = false; - } - prevMember = member; - } - if (prevMember === void 0) return Debug.fail(); - return prevMember; + function compareImportsOrRequireStatements(s1, s2, comparer) { + return compareModuleSpecifiersWorker(getModuleSpecifierExpression(s1), getModuleSpecifierExpression(s2), comparer) || compareImportKind(s1, s2); } - function getNodeToInsertConstantBefore(node, scope) { - Debug.assert(!isClassLike(scope)); - let prevScope; - for(let curr = node; curr !== scope; curr = curr.parent)if (isScope(curr)) prevScope = curr; - for(let curr = (prevScope || node).parent;; curr = curr.parent){ - if (isBlockLike(curr)) { - let prevStatement; - for (const statement of curr.statements){ - if (statement.pos > node.pos) break; - prevStatement = statement; - } - if (!prevStatement && isCaseClause(curr)) { - Debug.assert(isSwitchStatement(curr.parent.parent), "Grandparent isn't a switch statement"); - return curr.parent.parent; - } - return Debug.checkDefined(prevStatement, "prevStatement failed to get set"); - } - Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope"); + function compareImportKind(s1, s2) { + return compareValues(getImportKindOrder(s1), getImportKindOrder(s2)); + } + function getImportKindOrder(s1) { + var _a; + switch(s1.kind){ + case 272 /* ImportDeclaration */ : + if (!s1.importClause) return 0; + if (s1.importClause.isTypeOnly) return 1; + if (((_a = s1.importClause.namedBindings) == null ? void 0 : _a.kind) === 274 /* NamespaceImport */ ) return 2; + if (s1.importClause.name) return 3; + return 4; + case 271 /* ImportEqualsDeclaration */ : + return 5; + case 243 /* VariableStatement */ : + return 6; } } - function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { - const variableAssignments = map(exposedVariableDeclarations, (v)=>factory.createShorthandPropertyAssignment(v.symbol.name)); - const writeAssignments = map(writes, (w)=>factory.createShorthandPropertyAssignment(w.symbol.name)); - return variableAssignments === void 0 ? writeAssignments : writeAssignments === void 0 ? variableAssignments : variableAssignments.concat(writeAssignments); + function getNewImportSpecifiers(namedImports) { + return flatMap(namedImports, (namedImport)=>map(tryGetNamedBindingElements(namedImport), (importSpecifier)=>importSpecifier.name && importSpecifier.propertyName && importSpecifier.name.escapedText === importSpecifier.propertyName.escapedText ? factory.updateImportSpecifier(importSpecifier, importSpecifier.isTypeOnly, /*propertyName*/ void 0, importSpecifier.name) : importSpecifier)); } - function isReadonlyArray(v) { - return isArray(v); + function tryGetNamedBindingElements(namedImport) { + var _a; + return ((_a = namedImport.importClause) == null ? void 0 : _a.namedBindings) && isNamedImports(namedImport.importClause.namedBindings) ? namedImport.importClause.namedBindings.elements : void 0; } - function getEnclosingTextRange(targetRange, sourceFile) { - return isReadonlyArray(targetRange.range) ? { - pos: first(targetRange.range).getStart(sourceFile), - end: last(targetRange.range).getEnd() - } : targetRange.range; + function getOrganizeImportsOrdinalStringComparer(ignoreCase) { + return ignoreCase ? compareStringsCaseInsensitiveEslintCompatible : compareStringsCaseSensitive; } - function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) { - const allTypeParameterUsages = /* @__PURE__ */ new Map(); - const usagesPerScope = []; - const substitutionsPerScope = []; - const functionErrorsPerScope = []; - const constantErrorsPerScope = []; - const visibleDeclarationsInExtractedRange = []; - const exposedVariableSymbolSet = /* @__PURE__ */ new Map(); - const exposedVariableDeclarations = []; - let firstExposedNonVariableDeclaration; - const expression = !isReadonlyArray(targetRange.range) ? targetRange.range : targetRange.range.length === 1 && isExpressionStatement(targetRange.range[0]) ? targetRange.range[0].expression : void 0; - let expressionDiagnostic; - if (expression === void 0) { - const statements = targetRange.range; - const start = first(statements).getStart(); - const end = last(statements).end; - expressionDiagnostic = createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); - } else if (checker.getTypeAtLocation(expression).flags & 147456 /* Never */ ) expressionDiagnostic = createDiagnosticForNode(expression, Messages.uselessConstantType); - for (const scope of scopes){ - usagesPerScope.push({ - usages: /* @__PURE__ */ new Map(), - typeParameterUsages: /* @__PURE__ */ new Map(), - substitutions: /* @__PURE__ */ new Map() - }); - substitutionsPerScope.push(/* @__PURE__ */ new Map()); - functionErrorsPerScope.push([]); - const constantErrors = []; - if (expressionDiagnostic) constantErrors.push(expressionDiagnostic); - if (isClassLike(scope) && isInJSFile(scope)) constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); - if (isArrowFunction(scope) && !isBlock(scope.body)) constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction)); - constantErrorsPerScope.push(constantErrors); - } - const seenUsages = /* @__PURE__ */ new Map(); - const target = isReadonlyArray(targetRange.range) ? factory.createBlock(targetRange.range) : targetRange.range; - const unmodifiedNode = isReadonlyArray(targetRange.range) ? first(targetRange.range) : targetRange.range; - const inGenericContext = isInGenericContext(unmodifiedNode); - collectUsages(target); - if (inGenericContext && !isReadonlyArray(targetRange.range) && !isJsxAttribute(targetRange.range)) { - const contextualType = checker.getContextualType(targetRange.range); - recordTypeParameterUsages(contextualType); - } - if (allTypeParameterUsages.size > 0) { - const seenTypeParameterUsages = /* @__PURE__ */ new Map(); - let i = 0; - for(let curr = unmodifiedNode; curr !== void 0 && i < scopes.length; curr = curr.parent){ - if (curr === scopes[i]) { - seenTypeParameterUsages.forEach((typeParameter, id)=>{ - usagesPerScope[i].typeParameterUsages.set(id, typeParameter); - }); - i++; + function getOrganizeImportsUnicodeStringComparer(ignoreCase, preferences) { + const resolvedLocale = getOrganizeImportsLocale(preferences); + const caseFirst = preferences.organizeImportsCaseFirst ?? false; + const numeric = preferences.organizeImportsNumericCollation ?? false; + const accents = preferences.organizeImportsAccentCollation ?? true; + const sensitivity = ignoreCase ? accents ? "accent" : "base" : accents ? "variant" : "case"; + const collator = new Intl.Collator(resolvedLocale, { + usage: "sort", + caseFirst: caseFirst || "false", + sensitivity: sensitivity, + numeric: numeric + }); + return collator.compare; + } + function getOrganizeImportsLocale(preferences) { + let locale = preferences.organizeImportsLocale; + if (locale === "auto") locale = getUILocale(); + if (locale === void 0) locale = "en"; + const supportedLocales = Intl.Collator.supportedLocalesOf(locale); + const resolvedLocale = supportedLocales.length ? supportedLocales[0] : "en"; + return resolvedLocale; + } + function getOrganizeImportsComparer(preferences, ignoreCase) { + const collation = preferences.organizeImportsCollation ?? "ordinal"; + return collation === "unicode" ? getOrganizeImportsUnicodeStringComparer(ignoreCase, preferences) : getOrganizeImportsOrdinalStringComparer(ignoreCase); + } + function getOrganizeImportsComparerWithDetection(preferences, detectIgnoreCase) { + const ignoreCase = typeof preferences.organizeImportsIgnoreCase === "boolean" ? preferences.organizeImportsIgnoreCase : (detectIgnoreCase == null ? void 0 : detectIgnoreCase()) ?? false; + return getOrganizeImportsComparer(preferences, ignoreCase); + } + function getTopLevelExportGroups(sourceFile) { + const topLevelExportGroups = []; + const statements = sourceFile.statements; + const len = length(statements); + let i = 0; + let groupIndex = 0; + while(i < len)if (isExportDeclaration(statements[i])) { + if (topLevelExportGroups[groupIndex] === void 0) topLevelExportGroups[groupIndex] = []; + const exportDecl = statements[i]; + if (exportDecl.moduleSpecifier) { + topLevelExportGroups[groupIndex].push(exportDecl); + i++; + } else { + while(i < len && isExportDeclaration(statements[i]))topLevelExportGroups[groupIndex].push(statements[i++]); + groupIndex++; + } + } else i++; + return flatMap(topLevelExportGroups, (exportGroupDecls)=>groupByNewlineContiguous(sourceFile, exportGroupDecls)); + } + var ImportSpecifierSortingCache, detectImportSpecifierSorting; + var init_organizeImports = __esm({ + "src/services/organizeImports.ts" () { + "use strict"; + init_ts4(); + ImportSpecifierSortingCache = class { + has([specifiers, preferences]) { + if (this._lastPreferences !== preferences || !this._cache) return false; + return this._cache.has(specifiers); } - if (isDeclarationWithTypeParameters(curr)) for (const typeParameterDecl of getEffectiveTypeParameterDeclarations(curr)){ - const typeParameter = checker.getTypeAtLocation(typeParameterDecl); - if (allTypeParameterUsages.has(typeParameter.id.toString())) seenTypeParameterUsages.set(typeParameter.id.toString(), typeParameter); + get([specifiers, preferences]) { + if (this._lastPreferences !== preferences || !this._cache) return void 0; + return this._cache.get(specifiers); } - } - Debug.assert(i === scopes.length, "Should have iterated all scopes"); - } - if (visibleDeclarationsInExtractedRange.length) { - const containingLexicalScopeOfExtraction = isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : getEnclosingBlockScopeContainer(scopes[0]); - forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); - } - for(let i = 0; i < scopes.length; i++){ - const scopeUsages = usagesPerScope[i]; - if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) { - const errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; - constantErrorsPerScope[i].push(createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes)); - } - if (targetRange.facts & 16 /* UsesThisInFunction */ && isClassLike(scopes[i])) functionErrorsPerScope[i].push(createDiagnosticForNode(targetRange.thisNode, Messages.cannotExtractFunctionsContainingThisToMethod)); - let hasWrite = false; - let readonlyClassPropertyWrite; - usagesPerScope[i].usages.forEach((value1)=>{ - if (value1.usage === 2 /* Write */ ) { - hasWrite = true; - if (value1.symbol.flags & 106500 /* ClassMember */ && value1.symbol.valueDeclaration && hasEffectiveModifier(value1.symbol.valueDeclaration, 64 /* Readonly */ )) readonlyClassPropertyWrite = value1.symbol.valueDeclaration; + set([specifiers, preferences], value1) { + if (this._lastPreferences !== preferences) { + this._lastPreferences = preferences; + this._cache = void 0; + } + this._cache ?? (this._cache = /* @__PURE__ */ new WeakMap()); + this._cache.set(specifiers, value1); } - }); - Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0, "No variable declarations expected if something was extracted"); - if (hasWrite && !isReadonlyArray(targetRange.range)) { - const diag2 = createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression); - functionErrorsPerScope[i].push(diag2); - constantErrorsPerScope[i].push(diag2); - } else if (readonlyClassPropertyWrite && i > 0) { - const diag2 = createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor); - functionErrorsPerScope[i].push(diag2); - constantErrorsPerScope[i].push(diag2); - } else if (firstExposedNonVariableDeclaration) { - const diag2 = createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity); - functionErrorsPerScope[i].push(diag2); - constantErrorsPerScope[i].push(diag2); - } - } - return { - target: target, - usagesPerScope: usagesPerScope, - functionErrorsPerScope: functionErrorsPerScope, - constantErrorsPerScope: constantErrorsPerScope, - exposedVariableDeclarations: exposedVariableDeclarations - }; - function isInGenericContext(node) { - return !!findAncestor(node, (n)=>isDeclarationWithTypeParameters(n) && getEffectiveTypeParameterDeclarations(n).length !== 0); - } - function recordTypeParameterUsages(type) { - const symbolWalker = checker.getSymbolWalker(()=>(cancellationToken.throwIfCancellationRequested(), true)); - const { visitedTypes: visitedTypes } = symbolWalker.walkType(type); - for (const visitedType of visitedTypes)if (visitedType.isTypeParameter()) allTypeParameterUsages.set(visitedType.id.toString(), visitedType); - } - function collectUsages(node, valueUsage = 1 /* Read */ ) { - if (inGenericContext) { - const type = checker.getTypeAtLocation(node); - recordTypeParameterUsages(type); - } - if (isDeclaration(node) && node.symbol) visibleDeclarationsInExtractedRange.push(node); - if (isAssignmentExpression(node)) { - collectUsages(node.left, 2 /* Write */ ); - collectUsages(node.right); - } else if (isUnaryExpressionWithWrite(node)) collectUsages(node.operand, 2 /* Write */ ); - else if (isPropertyAccessExpression(node) || isElementAccessExpression(node)) forEachChild(node, collectUsages); - else if (isIdentifier(node)) { - if (!node.parent) return; - if (isQualifiedName(node.parent) && node !== node.parent.left) return; - if (isPropertyAccessExpression(node.parent) && node !== node.parent.expression) return; - recordUsage(node, valueUsage, /*isTypeNode*/ isPartOfTypeNode(node)); - } else forEachChild(node, collectUsages); + }; + detectImportSpecifierSorting = memoizeCached((specifiers, preferences)=>{ + if (!arrayIsSorted(specifiers, (s1, s2)=>compareBooleans(s1.isTypeOnly, s2.isTypeOnly))) return 0 /* None */ ; + const collateCaseSensitive = getOrganizeImportsComparer(preferences, /*ignoreCase*/ false); + const collateCaseInsensitive = getOrganizeImportsComparer(preferences, /*ignoreCase*/ true); + return detectSortCaseSensitivity(specifiers, (specifier)=>specifier.name.text, collateCaseSensitive, collateCaseInsensitive); + }, new ImportSpecifierSortingCache()); } - function recordUsage(n, usage, isTypeNode2) { - const symbolId = recordUsagebySymbol(n, usage, isTypeNode2); - if (symbolId) for(let i = 0; i < scopes.length; i++){ - const substitution = substitutionsPerScope[i].get(symbolId); - if (substitution) usagesPerScope[i].substitutions.set(getNodeId(n).toString(), substitution); - } + }); + // src/services/_namespaces/ts.OrganizeImports.ts + var ts_OrganizeImports_exports = {}; + __export(ts_OrganizeImports_exports, { + coalesceExports: ()=>coalesceExports, + coalesceImports: ()=>coalesceImports, + compareImportOrExportSpecifiers: ()=>compareImportOrExportSpecifiers, + compareImportsOrRequireStatements: ()=>compareImportsOrRequireStatements, + compareModuleSpecifiers: ()=>compareModuleSpecifiers2, + detectImportDeclarationSorting: ()=>detectImportDeclarationSorting, + detectImportSpecifierSorting: ()=>detectImportSpecifierSorting, + detectSorting: ()=>detectSorting, + getImportDeclarationInsertionIndex: ()=>getImportDeclarationInsertionIndex, + getImportSpecifierInsertionIndex: ()=>getImportSpecifierInsertionIndex, + getOrganizeImportsComparer: ()=>getOrganizeImportsComparer, + organizeImports: ()=>organizeImports + }); + var init_ts_OrganizeImports = __esm({ + "src/services/_namespaces/ts.OrganizeImports.ts" () { + "use strict"; + init_organizeImports(); } - function recordUsagebySymbol(identifier, usage, isTypeName) { - const symbol = getSymbolReferencedByIdentifier(identifier); - if (!symbol) return void 0; - const symbolId = getSymbolId(symbol).toString(); - const lastUsage = seenUsages.get(symbolId); - if (lastUsage && lastUsage >= usage) return symbolId; - seenUsages.set(symbolId, usage); - if (lastUsage) { - for (const perScope of usagesPerScope){ - const prevEntry = perScope.usages.get(identifier.text); - if (prevEntry) perScope.usages.set(identifier.text, { - usage: usage, - symbol: symbol, - node: identifier - }); - } - return symbolId; - } - const decls = symbol.getDeclarations(); - const declInFile = decls && find(decls, (d)=>d.getSourceFile() === sourceFile); - if (!declInFile) return void 0; - if (rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) return void 0; - if (targetRange.facts & 2 /* IsGenerator */ && usage === 2 /* Write */ ) { - const diag2 = createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators); - for (const errors of functionErrorsPerScope)errors.push(diag2); - for (const errors of constantErrorsPerScope)errors.push(diag2); + }); + // src/services/outliningElementsCollector.ts + function collectElements(sourceFile, cancellationToken) { + const res = []; + addNodeOutliningSpans(sourceFile, cancellationToken, res); + addRegionOutliningSpans(sourceFile, res); + return res.sort((span1, span2)=>span1.textSpan.start - span2.textSpan.start); + } + function addNodeOutliningSpans(sourceFile, cancellationToken, out) { + let depthRemaining = 40; + let current = 0; + const statements = [ + ...sourceFile.statements, + sourceFile.endOfFileToken + ]; + const n = statements.length; + while(current < n){ + while(current < n && !isAnyImportSyntax(statements[current])){ + visitNode3(statements[current]); + current++; } - for(let i = 0; i < scopes.length; i++){ - const scope = scopes[i]; - const resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags, /*excludeGlobals*/ false); - if (resolvedSymbol === symbol) continue; - if (!substitutionsPerScope[i].has(symbolId)) { - const substitution = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.exportSymbol || symbol, scope, isTypeName); - if (substitution) substitutionsPerScope[i].set(symbolId, substitution); - else if (isTypeName) { - if (!(symbol.flags & 262144 /* TypeParameter */ )) { - const diag2 = createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope); - functionErrorsPerScope[i].push(diag2); - constantErrorsPerScope[i].push(diag2); - } - } else usagesPerScope[i].usages.set(identifier.text, { - usage: usage, - symbol: symbol, - node: identifier - }); - } + if (current === n) break; + const firstImport = current; + while(current < n && isAnyImportSyntax(statements[current])){ + visitNode3(statements[current]); + current++; } - return symbolId; + const lastImport = current - 1; + if (lastImport !== firstImport) out.push(createOutliningSpanFromBounds(findChildOfKind(statements[firstImport], 102 /* ImportKeyword */ , sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */ )); } - function checkForUsedDeclarations(node) { - if (node === targetRange.range || isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0) return; - const sym = isIdentifier(node) ? getSymbolReferencedByIdentifier(node) : checker.getSymbolAtLocation(node); - if (sym) { - const decl = find(visibleDeclarationsInExtractedRange, (d)=>d.symbol === sym); - if (decl) { - if (isVariableDeclaration(decl)) { - const idString = decl.symbol.id.toString(); - if (!exposedVariableSymbolSet.has(idString)) { - exposedVariableDeclarations.push(decl); - exposedVariableSymbolSet.set(idString, true); - } - } else firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl; + function visitNode3(n2) { + var _a; + if (depthRemaining === 0) return; + cancellationToken.throwIfCancellationRequested(); + if (isDeclaration(n2) || isVariableStatement(n2) || isReturnStatement(n2) || isCallOrNewExpression(n2) || n2.kind === 1 /* EndOfFileToken */ ) addOutliningForLeadingCommentsForNode(n2, sourceFile, cancellationToken, out); + if (isFunctionLike(n2) && isBinaryExpression(n2.parent) && isPropertyAccessExpression(n2.parent.left)) addOutliningForLeadingCommentsForNode(n2.parent.left, sourceFile, cancellationToken, out); + if (isBlock(n2) || isModuleBlock(n2)) addOutliningForLeadingCommentsForPos(n2.statements.end, sourceFile, cancellationToken, out); + if (isClassLike(n2) || isInterfaceDeclaration(n2)) addOutliningForLeadingCommentsForPos(n2.members.end, sourceFile, cancellationToken, out); + const span = getOutliningSpanForNode(n2, sourceFile); + if (span) out.push(span); + depthRemaining--; + if (isCallExpression(n2)) { + depthRemaining++; + visitNode3(n2.expression); + depthRemaining--; + n2.arguments.forEach(visitNode3); + (_a = n2.typeArguments) == null || _a.forEach(visitNode3); + } else if (isIfStatement(n2) && n2.elseStatement && isIfStatement(n2.elseStatement)) { + visitNode3(n2.expression); + visitNode3(n2.thenStatement); + depthRemaining++; + visitNode3(n2.elseStatement); + depthRemaining--; + } else n2.forEachChild(visitNode3); + depthRemaining++; + } + } + function addRegionOutliningSpans(sourceFile, out) { + const regions = []; + const lineStarts = sourceFile.getLineStarts(); + for (const currentLineStart of lineStarts){ + const lineEnd = sourceFile.getLineEndOfPosition(currentLineStart); + const lineText = sourceFile.text.substring(currentLineStart, lineEnd); + const result = isRegionDelimiter(lineText); + if (!result || isInComment(sourceFile, currentLineStart)) continue; + if (!result[1]) { + const span = createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); + regions.push(createOutliningSpan(span, "region" /* Region */ , span, /*autoCollapse*/ false, result[2] || "#region")); + } else { + const region = regions.pop(); + if (region) { + region.textSpan.length = lineEnd - region.textSpan.start; + region.hintSpan.length = lineEnd - region.textSpan.start; + out.push(region); } } - forEachChild(node, checkForUsedDeclarations); - } - function getSymbolReferencedByIdentifier(identifier) { - return identifier.parent && isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier ? checker.getShorthandAssignmentValueSymbol(identifier.parent) : checker.getSymbolAtLocation(identifier); - } - function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode2) { - if (!symbol) return void 0; - const decls = symbol.getDeclarations(); - if (decls && decls.some((d)=>d.parent === scopeDecl)) return factory.createIdentifier(symbol.name); - const prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode2); - if (prefix === void 0) return void 0; - return isTypeNode2 ? factory.createQualifiedName(prefix, factory.createIdentifier(symbol.name)) : factory.createPropertyAccessExpression(prefix, symbol.name); } } - function getExtractableParent(node) { - return findAncestor(node, (node2)=>node2.parent && isExtractableExpression(node2) && !isBinaryExpression(node2.parent)); + function isRegionDelimiter(lineText) { + lineText = trimStringStart(lineText); + if (!startsWith(lineText, "//")) return null; + lineText = trimString(lineText.slice(2)); + return regionDelimiterRegExp.exec(lineText); } - function isExtractableExpression(node) { - const { parent: parent2 } = node; - switch(parent2.kind){ - case 302 /* EnumMember */ : - return false; - } - switch(node.kind){ - case 10 /* StringLiteral */ : - return parent2.kind !== 269 /* ImportDeclaration */ && parent2.kind !== 273 /* ImportSpecifier */ ; - case 227 /* SpreadElement */ : - case 203 /* ObjectBindingPattern */ : - case 205 /* BindingElement */ : - return false; - case 79 /* Identifier */ : - return parent2.kind !== 205 /* BindingElement */ && parent2.kind !== 273 /* ImportSpecifier */ && parent2.kind !== 278 /* ExportSpecifier */ ; + function addOutliningForLeadingCommentsForPos(pos, sourceFile, cancellationToken, out) { + const comments = getLeadingCommentRanges(sourceFile.text, pos); + if (!comments) return; + let firstSingleLineCommentStart = -1; + let lastSingleLineCommentEnd = -1; + let singleLineCommentCount = 0; + const sourceText = sourceFile.getFullText(); + for (const { kind: kind, pos: pos2, end: end } of comments){ + cancellationToken.throwIfCancellationRequested(); + switch(kind){ + case 2 /* SingleLineCommentTrivia */ : + const commentText = sourceText.slice(pos2, end); + if (isRegionDelimiter(commentText)) { + combineAndAddMultipleSingleLineComments(); + singleLineCommentCount = 0; + break; + } + if (singleLineCommentCount === 0) firstSingleLineCommentStart = pos2; + lastSingleLineCommentEnd = end; + singleLineCommentCount++; + break; + case 3 /* MultiLineCommentTrivia */ : + combineAndAddMultipleSingleLineComments(); + out.push(createOutliningSpanFromBounds(pos2, end, "comment" /* Comment */ )); + singleLineCommentCount = 0; + break; + default: + Debug.assertNever(kind); + } } - return true; - } - function isBlockLike(node) { - switch(node.kind){ - case 238 /* Block */ : - case 308 /* SourceFile */ : - case 265 /* ModuleBlock */ : - case 292 /* CaseClause */ : - return true; - default: - return false; + combineAndAddMultipleSingleLineComments(); + function combineAndAddMultipleSingleLineComments() { + if (singleLineCommentCount > 1) out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */ )); } } - function isInJSXContent(node) { - return isStringLiteralJsxAttribute(node) || (isJsxElement(node) || isJsxSelfClosingElement(node) || isJsxFragment(node)) && (isJsxElement(node.parent) || isJsxFragment(node.parent)); + function addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out) { + if (isJsxText(n)) return; + addOutliningForLeadingCommentsForPos(n.pos, sourceFile, cancellationToken, out); } - function isStringLiteralJsxAttribute(node) { - return isStringLiteral(node) && node.parent && isJsxAttribute(node.parent); + function createOutliningSpanFromBounds(pos, end, kind) { + return createOutliningSpan(createTextSpanFromBounds(pos, end), kind); } - var refactorName11, extractConstantAction, extractFunctionAction, Messages, RangeFacts; - var init_extractSymbol = __esm({ - "src/services/refactors/extractSymbol.ts" () { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName11 = "Extract Symbol"; - extractConstantAction = { - name: "Extract Constant", - description: getLocaleSpecificMessage(Diagnostics.Extract_constant), - kind: "refactor.extract.constant" - }; - extractFunctionAction = { - name: "Extract Function", - description: getLocaleSpecificMessage(Diagnostics.Extract_function), - kind: "refactor.extract.function" - }; - registerRefactor(refactorName11, { - kinds: [ - extractConstantAction.kind, - extractFunctionAction.kind - ], - getEditsForAction: getRefactorEditsToExtractSymbol, - getAvailableActions: getRefactorActionsToExtractSymbol - }); - ((Messages2)=>{ - function createMessage(message) { - return { - message: message, - code: 0, - category: 3 /* Message */ , - key: message - }; + function getOutliningSpanForNode(n, sourceFile) { + switch(n.kind){ + case 241 /* Block */ : + if (isFunctionLike(n.parent)) return functionSpan(n.parent, n, sourceFile); + switch(n.parent.kind){ + case 246 /* DoStatement */ : + case 249 /* ForInStatement */ : + case 250 /* ForOfStatement */ : + case 248 /* ForStatement */ : + case 245 /* IfStatement */ : + case 247 /* WhileStatement */ : + case 254 /* WithStatement */ : + case 299 /* CatchClause */ : + return spanForNode(n.parent); + case 258 /* TryStatement */ : + const tryStatement = n.parent; + if (tryStatement.tryBlock === n) return spanForNode(n.parent); + else if (tryStatement.finallyBlock === n) { + const node = findChildOfKind(tryStatement, 98 /* FinallyKeyword */ , sourceFile); + if (node) return spanForNode(node); + } + default: + return createOutliningSpan(createTextSpanFromNode(n, sourceFile), "code" /* Code */ ); } - Messages2.cannotExtractRange = createMessage("Cannot extract range."); - Messages2.cannotExtractImport = createMessage("Cannot extract import statement."); - Messages2.cannotExtractSuper = createMessage("Cannot extract super call."); - Messages2.cannotExtractJSDoc = createMessage("Cannot extract JSDoc."); - Messages2.cannotExtractEmpty = createMessage("Cannot extract empty range."); - Messages2.expressionExpected = createMessage("expression expected."); - Messages2.uselessConstantType = createMessage("No reason to extract constant of type."); - Messages2.statementOrExpressionExpected = createMessage("Statement or expression expected."); - Messages2.cannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); - Messages2.cannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); - Messages2.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); - Messages2.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); - Messages2.typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); - Messages2.functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); - Messages2.cannotExtractIdentifier = createMessage("Select more than a single identifier."); - Messages2.cannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); - Messages2.cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression"); - Messages2.cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); - Messages2.cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); - Messages2.cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes"); - Messages2.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); - Messages2.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); - Messages2.cannotExtractFunctionsContainingThisToMethod = createMessage("Cannot extract functions containing this to method"); - })(Messages || (Messages = {})); - RangeFacts = /* @__PURE__ */ ((RangeFacts2)=>{ - RangeFacts2[RangeFacts2["None"] = 0] = "None"; - RangeFacts2[RangeFacts2["HasReturn"] = 1] = "HasReturn"; - RangeFacts2[RangeFacts2["IsGenerator"] = 2] = "IsGenerator"; - RangeFacts2[RangeFacts2["IsAsyncFunction"] = 4] = "IsAsyncFunction"; - RangeFacts2[RangeFacts2["UsesThis"] = 8] = "UsesThis"; - RangeFacts2[RangeFacts2["UsesThisInFunction"] = 16] = "UsesThisInFunction"; - RangeFacts2[RangeFacts2["InStaticRegion"] = 32] = "InStaticRegion"; - return RangeFacts2; - })(RangeFacts || {}); + case 268 /* ModuleBlock */ : + return spanForNode(n.parent); + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 264 /* InterfaceDeclaration */ : + case 266 /* EnumDeclaration */ : + case 269 /* CaseBlock */ : + case 187 /* TypeLiteral */ : + case 206 /* ObjectBindingPattern */ : + return spanForNode(n); + case 189 /* TupleType */ : + return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !isTupleTypeNode(n.parent), 23 /* OpenBracketToken */ ); + case 296 /* CaseClause */ : + case 297 /* DefaultClause */ : + return spanForNodeArray(n.statements); + case 210 /* ObjectLiteralExpression */ : + return spanForObjectOrArrayLiteral(n); + case 209 /* ArrayLiteralExpression */ : + return spanForObjectOrArrayLiteral(n, 23 /* OpenBracketToken */ ); + case 284 /* JsxElement */ : + return spanForJSXElement(n); + case 288 /* JsxFragment */ : + return spanForJSXFragment(n); + case 285 /* JsxSelfClosingElement */ : + case 286 /* JsxOpeningElement */ : + return spanForJSXAttributes(n.attributes); + case 228 /* TemplateExpression */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + return spanForTemplateLiteral(n); + case 207 /* ArrayBindingPattern */ : + return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !isBindingElement(n.parent), 23 /* OpenBracketToken */ ); + case 219 /* ArrowFunction */ : + return spanForArrowFunction(n); + case 213 /* CallExpression */ : + return spanForCallExpression(n); + case 217 /* ParenthesizedExpression */ : + return spanForParenthesizedExpression(n); + case 275 /* NamedImports */ : + case 279 /* NamedExports */ : + case 300 /* AssertClause */ : + return spanForNamedImportsOrExportsOrAssertClause(n); } - }); - // src/services/_namespaces/ts.refactor.extractSymbol.ts - var ts_refactor_extractSymbol_exports = {}; - __export(ts_refactor_extractSymbol_exports, { - Messages: ()=>Messages, - RangeFacts: ()=>RangeFacts, - getRangeToExtract: ()=>getRangeToExtract2, - getRefactorActionsToExtractSymbol: ()=>getRefactorActionsToExtractSymbol, - getRefactorEditsToExtractSymbol: ()=>getRefactorEditsToExtractSymbol - }); - var init_ts_refactor_extractSymbol = __esm({ - "src/services/_namespaces/ts.refactor.extractSymbol.ts" () { - "use strict"; - init_extractSymbol(); + function spanForNamedImportsOrExportsOrAssertClause(node) { + if (!node.elements.length) return void 0; + const openToken = findChildOfKind(node, 19 /* OpenBraceToken */ , sourceFile); + const closeToken = findChildOfKind(node, 20 /* CloseBraceToken */ , sourceFile); + if (!openToken || !closeToken || positionsAreOnSameLine(openToken.pos, closeToken.pos, sourceFile)) return void 0; + return spanBetweenTokens(openToken, closeToken, node, sourceFile, /*autoCollapse*/ false, /*useFullStart*/ false); } - }); - // src/services/refactors/generateGetAccessorAndSetAccessor.ts - var actionName, actionDescription, generateGetSetAction; - var init_generateGetAccessorAndSetAccessor = __esm({ - "src/services/refactors/generateGetAccessorAndSetAccessor.ts" () { - "use strict"; - init_ts4(); - init_ts_refactor(); - actionName = "Generate 'get' and 'set' accessors"; - actionDescription = Diagnostics.Generate_get_and_set_accessors.message; - generateGetSetAction = { - name: actionName, - description: actionDescription, - kind: "refactor.rewrite.property.generateAccessors" - }; - registerRefactor(actionName, { - kinds: [ - generateGetSetAction.kind - ], - getEditsForAction: function getRefactorActionsToGenerateGetAndSetAccessors(context, actionName2) { - if (!context.endPosition) return void 0; - const info = ts_codefix_exports.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const edits = ts_codefix_exports.generateAccessorFromProperty(context.file, context.program, context.startPosition, context.endPosition, context, actionName2); - if (!edits) return void 0; - const renameFilename = context.file.fileName; - const nameNeedRename = info.renameAccessor ? info.accessorName : info.fieldName; - const renameLocationOffset = isIdentifier(nameNeedRename) ? 0 : -1; - const renameLocation = renameLocationOffset + getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ isParameter(info.declaration)); - return { - renameFilename: renameFilename, - renameLocation: renameLocation, - edits: edits - }; - }, - getAvailableActions (context) { - if (!context.endPosition) return emptyArray; - const info = ts_codefix_exports.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition, context.triggerReason === "invoked"); - if (!info) return emptyArray; - if (!isRefactorErrorInfo(info)) return [ - { - name: actionName, - description: actionDescription, - actions: [ - generateGetSetAction - ] - } - ]; - if (context.preferences.provideRefactorNotApplicableReason) return [ - { - name: actionName, - description: actionDescription, - actions: [ - { - ...generateGetSetAction, - notApplicableReason: info.error - } - ] - } - ]; - return emptyArray; - } - }); + function spanForCallExpression(node) { + if (!node.arguments.length) return void 0; + const openToken = findChildOfKind(node, 21 /* OpenParenToken */ , sourceFile); + const closeToken = findChildOfKind(node, 22 /* CloseParenToken */ , sourceFile); + if (!openToken || !closeToken || positionsAreOnSameLine(openToken.pos, closeToken.pos, sourceFile)) return void 0; + return spanBetweenTokens(openToken, closeToken, node, sourceFile, /*autoCollapse*/ false, /*useFullStart*/ true); } - }); - // src/services/_namespaces/ts.refactor.generateGetAccessorAndSetAccessor.ts - var ts_refactor_generateGetAccessorAndSetAccessor_exports = {}; - var init_ts_refactor_generateGetAccessorAndSetAccessor = __esm({ - "src/services/_namespaces/ts.refactor.generateGetAccessorAndSetAccessor.ts" () { - "use strict"; - init_generateGetAccessorAndSetAccessor(); + function spanForArrowFunction(node) { + if (isBlock(node.body) || isParenthesizedExpression(node.body) || positionsAreOnSameLine(node.body.getFullStart(), node.body.getEnd(), sourceFile)) return void 0; + const textSpan = createTextSpanFromBounds(node.body.getFullStart(), node.body.getEnd()); + return createOutliningSpan(textSpan, "code" /* Code */ , createTextSpanFromNode(node)); } - }); - // src/services/refactors/inferFunctionReturnType.ts - function getRefactorEditsToInferReturnType(context) { - const info = getInfo21(context); - if (info && !isRefactorErrorInfo(info)) { - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t)=>doChange38(context.file, t, info.declaration, info.returnTypeNode)); - return { - renameFilename: void 0, - renameLocation: void 0, - edits: edits - }; + function spanForJSXElement(node) { + const textSpan = createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd()); + const tagName = node.openingElement.tagName.getText(sourceFile); + const bannerText = "<" + tagName + ">..."; + return createOutliningSpan(textSpan, "code" /* Code */ , textSpan, /*autoCollapse*/ false, bannerText); + } + function spanForJSXFragment(node) { + const textSpan = createTextSpanFromBounds(node.openingFragment.getStart(sourceFile), node.closingFragment.getEnd()); + const bannerText = "<>..."; + return createOutliningSpan(textSpan, "code" /* Code */ , textSpan, /*autoCollapse*/ false, bannerText); + } + function spanForJSXAttributes(node) { + if (node.properties.length === 0) return void 0; + return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */ ); + } + function spanForTemplateLiteral(node) { + if (node.kind === 15 /* NoSubstitutionTemplateLiteral */ && node.text.length === 0) return void 0; + return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */ ); + } + function spanForObjectOrArrayLiteral(node, open = 19 /* OpenBraceToken */ ) { + return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !isArrayLiteralExpression(node.parent) && !isCallExpression(node.parent), open); + } + function spanForNode(hintSpanNode, autoCollapse = false, useFullStart = true, open = 19 /* OpenBraceToken */ , close = open === 19 /* OpenBraceToken */ ? 20 /* CloseBraceToken */ : 24 /* CloseBracketToken */ ) { + const openToken = findChildOfKind(n, open, sourceFile); + const closeToken = findChildOfKind(n, close, sourceFile); + return openToken && closeToken && spanBetweenTokens(openToken, closeToken, hintSpanNode, sourceFile, autoCollapse, useFullStart); + } + function spanForNodeArray(nodeArray) { + return nodeArray.length ? createOutliningSpan(createTextSpanFromRange(nodeArray), "code" /* Code */ ) : void 0; + } + function spanForParenthesizedExpression(node) { + if (positionsAreOnSameLine(node.getStart(), node.getEnd(), sourceFile)) return void 0; + const textSpan = createTextSpanFromBounds(node.getStart(), node.getEnd()); + return createOutliningSpan(textSpan, "code" /* Code */ , createTextSpanFromNode(node)); } - return void 0; } - function getRefactorActionsToInferReturnType(context) { - const info = getInfo21(context); - if (!info) return emptyArray; - if (!isRefactorErrorInfo(info)) return [ - { - name: refactorName12, - description: refactorDescription6, - actions: [ - inferReturnTypeAction - ] - } - ]; - if (context.preferences.provideRefactorNotApplicableReason) return [ - { - name: refactorName12, - description: refactorDescription6, - actions: [ - { - ...inferReturnTypeAction, - notApplicableReason: info.error - } - ] - } - ]; - return emptyArray; + function functionSpan(node, body, sourceFile) { + const openToken = tryGetFunctionOpenToken(node, body, sourceFile); + const closeToken = findChildOfKind(body, 20 /* CloseBraceToken */ , sourceFile); + return openToken && closeToken && spanBetweenTokens(openToken, closeToken, node, sourceFile, /*autoCollapse*/ node.kind !== 219 /* ArrowFunction */ ); } - function doChange38(sourceFile, changes, declaration, typeNode) { - const closeParen = findChildOfKind(declaration, 21 /* CloseParenToken */ , sourceFile); - const needParens = isArrowFunction(declaration) && closeParen === void 0; - const endNode2 = needParens ? first(declaration.parameters) : closeParen; - if (endNode2) { - if (needParens) { - changes.insertNodeBefore(sourceFile, endNode2, factory.createToken(20 /* OpenParenToken */ )); - changes.insertNodeAfter(sourceFile, endNode2, factory.createToken(21 /* CloseParenToken */ )); - } - changes.insertNodeAt(sourceFile, endNode2.end, typeNode, { - prefix: ": " - }); - } + function spanBetweenTokens(openToken, closeToken, hintSpanNode, sourceFile, autoCollapse = false, useFullStart = true) { + const textSpan = createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd()); + return createOutliningSpan(textSpan, "code" /* Code */ , createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); } - function getInfo21(context) { - if (isInJSFile(context.file) || !refactorKindBeginsWith(inferReturnTypeAction.kind, context.kind)) return; - const token = getTokenAtPosition(context.file, context.startPosition); - const declaration = findAncestor(token, (n)=>isBlock(n) || n.parent && isArrowFunction(n.parent) && (n.kind === 38 /* EqualsGreaterThanToken */ || n.parent.body === n) ? "quit" : isConvertibleDeclaration(n)); - if (!declaration || !declaration.body || declaration.type) return { - error: getLocaleSpecificMessage(Diagnostics.Return_type_must_be_inferred_from_a_function) - }; - const typeChecker = context.program.getTypeChecker(); - const returnType = tryGetReturnType(typeChecker, declaration); - if (!returnType) return { - error: getLocaleSpecificMessage(Diagnostics.Could_not_determine_function_return_type) - }; - const returnTypeNode = typeChecker.typeToTypeNode(returnType, declaration, 1 /* NoTruncation */ ); - if (returnTypeNode) return { - declaration: declaration, - returnTypeNode: returnTypeNode + function createOutliningSpan(textSpan, kind, hintSpan = textSpan, autoCollapse = false, bannerText = "...") { + return { + textSpan: textSpan, + kind: kind, + hintSpan: hintSpan, + bannerText: bannerText, + autoCollapse: autoCollapse }; } - function isConvertibleDeclaration(node) { - switch(node.kind){ - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - case 171 /* MethodDeclaration */ : - return true; - default: - return false; - } - } - function tryGetReturnType(typeChecker, node) { - if (typeChecker.isImplementationOfOverload(node)) { - const signatures = typeChecker.getTypeAtLocation(node).getCallSignatures(); - if (signatures.length > 1) return typeChecker.getUnionType(mapDefined(signatures, (s)=>s.getReturnType())); + function tryGetFunctionOpenToken(node, body, sourceFile) { + if (isNodeArrayMultiLine(node.parameters, sourceFile)) { + const openParenToken = findChildOfKind(node, 21 /* OpenParenToken */ , sourceFile); + if (openParenToken) return openParenToken; } - const signature = typeChecker.getSignatureFromDeclaration(node); - if (signature) return typeChecker.getReturnTypeOfSignature(signature); + return findChildOfKind(body, 19 /* OpenBraceToken */ , sourceFile); } - var refactorName12, refactorDescription6, inferReturnTypeAction; - var init_inferFunctionReturnType = __esm({ - "src/services/refactors/inferFunctionReturnType.ts" () { + var regionDelimiterRegExp; + var init_outliningElementsCollector = __esm({ + "src/services/outliningElementsCollector.ts" () { "use strict"; init_ts4(); - init_ts_refactor(); - refactorName12 = "Infer function return type"; - refactorDescription6 = Diagnostics.Infer_function_return_type.message; - inferReturnTypeAction = { - name: refactorName12, - description: refactorDescription6, - kind: "refactor.rewrite.function.returnType" - }; - registerRefactor(refactorName12, { - kinds: [ - inferReturnTypeAction.kind - ], - getEditsForAction: getRefactorEditsToInferReturnType, - getAvailableActions: getRefactorActionsToInferReturnType - }); - } - }); - // src/services/_namespaces/ts.refactor.inferFunctionReturnType.ts - var ts_refactor_inferFunctionReturnType_exports = {}; - var init_ts_refactor_inferFunctionReturnType = __esm({ - "src/services/_namespaces/ts.refactor.inferFunctionReturnType.ts" () { - "use strict"; - init_inferFunctionReturnType(); + regionDelimiterRegExp = /^#(end)?region(?:\s+(.*))?(?:\r)?$/; } }); - // src/services/_namespaces/ts.refactor.ts - var ts_refactor_exports = {}; - __export(ts_refactor_exports, { - addOrRemoveBracesToArrowFunction: ()=>ts_refactor_addOrRemoveBracesToArrowFunction_exports, - convertArrowFunctionOrFunctionExpression: ()=>ts_refactor_convertArrowFunctionOrFunctionExpression_exports, - convertParamsToDestructuredObject: ()=>ts_refactor_convertParamsToDestructuredObject_exports, - convertStringOrTemplateLiteral: ()=>ts_refactor_convertStringOrTemplateLiteral_exports, - convertToOptionalChainExpression: ()=>ts_refactor_convertToOptionalChainExpression_exports, - doChangeNamedToNamespaceOrDefault: ()=>doChangeNamedToNamespaceOrDefault, - extractSymbol: ()=>ts_refactor_extractSymbol_exports, - generateGetAccessorAndSetAccessor: ()=>ts_refactor_generateGetAccessorAndSetAccessor_exports, - getApplicableRefactors: ()=>getApplicableRefactors, - getEditsForRefactor: ()=>getEditsForRefactor, - inferFunctionReturnType: ()=>ts_refactor_inferFunctionReturnType_exports, - isRefactorErrorInfo: ()=>isRefactorErrorInfo, - refactorKindBeginsWith: ()=>refactorKindBeginsWith, - registerRefactor: ()=>registerRefactor + // src/services/_namespaces/ts.OutliningElementsCollector.ts + var ts_OutliningElementsCollector_exports = {}; + __export(ts_OutliningElementsCollector_exports, { + collectElements: ()=>collectElements }); - var init_ts_refactor = __esm({ - "src/services/_namespaces/ts.refactor.ts" () { + var init_ts_OutliningElementsCollector = __esm({ + "src/services/_namespaces/ts.OutliningElementsCollector.ts" () { "use strict"; - init_refactorProvider(); - init_convertExport(); - init_convertImport(); - init_extractType(); - init_helpers2(); - init_moveToNewFile(); - init_ts_refactor_addOrRemoveBracesToArrowFunction(); - init_ts_refactor_convertArrowFunctionOrFunctionExpression(); - init_ts_refactor_convertParamsToDestructuredObject(); - init_ts_refactor_convertStringOrTemplateLiteral(); - init_ts_refactor_convertToOptionalChainExpression(); - init_ts_refactor_extractSymbol(); - init_ts_refactor_generateGetAccessorAndSetAccessor(); - init_ts_refactor_inferFunctionReturnType(); + init_outliningElementsCollector(); } }); // src/services/rename.ts @@ -129578,7 +132524,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} } return void 0; } - const { declarations: declarations } = symbol; + const { declarations: declarations } = symbol; if (!declarations || declarations.length === 0) return; if (declarations.some((declaration)=>isDefinedInLibraryFile(program, declaration))) return getRenameInfoError(Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); if (isIdentifier(node) && node.escapedText === "default" && symbol.parent && symbol.parent.flags & 1536 /* Module */ ) return void 0; @@ -129586,7 +132532,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} const wouldRenameNodeModules = wouldRenameInOtherNodeModules(sourceFile, symbol, typeChecker, preferences); if (wouldRenameNodeModules) return getRenameInfoError(wouldRenameNodeModules); const kind = ts_SymbolDisplay_exports.getSymbolKind(typeChecker, symbol, node); - const specifierName = isImportOrExportSpecifierName(node) || isStringOrNumericLiteralLike(node) && node.parent.kind === 164 /* ComputedPropertyName */ ? stripQuotes(getTextOfIdentifierOrLiteral(node)) : void 0; + const specifierName = isImportOrExportSpecifierName(node) || isStringOrNumericLiteralLike(node) && node.parent.kind === 167 /* ComputedPropertyName */ ? stripQuotes(getTextOfIdentifierOrLiteral(node)) : void 0; const displayName = specifierName || typeChecker.symbolToString(symbol); const fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts_SymbolDisplay_exports.getSymbolModifiers(typeChecker, symbol), node, sourceFile); @@ -129600,7 +132546,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} const importSpecifier = symbol.declarations && find(symbol.declarations, (decl)=>isImportSpecifier(decl)); if (importSpecifier && !importSpecifier.propertyName) symbol = checker.getAliasedSymbol(symbol); } - const { declarations: declarations } = symbol; + const { declarations: declarations } = symbol; if (!declarations) return void 0; const originalPackage = getPackagePathComponents(originalFile.path); if (originalPackage === void 0) { @@ -129671,13 +132617,13 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} } function nodeIsEligibleForRename(node) { switch(node.kind){ - case 79 /* Identifier */ : - case 80 /* PrivateIdentifier */ : - case 10 /* StringLiteral */ : - case 14 /* NoSubstitutionTemplateLiteral */ : - case 108 /* ThisKeyword */ : + case 80 /* Identifier */ : + case 81 /* PrivateIdentifier */ : + case 11 /* StringLiteral */ : + case 15 /* NoSubstitutionTemplateLiteral */ : + case 110 /* ThisKeyword */ : return true; - case 8 /* NumericLiteral */ : + case 9 /* NumericLiteral */ : return isLiteralNameOfPropertyDeclarationOrIndexAccess(node); default: return false; @@ -129717,7 +132663,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} if (!candidateInfo) return isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : void 0; return typeChecker.runWithCancellationToken(cancellationToken, (typeChecker2)=>candidateInfo.kind === 0 /* Candidate */ ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker2) : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker2)); } - function getCandidateOrTypeInfo({ invocation: invocation , argumentCount: argumentCount }, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + function getCandidateOrTypeInfo({ invocation: invocation, argumentCount: argumentCount }, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { switch(invocation.kind){ case 0 /* Call */ : { @@ -129732,7 +132678,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} } case 1 /* TypeArgs */ : { - const { called: called } = invocation; + const { called: called } = invocation; if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, isIdentifier(called) ? called.parent : called)) return void 0; const candidates = getPossibleGenericSignatures(called, argumentCount, checker); if (candidates.length !== 0) return { @@ -129762,14 +132708,14 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} if (!isCallOrNewExpression(node)) return false; const invocationChildren = node.getChildren(sourceFile); switch(startingToken.kind){ - case 20 /* OpenParenToken */ : + case 21 /* OpenParenToken */ : return contains(invocationChildren, startingToken); - case 27 /* CommaToken */ : + case 28 /* CommaToken */ : { const containingList = findContainingList(startingToken); return !!containingList && contains(invocationChildren, containingList); } - case 29 /* LessThanToken */ : + case 30 /* LessThanToken */ : return containsPrecedingToken(startingToken, sourceFile, node.expression); default: return false; @@ -129807,7 +132753,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} function getArgumentOrParameterListInfo(node, position, sourceFile) { const info = getArgumentOrParameterListAndIndex(node, sourceFile); if (!info) return void 0; - const { list: list , argumentIndex: argumentIndex } = info; + const { list: list, argumentIndex: argumentIndex } = info; const argumentCount = getArgumentCount(list, /*ignoreTrailingComma*/ isInString(sourceFile, position, node)); if (argumentIndex !== 0) Debug.assertLessThan(argumentIndex, argumentCount); const argumentsSpan = getApplicableSpanForArguments(list, sourceFile); @@ -129819,7 +132765,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} }; } function getArgumentOrParameterListAndIndex(node, sourceFile) { - if (node.kind === 29 /* LessThanToken */ || node.kind === 20 /* OpenParenToken */ ) return { + if (node.kind === 30 /* LessThanToken */ || node.kind === 21 /* OpenParenToken */ ) return { list: getChildListThatStartsWithOpenerToken(node.parent, node, sourceFile), argumentIndex: 0 }; @@ -129832,12 +132778,12 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} } } function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { - const { parent: parent2 } = node; + const { parent: parent2 } = node; if (isCallOrNewExpression(parent2)) { const invocation = parent2; const info = getArgumentOrParameterListInfo(node, position, sourceFile); if (!info) return void 0; - const { list: list , argumentIndex: argumentIndex , argumentCount: argumentCount , argumentsSpan: argumentsSpan } = info; + const { list: list, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan } = info; const isTypeParameterList = !!parent2.typeArguments && parent2.typeArguments.pos === list.pos; return { isTypeParameterList: isTypeParameterList, @@ -129852,10 +132798,10 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} } else if (isNoSubstitutionTemplateLiteral(node) && isTaggedTemplateExpression(parent2)) { if (isInsideTemplateLiteral(node, position, sourceFile)) return getArgumentListInfoForTemplate(parent2, /*argumentIndex*/ 0, sourceFile); return void 0; - } else if (isTemplateHead(node) && parent2.parent.kind === 212 /* TaggedTemplateExpression */ ) { + } else if (isTemplateHead(node) && parent2.parent.kind === 215 /* TaggedTemplateExpression */ ) { const templateExpression = parent2; const tagExpression = templateExpression.parent; - Debug.assert(templateExpression.kind === 225 /* TemplateExpression */ ); + Debug.assert(templateExpression.kind === 228 /* TemplateExpression */ ); const argumentIndex = isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } else if (isTemplateSpan(parent2) && isTaggedTemplateExpression(parent2.parent.parent)) { @@ -129881,7 +132827,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} } else { const typeArgInfo = getPossibleTypeArgumentsInfo(node, sourceFile); if (typeArgInfo) { - const { called: called , nTypeArguments: nTypeArguments } = typeArgInfo; + const { called: called, nTypeArguments: nTypeArguments } = typeArgInfo; const invocation = { kind: 1 /* TypeArgs */ , called: called @@ -129908,9 +132854,11 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} return isBinaryExpression(b.left) ? countBinaryExpressionParameters(b.left) + 1 : 2; } function tryGetParameterInfo(startingToken, position, sourceFile, checker) { - const info = getContextualSignatureLocationInfo(startingToken, sourceFile, position, checker); - if (!info) return void 0; - const { contextualType: contextualType , argumentIndex: argumentIndex , argumentCount: argumentCount , argumentsSpan: argumentsSpan } = info; + const node = getAdjustedNode(startingToken); + if (node === void 0) return void 0; + const info = getContextualSignatureLocationInfo(node, sourceFile, position, checker); + if (info === void 0) return void 0; + const { contextualType: contextualType, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan } = info; const nonNullableContextualType = contextualType.getNonNullableType(); const symbol = nonNullableContextualType.symbol; if (symbol === void 0) return void 0; @@ -129930,17 +132878,25 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} argumentCount: argumentCount }; } - function getContextualSignatureLocationInfo(startingToken, sourceFile, position, checker) { - if (startingToken.kind !== 20 /* OpenParenToken */ && startingToken.kind !== 27 /* CommaToken */ ) return void 0; - const { parent: parent2 } = startingToken; + function getAdjustedNode(node) { + switch(node.kind){ + case 21 /* OpenParenToken */ : + case 28 /* CommaToken */ : + return node; + default: + return findAncestor(node.parent, (n)=>isParameter(n) ? true : isBindingElement(n) || isObjectBindingPattern(n) || isArrayBindingPattern(n) ? false : "quit"); + } + } + function getContextualSignatureLocationInfo(node, sourceFile, position, checker) { + const { parent: parent2 } = node; switch(parent2.kind){ - case 214 /* ParenthesizedExpression */ : - case 171 /* MethodDeclaration */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - const info = getArgumentOrParameterListInfo(startingToken, position, sourceFile); + case 217 /* ParenthesizedExpression */ : + case 174 /* MethodDeclaration */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + const info = getArgumentOrParameterListInfo(node, position, sourceFile); if (!info) return void 0; - const { argumentIndex: argumentIndex , argumentCount: argumentCount , argumentsSpan: argumentsSpan } = info; + const { argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan } = info; const contextualType = isMethodDeclaration(parent2) ? checker.getContextualTypeForObjectLiteralElement(parent2) : checker.getContextualType(parent2); return contextualType && { contextualType: contextualType, @@ -129948,11 +132904,11 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} argumentCount: argumentCount, argumentsSpan: argumentsSpan }; - case 223 /* BinaryExpression */ : + case 226 /* BinaryExpression */ : { const highestBinary = getHighestBinary(parent2); const contextualType2 = checker.getContextualType(highestBinary); - const argumentIndex2 = startingToken.kind === 20 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent2) - 1; + const argumentIndex2 = node.kind === 21 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent2) - 1; const argumentCount2 = countBinaryExpressionParameters(highestBinary); return contextualType2 && { contextualType: contextualType2, @@ -129967,22 +132923,22 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} } function chooseBetterSymbol(s) { return s.name === "__type" /* Type */ ? firstDefined(s.declarations, (d)=>{ - var _a2; - return isFunctionTypeNode(d) ? (_a2 = tryCast(d.parent, canHaveSymbol)) == null ? void 0 : _a2.symbol : void 0; + var _a; + return isFunctionTypeNode(d) ? (_a = tryCast(d.parent, canHaveSymbol)) == null ? void 0 : _a.symbol : void 0; }) || s : s; } function getArgumentIndex(argumentsList, node) { let argumentIndex = 0; for (const child of argumentsList.getChildren()){ if (child === node) break; - if (child.kind !== 27 /* CommaToken */ ) argumentIndex++; + if (child.kind !== 28 /* CommaToken */ ) argumentIndex++; } return argumentIndex; } function getArgumentCount(argumentsList, ignoreTrailingComma) { const listChildren = argumentsList.getChildren(); - let argumentCount = countWhere(listChildren, (arg)=>arg.kind !== 27 /* CommaToken */ ); - if (!ignoreTrailingComma && listChildren.length > 0 && last(listChildren).kind === 27 /* CommaToken */ ) argumentCount++; + let argumentCount = countWhere(listChildren, (arg)=>arg.kind !== 28 /* CommaToken */ ); + if (!ignoreTrailingComma && listChildren.length > 0 && last(listChildren).kind === 28 /* CommaToken */ ) argumentCount++; return argumentCount; } function getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile) { @@ -130016,7 +132972,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} const template = taggedTemplate.template; const applicableSpanStart = template.getStart(); let applicableSpanEnd = template.getEnd(); - if (template.kind === 225 /* TemplateExpression */ ) { + if (template.kind === 228 /* TemplateExpression */ ) { const lastSpan = last(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) applicableSpanEnd = skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); } @@ -130042,10 +132998,10 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} function getEnclosingDeclarationFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; } - function createSignatureHelpItems(candidates, resolvedSignature, { isTypeParameterList: isTypeParameterList , argumentCount: argumentCount , argumentsSpan: applicableSpan , invocation: invocation , argumentIndex: argumentIndex }, sourceFile, typeChecker, useFullPrefix) { - var _a2; + function createSignatureHelpItems(candidates, resolvedSignature, { isTypeParameterList: isTypeParameterList, argumentCount: argumentCount, argumentsSpan: applicableSpan, invocation: invocation, argumentIndex: argumentIndex }, sourceFile, typeChecker, useFullPrefix) { + var _a; const enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation); - const callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)) || useFullPrefix && ((_a2 = resolvedSignature.declaration) == null ? void 0 : _a2.symbol); + const callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)) || useFullPrefix && ((_a = resolvedSignature.declaration) == null ? void 0 : _a.symbol); const callTargetDisplayParts = callTargetSymbol ? symbolToDisplayParts(typeChecker, callTargetSymbol, useFullPrefix ? sourceFile : void 0, /*meaning*/ void 0) : emptyArray; const items = map(candidates, (candidateSignature)=>getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile)); if (argumentIndex !== 0) Debug.assertLessThan(argumentIndex, argumentCount); @@ -130084,7 +133040,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} } return help; } - function createTypeHelpItems(symbol, { argumentCount: argumentCount , argumentsSpan: applicableSpan , invocation: invocation , argumentIndex: argumentIndex }, sourceFile, checker) { + function createTypeHelpItems(symbol, { argumentCount: argumentCount, argumentsSpan: applicableSpan, invocation: invocation, argumentIndex: argumentIndex }, sourceFile, checker) { const typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); if (!typeParameters) return void 0; const items = [ @@ -130106,13 +133062,13 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} const tags = symbol.getJsDocTags(checker); const prefixDisplayParts = [ ...typeSymbolDisplay, - punctuationPart(29 /* LessThanToken */ ) + punctuationPart(30 /* LessThanToken */ ) ]; return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ - punctuationPart(31 /* GreaterThanToken */ ) + punctuationPart(32 /* GreaterThanToken */ ) ], separatorDisplayParts: separatorDisplayParts, parameters: parameters, @@ -130122,7 +133078,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} } function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { const infos = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile); - return map(infos, ({ isVariadic: isVariadic , parameters: parameters , prefix: prefix , suffix: suffix })=>{ + return map(infos, ({ isVariadic: isVariadic, parameters: parameters, prefix: prefix, suffix: suffix })=>{ const prefixDisplayParts = [ ...callTargetDisplayParts, ...prefix @@ -130172,10 +133128,10 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} isVariadic: false, parameters: parameters, prefix: [ - punctuationPart(29 /* LessThanToken */ ) + punctuationPart(30 /* LessThanToken */ ) ], suffix: [ - punctuationPart(31 /* GreaterThanToken */ ), + punctuationPart(32 /* GreaterThanToken */ ), ...parameterParts ] }; @@ -130191,18 +133147,18 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} }); const lists = checker.getExpandedParameters(candidateSignature); const isVariadic = !checker.hasEffectiveRestParameter(candidateSignature) ? (_)=>false : lists.length === 1 ? (_)=>true : (pList)=>{ - var _a2; - return !!(pList.length && ((_a2 = tryCast(pList[pList.length - 1], isTransientSymbol)) == null ? void 0 : _a2.links.checkFlags) & 32768 /* RestParameter */ ); + var _a; + return !!(pList.length && ((_a = tryCast(pList[pList.length - 1], isTransientSymbol)) == null ? void 0 : _a.links.checkFlags) & 32768 /* RestParameter */ ); }; return lists.map((parameterList)=>({ isVariadic: isVariadic(parameterList), parameters: parameterList.map((p)=>createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer)), prefix: [ ...typeParameterParts, - punctuationPart(20 /* OpenParenToken */ ) + punctuationPart(21 /* OpenParenToken */ ) ], suffix: [ - punctuationPart(21 /* CloseParenToken */ ) + punctuationPart(22 /* CloseParenToken */ ) ] })); } @@ -130241,7 +133197,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} init_ts4(); signatureHelpNodeBuilderFlags = 70246400 /* UseAliasDefinedOutsideCurrentScope */ ; separatorDisplayParts = [ - punctuationPart(27 /* CommaToken */ ), + punctuationPart(28 /* CommaToken */ ), spacePart() ]; } @@ -130260,7 +133216,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} }); // src/services/smartSelection.ts function getSmartSelectionRange(pos, sourceFile) { - var _a2, _b; + var _a, _b; let selectionRange = { textSpan: createTextSpanFromBounds(sourceFile.getFullStart(), sourceFile.getEnd()) }; @@ -130289,7 +133245,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} const isBetweenMultiLineBookends = isSyntaxList(node) && isListOpener(prevNode) && isListCloser(nextNode) && !positionsAreOnSameLine(prevNode.getStart(), nextNode.getStart(), sourceFile); let start = isBetweenMultiLineBookends ? prevNode.getEnd() : node.getStart(); const end = isBetweenMultiLineBookends ? nextNode.getStart() : getEndPos(sourceFile, node); - if (hasJSDocNodes(node) && ((_a2 = node.jsDoc) == null ? void 0 : _a2.length)) pushSelectionRange(first(node.jsDoc).getStart(), end); + if (hasJSDocNodes(node) && ((_a = node.jsDoc) == null ? void 0 : _a.length)) pushSelectionRange(first(node.jsDoc).getStart(), end); if (isSyntaxList(node)) { const firstChild = node.getChildren()[0]; if (firstChild && hasJSDocNodes(firstChild) && ((_b = firstChild.jsDoc) == null ? void 0 : _b.length) && firstChild.getStart() !== node.pos) start = Math.min(start, first(firstChild.jsDoc).getStart()); @@ -130307,7 +133263,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} if (start !== end) { const textSpan = createTextSpanFromBounds(start, end); if (!selectionRange || // Skip ranges that are identical to the parent - !textSpansEqual(textSpan, selectionRange.textSpan) && // Skip ranges that don’t contain the original position + !textSpansEqual(textSpan, selectionRange.textSpan) && // Skip ranges that don't contain the original position textSpanIntersectsWithPosition(textSpan, pos)) selectionRange = { textSpan: textSpan, ...selectionRange && { @@ -130331,27 +133287,27 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} return false; } function getSelectionChildren(node) { - var _a2; + var _a; if (isSourceFile(node)) return groupChildren(node.getChildAt(0).getChildren(), isImport2); if (isMappedTypeNode(node)) { const [openBraceToken, ...children] = node.getChildren(); const closeBraceToken = Debug.checkDefined(children.pop()); - Debug.assertEqual(openBraceToken.kind, 18 /* OpenBraceToken */ ); - Debug.assertEqual(closeBraceToken.kind, 19 /* CloseBraceToken */ ); - const groupedWithPlusMinusTokens = groupChildren(children, (child)=>child === node.readonlyToken || child.kind === 146 /* ReadonlyKeyword */ || child === node.questionToken || child.kind === 57 /* QuestionToken */ ); - const groupedWithBrackets = groupChildren(groupedWithPlusMinusTokens, ({ kind: kind })=>kind === 22 /* OpenBracketToken */ || kind === 165 /* TypeParameter */ || kind === 23 /* CloseBracketToken */ ); + Debug.assertEqual(openBraceToken.kind, 19 /* OpenBraceToken */ ); + Debug.assertEqual(closeBraceToken.kind, 20 /* CloseBraceToken */ ); + const groupedWithPlusMinusTokens = groupChildren(children, (child)=>child === node.readonlyToken || child.kind === 148 /* ReadonlyKeyword */ || child === node.questionToken || child.kind === 58 /* QuestionToken */ ); + const groupedWithBrackets = groupChildren(groupedWithPlusMinusTokens, ({ kind: kind })=>kind === 23 /* OpenBracketToken */ || kind === 168 /* TypeParameter */ || kind === 24 /* CloseBracketToken */ ); return [ openBraceToken, // Pivot on `:` - createSyntaxList2(splitChildren(groupedWithBrackets, ({ kind: kind })=>kind === 58 /* ColonToken */ )), + createSyntaxList2(splitChildren(groupedWithBrackets, ({ kind: kind })=>kind === 59 /* ColonToken */ )), closeBraceToken ]; } if (isPropertySignature(node)) { const children = groupChildren(node.getChildren(), (child)=>child === node.name || contains(node.modifiers, child)); - const firstJSDocChild = ((_a2 = children[0]) == null ? void 0 : _a2.kind) === 323 /* JSDoc */ ? children[0] : void 0; + const firstJSDocChild = ((_a = children[0]) == null ? void 0 : _a.kind) === 327 /* JSDoc */ ? children[0] : void 0; const withJSDocSeparated = firstJSDocChild ? children.slice(1) : children; - const splittedChildren = splitChildren(withJSDocSeparated, ({ kind: kind })=>kind === 58 /* ColonToken */ ); + const splittedChildren = splitChildren(withJSDocSeparated, ({ kind: kind })=>kind === 59 /* ColonToken */ ); return firstJSDocChild ? [ firstJSDocChild, createSyntaxList2(splittedChildren) @@ -130360,9 +133316,9 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} if (isParameter(node)) { const groupedDotDotDotAndName = groupChildren(node.getChildren(), (child)=>child === node.dotDotDotToken || child === node.name); const groupedWithQuestionToken = groupChildren(groupedDotDotDotAndName, (child)=>child === groupedDotDotDotAndName[0] || child === node.questionToken); - return splitChildren(groupedWithQuestionToken, ({ kind: kind })=>kind === 63 /* EqualsToken */ ); + return splitChildren(groupedWithQuestionToken, ({ kind: kind })=>kind === 64 /* EqualsToken */ ); } - if (isBindingElement(node)) return splitChildren(node.getChildren(), ({ kind: kind })=>kind === 63 /* EqualsToken */ ); + if (isBindingElement(node)) return splitChildren(node.getChildren(), ({ kind: kind })=>kind === 64 /* EqualsToken */ ); return node.getChildren(); } function groupChildren(children, groupOn) { @@ -130388,7 +133344,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} const leftChildren = children.slice(0, splitTokenIndex); const splitToken = children[splitTokenIndex]; const lastToken = last(children); - const separateLastToken = separateTrailingSemicolon && lastToken.kind === 26 /* SemicolonToken */ ; + const separateLastToken = separateTrailingSemicolon && lastToken.kind === 27 /* SemicolonToken */ ; const rightChildren = children.slice(splitTokenIndex + 1, separateLastToken ? children.length - 1 : void 0); const result = compact([ leftChildren.length ? createSyntaxList2(leftChildren) : void 0, @@ -130403,19 +133359,19 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} } function isListOpener(token) { const kind = token && token.kind; - return kind === 18 /* OpenBraceToken */ || kind === 22 /* OpenBracketToken */ || kind === 20 /* OpenParenToken */ || kind === 283 /* JsxOpeningElement */ ; + return kind === 19 /* OpenBraceToken */ || kind === 23 /* OpenBracketToken */ || kind === 21 /* OpenParenToken */ || kind === 286 /* JsxOpeningElement */ ; } function isListCloser(token) { const kind = token && token.kind; - return kind === 19 /* CloseBraceToken */ || kind === 23 /* CloseBracketToken */ || kind === 21 /* CloseParenToken */ || kind === 284 /* JsxClosingElement */ ; + return kind === 20 /* CloseBraceToken */ || kind === 24 /* CloseBracketToken */ || kind === 22 /* CloseParenToken */ || kind === 287 /* JsxClosingElement */ ; } function getEndPos(sourceFile, node) { switch(node.kind){ - case 344 /* JSDocParameterTag */ : - case 341 /* JSDocCallbackTag */ : - case 351 /* JSDocPropertyTag */ : - case 349 /* JSDocTypedefTag */ : - case 346 /* JSDocThisTag */ : + case 348 /* JSDocParameterTag */ : + case 345 /* JSDocCallbackTag */ : + case 355 /* JSDocPropertyTag */ : + case 353 /* JSDocTypedefTag */ : + case 350 /* JSDocThisTag */ : return sourceFile.getLineEndOfPosition(node.getStart()); default: return node.getEnd(); @@ -130445,7 +133401,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} const result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); if (result !== "" /* unknown */ ) return result; const flags = getCombinedLocalAndExportSymbolFlags(symbol); - if (flags & 32 /* Class */ ) return getDeclarationOfKind(symbol, 228 /* ClassExpression */ ) ? "local class" /* localClassElement */ : "class" /* classElement */ ; + if (flags & 32 /* Class */ ) return getDeclarationOfKind(symbol, 231 /* ClassExpression */ ) ? "local class" /* localClassElement */ : "class" /* classElement */ ; if (flags & 384 /* Enum */ ) return "enum" /* enumElement */ ; if (flags & 524288 /* TypeAlias */ ) return "type" /* typeElement */ ; if (flags & 64 /* Interface */ ) return "interface" /* interfaceElement */ ; @@ -130460,11 +133416,13 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} if (roots.length === 1 && first(roots).flags & 8192 /* Method */ && typeChecker.getTypeOfSymbolAtLocation(symbol, location).getNonNullableType().getCallSignatures().length !== 0) return "method" /* memberFunctionElement */ ; if (typeChecker.isUndefinedSymbol(symbol)) return "var" /* variableElement */ ; if (typeChecker.isArgumentsSymbol(symbol)) return "local var" /* localVariableElement */ ; - if (location.kind === 108 /* ThisKeyword */ && isExpression(location) || isThisInTypeQuery(location)) return "parameter" /* parameterElement */ ; + if (location.kind === 110 /* ThisKeyword */ && isExpression(location) || isThisInTypeQuery(location)) return "parameter" /* parameterElement */ ; const flags = getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 3 /* Variable */ ) { if (isFirstDeclarationOfSymbolParameter(symbol)) return "parameter" /* parameterElement */ ; else if (symbol.valueDeclaration && isVarConst(symbol.valueDeclaration)) return "const" /* constElement */ ; + else if (symbol.valueDeclaration && isVarUsing(symbol.valueDeclaration)) return "using" /* variableUsingElement */ ; + else if (symbol.valueDeclaration && isVarAwaitUsing(symbol.valueDeclaration)) return "await using" /* variableAwaitUsingElement */ ; else if (forEach(symbol.declarations, isLet)) return "let" /* letElement */ ; return isLocalVariableOrFunction(symbol) ? "local var" /* localVariableElement */ : "var" /* variableElement */ ; } @@ -130512,22 +133470,21 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} if (symbol.flags & 16777216 /* Optional */ ) modifiers.add("optional" /* optionalModifier */ ); return modifiers.size > 0 ? arrayFrom(modifiers.values()).join(",") : "" /* none */ ; } - function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning = getMeaningFromLocation(location), alias) { - var _a2; + function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker, symbol, sourceFile, enclosingDeclaration, location, type, semanticMeaning, alias) { + var _a; const displayParts = []; let documentation = []; let tags = []; const symbolFlags = getCombinedLocalAndExportSymbolFlags(symbol); let symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */ ; let hasAddedSymbolInfo = false; - const isThisExpression = location.kind === 108 /* ThisKeyword */ && isInExpressionContext(location) || isThisInTypeQuery(location); - let type; + const isThisExpression = location.kind === 110 /* ThisKeyword */ && isInExpressionContext(location) || isThisInTypeQuery(location); let documentationFromAlias; let tagsFromAlias; let hasMultipleSignatures = false; - if (location.kind === 108 /* ThisKeyword */ && !isThisExpression) return { + if (location.kind === 110 /* ThisKeyword */ && !isThisExpression) return { displayParts: [ - keywordPart(108 /* ThisKeyword */ ) + keywordPart(110 /* ThisKeyword */ ) ], documentation: [], symbolKind: "primitive type" /* primitiveType */ , @@ -130537,13 +133494,13 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} if (symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */ ) { const declaration = find(symbol.declarations, (declaration2)=>declaration2.name === location); if (declaration) switch(declaration.kind){ - case 174 /* GetAccessor */ : + case 177 /* GetAccessor */ : symbolKind = "getter" /* memberGetAccessorElement */ ; break; - case 175 /* SetAccessor */ : + case 178 /* SetAccessor */ : symbolKind = "setter" /* memberSetAccessorElement */ ; break; - case 169 /* PropertyDeclaration */ : + case 172 /* PropertyDeclaration */ : symbolKind = "accessor" /* memberAccessorVariableElement */ ; break; default: @@ -130552,8 +133509,8 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} else symbolKind = "property" /* memberVariableElement */ ; } let signature; - type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); - if (location.parent && location.parent.kind === 208 /* PropertyAccessExpression */ ) { + type ?? (type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location)); + if (location.parent && location.parent.kind === 211 /* PropertyAccessExpression */ ) { const right = location.parent.name; if (right === location || right && right.getFullWidth() === 0) location = location.parent; } @@ -130563,7 +133520,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} else if (location.parent && (isJsxOpeningLikeElement(location.parent) || isTaggedTemplateExpression(location.parent)) && isFunctionLike(symbol.valueDeclaration)) callExpressionLike = location.parent; if (callExpressionLike) { signature = typeChecker.getResolvedSignature(callExpressionLike); - const useConstructSignatures = callExpressionLike.kind === 211 /* NewExpression */ || isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 106 /* SuperKeyword */ ; + const useConstructSignatures = callExpressionLike.kind === 214 /* NewExpression */ || isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 108 /* SuperKeyword */ ; const allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (signature && !contains(allSignatures, signature.target) && !contains(allSignatures, signature)) signature = allSignatures.length ? allSignatures[0] : void 0; if (signature) { @@ -130576,10 +133533,10 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} displayParts.push(spacePart()); if (useConstructSignatures) { if (signature.flags & 4 /* Abstract */ ) { - displayParts.push(keywordPart(126 /* AbstractKeyword */ )); + displayParts.push(keywordPart(128 /* AbstractKeyword */ )); displayParts.push(spacePart()); } - displayParts.push(keywordPart(103 /* NewKeyword */ )); + displayParts.push(keywordPart(105 /* NewKeyword */ )); displayParts.push(spacePart()); } addFullSymbolName(symbol); @@ -130592,7 +133549,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} case "let" /* letElement */ : case "parameter" /* parameterElement */ : case "local var" /* localVariableElement */ : - displayParts.push(punctuationPart(58 /* ColonToken */ )); + displayParts.push(punctuationPart(59 /* ColonToken */ )); displayParts.push(spacePart()); if (!(getObjectFlags(type) & 16 /* Anonymous */ ) && type.symbol) { addRange(displayParts, symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ void 0, 5 /* WriteTypeParametersOrArguments */ )); @@ -130600,10 +133557,10 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} } if (useConstructSignatures) { if (signature.flags & 4 /* Abstract */ ) { - displayParts.push(keywordPart(126 /* AbstractKeyword */ )); + displayParts.push(keywordPart(128 /* AbstractKeyword */ )); displayParts.push(spacePart()); } - displayParts.push(keywordPart(103 /* NewKeyword */ )); + displayParts.push(keywordPart(105 /* NewKeyword */ )); displayParts.push(spacePart()); } addSignatureDisplayParts(signature, allSignatures, 262144 /* WriteArrowStyleSignature */ ); @@ -130615,17 +133572,17 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} hasMultipleSignatures = allSignatures.length > 1; } } else if (isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */ ) || // name of function declaration - location.kind === 135 /* ConstructorKeyword */ && location.parent.kind === 173 /* Constructor */ ) { + location.kind === 137 /* ConstructorKeyword */ && location.parent.kind === 176 /* Constructor */ ) { const functionDeclaration = location.parent; - const locationIsSymbolDeclaration = symbol.declarations && find(symbol.declarations, (declaration)=>declaration === (location.kind === 135 /* ConstructorKeyword */ ? functionDeclaration.parent : functionDeclaration)); + const locationIsSymbolDeclaration = symbol.declarations && find(symbol.declarations, (declaration)=>declaration === (location.kind === 137 /* ConstructorKeyword */ ? functionDeclaration.parent : functionDeclaration)); if (locationIsSymbolDeclaration) { - const allSignatures = functionDeclaration.kind === 173 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + const allSignatures = functionDeclaration.kind === 176 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration)) signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); else signature = allSignatures[0]; - if (functionDeclaration.kind === 173 /* Constructor */ ) { + if (functionDeclaration.kind === 176 /* Constructor */ ) { symbolKind = "constructor" /* constructorImplementationElement */ ; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); - } else addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 176 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */ ) ? type.symbol : symbol, symbolKind); + } else addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 179 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */ ) ? type.symbol : symbol, symbolKind); if (signature) addSignatureDisplayParts(signature, allSignatures); hasAddedSymbolInfo = true; hasMultipleSignatures = allSignatures.length > 1; @@ -130634,53 +133591,53 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { addAliasPrefixIfNecessary(); - if (getDeclarationOfKind(symbol, 228 /* ClassExpression */ )) pushSymbolKind("local class" /* localClassElement */ ); - else displayParts.push(keywordPart(84 /* ClassKeyword */ )); + if (getDeclarationOfKind(symbol, 231 /* ClassExpression */ )) pushSymbolKind("local class" /* localClassElement */ ); + else displayParts.push(keywordPart(86 /* ClassKeyword */ )); displayParts.push(spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } if (symbolFlags & 64 /* Interface */ && semanticMeaning & 2 /* Type */ ) { prefixNextMeaning(); - displayParts.push(keywordPart(118 /* InterfaceKeyword */ )); + displayParts.push(keywordPart(120 /* InterfaceKeyword */ )); displayParts.push(spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } if (symbolFlags & 524288 /* TypeAlias */ && semanticMeaning & 2 /* Type */ ) { prefixNextMeaning(); - displayParts.push(keywordPart(154 /* TypeKeyword */ )); + displayParts.push(keywordPart(156 /* TypeKeyword */ )); displayParts.push(spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); displayParts.push(spacePart()); - displayParts.push(operatorPart(63 /* EqualsToken */ )); + displayParts.push(operatorPart(64 /* EqualsToken */ )); displayParts.push(spacePart()); - addRange(displayParts, typeToDisplayParts(typeChecker, isConstTypeReference(location.parent) ? typeChecker.getTypeAtLocation(location.parent) : typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */ )); + addRange(displayParts, typeToDisplayParts(typeChecker, location.parent && isConstTypeReference(location.parent) ? typeChecker.getTypeAtLocation(location.parent) : typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */ )); } if (symbolFlags & 384 /* Enum */ ) { prefixNextMeaning(); if (some(symbol.declarations, (d)=>isEnumDeclaration(d) && isEnumConst(d))) { - displayParts.push(keywordPart(85 /* ConstKeyword */ )); + displayParts.push(keywordPart(87 /* ConstKeyword */ )); displayParts.push(spacePart()); } - displayParts.push(keywordPart(92 /* EnumKeyword */ )); + displayParts.push(keywordPart(94 /* EnumKeyword */ )); displayParts.push(spacePart()); addFullSymbolName(symbol); } if (symbolFlags & 1536 /* Module */ && !isThisExpression) { prefixNextMeaning(); - const declaration = getDeclarationOfKind(symbol, 264 /* ModuleDeclaration */ ); - const isNamespace = declaration && declaration.name && declaration.name.kind === 79 /* Identifier */ ; - displayParts.push(keywordPart(isNamespace ? 143 /* NamespaceKeyword */ : 142 /* ModuleKeyword */ )); + const declaration = getDeclarationOfKind(symbol, 267 /* ModuleDeclaration */ ); + const isNamespace = declaration && declaration.name && declaration.name.kind === 80 /* Identifier */ ; + displayParts.push(keywordPart(isNamespace ? 145 /* NamespaceKeyword */ : 144 /* ModuleKeyword */ )); displayParts.push(spacePart()); addFullSymbolName(symbol); } if (symbolFlags & 262144 /* TypeParameter */ && semanticMeaning & 2 /* Type */ ) { prefixNextMeaning(); - displayParts.push(punctuationPart(20 /* OpenParenToken */ )); + displayParts.push(punctuationPart(21 /* OpenParenToken */ )); displayParts.push(textPart("type parameter")); - displayParts.push(punctuationPart(21 /* CloseParenToken */ )); + displayParts.push(punctuationPart(22 /* CloseParenToken */ )); displayParts.push(spacePart()); addFullSymbolName(symbol); if (symbol.parent) { @@ -130688,21 +133645,21 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} addFullSymbolName(symbol.parent, enclosingDeclaration); writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); } else { - const decl = getDeclarationOfKind(symbol, 165 /* TypeParameter */ ); + const decl = getDeclarationOfKind(symbol, 168 /* TypeParameter */ ); if (decl === void 0) return Debug.fail(); const declaration = decl.parent; if (declaration) { if (isFunctionLike(declaration)) { addInPrefix(); const signature = typeChecker.getSignatureFromDeclaration(declaration); - if (declaration.kind === 177 /* ConstructSignature */ ) { - displayParts.push(keywordPart(103 /* NewKeyword */ )); + if (declaration.kind === 180 /* ConstructSignature */ ) { + displayParts.push(keywordPart(105 /* NewKeyword */ )); displayParts.push(spacePart()); - } else if (declaration.kind !== 176 /* CallSignature */ && declaration.name) addFullSymbolName(declaration.symbol); + } else if (declaration.kind !== 179 /* CallSignature */ && declaration.name) addFullSymbolName(declaration.symbol); addRange(displayParts, signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */ )); } else if (isTypeAliasDeclaration(declaration)) { addInPrefix(); - displayParts.push(keywordPart(154 /* TypeKeyword */ )); + displayParts.push(keywordPart(156 /* TypeKeyword */ )); displayParts.push(spacePart()); addFullSymbolName(declaration.symbol); writeTypeParametersOfSymbol(declaration.symbol, sourceFile); @@ -130713,12 +133670,12 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} if (symbolFlags & 8 /* EnumMember */ ) { symbolKind = "enum member" /* enumMemberElement */ ; addPrefixForAnyFunctionOrVar(symbol, "enum member"); - const declaration = (_a2 = symbol.declarations) == null ? void 0 : _a2[0]; - if ((declaration == null ? void 0 : declaration.kind) === 302 /* EnumMember */ ) { + const declaration = (_a = symbol.declarations) == null ? void 0 : _a[0]; + if ((declaration == null ? void 0 : declaration.kind) === 306 /* EnumMember */ ) { const constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== void 0) { displayParts.push(spacePart()); - displayParts.push(operatorPart(63 /* EqualsToken */ )); + displayParts.push(operatorPart(64 /* EqualsToken */ )); displayParts.push(spacePart()); displayParts.push(displayPart(getTextOfConstantValue(constantValue), typeof constantValue === "number" ? 7 /* numericLiteral */ : 8 /* stringLiteral */ )); } @@ -130726,15 +133683,15 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} } if (symbol.flags & 2097152 /* Alias */ ) { prefixNextMeaning(); - if (!hasAddedSymbolInfo) { + if (!hasAddedSymbolInfo || documentation.length === 0 && tags.length === 0) { const resolvedSymbol = typeChecker.getAliasedSymbol(symbol); if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) { const resolvedNode = resolvedSymbol.declarations[0]; const declarationName = getNameOfDeclaration(resolvedNode); - if (declarationName) { + if (declarationName && !hasAddedSymbolInfo) { const isExternalModuleDeclaration = isModuleWithStringLiteralName(resolvedNode) && hasSyntacticModifier(resolvedNode, 2 /* Ambient */ ); const shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; - const resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, resolvedSymbol, getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, semanticMeaning, shouldUseAliasName ? symbol : resolvedSymbol); + const resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker, resolvedSymbol, getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, type, semanticMeaning, shouldUseAliasName ? symbol : resolvedSymbol); displayParts.push(...resolvedInfo.displayParts); displayParts.push(lineBreakPart()); documentationFromAlias = resolvedInfo.documentation; @@ -130746,40 +133703,40 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} } } if (symbol.declarations) switch(symbol.declarations[0].kind){ - case 267 /* NamespaceExportDeclaration */ : - displayParts.push(keywordPart(93 /* ExportKeyword */ )); + case 270 /* NamespaceExportDeclaration */ : + displayParts.push(keywordPart(95 /* ExportKeyword */ )); displayParts.push(spacePart()); - displayParts.push(keywordPart(143 /* NamespaceKeyword */ )); + displayParts.push(keywordPart(145 /* NamespaceKeyword */ )); break; - case 274 /* ExportAssignment */ : - displayParts.push(keywordPart(93 /* ExportKeyword */ )); + case 277 /* ExportAssignment */ : + displayParts.push(keywordPart(95 /* ExportKeyword */ )); displayParts.push(spacePart()); - displayParts.push(keywordPart(symbol.declarations[0].isExportEquals ? 63 /* EqualsToken */ : 88 /* DefaultKeyword */ )); + displayParts.push(keywordPart(symbol.declarations[0].isExportEquals ? 64 /* EqualsToken */ : 90 /* DefaultKeyword */ )); break; - case 278 /* ExportSpecifier */ : - displayParts.push(keywordPart(93 /* ExportKeyword */ )); + case 281 /* ExportSpecifier */ : + displayParts.push(keywordPart(95 /* ExportKeyword */ )); break; default: - displayParts.push(keywordPart(100 /* ImportKeyword */ )); + displayParts.push(keywordPart(102 /* ImportKeyword */ )); } displayParts.push(spacePart()); addFullSymbolName(symbol); forEach(symbol.declarations, (declaration)=>{ - if (declaration.kind === 268 /* ImportEqualsDeclaration */ ) { + if (declaration.kind === 271 /* ImportEqualsDeclaration */ ) { const importEqualsDeclaration = declaration; if (isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(spacePart()); - displayParts.push(operatorPart(63 /* EqualsToken */ )); + displayParts.push(operatorPart(64 /* EqualsToken */ )); displayParts.push(spacePart()); - displayParts.push(keywordPart(147 /* RequireKeyword */ )); - displayParts.push(punctuationPart(20 /* OpenParenToken */ )); + displayParts.push(keywordPart(149 /* RequireKeyword */ )); + displayParts.push(punctuationPart(21 /* OpenParenToken */ )); displayParts.push(displayPart(getTextOfNode(getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), 8 /* stringLiteral */ )); - displayParts.push(punctuationPart(21 /* CloseParenToken */ )); + displayParts.push(punctuationPart(22 /* CloseParenToken */ )); } else { const internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); if (internalAliasSymbol) { displayParts.push(spacePart()); - displayParts.push(operatorPart(63 /* EqualsToken */ )); + displayParts.push(operatorPart(64 /* EqualsToken */ )); displayParts.push(spacePart()); addFullSymbolName(internalAliasSymbol, enclosingDeclaration); } @@ -130793,10 +133750,10 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} if (type) { if (isThisExpression) { prefixNextMeaning(); - displayParts.push(keywordPart(108 /* ThisKeyword */ )); + displayParts.push(keywordPart(110 /* ThisKeyword */ )); } else addPrefixForAnyFunctionOrVar(symbol, symbolKind); - if (symbolKind === "property" /* memberVariableElement */ || symbolKind === "accessor" /* memberAccessorVariableElement */ || symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */ || symbolKind === "JSX attribute" /* jsxAttribute */ || symbolFlags & 3 /* Variable */ || symbolKind === "local var" /* localVariableElement */ || symbolKind === "index" /* indexSignatureElement */ || isThisExpression) { - displayParts.push(punctuationPart(58 /* ColonToken */ )); + if (symbolKind === "property" /* memberVariableElement */ || symbolKind === "accessor" /* memberAccessorVariableElement */ || symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */ || symbolKind === "JSX attribute" /* jsxAttribute */ || symbolFlags & 3 /* Variable */ || symbolKind === "local var" /* localVariableElement */ || symbolKind === "index" /* indexSignatureElement */ || symbolKind === "using" /* variableUsingElement */ || symbolKind === "await using" /* variableAwaitUsingElement */ || isThisExpression) { + displayParts.push(punctuationPart(59 /* ColonToken */ )); displayParts.push(spacePart()); if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */ && symbolKind !== "index" /* indexSignatureElement */ ) { const typeParameterParts = mapToDisplayParts((writer)=>{ @@ -130809,9 +133766,9 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} const labelDecl = symbol.links.target.links.tupleLabelDeclaration; Debug.assertNode(labelDecl.name, isIdentifier); displayParts.push(spacePart()); - displayParts.push(punctuationPart(20 /* OpenParenToken */ )); + displayParts.push(punctuationPart(21 /* OpenParenToken */ )); displayParts.push(textPart(idText(labelDecl.name))); - displayParts.push(punctuationPart(21 /* CloseParenToken */ )); + displayParts.push(punctuationPart(22 /* CloseParenToken */ )); } } else if (symbolFlags & 16 /* Function */ || symbolFlags & 8192 /* Method */ || symbolFlags & 16384 /* Constructor */ || symbolFlags & 131072 /* Signature */ || symbolFlags & 98304 /* Accessor */ || symbolKind === "method" /* memberFunctionElement */ ) { const allSignatures = type.getNonNullableType().getCallSignatures(); @@ -130825,8 +133782,8 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} } if (documentation.length === 0 && !hasMultipleSignatures) documentation = symbol.getContextualDocumentationComment(enclosingDeclaration, typeChecker); if (documentation.length === 0 && symbolFlags & 4 /* Property */ ) { - if (symbol.parent && symbol.declarations && forEach(symbol.parent.declarations, (declaration)=>declaration.kind === 308 /* SourceFile */ )) for (const declaration of symbol.declarations){ - if (!declaration.parent || declaration.parent.kind !== 223 /* BinaryExpression */ ) continue; + if (symbol.parent && symbol.declarations && forEach(symbol.parent.declarations, (declaration)=>declaration.kind === 312 /* SourceFile */ )) for (const declaration of symbol.declarations){ + if (!declaration.parent || declaration.parent.kind !== 226 /* BinaryExpression */ ) continue; const rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); if (!rhsSymbol) continue; documentation = rhsSymbol.getDocumentationComment(typeChecker); @@ -130872,7 +133829,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} } function addInPrefix() { displayParts.push(spacePart()); - displayParts.push(keywordPart(101 /* InKeyword */ )); + displayParts.push(keywordPart(103 /* InKeyword */ )); displayParts.push(spacePart()); } function addFullSymbolName(symbolToDisplay, enclosingDeclaration2) { @@ -130882,19 +133839,19 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} let fullSymbolDisplayParts = []; if (symbolToDisplay.flags & 131072 /* Signature */ && indexInfos) { if (symbolToDisplay.parent) fullSymbolDisplayParts = symbolToDisplayParts(typeChecker, symbolToDisplay.parent); - fullSymbolDisplayParts.push(punctuationPart(22 /* OpenBracketToken */ )); + fullSymbolDisplayParts.push(punctuationPart(23 /* OpenBracketToken */ )); indexInfos.forEach((info, i)=>{ fullSymbolDisplayParts.push(...typeToDisplayParts(typeChecker, info.keyType)); if (i !== indexInfos.length - 1) { fullSymbolDisplayParts.push(spacePart()); - fullSymbolDisplayParts.push(punctuationPart(51 /* BarToken */ )); + fullSymbolDisplayParts.push(punctuationPart(52 /* BarToken */ )); fullSymbolDisplayParts.push(spacePart()); } }); - fullSymbolDisplayParts.push(punctuationPart(23 /* CloseBracketToken */ )); + fullSymbolDisplayParts.push(punctuationPart(24 /* CloseBracketToken */ )); } else fullSymbolDisplayParts = symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration2 || sourceFile, /*meaning*/ void 0, 7 /* AllowAnyNodeKind */ ); addRange(displayParts, fullSymbolDisplayParts); - if (symbol.flags & 16777216 /* Optional */ ) displayParts.push(punctuationPart(57 /* QuestionToken */ )); + if (symbol.flags & 16777216 /* Optional */ ) displayParts.push(punctuationPart(58 /* QuestionToken */ )); } function addPrefixForAnyFunctionOrVar(symbol2, symbolKind2) { prefixNextMeaning(); @@ -130913,12 +133870,14 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} case "let" /* letElement */ : case "const" /* constElement */ : case "constructor" /* constructorImplementationElement */ : + case "using" /* variableUsingElement */ : + case "await using" /* variableAwaitUsingElement */ : displayParts.push(textOrKeywordPart(symbolKind2)); return; default: - displayParts.push(punctuationPart(20 /* OpenParenToken */ )); + displayParts.push(punctuationPart(21 /* OpenParenToken */ )); displayParts.push(textOrKeywordPart(symbolKind2)); - displayParts.push(punctuationPart(21 /* CloseParenToken */ )); + displayParts.push(punctuationPart(22 /* CloseParenToken */ )); return; } } @@ -130926,12 +133885,12 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} addRange(displayParts, signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */ )); if (allSignatures.length > 1) { displayParts.push(spacePart()); - displayParts.push(punctuationPart(20 /* OpenParenToken */ )); - displayParts.push(operatorPart(39 /* PlusToken */ )); + displayParts.push(punctuationPart(21 /* OpenParenToken */ )); + displayParts.push(operatorPart(40 /* PlusToken */ )); displayParts.push(displayPart((allSignatures.length - 1).toString(), 7 /* numericLiteral */ )); displayParts.push(spacePart()); displayParts.push(textPart(allSignatures.length === 2 ? "overload" : "overloads")); - displayParts.push(punctuationPart(21 /* CloseParenToken */ )); + displayParts.push(punctuationPart(22 /* CloseParenToken */ )); } documentation = signature.getDocumentationComment(typeChecker); tags = signature.getJsDocTags(); @@ -130948,13 +133907,16 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} addRange(displayParts, typeParameterParts); } } + function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning = getMeaningFromLocation(location), alias) { + return getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker, symbol, sourceFile, enclosingDeclaration, location, /*type*/ void 0, semanticMeaning, alias); + } function isLocalVariableOrFunction(symbol) { if (symbol.parent) return false; return forEach(symbol.declarations, (declaration)=>{ - if (declaration.kind === 215 /* FunctionExpression */ ) return true; - if (declaration.kind !== 257 /* VariableDeclaration */ && declaration.kind !== 259 /* FunctionDeclaration */ ) return false; + if (declaration.kind === 218 /* FunctionExpression */ ) return true; + if (declaration.kind !== 260 /* VariableDeclaration */ && declaration.kind !== 262 /* FunctionDeclaration */ ) return false; for(let parent2 = declaration.parent; !isFunctionBlock(parent2); parent2 = parent2.parent){ - if (parent2.kind === 308 /* SourceFile */ || parent2.kind === 265 /* ModuleBlock */ ) return false; + if (parent2.kind === 312 /* SourceFile */ || parent2.kind === 268 /* ModuleBlock */ ) return false; } return true; }); @@ -131021,8 +133983,8 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} }; } function getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment = false) { - var _a2, _b; - const { leadingTriviaOption: leadingTriviaOption } = options; + var _a, _b; + const { leadingTriviaOption: leadingTriviaOption } = options; if (leadingTriviaOption === 0 /* Exclude */ ) return node.getStart(sourceFile); if (leadingTriviaOption === 3 /* StartLine */ ) { const startPos = node.getStart(sourceFile); @@ -131040,7 +134002,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} const startLine = getLineStartPositionForPosition(start, sourceFile); if (startLine === fullStartLine) return leadingTriviaOption === 1 /* IncludeAll */ ? fullStart : start; if (hasTrailingComment) { - const comment = ((_a2 = getLeadingCommentRanges(sourceFile.text, fullStart)) == null ? void 0 : _a2[0]) || ((_b = getTrailingCommentRanges(sourceFile.text, fullStart)) == null ? void 0 : _b[0]); + const comment = ((_a = getLeadingCommentRanges(sourceFile.text, fullStart)) == null ? void 0 : _a[0]) || ((_b = getTrailingCommentRanges(sourceFile.text, fullStart)) == null ? void 0 : _b[0]); if (comment) return skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); } const nextLineStart = fullStart > 0 ? 1 : 0; @@ -131049,8 +134011,8 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} return getStartPositionOfLine(getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } function getEndPositionOfMultilineTrailingComment(sourceFile, node, options) { - const { end: end } = node; - const { trailingTriviaOption: trailingTriviaOption } = options; + const { end: end } = node; + const { trailingTriviaOption: trailingTriviaOption } = options; if (trailingTriviaOption === 2 /* Include */ ) { const comments = getTrailingCommentRanges(sourceFile.text, end); if (comments) { @@ -131065,13 +134027,13 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} return void 0; } function getAdjustedEndPosition(sourceFile, node, options) { - var _a2; - const { end: end } = node; - const { trailingTriviaOption: trailingTriviaOption } = options; + var _a; + const { end: end } = node; + const { trailingTriviaOption: trailingTriviaOption } = options; if (trailingTriviaOption === 0 /* Exclude */ ) return end; if (trailingTriviaOption === 1 /* ExcludeWhitespace */ ) { const comments = concatenate(getTrailingCommentRanges(sourceFile.text, end), getLeadingCommentRanges(sourceFile.text, end)); - const realEnd = (_a2 = comments == null ? void 0 : comments[comments.length - 1]) == null ? void 0 : _a2.end; + const realEnd = (_a = comments == null ? void 0 : comments[comments.length - 1]) == null ? void 0 : _a.end; if (realEnd) return realEnd; return end; } @@ -131081,29 +134043,29 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} return newEnd !== end && (trailingTriviaOption === 2 /* Include */ || isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))) ? newEnd : end; } function isSeparator(node, candidate) { - return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 207 /* ObjectLiteralExpression */ ); + return !!candidate && !!node.parent && (candidate.kind === 28 /* CommaToken */ || candidate.kind === 27 /* SemicolonToken */ && node.parent.kind === 210 /* ObjectLiteralExpression */ ); } function isThisTypeAnnotatable(containingFunction) { return isFunctionExpression(containingFunction) || isFunctionDeclaration(containingFunction); } function updateJSDocHost(parent2) { - if (parent2.kind !== 216 /* ArrowFunction */ ) return parent2; - const jsDocNode = parent2.parent.kind === 169 /* PropertyDeclaration */ ? parent2.parent : parent2.parent.parent; + if (parent2.kind !== 219 /* ArrowFunction */ ) return parent2; + const jsDocNode = parent2.parent.kind === 172 /* PropertyDeclaration */ ? parent2.parent : parent2.parent.parent; jsDocNode.jsDoc = parent2.jsDoc; return jsDocNode; } function tryMergeJsdocTags(oldTag, newTag) { if (oldTag.kind !== newTag.kind) return void 0; switch(oldTag.kind){ - case 344 /* JSDocParameterTag */ : + case 348 /* JSDocParameterTag */ : { const oldParam = oldTag; const newParam = newTag; return isIdentifier(oldParam.name) && isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText ? factory.createJSDocParameterTag(/*tagName*/ void 0, newParam.name, /*isBracketed*/ false, newParam.typeExpression, newParam.isNameFirst, oldParam.comment) : void 0; } - case 345 /* JSDocReturnTag */ : + case 349 /* JSDocReturnTag */ : return factory.createJSDocReturnTag(/*tagName*/ void 0, newTag.typeExpression, oldTag.comment); - case 347 /* JSDocTypeTag */ : + case 351 /* JSDocTypeTag */ : return factory.createJSDocTypeTag(/*tagName*/ void 0, newTag.typeExpression, oldTag.comment); } } @@ -131127,8 +134089,8 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} return end; } function getClassOrObjectBraceEnds(cls, sourceFile) { - const open = findChildOfKind(cls, 18 /* OpenBraceToken */ , sourceFile); - const close = findChildOfKind(cls, 19 /* CloseBraceToken */ , sourceFile); + const open = findChildOfKind(cls, 19 /* OpenBraceToken */ , sourceFile); + const close = findChildOfKind(cls, 20 /* CloseBraceToken */ , sourceFile); return [ open == null ? void 0 : open.end, close == null ? void 0 : close.end @@ -131137,12 +134099,9 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} function getMembersOrProperties(node) { return isObjectLiteralExpression(node) ? node.properties : node.members; } - function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { - return changesToText.newFileChangesWorker(/*oldFile*/ void 0, scriptKind, statements, newLineCharacter, formatContext); - } function applyChanges(text, changes) { for(let i = changes.length - 1; i >= 0; i--){ - const { span: span , newText: newText } = changes[i]; + const { span: span, newText: newText } = changes[i]; text = `${text.substring(0, span.start)}${newText}${text.substring(textSpanEnd(span))}`; } return text; @@ -131382,7 +134341,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} return !isInComment(sourceFile, position) && !isInString(sourceFile, position) && !isInTemplateString(sourceFile, position) && !isInJSXText(sourceFile, position); } function needSemicolonBetween(a, b) { - return (isPropertySignature(a) || isPropertyDeclaration(a)) && isClassOrTypeElement(b) && b.name.kind === 164 /* ComputedPropertyName */ || isStatementButNotDeclaration(a) && isStatementButNotDeclaration(b); + return (isPropertySignature(a) || isPropertyDeclaration(a)) && isClassOrTypeElement(b) && b.name.kind === 167 /* ComputedPropertyName */ || isStatementButNotDeclaration(a) && isStatementButNotDeclaration(b); } function deleteNode(changes, sourceFile, node, options = { leadingTriviaOption: 1 /* IncludeAll */ @@ -131431,21 +134390,20 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} leadingTriviaOption: 0 /* Exclude */ , trailingTriviaOption: 0 /* Exclude */ }; - ChangeTracker = class { + ChangeTracker = class _ChangeTracker { /** Public for tests only. Other callers should use `ChangeTracker.with`. */ constructor(newLineCharacter, formatContext){ this.newLineCharacter = newLineCharacter; this.formatContext = formatContext; this.changes = []; - this.newFiles = []; this.classesWithNodesInsertedAtStart = /* @__PURE__ */ new Map(); // Set implemented as Map this.deletedNodes = []; } static fromContext(context) { - return new ChangeTracker(getNewLineOrDefaultFromHost(context.host, context.formatContext.options), context.formatContext); + return new _ChangeTracker(getNewLineOrDefaultFromHost(context.host, context.formatContext.options), context.formatContext); } static with(context, cb) { - const tracker = ChangeTracker.fromContext(context); + const tracker = _ChangeTracker.fromContext(context); cb(tracker); return tracker.getChanges(); } @@ -131553,7 +134511,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} } nextCommaToken(sourceFile, node) { const next = findNextToken(node, node.parent, sourceFile); - return next && next.kind === 27 /* CommaToken */ ? next : void 0; + return next && next.kind === 28 /* CommaToken */ ? next : void 0; } replacePropertyAssignment(sourceFile, oldNode, newNode) { const suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : "," + this.newLineCharacter; @@ -131582,6 +134540,24 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} if (isArray(insert)) this.insertNodesAt(sourceFile, pos, insert, options); else this.insertNodeAt(sourceFile, pos, insert, options); } + insertNodesAtEndOfFile(sourceFile, newNodes, blankLineBetween) { + this.insertAtEndOfFile(sourceFile, newNodes, blankLineBetween); + } + insertAtEndOfFile(sourceFile, insert, blankLineBetween) { + const pos = sourceFile.end + 1; + const options = { + prefix: this.newLineCharacter, + suffix: this.newLineCharacter + (blankLineBetween ? this.newLineCharacter : "") + }; + this.insertNodesAt(sourceFile, pos, insert, options); + } + insertStatementsInNewFile(fileName, statements, oldFile) { + if (!this.newFileChanges) this.newFileChanges = createMultiMap(); + this.newFileChanges.add(fileName, { + oldFile: oldFile, + statements: statements + }); + } insertFirstParameter(sourceFile, parameters, newParam) { const p0 = firstOrUndefined(parameters); if (p0) this.insertNodeBefore(sourceFile, p0, newParam); @@ -131590,6 +134566,9 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} insertNodeBefore(sourceFile, before, newNode, blankLineBetween = false, options = {}) { this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, options), newNode, this.getOptionsForInsertNodeBefore(before, newNode, blankLineBetween)); } + insertNodesBefore(sourceFile, before, newNodes, blankLineBetween = false, options = {}) { + this.insertNodesAt(sourceFile, getAdjustedStartPosition(sourceFile, before, options), newNodes, this.getOptionsForInsertNodeBefore(before, first(newNodes), blankLineBetween)); + } insertModifierAt(sourceFile, pos, modifier, options = {}) { this.insertNodeAt(sourceFile, pos, factory.createToken(modifier), options); } @@ -131654,22 +134633,21 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} this.replaceRangeWithText(sourceFile, createRange(pos), text); } /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ tryInsertTypeAnnotation(sourceFile, node, type) { - var _a2; let endNode2; if (isFunctionLike(node)) { - endNode2 = findChildOfKind(node, 21 /* CloseParenToken */ , sourceFile); + endNode2 = findChildOfKind(node, 22 /* CloseParenToken */ , sourceFile); if (!endNode2) { if (!isArrowFunction(node)) return false; endNode2 = first(node.parameters); } - } else endNode2 = (_a2 = node.kind === 257 /* VariableDeclaration */ ? node.exclamationToken : node.questionToken) != null ? _a2 : node.name; + } else endNode2 = (node.kind === 260 /* VariableDeclaration */ ? node.exclamationToken : node.questionToken) ?? node.name; this.insertNodeAt(sourceFile, endNode2.end, type, { prefix: ": " }); return true; } tryInsertThisTypeAnnotation(sourceFile, node, type) { - const start = findChildOfKind(node, 20 /* OpenParenToken */ , sourceFile).getStart(sourceFile) + 1; + const start = findChildOfKind(node, 21 /* OpenParenToken */ , sourceFile).getStart(sourceFile) + 1; const suffix = node.parameters.length ? ", " : ""; this.insertNodeAt(sourceFile, start, type, { prefix: "this: ", @@ -131677,7 +134655,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} }); } insertTypeParameters(sourceFile, node, typeParameters) { - const start = (findChildOfKind(node, 20 /* OpenParenToken */ , sourceFile) || first(node.parameters)).getStart(sourceFile); + const start = (findChildOfKind(node, 21 /* OpenParenToken */ , sourceFile) || first(node.parameters)).getStart(sourceFile); this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">", @@ -131743,8 +134721,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} this.insertNodeAtStartWorker(sourceFile, obj, newElement); } insertNodeAtStartWorker(sourceFile, node, newElement) { - var _a2; - const indentation = (_a2 = this.guessIndentationFromExistingMembers(sourceFile, node)) != null ? _a2 : this.computeIndentationForNewMember(sourceFile, node); + const indentation = this.guessIndentationFromExistingMembers(sourceFile, node) ?? this.computeIndentationForNewMember(sourceFile, node); this.insertNodeAt(sourceFile, getMembersOrProperties(node).pos, newElement, this.getInsertNodeAtStartInsertOptions(sourceFile, node, indentation)); } /** @@ -131764,9 +134741,8 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} return indentation; } computeIndentationForNewMember(sourceFile, node) { - var _a2; const nodeStart = node.getStart(sourceFile); - return ts_formatting_exports.SmartIndenter.findFirstNonWhitespaceColumn(getLineStartPositionForPosition(nodeStart, sourceFile), nodeStart, sourceFile, this.formatContext.options) + ((_a2 = this.formatContext.options.indentSize) != null ? _a2 : 4); + return ts_formatting_exports.SmartIndenter.findFirstNonWhitespaceColumn(getLineStartPositionForPosition(nodeStart, sourceFile), nodeStart, sourceFile, this.formatContext.options) + (this.formatContext.options.indentSize ?? 4); } getInsertNodeAtStartInsertOptions(sourceFile, node, indentation) { const members = getMembersOrProperties(node); @@ -131802,7 +134778,7 @@ ${newComment.split("\n").map((c)=>` * ${c}`).join("\n")} } insertNodeAfterWorker(sourceFile, after, newNode) { if (needSemicolonBetween(after, newNode)) { - if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */ ) this.replaceRange(sourceFile, createRange(after.end), factory.createToken(26 /* SemicolonToken */ )); + if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */ ) this.replaceRange(sourceFile, createRange(after.end), factory.createToken(27 /* SemicolonToken */ )); } const endPosition = getAdjustedEndPosition(sourceFile, after, {}); return endPosition; @@ -131817,27 +134793,27 @@ ${options.prefix}` : "\n" : options.prefix } getInsertNodeAfterOptionsWorker(node) { switch(node.kind){ - case 260 /* ClassDeclaration */ : - case 264 /* ModuleDeclaration */ : + case 263 /* ClassDeclaration */ : + case 267 /* ModuleDeclaration */ : return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; - case 257 /* VariableDeclaration */ : - case 10 /* StringLiteral */ : - case 79 /* Identifier */ : + case 260 /* VariableDeclaration */ : + case 11 /* StringLiteral */ : + case 80 /* Identifier */ : return { prefix: ", " }; - case 299 /* PropertyAssignment */ : + case 303 /* PropertyAssignment */ : return { suffix: "," + this.newLineCharacter }; - case 93 /* ExportKeyword */ : + case 95 /* ExportKeyword */ : return { prefix: " " }; - case 166 /* Parameter */ : + case 169 /* Parameter */ : return {}; default: Debug.assert(isStatement(node) || isClassOrTypeElement(node)); @@ -131848,12 +134824,12 @@ ${options.prefix}` : "\n" : options.prefix } insertName(sourceFile, node, name) { Debug.assert(!node.name); - if (node.kind === 216 /* ArrowFunction */ ) { - const arrow = findChildOfKind(node, 38 /* EqualsGreaterThanToken */ , sourceFile); - const lparen = findChildOfKind(node, 20 /* OpenParenToken */ , sourceFile); + if (node.kind === 219 /* ArrowFunction */ ) { + const arrow = findChildOfKind(node, 39 /* EqualsGreaterThanToken */ , sourceFile); + const lparen = findChildOfKind(node, 21 /* OpenParenToken */ , sourceFile); if (lparen) { this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [ - factory.createToken(98 /* FunctionKeyword */ ), + factory.createToken(100 /* FunctionKeyword */ ), factory.createIdentifier(name) ], { joiner: " " @@ -131861,25 +134837,25 @@ ${options.prefix}` : "\n" : options.prefix deleteNode(this, sourceFile, arrow); } else { this.insertText(sourceFile, first(node.parameters).getStart(sourceFile), `function ${name}(`); - this.replaceRange(sourceFile, arrow, factory.createToken(21 /* CloseParenToken */ )); + this.replaceRange(sourceFile, arrow, factory.createToken(22 /* CloseParenToken */ )); } - if (node.body.kind !== 238 /* Block */ ) { + if (node.body.kind !== 241 /* Block */ ) { this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ - factory.createToken(18 /* OpenBraceToken */ ), - factory.createToken(105 /* ReturnKeyword */ ) + factory.createToken(19 /* OpenBraceToken */ ), + factory.createToken(107 /* ReturnKeyword */ ) ], { joiner: " ", suffix: " " }); this.insertNodesAt(sourceFile, node.body.end, [ - factory.createToken(26 /* SemicolonToken */ ), - factory.createToken(19 /* CloseBraceToken */ ) + factory.createToken(27 /* SemicolonToken */ ), + factory.createToken(20 /* CloseBraceToken */ ) ], { joiner: " " }); } } else { - const pos = findChildOfKind(node, node.kind === 215 /* FunctionExpression */ ? 98 /* FunctionKeyword */ : 84 /* ClassKeyword */ , sourceFile).end; + const pos = findChildOfKind(node, node.kind === 218 /* FunctionExpression */ ? 100 /* FunctionKeyword */ : 86 /* ClassKeyword */ , sourceFile).end; this.insertNodeAt(sourceFile, pos, factory.createIdentifier(name), { prefix: " " }); @@ -131922,10 +134898,10 @@ ${options.prefix}` : "\n" : options.prefix const afterStartLinePosition = getLineStartPositionForPosition(afterStart, sourceFile); let separator; let multilineList = false; - if (containingList.length === 1) separator = 27 /* CommaToken */ ; + if (containingList.length === 1) separator = 28 /* CommaToken */ ; else { const tokenBeforeInsertPosition = findPrecedingToken(after.pos, sourceFile); - separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 27 /* CommaToken */ ; + separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 28 /* CommaToken */ ; const afterMinusOneStartLinePosition = getLineStartPositionForPosition(containingList[index - 1].getStart(sourceFile), sourceFile); multilineList = afterMinusOneStartLinePosition !== afterStartLinePosition; } @@ -131948,7 +134924,7 @@ ${options.prefix}` : "\n" : options.prefix this.replaceRange(sourceFile, rangeOfNode(expression), factory.createParenthesizedExpression(expression)); } finishClassesWithNodesInsertedAtStart() { - this.classesWithNodesInsertedAtStart.forEach(({ node: node , sourceFile: sourceFile })=>{ + this.classesWithNodesInsertedAtStart.forEach(({ node: node, sourceFile: sourceFile })=>{ const [openBraceEnd, closeBraceEnd] = getClassOrObjectBraceEnds(node, sourceFile); if (openBraceEnd !== void 0 && closeBraceEnd !== void 0) { const isEmpty = getMembersOrProperties(node).length === 0; @@ -131960,7 +134936,7 @@ ${options.prefix}` : "\n" : options.prefix } finishDeleteDeclarations() { const deletedNodesInLists = /* @__PURE__ */ new Set(); - for (const { sourceFile: sourceFile , node: node } of this.deletedNodes)if (!this.deletedNodes.some((d)=>d.sourceFile === sourceFile && rangeContainsRangeExclusive(d.node, node))) { + for (const { sourceFile: sourceFile, node: node } of this.deletedNodes)if (!this.deletedNodes.some((d)=>d.sourceFile === sourceFile && rangeContainsRangeExclusive(d.node, node))) { if (isArray(node)) this.deleteRange(sourceFile, rangeOfTypeParameters(sourceFile, node)); else deleteDeclaration.deleteDeclaration(this, deletedNodesInLists, sourceFile, node); } @@ -131984,15 +134960,13 @@ ${options.prefix}` : "\n" : options.prefix this.finishDeleteDeclarations(); this.finishClassesWithNodesInsertedAtStart(); const changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); - for (const { oldFile: oldFile , fileName: fileName , statements: statements } of this.newFiles)changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext)); + if (this.newFileChanges) this.newFileChanges.forEach((insertions, fileName)=>{ + changes.push(changesToText.newFileChanges(fileName, insertions, this.newLineCharacter, this.formatContext)); + }); return changes; } createNewFile(oldFile, fileName, statements) { - this.newFiles.push({ - oldFile: oldFile, - fileName: fileName, - statements: statements - }); + this.insertStatementsInNewFile(fileName, statements, oldFile); } }; ((changesToText2)=>{ @@ -132003,8 +134977,9 @@ ${options.prefix}` : "\n" : options.prefix for(let i = 0; i < normalized.length - 1; i++)Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", ()=>`${JSON.stringify(normalized[i].range)} and ${JSON.stringify(normalized[i + 1].range)}`); const textChanges2 = mapDefined(normalized, (c)=>{ const span = createTextSpanFromRange(c.range); - const newText = computeNewText(c, sourceFile, newLineCharacter, formatContext, validate); - if (span.length === newText.length && stringContainsAt(sourceFile.text, newText, span.start)) return void 0; + const targetSourceFile = c.kind === 1 /* ReplaceWithSingleNode */ ? getSourceFileOfNode(getOriginalNode(c.node)) ?? c.sourceFile : c.kind === 2 /* ReplaceWithMultipleNodes */ ? getSourceFileOfNode(getOriginalNode(c.nodes[0])) ?? c.sourceFile : c.sourceFile; + const newText = computeNewText(c, targetSourceFile, sourceFile, newLineCharacter, formatContext, validate); + if (span.length === newText.length && stringContainsAt(targetSourceFile.text, newText, span.start)) return void 0; return createTextChange(span, newText); }); return textChanges2.length > 0 ? { @@ -132014,8 +134989,8 @@ ${options.prefix}` : "\n" : options.prefix }); } changesToText2.getTextChangesFromChanges = getTextChangesFromChanges; - function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { - const text = newFileChangesWorker(oldFile, getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); + function newFileChanges(fileName, insertions, newLineCharacter, formatContext) { + const text = newFileChangesWorker(getScriptKindFromFileName(fileName), insertions, newLineCharacter, formatContext); return { fileName: fileName, textChanges: [ @@ -132025,28 +135000,28 @@ ${options.prefix}` : "\n" : options.prefix }; } changesToText2.newFileChanges = newFileChanges; - function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { - const nonFormattedText = statements.map((s)=>s === 4 /* NewLineTrivia */ ? "" : getNonformattedText(s, oldFile, newLineCharacter).text).join(newLineCharacter); + function newFileChangesWorker(scriptKind, insertions, newLineCharacter, formatContext) { + const nonFormattedText = flatMap(insertions, (insertion)=>insertion.statements.map((s)=>s === 4 /* NewLineTrivia */ ? "" : getNonformattedText(s, insertion.oldFile, newLineCharacter).text)).join(newLineCharacter); const sourceFile = createSourceFile("any file name", nonFormattedText, 99 /* ESNext */ , /*setParentNodes*/ true, scriptKind); const changes = ts_formatting_exports.formatDocument(sourceFile, formatContext); return applyChanges(nonFormattedText, changes) + newLineCharacter; } changesToText2.newFileChangesWorker = newFileChangesWorker; - function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { - var _a2; + function computeNewText(change, targetSourceFile, sourceFile, newLineCharacter, formatContext, validate) { + var _a; if (change.kind === 0 /* Remove */ ) return ""; if (change.kind === 3 /* Text */ ) return change.text; - const { options: options = {} , range: { pos: pos } } = change; - const format = (n)=>getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); - const text = change.kind === 2 /* ReplaceWithMultipleNodes */ ? change.nodes.map((n)=>removeSuffix(format(n), newLineCharacter)).join(((_a2 = change.options) == null ? void 0 : _a2.joiner) || newLineCharacter) : format(change.node); - const noIndent = options.indentation !== void 0 || getLineStartPositionForPosition(pos, sourceFile) === pos ? text : text.replace(/^\s+/, ""); + const { options: options = {}, range: { pos: pos } } = change; + const format = (n)=>getFormattedTextOfNode(n, targetSourceFile, sourceFile, pos, options, newLineCharacter, formatContext, validate); + const text = change.kind === 2 /* ReplaceWithMultipleNodes */ ? change.nodes.map((n)=>removeSuffix(format(n), newLineCharacter)).join(((_a = change.options) == null ? void 0 : _a.joiner) || newLineCharacter) : format(change.node); + const noIndent = options.indentation !== void 0 || getLineStartPositionForPosition(pos, targetSourceFile) === pos ? text : text.replace(/^\s+/, ""); return (options.prefix || "") + noIndent + (!options.suffix || endsWith(noIndent, options.suffix) ? "" : options.suffix); } - function getFormattedTextOfNode(nodeIn, sourceFile, pos, { indentation: indentation , prefix: prefix , delta: delta }, newLineCharacter, formatContext, validate) { - const { node: node , text: text } = getNonformattedText(nodeIn, sourceFile, newLineCharacter); + function getFormattedTextOfNode(nodeIn, targetSourceFile, sourceFile, pos, { indentation: indentation, prefix: prefix, delta: delta }, newLineCharacter, formatContext, validate) { + const { node: node, text: text } = getNonformattedText(nodeIn, targetSourceFile, newLineCharacter); if (validate) validate(node, text); - const formatOptions = getFormatCodeSettingsForWriting(formatContext, sourceFile); - const initialIndentation = indentation !== void 0 ? indentation : ts_formatting_exports.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || getLineStartPositionForPosition(pos, sourceFile) === pos); + const formatOptions = getFormatCodeSettingsForWriting(formatContext, targetSourceFile); + const initialIndentation = indentation !== void 0 ? indentation : ts_formatting_exports.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || getLineStartPositionForPosition(pos, targetSourceFile) === pos); if (delta === void 0) delta = ts_formatting_exports.SmartIndenter.shouldIndentChildNode(formatOptions, nodeIn) ? formatOptions.indentSize || 0 : 0; const file = { text: text, @@ -132054,7 +135029,7 @@ ${options.prefix}` : "\n" : options.prefix return getLineAndCharacterOfPosition(this, pos2); } }; - const changes = ts_formatting_exports.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, { + const changes = ts_formatting_exports.formatNodeGivenIndentation(node, file, targetSourceFile.languageVariant, initialIndentation, delta, { ...formatContext, options: formatOptions }); @@ -132083,52 +135058,52 @@ ${options.prefix}` : "\n" : options.prefix ((_deleteDeclaration)=>{ function deleteDeclaration2(changes, deletedNodesInLists, sourceFile, node) { switch(node.kind){ - case 166 /* Parameter */ : + case 169 /* Parameter */ : { const oldFunction = node.parent; - if (isArrowFunction(oldFunction) && oldFunction.parameters.length === 1 && !findChildOfKind(oldFunction, 20 /* OpenParenToken */ , sourceFile)) changes.replaceNodeWithText(sourceFile, node, "()"); + if (isArrowFunction(oldFunction) && oldFunction.parameters.length === 1 && !findChildOfKind(oldFunction, 21 /* OpenParenToken */ , sourceFile)) changes.replaceNodeWithText(sourceFile, node, "()"); else deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); break; } - case 269 /* ImportDeclaration */ : - case 268 /* ImportEqualsDeclaration */ : + case 272 /* ImportDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : const isFirstImport = sourceFile.imports.length && node === first(sourceFile.imports).parent || node === find(sourceFile.statements, isAnyImportSyntax); deleteNode(changes, sourceFile, node, { leadingTriviaOption: isFirstImport ? 0 /* Exclude */ : hasJSDocNodes(node) ? 2 /* JSDoc */ : 3 /* StartLine */ }); break; - case 205 /* BindingElement */ : + case 208 /* BindingElement */ : const pattern = node.parent; - const preserveComma = pattern.kind === 204 /* ArrayBindingPattern */ && node !== last(pattern.elements); + const preserveComma = pattern.kind === 207 /* ArrayBindingPattern */ && node !== last(pattern.elements); if (preserveComma) deleteNode(changes, sourceFile, node); else deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); break; - case 257 /* VariableDeclaration */ : + case 260 /* VariableDeclaration */ : deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node); break; - case 165 /* TypeParameter */ : + case 168 /* TypeParameter */ : deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); break; - case 273 /* ImportSpecifier */ : + case 276 /* ImportSpecifier */ : const namedImports = node.parent; if (namedImports.elements.length === 1) deleteImportBinding(changes, sourceFile, namedImports); else deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); break; - case 271 /* NamespaceImport */ : + case 274 /* NamespaceImport */ : deleteImportBinding(changes, sourceFile, node); break; - case 26 /* SemicolonToken */ : + case 27 /* SemicolonToken */ : deleteNode(changes, sourceFile, node, { trailingTriviaOption: 0 /* Exclude */ }); break; - case 98 /* FunctionKeyword */ : + case 100 /* FunctionKeyword */ : deleteNode(changes, sourceFile, node, { leadingTriviaOption: 0 /* Exclude */ }); break; - case 260 /* ClassDeclaration */ : - case 259 /* FunctionDeclaration */ : + case 263 /* ClassDeclaration */ : + case 262 /* FunctionDeclaration */ : deleteNode(changes, sourceFile, node, { leadingTriviaOption: hasJSDocNodes(node) ? 2 /* JSDoc */ : 3 /* StartLine */ }); @@ -132146,8 +135121,8 @@ ${options.prefix}` : "\n" : options.prefix else { const start = importClause.name.getStart(sourceFile); const nextToken = getTokenAtPosition(sourceFile, importClause.name.end); - if (nextToken && nextToken.kind === 27 /* CommaToken */ ) { - const end = skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true); + if (nextToken && nextToken.kind === 28 /* CommaToken */ ) { + const end = skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); changes.deleteRange(sourceFile, { pos: start, end: end @@ -132163,14 +135138,14 @@ ${options.prefix}` : "\n" : options.prefix end: node.end }); } else { - const importDecl = getAncestor(node, 269 /* ImportDeclaration */ ); + const importDecl = getAncestor(node, 272 /* ImportDeclaration */ ); deleteNode(changes, sourceFile, importDecl); } } function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) { - const { parent: parent2 } = node; - if (parent2.kind === 295 /* CatchClause */ ) { - changes.deleteNodeRange(sourceFile, findChildOfKind(parent2, 20 /* OpenParenToken */ , sourceFile), findChildOfKind(parent2, 21 /* CloseParenToken */ , sourceFile)); + const { parent: parent2 } = node; + if (parent2.kind === 299 /* CatchClause */ ) { + changes.deleteNodeRange(sourceFile, findChildOfKind(parent2, 21 /* OpenParenToken */ , sourceFile), findChildOfKind(parent2, 22 /* CloseParenToken */ , sourceFile)); return; } if (parent2.declarations.length !== 1) { @@ -132179,14 +135154,14 @@ ${options.prefix}` : "\n" : options.prefix } const gp = parent2.parent; switch(gp.kind){ - case 247 /* ForOfStatement */ : - case 246 /* ForInStatement */ : + case 250 /* ForOfStatement */ : + case 249 /* ForInStatement */ : changes.replaceNode(sourceFile, node, factory.createObjectLiteralExpression()); break; - case 245 /* ForStatement */ : + case 248 /* ForStatement */ : deleteNode(changes, sourceFile, parent2); break; - case 240 /* VariableStatement */ : + case 243 /* VariableStatement */ : deleteNode(changes, sourceFile, gp, { leadingTriviaOption: hasJSDocNodes(gp) ? 2 /* JSDoc */ : 3 /* StartLine */ }); @@ -132208,7 +135183,6 @@ ${options.prefix}` : "\n" : options.prefix assignPositionsToNode: ()=>assignPositionsToNode, createWriter: ()=>createWriter, deleteNode: ()=>deleteNode, - getNewFileText: ()=>getNewFileText, isThisTypeAnnotatable: ()=>isThisTypeAnnotatable, isValidLocationToAddComment: ()=>isValidLocationToAddComment }); @@ -132281,8 +135255,8 @@ ${options.prefix}` : "\n" : options.prefix return startLine === endLine; } BlockIsOnOneLine(node) { - const openBrace = findChildOfKind(node, 18 /* OpenBraceToken */ , this.sourceFile); - const closeBrace = findChildOfKind(node, 19 /* CloseBraceToken */ , this.sourceFile); + const openBrace = findChildOfKind(node, 19 /* OpenBraceToken */ , this.sourceFile); + const closeBrace = findChildOfKind(node, 20 /* CloseBraceToken */ , this.sourceFile); if (openBrace && closeBrace) { const startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; const endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; @@ -132297,7 +135271,7 @@ ${options.prefix}` : "\n" : options.prefix function getFormattingScanner(text, languageVariant, startPos, endPos, cb) { const scanner2 = languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner; scanner2.setText(text); - scanner2.setTextPos(startPos); + scanner2.resetTokenState(startPos); let wasNewLine = true; let leadingTrivia; let trailingTrivia; @@ -132314,88 +135288,86 @@ ${options.prefix}` : "\n" : options.prefix lastTrailingTriviaWasNewLine: ()=>wasNewLine, skipToEndOf: skipToEndOf, skipToStartOf: skipToStartOf, - getStartPos: ()=>{ - var _a2; - return (_a2 = lastTokenInfo == null ? void 0 : lastTokenInfo.token.pos) != null ? _a2 : scanner2.getTokenPos(); - } + getTokenFullStart: ()=>(lastTokenInfo == null ? void 0 : lastTokenInfo.token.pos) ?? scanner2.getTokenStart(), + getStartPos: ()=>(lastTokenInfo == null ? void 0 : lastTokenInfo.token.pos) ?? scanner2.getTokenStart() }); lastTokenInfo = void 0; scanner2.setText(void 0); return res; function advance() { lastTokenInfo = void 0; - const isStarted = scanner2.getStartPos() !== startPos; + const isStarted = scanner2.getTokenFullStart() !== startPos; if (isStarted) wasNewLine = !!trailingTrivia && last(trailingTrivia).kind === 4 /* NewLineTrivia */ ; else scanner2.scan(); leadingTrivia = void 0; trailingTrivia = void 0; - let pos = scanner2.getStartPos(); + let pos = scanner2.getTokenFullStart(); while(pos < endPos){ const t = scanner2.getToken(); if (!isTrivia(t)) break; scanner2.scan(); const item = { pos: pos, - end: scanner2.getStartPos(), + end: scanner2.getTokenFullStart(), kind: t }; - pos = scanner2.getStartPos(); + pos = scanner2.getTokenFullStart(); leadingTrivia = append(leadingTrivia, item); } - savedPos = scanner2.getStartPos(); + savedPos = scanner2.getTokenFullStart(); } function shouldRescanGreaterThanToken(node) { switch(node.kind){ - case 33 /* GreaterThanEqualsToken */ : - case 71 /* GreaterThanGreaterThanEqualsToken */ : - case 72 /* GreaterThanGreaterThanGreaterThanEqualsToken */ : - case 49 /* GreaterThanGreaterThanGreaterThanToken */ : - case 48 /* GreaterThanGreaterThanToken */ : + case 34 /* GreaterThanEqualsToken */ : + case 72 /* GreaterThanGreaterThanEqualsToken */ : + case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */ : + case 50 /* GreaterThanGreaterThanGreaterThanToken */ : + case 49 /* GreaterThanGreaterThanToken */ : return true; } return false; } function shouldRescanJsxIdentifier(node) { if (node.parent) switch(node.parent.kind){ - case 288 /* JsxAttribute */ : - case 283 /* JsxOpeningElement */ : - case 284 /* JsxClosingElement */ : - case 282 /* JsxSelfClosingElement */ : - return isKeyword(node.kind) || node.kind === 79 /* Identifier */ ; + case 291 /* JsxAttribute */ : + case 286 /* JsxOpeningElement */ : + case 287 /* JsxClosingElement */ : + case 285 /* JsxSelfClosingElement */ : + return isKeyword(node.kind) || node.kind === 80 /* Identifier */ ; } return false; } function shouldRescanJsxText(node) { - return isJsxText(node) || isJsxElement(node) && (lastTokenInfo == null ? void 0 : lastTokenInfo.token.kind) === 11 /* JsxText */ ; + return isJsxText(node) || isJsxElement(node) && (lastTokenInfo == null ? void 0 : lastTokenInfo.token.kind) === 12 /* JsxText */ ; } function shouldRescanSlashToken(container) { - return container.kind === 13 /* RegularExpressionLiteral */ ; + return container.kind === 14 /* RegularExpressionLiteral */ ; } function shouldRescanTemplateToken(container) { - return container.kind === 16 /* TemplateMiddle */ || container.kind === 17 /* TemplateTail */ ; + return container.kind === 17 /* TemplateMiddle */ || container.kind === 18 /* TemplateTail */ ; } function shouldRescanJsxAttributeValue(node) { return node.parent && isJsxAttribute(node.parent) && node.parent.initializer === node; } function startsWithSlashToken(t) { - return t === 43 /* SlashToken */ || t === 68 /* SlashEqualsToken */ ; + return t === 44 /* SlashToken */ || t === 69 /* SlashEqualsToken */ ; } function readTokenInfo(n) { Debug.assert(isOnToken()); const expectedScanAction = shouldRescanGreaterThanToken(n) ? 1 /* RescanGreaterThanToken */ : shouldRescanSlashToken(n) ? 2 /* RescanSlashToken */ : shouldRescanTemplateToken(n) ? 3 /* RescanTemplateToken */ : shouldRescanJsxIdentifier(n) ? 4 /* RescanJsxIdentifier */ : shouldRescanJsxText(n) ? 5 /* RescanJsxText */ : shouldRescanJsxAttributeValue(n) ? 6 /* RescanJsxAttributeValue */ : 0 /* Scan */ ; if (lastTokenInfo && expectedScanAction === lastScanAction) return fixTokenKind(lastTokenInfo, n); - if (scanner2.getStartPos() !== savedPos) { + if (scanner2.getTokenFullStart() !== savedPos) { Debug.assert(lastTokenInfo !== void 0); - scanner2.setTextPos(savedPos); + scanner2.resetTokenState(savedPos); scanner2.scan(); } let currentToken = getNextToken(n, expectedScanAction); - const token = createTextRangeWithKind(scanner2.getStartPos(), scanner2.getTextPos(), currentToken); + const token = createTextRangeWithKind(scanner2.getTokenFullStart(), scanner2.getTokenEnd(), currentToken); if (trailingTrivia) trailingTrivia = void 0; - while(scanner2.getStartPos() < endPos){ + while(scanner2.getTokenFullStart() < endPos){ currentToken = scanner2.scan(); if (!isTrivia(currentToken)) break; - const trivia = createTextRangeWithKind(scanner2.getStartPos(), scanner2.getTextPos(), currentToken); + const trivia = createTextRangeWithKind(scanner2.getTokenFullStart(), scanner2.getTokenEnd(), currentToken); if (!trailingTrivia) trailingTrivia = []; trailingTrivia.push(trivia); if (currentToken === 4 /* NewLineTrivia */ ) { @@ -132415,7 +135387,7 @@ ${options.prefix}` : "\n" : options.prefix lastScanAction = 0 /* Scan */ ; switch(expectedScanAction){ case 1 /* RescanGreaterThanToken */ : - if (token === 31 /* GreaterThanToken */ ) { + if (token === 32 /* GreaterThanToken */ ) { lastScanAction = 1 /* RescanGreaterThanToken */ ; const newToken = scanner2.reScanGreaterToken(); Debug.assert(n.kind === newToken); @@ -132431,9 +135403,9 @@ ${options.prefix}` : "\n" : options.prefix } break; case 3 /* RescanTemplateToken */ : - if (token === 19 /* CloseBraceToken */ ) { + if (token === 20 /* CloseBraceToken */ ) { lastScanAction = 3 /* RescanTemplateToken */ ; - return scanner2.reScanTemplateToken(/* isTaggedTemplate */ false); + return scanner2.reScanTemplateToken(/*isTaggedTemplate*/ false); } break; case 4 /* RescanJsxIdentifier */ : @@ -132441,7 +135413,7 @@ ${options.prefix}` : "\n" : options.prefix return scanner2.scanJsxIdentifier(); case 5 /* RescanJsxText */ : lastScanAction = 5 /* RescanJsxText */ ; - return scanner2.reScanJsxToken(/* allowMultilineJsxText */ false); + return scanner2.reScanJsxToken(/*allowMultilineJsxText*/ false); case 6 /* RescanJsxAttributeValue */ : lastScanAction = 6 /* RescanJsxAttributeValue */ ; return scanner2.reScanJsxAttributeValue(); @@ -132454,7 +135426,7 @@ ${options.prefix}` : "\n" : options.prefix } function readEOFTokenRange() { Debug.assert(isOnEOF()); - return createTextRangeWithKind(scanner2.getStartPos(), scanner2.getTextPos(), 1 /* EndOfFileToken */ ); + return createTextRangeWithKind(scanner2.getTokenFullStart(), scanner2.getTokenEnd(), 1 /* EndOfFileToken */ ); } function isOnToken() { const current = lastTokenInfo ? lastTokenInfo.token.kind : scanner2.getToken(); @@ -132469,8 +135441,8 @@ ${options.prefix}` : "\n" : options.prefix return tokenInfo; } function skipToEndOf(node) { - scanner2.setTextPos(node.end); - savedPos = scanner2.getStartPos(); + scanner2.resetTokenState(node.end); + savedPos = scanner2.getTokenFullStart(); lastScanAction = void 0; lastTokenInfo = void 0; wasNewLine = false; @@ -132478,8 +135450,8 @@ ${options.prefix}` : "\n" : options.prefix trailingTrivia = void 0; } function skipToStartOf(node) { - scanner2.setTextPos(node.pos); - savedPos = scanner2.getStartPos(); + scanner2.resetTokenState(node.pos); + savedPos = scanner2.getTokenFullStart(); lastScanAction = void 0; lastTokenInfo = void 0; wasNewLine = false; @@ -132528,7 +135500,7 @@ ${options.prefix}` : "\n" : options.prefix // src/services/formatting/rules.ts function getAllRules() { const allTokens = []; - for(let token = 0 /* FirstToken */ ; token <= 162 /* LastToken */ ; token++)if (token !== 1 /* EndOfFileToken */ ) allTokens.push(token); + for(let token = 0 /* FirstToken */ ; token <= 165 /* LastToken */ ; token++)if (token !== 1 /* EndOfFileToken */ ) allTokens.push(token); function anyTokenExcept(...tokens) { return { tokens: allTokens.filter((t)=>!tokens.some((t2)=>t2 === t)), @@ -132547,121 +135519,121 @@ ${options.prefix}` : "\n" : options.prefix ...allTokens, 1 /* EndOfFileToken */ ]); - const keywords = tokenRangeFromRange(81 /* FirstKeyword */ , 162 /* LastKeyword */ ); - const binaryOperators = tokenRangeFromRange(29 /* FirstBinaryOperator */ , 78 /* LastBinaryOperator */ ); + const keywords = tokenRangeFromRange(83 /* FirstKeyword */ , 165 /* LastKeyword */ ); + const binaryOperators = tokenRangeFromRange(30 /* FirstBinaryOperator */ , 79 /* LastBinaryOperator */ ); const binaryKeywordOperators = [ - 101 /* InKeyword */ , - 102 /* InstanceOfKeyword */ , - 162 /* OfKeyword */ , - 128 /* AsKeyword */ , - 140 /* IsKeyword */ , - 150 /* SatisfiesKeyword */ + 103 /* InKeyword */ , + 104 /* InstanceOfKeyword */ , + 165 /* OfKeyword */ , + 130 /* AsKeyword */ , + 142 /* IsKeyword */ , + 152 /* SatisfiesKeyword */ ]; const unaryPrefixOperators = [ - 45 /* PlusPlusToken */ , - 46 /* MinusMinusToken */ , - 54 /* TildeToken */ , - 53 /* ExclamationToken */ + 46 /* PlusPlusToken */ , + 47 /* MinusMinusToken */ , + 55 /* TildeToken */ , + 54 /* ExclamationToken */ ]; const unaryPrefixExpressions = [ - 8 /* NumericLiteral */ , - 9 /* BigIntLiteral */ , - 79 /* Identifier */ , - 20 /* OpenParenToken */ , - 22 /* OpenBracketToken */ , - 18 /* OpenBraceToken */ , - 108 /* ThisKeyword */ , - 103 /* NewKeyword */ + 9 /* NumericLiteral */ , + 10 /* BigIntLiteral */ , + 80 /* Identifier */ , + 21 /* OpenParenToken */ , + 23 /* OpenBracketToken */ , + 19 /* OpenBraceToken */ , + 110 /* ThisKeyword */ , + 105 /* NewKeyword */ ]; const unaryPreincrementExpressions = [ - 79 /* Identifier */ , - 20 /* OpenParenToken */ , - 108 /* ThisKeyword */ , - 103 /* NewKeyword */ + 80 /* Identifier */ , + 21 /* OpenParenToken */ , + 110 /* ThisKeyword */ , + 105 /* NewKeyword */ ]; const unaryPostincrementExpressions = [ - 79 /* Identifier */ , - 21 /* CloseParenToken */ , - 23 /* CloseBracketToken */ , - 103 /* NewKeyword */ + 80 /* Identifier */ , + 22 /* CloseParenToken */ , + 24 /* CloseBracketToken */ , + 105 /* NewKeyword */ ]; const unaryPredecrementExpressions = [ - 79 /* Identifier */ , - 20 /* OpenParenToken */ , - 108 /* ThisKeyword */ , - 103 /* NewKeyword */ + 80 /* Identifier */ , + 21 /* OpenParenToken */ , + 110 /* ThisKeyword */ , + 105 /* NewKeyword */ ]; const unaryPostdecrementExpressions = [ - 79 /* Identifier */ , - 21 /* CloseParenToken */ , - 23 /* CloseBracketToken */ , - 103 /* NewKeyword */ + 80 /* Identifier */ , + 22 /* CloseParenToken */ , + 24 /* CloseBracketToken */ , + 105 /* NewKeyword */ ]; const comments = [ 2 /* SingleLineCommentTrivia */ , 3 /* MultiLineCommentTrivia */ ]; const typeNames = [ - 79 /* Identifier */ , + 80 /* Identifier */ , ...typeKeywords ]; const functionOpenBraceLeftTokenRange = anyTokenIncludingMultilineComments; const typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([ - 79 /* Identifier */ , + 80 /* Identifier */ , 3 /* MultiLineCommentTrivia */ , - 84 /* ClassKeyword */ , - 93 /* ExportKeyword */ , - 100 /* ImportKeyword */ + 86 /* ClassKeyword */ , + 95 /* ExportKeyword */ , + 102 /* ImportKeyword */ ]); const controlOpenBraceLeftTokenRange = tokenRangeFrom([ - 21 /* CloseParenToken */ , + 22 /* CloseParenToken */ , 3 /* MultiLineCommentTrivia */ , - 90 /* DoKeyword */ , - 111 /* TryKeyword */ , - 96 /* FinallyKeyword */ , - 91 /* ElseKeyword */ + 92 /* DoKeyword */ , + 113 /* TryKeyword */ , + 98 /* FinallyKeyword */ , + 93 /* ElseKeyword */ ]); const highPriorityCommonRules = [ // Leave comments alone rule("IgnoreBeforeComment", anyToken, comments, anyContext, 1 /* StopProcessingSpaceActions */ ), rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */ , anyToken, anyContext, 1 /* StopProcessingSpaceActions */ ), - rule("NotSpaceBeforeColon", anyToken, 58 /* ColonToken */ , [ + rule("NotSpaceBeforeColon", anyToken, 59 /* ColonToken */ , [ isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext ], 16 /* DeleteSpace */ ), - rule("SpaceAfterColon", 58 /* ColonToken */ , anyToken, [ + rule("SpaceAfterColon", 59 /* ColonToken */ , anyToken, [ isNonJsxSameLineTokenContext, isNotBinaryOpContext ], 4 /* InsertSpace */ ), - rule("NoSpaceBeforeQuestionMark", anyToken, 57 /* QuestionToken */ , [ + rule("NoSpaceBeforeQuestionMark", anyToken, 58 /* QuestionToken */ , [ isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext ], 16 /* DeleteSpace */ ), // insert space after '?' only when it is used in conditional operator - rule("SpaceAfterQuestionMarkInConditionalOperator", 57 /* QuestionToken */ , anyToken, [ + rule("SpaceAfterQuestionMarkInConditionalOperator", 58 /* QuestionToken */ , anyToken, [ isNonJsxSameLineTokenContext, isConditionalOperatorContext ], 4 /* InsertSpace */ ), // in other cases there should be no space between '?' and next token - rule("NoSpaceAfterQuestionMark", 57 /* QuestionToken */ , anyToken, [ + rule("NoSpaceAfterQuestionMark", 58 /* QuestionToken */ , anyToken, [ isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), rule("NoSpaceBeforeDot", anyToken, [ - 24 /* DotToken */ , - 28 /* QuestionDotToken */ + 25 /* DotToken */ , + 29 /* QuestionDotToken */ ], [ isNonJsxSameLineTokenContext, isNotPropertyAccessOnIntegerLiteral ], 16 /* DeleteSpace */ ), rule("NoSpaceAfterDot", [ - 24 /* DotToken */ , - 28 /* QuestionDotToken */ + 25 /* DotToken */ , + 29 /* QuestionDotToken */ ], anyToken, [ isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), - rule("NoSpaceBetweenImportParenInImportType", 100 /* ImportKeyword */ , 20 /* OpenParenToken */ , [ + rule("NoSpaceBetweenImportParenInImportType", 102 /* ImportKeyword */ , 21 /* OpenParenToken */ , [ isNonJsxSameLineTokenContext, isImportTypeContext ], 16 /* DeleteSpace */ ), @@ -132672,17 +135644,17 @@ ${options.prefix}` : "\n" : options.prefix isNonJsxSameLineTokenContext, isNotBinaryOpContext ], 16 /* DeleteSpace */ ), - rule("NoSpaceAfterUnaryPreincrementOperator", 45 /* PlusPlusToken */ , unaryPreincrementExpressions, [ + rule("NoSpaceAfterUnaryPreincrementOperator", 46 /* PlusPlusToken */ , unaryPreincrementExpressions, [ isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), - rule("NoSpaceAfterUnaryPredecrementOperator", 46 /* MinusMinusToken */ , unaryPredecrementExpressions, [ + rule("NoSpaceAfterUnaryPredecrementOperator", 47 /* MinusMinusToken */ , unaryPredecrementExpressions, [ isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), - rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 45 /* PlusPlusToken */ , [ + rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 46 /* PlusPlusToken */ , [ isNonJsxSameLineTokenContext, isNotStatementConditionContext ], 16 /* DeleteSpace */ ), - rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 46 /* MinusMinusToken */ , [ + rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 47 /* MinusMinusToken */ , [ isNonJsxSameLineTokenContext, isNotStatementConditionContext ], 16 /* DeleteSpace */ ), @@ -132691,72 +135663,72 @@ ${options.prefix}` : "\n" : options.prefix // around unary operators. Examples: // 1 - -2 --X--> 1--2 // a + ++b --X--> a+++b - rule("SpaceAfterPostincrementWhenFollowedByAdd", 45 /* PlusPlusToken */ , 39 /* PlusToken */ , [ + rule("SpaceAfterPostincrementWhenFollowedByAdd", 46 /* PlusPlusToken */ , 40 /* PlusToken */ , [ isNonJsxSameLineTokenContext, isBinaryOpContext ], 4 /* InsertSpace */ ), - rule("SpaceAfterAddWhenFollowedByUnaryPlus", 39 /* PlusToken */ , 39 /* PlusToken */ , [ + rule("SpaceAfterAddWhenFollowedByUnaryPlus", 40 /* PlusToken */ , 40 /* PlusToken */ , [ isNonJsxSameLineTokenContext, isBinaryOpContext ], 4 /* InsertSpace */ ), - rule("SpaceAfterAddWhenFollowedByPreincrement", 39 /* PlusToken */ , 45 /* PlusPlusToken */ , [ + rule("SpaceAfterAddWhenFollowedByPreincrement", 40 /* PlusToken */ , 46 /* PlusPlusToken */ , [ isNonJsxSameLineTokenContext, isBinaryOpContext ], 4 /* InsertSpace */ ), - rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 46 /* MinusMinusToken */ , 40 /* MinusToken */ , [ + rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 47 /* MinusMinusToken */ , 41 /* MinusToken */ , [ isNonJsxSameLineTokenContext, isBinaryOpContext ], 4 /* InsertSpace */ ), - rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 40 /* MinusToken */ , 40 /* MinusToken */ , [ + rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 41 /* MinusToken */ , 41 /* MinusToken */ , [ isNonJsxSameLineTokenContext, isBinaryOpContext ], 4 /* InsertSpace */ ), - rule("SpaceAfterSubtractWhenFollowedByPredecrement", 40 /* MinusToken */ , 46 /* MinusMinusToken */ , [ + rule("SpaceAfterSubtractWhenFollowedByPredecrement", 41 /* MinusToken */ , 47 /* MinusMinusToken */ , [ isNonJsxSameLineTokenContext, isBinaryOpContext ], 4 /* InsertSpace */ ), - rule("NoSpaceAfterCloseBrace", 19 /* CloseBraceToken */ , [ - 27 /* CommaToken */ , - 26 /* SemicolonToken */ + rule("NoSpaceAfterCloseBrace", 20 /* CloseBraceToken */ , [ + 28 /* CommaToken */ , + 27 /* SemicolonToken */ ], [ isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), // For functions and control block place } on a new line [multi-line rule] - rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 19 /* CloseBraceToken */ , [ + rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 20 /* CloseBraceToken */ , [ isMultilineBlockContext ], 8 /* InsertNewLine */ ), // Space/new line after }. - rule("SpaceAfterCloseBrace", 19 /* CloseBraceToken */ , anyTokenExcept(21 /* CloseParenToken */ ), [ + rule("SpaceAfterCloseBrace", 20 /* CloseBraceToken */ , anyTokenExcept(22 /* CloseParenToken */ ), [ isNonJsxSameLineTokenContext, isAfterCodeBlockContext ], 4 /* InsertSpace */ ), // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied // Also should not apply to }) - rule("SpaceBetweenCloseBraceAndElse", 19 /* CloseBraceToken */ , 91 /* ElseKeyword */ , [ + rule("SpaceBetweenCloseBraceAndElse", 20 /* CloseBraceToken */ , 93 /* ElseKeyword */ , [ isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ), - rule("SpaceBetweenCloseBraceAndWhile", 19 /* CloseBraceToken */ , 115 /* WhileKeyword */ , [ + rule("SpaceBetweenCloseBraceAndWhile", 20 /* CloseBraceToken */ , 117 /* WhileKeyword */ , [ isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ), - rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */ , 19 /* CloseBraceToken */ , [ + rule("NoSpaceBetweenEmptyBraceBrackets", 19 /* OpenBraceToken */ , 20 /* CloseBraceToken */ , [ isNonJsxSameLineTokenContext, isObjectContext ], 16 /* DeleteSpace */ ), // Add a space after control dec context if the next character is an open bracket ex: 'if (false)[a, b] = [1, 2];' -> 'if (false) [a, b] = [1, 2];' - rule("SpaceAfterConditionalClosingParen", 21 /* CloseParenToken */ , 22 /* OpenBracketToken */ , [ + rule("SpaceAfterConditionalClosingParen", 22 /* CloseParenToken */ , 23 /* OpenBracketToken */ , [ isControlDeclContext ], 4 /* InsertSpace */ ), - rule("NoSpaceBetweenFunctionKeywordAndStar", 98 /* FunctionKeyword */ , 41 /* AsteriskToken */ , [ + rule("NoSpaceBetweenFunctionKeywordAndStar", 100 /* FunctionKeyword */ , 42 /* AsteriskToken */ , [ isFunctionDeclarationOrFunctionExpressionContext ], 16 /* DeleteSpace */ ), - rule("SpaceAfterStarInGeneratorDeclaration", 41 /* AsteriskToken */ , 79 /* Identifier */ , [ + rule("SpaceAfterStarInGeneratorDeclaration", 42 /* AsteriskToken */ , 80 /* Identifier */ , [ isFunctionDeclarationOrFunctionExpressionContext ], 4 /* InsertSpace */ ), - rule("SpaceAfterFunctionInFuncDecl", 98 /* FunctionKeyword */ , anyToken, [ + rule("SpaceAfterFunctionInFuncDecl", 100 /* FunctionKeyword */ , anyToken, [ isFunctionDeclContext ], 4 /* InsertSpace */ ), // Insert new line after { and before } in multi-line contexts. - rule("NewLineAfterOpenBraceInBlockContext", 18 /* OpenBraceToken */ , anyToken, [ + rule("NewLineAfterOpenBraceInBlockContext", 19 /* OpenBraceToken */ , anyToken, [ isMultilineBlockContext ], 8 /* InsertNewLine */ ), // For get/set members, we check for (identifier,identifier) since get/set don't have tokens and they are represented as just an identifier token. @@ -132764,44 +135736,44 @@ ${options.prefix}` : "\n" : options.prefix // get x() {} // set x(val) {} rule("SpaceAfterGetSetInMember", [ - 137 /* GetKeyword */ , - 151 /* SetKeyword */ - ], 79 /* Identifier */ , [ + 139 /* GetKeyword */ , + 153 /* SetKeyword */ + ], 80 /* Identifier */ , [ isFunctionDeclContext ], 4 /* InsertSpace */ ), - rule("NoSpaceBetweenYieldKeywordAndStar", 125 /* YieldKeyword */ , 41 /* AsteriskToken */ , [ + rule("NoSpaceBetweenYieldKeywordAndStar", 127 /* YieldKeyword */ , 42 /* AsteriskToken */ , [ isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand ], 16 /* DeleteSpace */ ), rule("SpaceBetweenYieldOrYieldStarAndOperand", [ - 125 /* YieldKeyword */ , - 41 /* AsteriskToken */ + 127 /* YieldKeyword */ , + 42 /* AsteriskToken */ ], anyToken, [ isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand ], 4 /* InsertSpace */ ), - rule("NoSpaceBetweenReturnAndSemicolon", 105 /* ReturnKeyword */ , 26 /* SemicolonToken */ , [ + rule("NoSpaceBetweenReturnAndSemicolon", 107 /* ReturnKeyword */ , 27 /* SemicolonToken */ , [ isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), rule("SpaceAfterCertainKeywords", [ - 113 /* VarKeyword */ , - 109 /* ThrowKeyword */ , - 103 /* NewKeyword */ , - 89 /* DeleteKeyword */ , - 105 /* ReturnKeyword */ , - 112 /* TypeOfKeyword */ , - 133 /* AwaitKeyword */ + 115 /* VarKeyword */ , + 111 /* ThrowKeyword */ , + 105 /* NewKeyword */ , + 91 /* DeleteKeyword */ , + 107 /* ReturnKeyword */ , + 114 /* TypeOfKeyword */ , + 135 /* AwaitKeyword */ ], anyToken, [ isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ), rule("SpaceAfterLetConstInVariableDeclaration", [ - 119 /* LetKeyword */ , - 85 /* ConstKeyword */ + 121 /* LetKeyword */ , + 87 /* ConstKeyword */ ], anyToken, [ isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList ], 4 /* InsertSpace */ ), - rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 20 /* OpenParenToken */ , [ + rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 21 /* OpenParenToken */ , [ isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma @@ -132815,145 +135787,145 @@ ${options.prefix}` : "\n" : options.prefix isNonJsxSameLineTokenContext, isBinaryOpContext ], 4 /* InsertSpace */ ), - rule("SpaceAfterVoidOperator", 114 /* VoidKeyword */ , anyToken, [ + rule("SpaceAfterVoidOperator", 116 /* VoidKeyword */ , anyToken, [ isNonJsxSameLineTokenContext, isVoidOpContext ], 4 /* InsertSpace */ ), // Async-await - rule("SpaceBetweenAsyncAndOpenParen", 132 /* AsyncKeyword */ , 20 /* OpenParenToken */ , [ + rule("SpaceBetweenAsyncAndOpenParen", 134 /* AsyncKeyword */ , 21 /* OpenParenToken */ , [ isArrowFunctionContext, isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ), - rule("SpaceBetweenAsyncAndFunctionKeyword", 132 /* AsyncKeyword */ , [ - 98 /* FunctionKeyword */ , - 79 /* Identifier */ + rule("SpaceBetweenAsyncAndFunctionKeyword", 134 /* AsyncKeyword */ , [ + 100 /* FunctionKeyword */ , + 80 /* Identifier */ ], [ isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ), // Template string rule("NoSpaceBetweenTagAndTemplateString", [ - 79 /* Identifier */ , - 21 /* CloseParenToken */ + 80 /* Identifier */ , + 22 /* CloseParenToken */ ], [ - 14 /* NoSubstitutionTemplateLiteral */ , - 15 /* TemplateHead */ + 15 /* NoSubstitutionTemplateLiteral */ , + 16 /* TemplateHead */ ], [ isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), // JSX opening elements - rule("SpaceBeforeJsxAttribute", anyToken, 79 /* Identifier */ , [ + rule("SpaceBeforeJsxAttribute", anyToken, 80 /* Identifier */ , [ isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ), - rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 43 /* SlashToken */ , [ + rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 44 /* SlashToken */ , [ isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ), - rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 43 /* SlashToken */ , 31 /* GreaterThanToken */ , [ + rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 44 /* SlashToken */ , 32 /* GreaterThanToken */ , [ isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), - rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 63 /* EqualsToken */ , [ + rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 64 /* EqualsToken */ , [ isJsxAttributeContext, isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), - rule("NoSpaceAfterEqualInJsxAttribute", 63 /* EqualsToken */ , anyToken, [ + rule("NoSpaceAfterEqualInJsxAttribute", 64 /* EqualsToken */ , anyToken, [ isJsxAttributeContext, isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), // TypeScript-specific rules // Use of module as a function call. e.g.: import m2 = module("m2"); rule("NoSpaceAfterModuleImport", [ - 142 /* ModuleKeyword */ , - 147 /* RequireKeyword */ - ], 20 /* OpenParenToken */ , [ + 144 /* ModuleKeyword */ , + 149 /* RequireKeyword */ + ], 21 /* OpenParenToken */ , [ isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), // Add a space around certain TypeScript keywords rule("SpaceAfterCertainTypeScriptKeywords", [ - 126 /* AbstractKeyword */ , - 127 /* AccessorKeyword */ , - 84 /* ClassKeyword */ , - 136 /* DeclareKeyword */ , - 88 /* DefaultKeyword */ , - 92 /* EnumKeyword */ , - 93 /* ExportKeyword */ , - 94 /* ExtendsKeyword */ , - 137 /* GetKeyword */ , - 117 /* ImplementsKeyword */ , - 100 /* ImportKeyword */ , - 118 /* InterfaceKeyword */ , - 142 /* ModuleKeyword */ , - 143 /* NamespaceKeyword */ , - 121 /* PrivateKeyword */ , - 123 /* PublicKeyword */ , - 122 /* ProtectedKeyword */ , - 146 /* ReadonlyKeyword */ , - 151 /* SetKeyword */ , - 124 /* StaticKeyword */ , - 154 /* TypeKeyword */ , - 158 /* FromKeyword */ , - 141 /* KeyOfKeyword */ , - 138 /* InferKeyword */ + 128 /* AbstractKeyword */ , + 129 /* AccessorKeyword */ , + 86 /* ClassKeyword */ , + 138 /* DeclareKeyword */ , + 90 /* DefaultKeyword */ , + 94 /* EnumKeyword */ , + 95 /* ExportKeyword */ , + 96 /* ExtendsKeyword */ , + 139 /* GetKeyword */ , + 119 /* ImplementsKeyword */ , + 102 /* ImportKeyword */ , + 120 /* InterfaceKeyword */ , + 144 /* ModuleKeyword */ , + 145 /* NamespaceKeyword */ , + 123 /* PrivateKeyword */ , + 125 /* PublicKeyword */ , + 124 /* ProtectedKeyword */ , + 148 /* ReadonlyKeyword */ , + 153 /* SetKeyword */ , + 126 /* StaticKeyword */ , + 156 /* TypeKeyword */ , + 161 /* FromKeyword */ , + 143 /* KeyOfKeyword */ , + 140 /* InferKeyword */ ], anyToken, [ isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ), rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [ - 94 /* ExtendsKeyword */ , - 117 /* ImplementsKeyword */ , - 158 /* FromKeyword */ + 96 /* ExtendsKeyword */ , + 119 /* ImplementsKeyword */ , + 161 /* FromKeyword */ ], [ isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ), // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { - rule("SpaceAfterModuleName", 10 /* StringLiteral */ , 18 /* OpenBraceToken */ , [ + rule("SpaceAfterModuleName", 11 /* StringLiteral */ , 19 /* OpenBraceToken */ , [ isModuleDeclContext ], 4 /* InsertSpace */ ), // Lambda expressions - rule("SpaceBeforeArrow", anyToken, 38 /* EqualsGreaterThanToken */ , [ + rule("SpaceBeforeArrow", anyToken, 39 /* EqualsGreaterThanToken */ , [ isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ), - rule("SpaceAfterArrow", 38 /* EqualsGreaterThanToken */ , anyToken, [ + rule("SpaceAfterArrow", 39 /* EqualsGreaterThanToken */ , anyToken, [ isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ), // Optional parameters and let args - rule("NoSpaceAfterEllipsis", 25 /* DotDotDotToken */ , 79 /* Identifier */ , [ + rule("NoSpaceAfterEllipsis", 26 /* DotDotDotToken */ , 80 /* Identifier */ , [ isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), - rule("NoSpaceAfterOptionalParameters", 57 /* QuestionToken */ , [ - 21 /* CloseParenToken */ , - 27 /* CommaToken */ + rule("NoSpaceAfterOptionalParameters", 58 /* QuestionToken */ , [ + 22 /* CloseParenToken */ , + 28 /* CommaToken */ ], [ isNonJsxSameLineTokenContext, isNotBinaryOpContext ], 16 /* DeleteSpace */ ), // Remove spaces in empty interface literals. e.g.: x: {} - rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 18 /* OpenBraceToken */ , 19 /* CloseBraceToken */ , [ + rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 19 /* OpenBraceToken */ , 20 /* CloseBraceToken */ , [ isNonJsxSameLineTokenContext, isObjectTypeContext ], 16 /* DeleteSpace */ ), // generics and type assertions - rule("NoSpaceBeforeOpenAngularBracket", typeNames, 29 /* LessThanToken */ , [ + rule("NoSpaceBeforeOpenAngularBracket", typeNames, 30 /* LessThanToken */ , [ isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext ], 16 /* DeleteSpace */ ), - rule("NoSpaceBetweenCloseParenAndAngularBracket", 21 /* CloseParenToken */ , 29 /* LessThanToken */ , [ + rule("NoSpaceBetweenCloseParenAndAngularBracket", 22 /* CloseParenToken */ , 30 /* LessThanToken */ , [ isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext ], 16 /* DeleteSpace */ ), - rule("NoSpaceAfterOpenAngularBracket", 29 /* LessThanToken */ , anyToken, [ + rule("NoSpaceAfterOpenAngularBracket", 30 /* LessThanToken */ , anyToken, [ isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext ], 16 /* DeleteSpace */ ), - rule("NoSpaceBeforeCloseAngularBracket", anyToken, 31 /* GreaterThanToken */ , [ + rule("NoSpaceBeforeCloseAngularBracket", anyToken, 32 /* GreaterThanToken */ , [ isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext ], 16 /* DeleteSpace */ ), - rule("NoSpaceAfterCloseAngularBracket", 31 /* GreaterThanToken */ , [ - 20 /* OpenParenToken */ , - 22 /* OpenBracketToken */ , - 31 /* GreaterThanToken */ , - 27 /* CommaToken */ + rule("NoSpaceAfterCloseAngularBracket", 32 /* GreaterThanToken */ , [ + 21 /* OpenParenToken */ , + 23 /* OpenBracketToken */ , + 32 /* GreaterThanToken */ , + 28 /* CommaToken */ ], [ isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext, @@ -132962,220 +135934,220 @@ ${options.prefix}` : "\n" : options.prefix ], 16 /* DeleteSpace */ ), // decorators rule("SpaceBeforeAt", [ - 21 /* CloseParenToken */ , - 79 /* Identifier */ - ], 59 /* AtToken */ , [ + 22 /* CloseParenToken */ , + 80 /* Identifier */ + ], 60 /* AtToken */ , [ isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ), - rule("NoSpaceAfterAt", 59 /* AtToken */ , anyToken, [ + rule("NoSpaceAfterAt", 60 /* AtToken */ , anyToken, [ isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), // Insert space after @ in decorator rule("SpaceAfterDecorator", anyToken, [ - 126 /* AbstractKeyword */ , - 79 /* Identifier */ , - 93 /* ExportKeyword */ , - 88 /* DefaultKeyword */ , - 84 /* ClassKeyword */ , - 124 /* StaticKeyword */ , - 123 /* PublicKeyword */ , - 121 /* PrivateKeyword */ , - 122 /* ProtectedKeyword */ , - 137 /* GetKeyword */ , - 151 /* SetKeyword */ , - 22 /* OpenBracketToken */ , - 41 /* AsteriskToken */ + 128 /* AbstractKeyword */ , + 80 /* Identifier */ , + 95 /* ExportKeyword */ , + 90 /* DefaultKeyword */ , + 86 /* ClassKeyword */ , + 126 /* StaticKeyword */ , + 125 /* PublicKeyword */ , + 123 /* PrivateKeyword */ , + 124 /* ProtectedKeyword */ , + 139 /* GetKeyword */ , + 153 /* SetKeyword */ , + 23 /* OpenBracketToken */ , + 42 /* AsteriskToken */ ], [ isEndOfDecoratorContextOnSameLine ], 4 /* InsertSpace */ ), - rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 53 /* ExclamationToken */ , [ + rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 54 /* ExclamationToken */ , [ isNonJsxSameLineTokenContext, isNonNullAssertionContext ], 16 /* DeleteSpace */ ), - rule("NoSpaceAfterNewKeywordOnConstructorSignature", 103 /* NewKeyword */ , 20 /* OpenParenToken */ , [ + rule("NoSpaceAfterNewKeywordOnConstructorSignature", 105 /* NewKeyword */ , 21 /* OpenParenToken */ , [ isNonJsxSameLineTokenContext, isConstructorSignatureContext ], 16 /* DeleteSpace */ ), - rule("SpaceLessThanAndNonJSXTypeAnnotation", 29 /* LessThanToken */ , 29 /* LessThanToken */ , [ + rule("SpaceLessThanAndNonJSXTypeAnnotation", 30 /* LessThanToken */ , 30 /* LessThanToken */ , [ isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ) ]; const userConfigurableRules = [ // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses - rule("SpaceAfterConstructor", 135 /* ConstructorKeyword */ , 20 /* OpenParenToken */ , [ + rule("SpaceAfterConstructor", 137 /* ConstructorKeyword */ , 21 /* OpenParenToken */ , [ isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ), - rule("NoSpaceAfterConstructor", 135 /* ConstructorKeyword */ , 20 /* OpenParenToken */ , [ + rule("NoSpaceAfterConstructor", 137 /* ConstructorKeyword */ , 21 /* OpenParenToken */ , [ isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), - rule("SpaceAfterComma", 27 /* CommaToken */ , anyToken, [ + rule("SpaceAfterComma", 28 /* CommaToken */ , anyToken, [ isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket, isNextTokenNotCloseParen ], 4 /* InsertSpace */ ), - rule("NoSpaceAfterComma", 27 /* CommaToken */ , anyToken, [ + rule("NoSpaceAfterComma", 28 /* CommaToken */ , anyToken, [ isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext ], 16 /* DeleteSpace */ ), // Insert space after function keyword for anonymous functions rule("SpaceAfterAnonymousFunctionKeyword", [ - 98 /* FunctionKeyword */ , - 41 /* AsteriskToken */ - ], 20 /* OpenParenToken */ , [ + 100 /* FunctionKeyword */ , + 42 /* AsteriskToken */ + ], 21 /* OpenParenToken */ , [ isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext ], 4 /* InsertSpace */ ), rule("NoSpaceAfterAnonymousFunctionKeyword", [ - 98 /* FunctionKeyword */ , - 41 /* AsteriskToken */ - ], 20 /* OpenParenToken */ , [ + 100 /* FunctionKeyword */ , + 42 /* AsteriskToken */ + ], 21 /* OpenParenToken */ , [ isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext ], 16 /* DeleteSpace */ ), // Insert space after keywords in control flow statements - rule("SpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */ , [ + rule("SpaceAfterKeywordInControl", keywords, 21 /* OpenParenToken */ , [ isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext ], 4 /* InsertSpace */ ), - rule("NoSpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */ , [ + rule("NoSpaceAfterKeywordInControl", keywords, 21 /* OpenParenToken */ , [ isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext ], 16 /* DeleteSpace */ ), // Insert space after opening and before closing nonempty parenthesis - rule("SpaceAfterOpenParen", 20 /* OpenParenToken */ , anyToken, [ + rule("SpaceAfterOpenParen", 21 /* OpenParenToken */ , anyToken, [ isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ), - rule("SpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */ , [ + rule("SpaceBeforeCloseParen", anyToken, 22 /* CloseParenToken */ , [ isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ), - rule("SpaceBetweenOpenParens", 20 /* OpenParenToken */ , 20 /* OpenParenToken */ , [ + rule("SpaceBetweenOpenParens", 21 /* OpenParenToken */ , 21 /* OpenParenToken */ , [ isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ), - rule("NoSpaceBetweenParens", 20 /* OpenParenToken */ , 21 /* CloseParenToken */ , [ + rule("NoSpaceBetweenParens", 21 /* OpenParenToken */ , 22 /* CloseParenToken */ , [ isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), - rule("NoSpaceAfterOpenParen", 20 /* OpenParenToken */ , anyToken, [ + rule("NoSpaceAfterOpenParen", 21 /* OpenParenToken */ , anyToken, [ isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), - rule("NoSpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */ , [ + rule("NoSpaceBeforeCloseParen", anyToken, 22 /* CloseParenToken */ , [ isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), // Insert space after opening and before closing nonempty brackets - rule("SpaceAfterOpenBracket", 22 /* OpenBracketToken */ , anyToken, [ + rule("SpaceAfterOpenBracket", 23 /* OpenBracketToken */ , anyToken, [ isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ), - rule("SpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */ , [ + rule("SpaceBeforeCloseBracket", anyToken, 24 /* CloseBracketToken */ , [ isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ), - rule("NoSpaceBetweenBrackets", 22 /* OpenBracketToken */ , 23 /* CloseBracketToken */ , [ + rule("NoSpaceBetweenBrackets", 23 /* OpenBracketToken */ , 24 /* CloseBracketToken */ , [ isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), - rule("NoSpaceAfterOpenBracket", 22 /* OpenBracketToken */ , anyToken, [ + rule("NoSpaceAfterOpenBracket", 23 /* OpenBracketToken */ , anyToken, [ isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), - rule("NoSpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */ , [ + rule("NoSpaceBeforeCloseBracket", anyToken, 24 /* CloseBracketToken */ , [ isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. - rule("SpaceAfterOpenBrace", 18 /* OpenBraceToken */ , anyToken, [ + rule("SpaceAfterOpenBrace", 19 /* OpenBraceToken */ , anyToken, [ isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext ], 4 /* InsertSpace */ ), - rule("SpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */ , [ + rule("SpaceBeforeCloseBrace", anyToken, 20 /* CloseBraceToken */ , [ isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext ], 4 /* InsertSpace */ ), - rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */ , 19 /* CloseBraceToken */ , [ + rule("NoSpaceBetweenEmptyBraceBrackets", 19 /* OpenBraceToken */ , 20 /* CloseBraceToken */ , [ isNonJsxSameLineTokenContext, isObjectContext ], 16 /* DeleteSpace */ ), - rule("NoSpaceAfterOpenBrace", 18 /* OpenBraceToken */ , anyToken, [ + rule("NoSpaceAfterOpenBrace", 19 /* OpenBraceToken */ , anyToken, [ isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), - rule("NoSpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */ , [ + rule("NoSpaceBeforeCloseBrace", anyToken, 20 /* CloseBraceToken */ , [ isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), // Insert a space after opening and before closing empty brace brackets - rule("SpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */ , 19 /* CloseBraceToken */ , [ + rule("SpaceBetweenEmptyBraceBrackets", 19 /* OpenBraceToken */ , 20 /* CloseBraceToken */ , [ isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingEmptyBraces") ], 4 /* InsertSpace */ ), - rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */ , 19 /* CloseBraceToken */ , [ + rule("NoSpaceBetweenEmptyBraceBrackets", 19 /* OpenBraceToken */ , 20 /* CloseBraceToken */ , [ isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingEmptyBraces"), isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), // Insert space after opening and before closing template string braces rule("SpaceAfterTemplateHeadAndMiddle", [ - 15 /* TemplateHead */ , - 16 /* TemplateMiddle */ + 16 /* TemplateHead */ , + 17 /* TemplateMiddle */ ], anyToken, [ isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxTextContext ], 4 /* InsertSpace */ , 1 /* CanDeleteNewLines */ ), rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [ - 16 /* TemplateMiddle */ , - 17 /* TemplateTail */ + 17 /* TemplateMiddle */ , + 18 /* TemplateTail */ ], [ isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ), rule("NoSpaceAfterTemplateHeadAndMiddle", [ - 15 /* TemplateHead */ , - 16 /* TemplateMiddle */ + 16 /* TemplateHead */ , + 17 /* TemplateMiddle */ ], anyToken, [ isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxTextContext ], 16 /* DeleteSpace */ , 1 /* CanDeleteNewLines */ ), rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [ - 16 /* TemplateMiddle */ , - 17 /* TemplateTail */ + 17 /* TemplateMiddle */ , + 18 /* TemplateTail */ ], [ isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), // No space after { and before } in JSX expression - rule("SpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */ , anyToken, [ + rule("SpaceAfterOpenBraceInJsxExpression", 19 /* OpenBraceToken */ , anyToken, [ isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext ], 4 /* InsertSpace */ ), - rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */ , [ + rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 20 /* CloseBraceToken */ , [ isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext ], 4 /* InsertSpace */ ), - rule("NoSpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */ , anyToken, [ + rule("NoSpaceAfterOpenBraceInJsxExpression", 19 /* OpenBraceToken */ , anyToken, [ isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext ], 16 /* DeleteSpace */ ), - rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */ , [ + rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 20 /* CloseBraceToken */ , [ isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext ], 16 /* DeleteSpace */ ), // Insert space after semicolon in for statement - rule("SpaceAfterSemicolonInFor", 26 /* SemicolonToken */ , anyToken, [ + rule("SpaceAfterSemicolonInFor", 27 /* SemicolonToken */ , anyToken, [ isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext ], 4 /* InsertSpace */ ), - rule("NoSpaceAfterSemicolonInFor", 26 /* SemicolonToken */ , anyToken, [ + rule("NoSpaceAfterSemicolonInFor", 27 /* SemicolonToken */ , anyToken, [ isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext @@ -133201,62 +136173,62 @@ ${options.prefix}` : "\n" : options.prefix isNonJsxSameLineTokenContext, isBinaryOpContext ], 16 /* DeleteSpace */ ), - rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */ , [ + rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 21 /* OpenParenToken */ , [ isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext ], 4 /* InsertSpace */ ), - rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */ , [ + rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 21 /* OpenParenToken */ , [ isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext ], 16 /* DeleteSpace */ ), // Open Brace braces after control block - rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */ , [ + rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 19 /* OpenBraceToken */ , [ isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext ], 8 /* InsertNewLine */ , 1 /* CanDeleteNewLines */ ), // Open Brace braces after function // TypeScript: Function can have return types, which can be made of tons of different token kinds - rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */ , [ + rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 19 /* OpenBraceToken */ , [ isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext ], 8 /* InsertNewLine */ , 1 /* CanDeleteNewLines */ ), // Open Brace braces after TypeScript module/class/interface - rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */ , [ + rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 19 /* OpenBraceToken */ , [ isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext ], 8 /* InsertNewLine */ , 1 /* CanDeleteNewLines */ ), - rule("SpaceAfterTypeAssertion", 31 /* GreaterThanToken */ , anyToken, [ + rule("SpaceAfterTypeAssertion", 32 /* GreaterThanToken */ , anyToken, [ isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext ], 4 /* InsertSpace */ ), - rule("NoSpaceAfterTypeAssertion", 31 /* GreaterThanToken */ , anyToken, [ + rule("NoSpaceAfterTypeAssertion", 32 /* GreaterThanToken */ , anyToken, [ isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext ], 16 /* DeleteSpace */ ), rule("SpaceBeforeTypeAnnotation", anyToken, [ - 57 /* QuestionToken */ , - 58 /* ColonToken */ + 58 /* QuestionToken */ , + 59 /* ColonToken */ ], [ isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext ], 4 /* InsertSpace */ ), rule("NoSpaceBeforeTypeAnnotation", anyToken, [ - 57 /* QuestionToken */ , - 58 /* ColonToken */ + 58 /* QuestionToken */ , + 59 /* ColonToken */ ], [ isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext ], 16 /* DeleteSpace */ ), - rule("NoOptionalSemicolon", 26 /* SemicolonToken */ , anyTokenIncludingEOF, [ + rule("NoOptionalSemicolon", 27 /* SemicolonToken */ , anyTokenIncludingEOF, [ optionEquals("semicolons", "remove" /* Remove */ ), isSemicolonDeletionContext ], 32 /* DeleteToken */ ), @@ -133267,53 +136239,53 @@ ${options.prefix}` : "\n" : options.prefix ]; const lowPriorityCommonRules = [ // Space after keyword but not before ; or : or ? - rule("NoSpaceBeforeSemicolon", anyToken, 26 /* SemicolonToken */ , [ + rule("NoSpaceBeforeSemicolon", anyToken, 27 /* SemicolonToken */ , [ isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), - rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */ , [ + rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 19 /* OpenBraceToken */ , [ isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext ], 4 /* InsertSpace */ , 1 /* CanDeleteNewLines */ ), - rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */ , [ + rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 19 /* OpenBraceToken */ , [ isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext ], 4 /* InsertSpace */ , 1 /* CanDeleteNewLines */ ), - rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */ , [ + rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 19 /* OpenBraceToken */ , [ isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext ], 4 /* InsertSpace */ , 1 /* CanDeleteNewLines */ ), - rule("NoSpaceBeforeComma", anyToken, 27 /* CommaToken */ , [ + rule("NoSpaceBeforeComma", anyToken, 28 /* CommaToken */ , [ isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), // No space before and after indexer `x[]` - rule("NoSpaceBeforeOpenBracket", anyTokenExcept(132 /* AsyncKeyword */ , 82 /* CaseKeyword */ ), 22 /* OpenBracketToken */ , [ + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(134 /* AsyncKeyword */ , 84 /* CaseKeyword */ ), 23 /* OpenBracketToken */ , [ isNonJsxSameLineTokenContext ], 16 /* DeleteSpace */ ), - rule("NoSpaceAfterCloseBracket", 23 /* CloseBracketToken */ , anyToken, [ + rule("NoSpaceAfterCloseBracket", 24 /* CloseBracketToken */ , anyToken, [ isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext ], 16 /* DeleteSpace */ ), - rule("SpaceAfterSemicolon", 26 /* SemicolonToken */ , anyToken, [ + rule("SpaceAfterSemicolon", 27 /* SemicolonToken */ , anyToken, [ isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ), // Remove extra space between for and await - rule("SpaceBetweenForAndAwaitKeyword", 97 /* ForKeyword */ , 133 /* AwaitKeyword */ , [ + rule("SpaceBetweenForAndAwaitKeyword", 99 /* ForKeyword */ , 135 /* AwaitKeyword */ , [ isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ), // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] rule("SpaceBetweenStatements", [ - 21 /* CloseParenToken */ , - 90 /* DoKeyword */ , - 91 /* ElseKeyword */ , - 82 /* CaseKeyword */ + 22 /* CloseParenToken */ , + 92 /* DoKeyword */ , + 93 /* ElseKeyword */ , + 84 /* CaseKeyword */ ], anyToken, [ isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, @@ -133321,10 +136293,10 @@ ${options.prefix}` : "\n" : options.prefix ], 4 /* InsertSpace */ ), // This low-pri rule takes care of "try {", "catch {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. rule("SpaceAfterTryCatchFinally", [ - 111 /* TryKeyword */ , - 83 /* CatchKeyword */ , - 96 /* FinallyKeyword */ - ], 18 /* OpenBraceToken */ , [ + 113 /* TryKeyword */ , + 85 /* CatchKeyword */ , + 98 /* FinallyKeyword */ + ], 19 /* OpenBraceToken */ , [ isNonJsxSameLineTokenContext ], 4 /* InsertSpace */ ) ]; @@ -133381,40 +136353,40 @@ ${options.prefix}` : "\n" : options.prefix return (context)=>!context.options || !hasProperty(context.options, optionName) || !!context.options[optionName]; } function isForContext(context) { - return context.contextNode.kind === 245 /* ForStatement */ ; + return context.contextNode.kind === 248 /* ForStatement */ ; } function isNotForContext(context) { return !isForContext(context); } function isBinaryOpContext(context) { switch(context.contextNode.kind){ - case 223 /* BinaryExpression */ : - return context.contextNode.operatorToken.kind !== 27 /* CommaToken */ ; - case 224 /* ConditionalExpression */ : - case 191 /* ConditionalType */ : - case 231 /* AsExpression */ : - case 278 /* ExportSpecifier */ : - case 273 /* ImportSpecifier */ : - case 179 /* TypePredicate */ : - case 189 /* UnionType */ : - case 190 /* IntersectionType */ : - case 235 /* SatisfiesExpression */ : + case 226 /* BinaryExpression */ : + return context.contextNode.operatorToken.kind !== 28 /* CommaToken */ ; + case 227 /* ConditionalExpression */ : + case 194 /* ConditionalType */ : + case 234 /* AsExpression */ : + case 281 /* ExportSpecifier */ : + case 276 /* ImportSpecifier */ : + case 182 /* TypePredicate */ : + case 192 /* UnionType */ : + case 193 /* IntersectionType */ : + case 238 /* SatisfiesExpression */ : return true; - case 205 /* BindingElement */ : - case 262 /* TypeAliasDeclaration */ : - case 268 /* ImportEqualsDeclaration */ : - case 274 /* ExportAssignment */ : - case 257 /* VariableDeclaration */ : - case 166 /* Parameter */ : - case 302 /* EnumMember */ : - case 169 /* PropertyDeclaration */ : - case 168 /* PropertySignature */ : - return context.currentTokenSpan.kind === 63 /* EqualsToken */ || context.nextTokenSpan.kind === 63 /* EqualsToken */ ; - case 246 /* ForInStatement */ : - case 165 /* TypeParameter */ : - return context.currentTokenSpan.kind === 101 /* InKeyword */ || context.nextTokenSpan.kind === 101 /* InKeyword */ || context.currentTokenSpan.kind === 63 /* EqualsToken */ || context.nextTokenSpan.kind === 63 /* EqualsToken */ ; - case 247 /* ForOfStatement */ : - return context.currentTokenSpan.kind === 162 /* OfKeyword */ || context.nextTokenSpan.kind === 162 /* OfKeyword */ ; + case 208 /* BindingElement */ : + case 265 /* TypeAliasDeclaration */ : + case 271 /* ImportEqualsDeclaration */ : + case 277 /* ExportAssignment */ : + case 260 /* VariableDeclaration */ : + case 169 /* Parameter */ : + case 306 /* EnumMember */ : + case 172 /* PropertyDeclaration */ : + case 171 /* PropertySignature */ : + return context.currentTokenSpan.kind === 64 /* EqualsToken */ || context.nextTokenSpan.kind === 64 /* EqualsToken */ ; + case 249 /* ForInStatement */ : + case 168 /* TypeParameter */ : + return context.currentTokenSpan.kind === 103 /* InKeyword */ || context.nextTokenSpan.kind === 103 /* InKeyword */ || context.currentTokenSpan.kind === 64 /* EqualsToken */ || context.nextTokenSpan.kind === 64 /* EqualsToken */ ; + case 250 /* ForOfStatement */ : + return context.currentTokenSpan.kind === 165 /* OfKeyword */ || context.nextTokenSpan.kind === 165 /* OfKeyword */ ; } return false; } @@ -133426,16 +136398,16 @@ ${options.prefix}` : "\n" : options.prefix } function isTypeAnnotationContext(context) { const contextKind = context.contextNode.kind; - return contextKind === 169 /* PropertyDeclaration */ || contextKind === 168 /* PropertySignature */ || contextKind === 166 /* Parameter */ || contextKind === 257 /* VariableDeclaration */ || isFunctionLikeKind(contextKind); + return contextKind === 172 /* PropertyDeclaration */ || contextKind === 171 /* PropertySignature */ || contextKind === 169 /* Parameter */ || contextKind === 260 /* VariableDeclaration */ || isFunctionLikeKind(contextKind); } function isConditionalOperatorContext(context) { - return context.contextNode.kind === 224 /* ConditionalExpression */ || context.contextNode.kind === 191 /* ConditionalType */ ; + return context.contextNode.kind === 227 /* ConditionalExpression */ || context.contextNode.kind === 194 /* ConditionalType */ ; } function isSameLineTokenOrBeforeBlockContext(context) { return context.TokensAreOnSameLine() || isBeforeBlockContext(context); } function isBraceWrappedContext(context) { - return context.contextNode.kind === 203 /* ObjectBindingPattern */ || context.contextNode.kind === 197 /* MappedType */ || isSingleLineBlockContext(context); + return context.contextNode.kind === 206 /* ObjectBindingPattern */ || context.contextNode.kind === 200 /* MappedType */ || isSingleLineBlockContext(context); } function isBeforeMultilineBlockContext(context) { return isBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine()); @@ -133455,26 +136427,26 @@ ${options.prefix}` : "\n" : options.prefix function nodeIsBlockContext(node) { if (nodeIsTypeScriptDeclWithBlockContext(node)) return true; switch(node.kind){ - case 238 /* Block */ : - case 266 /* CaseBlock */ : - case 207 /* ObjectLiteralExpression */ : - case 265 /* ModuleBlock */ : + case 241 /* Block */ : + case 269 /* CaseBlock */ : + case 210 /* ObjectLiteralExpression */ : + case 268 /* ModuleBlock */ : return true; } return false; } function isFunctionDeclContext(context) { switch(context.contextNode.kind){ - case 259 /* FunctionDeclaration */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - case 176 /* CallSignature */ : - case 215 /* FunctionExpression */ : - case 173 /* Constructor */ : - case 216 /* ArrowFunction */ : - case 261 /* InterfaceDeclaration */ : + case 262 /* FunctionDeclaration */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + case 179 /* CallSignature */ : + case 218 /* FunctionExpression */ : + case 176 /* Constructor */ : + case 219 /* ArrowFunction */ : + case 264 /* InterfaceDeclaration */ : return true; } return false; @@ -133483,108 +136455,108 @@ ${options.prefix}` : "\n" : options.prefix return !isFunctionDeclContext(context); } function isFunctionDeclarationOrFunctionExpressionContext(context) { - return context.contextNode.kind === 259 /* FunctionDeclaration */ || context.contextNode.kind === 215 /* FunctionExpression */ ; + return context.contextNode.kind === 262 /* FunctionDeclaration */ || context.contextNode.kind === 218 /* FunctionExpression */ ; } function isTypeScriptDeclWithBlockContext(context) { return nodeIsTypeScriptDeclWithBlockContext(context.contextNode); } function nodeIsTypeScriptDeclWithBlockContext(node) { switch(node.kind){ - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : - case 261 /* InterfaceDeclaration */ : - case 263 /* EnumDeclaration */ : - case 184 /* TypeLiteral */ : - case 264 /* ModuleDeclaration */ : - case 275 /* ExportDeclaration */ : - case 276 /* NamedExports */ : - case 269 /* ImportDeclaration */ : - case 272 /* NamedImports */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 264 /* InterfaceDeclaration */ : + case 266 /* EnumDeclaration */ : + case 187 /* TypeLiteral */ : + case 267 /* ModuleDeclaration */ : + case 278 /* ExportDeclaration */ : + case 279 /* NamedExports */ : + case 272 /* ImportDeclaration */ : + case 275 /* NamedImports */ : return true; } return false; } function isAfterCodeBlockContext(context) { switch(context.currentTokenParent.kind){ - case 260 /* ClassDeclaration */ : - case 264 /* ModuleDeclaration */ : - case 263 /* EnumDeclaration */ : - case 295 /* CatchClause */ : - case 265 /* ModuleBlock */ : - case 252 /* SwitchStatement */ : + case 263 /* ClassDeclaration */ : + case 267 /* ModuleDeclaration */ : + case 266 /* EnumDeclaration */ : + case 299 /* CatchClause */ : + case 268 /* ModuleBlock */ : + case 255 /* SwitchStatement */ : return true; - case 238 /* Block */ : + case 241 /* Block */ : { const blockParent = context.currentTokenParent.parent; - if (!blockParent || blockParent.kind !== 216 /* ArrowFunction */ && blockParent.kind !== 215 /* FunctionExpression */ ) return true; + if (!blockParent || blockParent.kind !== 219 /* ArrowFunction */ && blockParent.kind !== 218 /* FunctionExpression */ ) return true; } } return false; } function isControlDeclContext(context) { switch(context.contextNode.kind){ - case 242 /* IfStatement */ : - case 252 /* SwitchStatement */ : - case 245 /* ForStatement */ : - case 246 /* ForInStatement */ : - case 247 /* ForOfStatement */ : - case 244 /* WhileStatement */ : - case 255 /* TryStatement */ : - case 243 /* DoStatement */ : - case 251 /* WithStatement */ : - case 295 /* CatchClause */ : + case 245 /* IfStatement */ : + case 255 /* SwitchStatement */ : + case 248 /* ForStatement */ : + case 249 /* ForInStatement */ : + case 250 /* ForOfStatement */ : + case 247 /* WhileStatement */ : + case 258 /* TryStatement */ : + case 246 /* DoStatement */ : + case 254 /* WithStatement */ : + case 299 /* CatchClause */ : return true; default: return false; } } function isObjectContext(context) { - return context.contextNode.kind === 207 /* ObjectLiteralExpression */ ; + return context.contextNode.kind === 210 /* ObjectLiteralExpression */ ; } function isFunctionCallContext(context) { - return context.contextNode.kind === 210 /* CallExpression */ ; + return context.contextNode.kind === 213 /* CallExpression */ ; } function isNewContext(context) { - return context.contextNode.kind === 211 /* NewExpression */ ; + return context.contextNode.kind === 214 /* NewExpression */ ; } function isFunctionCallOrNewContext(context) { return isFunctionCallContext(context) || isNewContext(context); } function isPreviousTokenNotComma(context) { - return context.currentTokenSpan.kind !== 27 /* CommaToken */ ; + return context.currentTokenSpan.kind !== 28 /* CommaToken */ ; } function isNextTokenNotCloseBracket(context) { - return context.nextTokenSpan.kind !== 23 /* CloseBracketToken */ ; + return context.nextTokenSpan.kind !== 24 /* CloseBracketToken */ ; } function isNextTokenNotCloseParen(context) { - return context.nextTokenSpan.kind !== 21 /* CloseParenToken */ ; + return context.nextTokenSpan.kind !== 22 /* CloseParenToken */ ; } function isArrowFunctionContext(context) { - return context.contextNode.kind === 216 /* ArrowFunction */ ; + return context.contextNode.kind === 219 /* ArrowFunction */ ; } function isImportTypeContext(context) { - return context.contextNode.kind === 202 /* ImportType */ ; + return context.contextNode.kind === 205 /* ImportType */ ; } function isNonJsxSameLineTokenContext(context) { - return context.TokensAreOnSameLine() && context.contextNode.kind !== 11 /* JsxText */ ; + return context.TokensAreOnSameLine() && context.contextNode.kind !== 12 /* JsxText */ ; } function isNonJsxTextContext(context) { - return context.contextNode.kind !== 11 /* JsxText */ ; + return context.contextNode.kind !== 12 /* JsxText */ ; } function isNonJsxElementOrFragmentContext(context) { - return context.contextNode.kind !== 281 /* JsxElement */ && context.contextNode.kind !== 285 /* JsxFragment */ ; + return context.contextNode.kind !== 284 /* JsxElement */ && context.contextNode.kind !== 288 /* JsxFragment */ ; } function isJsxExpressionContext(context) { - return context.contextNode.kind === 291 /* JsxExpression */ || context.contextNode.kind === 290 /* JsxSpreadAttribute */ ; + return context.contextNode.kind === 294 /* JsxExpression */ || context.contextNode.kind === 293 /* JsxSpreadAttribute */ ; } function isNextTokenParentJsxAttribute(context) { - return context.nextTokenParent.kind === 288 /* JsxAttribute */ ; + return context.nextTokenParent.kind === 291 /* JsxAttribute */ ; } function isJsxAttributeContext(context) { - return context.contextNode.kind === 288 /* JsxAttribute */ ; + return context.contextNode.kind === 291 /* JsxAttribute */ ; } function isJsxSelfClosingElementContext(context) { - return context.contextNode.kind === 282 /* JsxSelfClosingElement */ ; + return context.contextNode.kind === 285 /* JsxSelfClosingElement */ ; } function isNotBeforeBlockInFunctionDeclarationContext(context) { return !isFunctionDeclContext(context) && !isBeforeBlockContext(context); @@ -133594,42 +136566,42 @@ ${options.prefix}` : "\n" : options.prefix } function nodeIsInDecoratorContext(node) { while(node && isExpression(node))node = node.parent; - return node && node.kind === 167 /* Decorator */ ; + return node && node.kind === 170 /* Decorator */ ; } function isStartOfVariableDeclarationList(context) { - return context.currentTokenParent.kind === 258 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; + return context.currentTokenParent.kind === 261 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; } function isNotFormatOnEnter(context) { return context.formattingRequestKind !== 2 /* FormatOnEnter */ ; } function isModuleDeclContext(context) { - return context.contextNode.kind === 264 /* ModuleDeclaration */ ; + return context.contextNode.kind === 267 /* ModuleDeclaration */ ; } function isObjectTypeContext(context) { - return context.contextNode.kind === 184 /* TypeLiteral */ ; + return context.contextNode.kind === 187 /* TypeLiteral */ ; } function isConstructorSignatureContext(context) { - return context.contextNode.kind === 177 /* ConstructSignature */ ; + return context.contextNode.kind === 180 /* ConstructSignature */ ; } function isTypeArgumentOrParameterOrAssertion(token, parent2) { - if (token.kind !== 29 /* LessThanToken */ && token.kind !== 31 /* GreaterThanToken */ ) return false; + if (token.kind !== 30 /* LessThanToken */ && token.kind !== 32 /* GreaterThanToken */ ) return false; switch(parent2.kind){ - case 180 /* TypeReference */ : - case 213 /* TypeAssertionExpression */ : - case 262 /* TypeAliasDeclaration */ : - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : - case 261 /* InterfaceDeclaration */ : - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 176 /* CallSignature */ : - case 177 /* ConstructSignature */ : - case 210 /* CallExpression */ : - case 211 /* NewExpression */ : - case 230 /* ExpressionWithTypeArguments */ : + case 183 /* TypeReference */ : + case 216 /* TypeAssertionExpression */ : + case 265 /* TypeAliasDeclaration */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 264 /* InterfaceDeclaration */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 179 /* CallSignature */ : + case 180 /* ConstructSignature */ : + case 213 /* CallExpression */ : + case 214 /* NewExpression */ : + case 233 /* ExpressionWithTypeArguments */ : return true; default: return false; @@ -133639,31 +136611,31 @@ ${options.prefix}` : "\n" : options.prefix return isTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) || isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); } function isTypeAssertionContext(context) { - return context.contextNode.kind === 213 /* TypeAssertionExpression */ ; + return context.contextNode.kind === 216 /* TypeAssertionExpression */ ; } function isNonTypeAssertionContext(context) { return !isTypeAssertionContext(context); } function isVoidOpContext(context) { - return context.currentTokenSpan.kind === 114 /* VoidKeyword */ && context.currentTokenParent.kind === 219 /* VoidExpression */ ; + return context.currentTokenSpan.kind === 116 /* VoidKeyword */ && context.currentTokenParent.kind === 222 /* VoidExpression */ ; } function isYieldOrYieldStarWithOperand(context) { - return context.contextNode.kind === 226 /* YieldExpression */ && context.contextNode.expression !== void 0; + return context.contextNode.kind === 229 /* YieldExpression */ && context.contextNode.expression !== void 0; } function isNonNullAssertionContext(context) { - return context.contextNode.kind === 232 /* NonNullExpression */ ; + return context.contextNode.kind === 235 /* NonNullExpression */ ; } function isNotStatementConditionContext(context) { return !isStatementConditionContext(context); } function isStatementConditionContext(context) { switch(context.contextNode.kind){ - case 242 /* IfStatement */ : - case 245 /* ForStatement */ : - case 246 /* ForInStatement */ : - case 247 /* ForOfStatement */ : - case 243 /* DoStatement */ : - case 244 /* WhileStatement */ : + case 245 /* IfStatement */ : + case 248 /* ForStatement */ : + case 249 /* ForInStatement */ : + case 250 /* ForOfStatement */ : + case 246 /* DoStatement */ : + case 247 /* WhileStatement */ : return true; default: return false; @@ -133680,11 +136652,11 @@ ${options.prefix}` : "\n" : options.prefix } const startLine = context.sourceFile.getLineAndCharacterOfPosition(context.currentTokenSpan.pos).line; const endLine = context.sourceFile.getLineAndCharacterOfPosition(nextTokenStart).line; - if (startLine === endLine) return nextTokenKind === 19 /* CloseBraceToken */ || nextTokenKind === 1 /* EndOfFileToken */ ; - if (nextTokenKind === 237 /* SemicolonClassElement */ || nextTokenKind === 26 /* SemicolonToken */ ) return false; - if (context.contextNode.kind === 261 /* InterfaceDeclaration */ || context.contextNode.kind === 262 /* TypeAliasDeclaration */ ) return !isPropertySignature(context.currentTokenParent) || !!context.currentTokenParent.type || nextTokenKind !== 20 /* OpenParenToken */ ; + if (startLine === endLine) return nextTokenKind === 20 /* CloseBraceToken */ || nextTokenKind === 1 /* EndOfFileToken */ ; + if (nextTokenKind === 240 /* SemicolonClassElement */ || nextTokenKind === 27 /* SemicolonToken */ ) return false; + if (context.contextNode.kind === 264 /* InterfaceDeclaration */ || context.contextNode.kind === 265 /* TypeAliasDeclaration */ ) return !isPropertySignature(context.currentTokenParent) || !!context.currentTokenParent.type || nextTokenKind !== 21 /* OpenParenToken */ ; if (isPropertyDeclaration(context.currentTokenParent)) return !context.currentTokenParent.initializer; - return context.currentTokenParent.kind !== 245 /* ForStatement */ && context.currentTokenParent.kind !== 239 /* EmptyStatement */ && context.currentTokenParent.kind !== 237 /* SemicolonClassElement */ && nextTokenKind !== 22 /* OpenBracketToken */ && nextTokenKind !== 20 /* OpenParenToken */ && nextTokenKind !== 39 /* PlusToken */ && nextTokenKind !== 40 /* MinusToken */ && nextTokenKind !== 43 /* SlashToken */ && nextTokenKind !== 13 /* RegularExpressionLiteral */ && nextTokenKind !== 27 /* CommaToken */ && nextTokenKind !== 225 /* TemplateExpression */ && nextTokenKind !== 15 /* TemplateHead */ && nextTokenKind !== 14 /* NoSubstitutionTemplateLiteral */ && nextTokenKind !== 24 /* DotToken */ ; + return context.currentTokenParent.kind !== 248 /* ForStatement */ && context.currentTokenParent.kind !== 242 /* EmptyStatement */ && context.currentTokenParent.kind !== 240 /* SemicolonClassElement */ && nextTokenKind !== 23 /* OpenBracketToken */ && nextTokenKind !== 21 /* OpenParenToken */ && nextTokenKind !== 40 /* PlusToken */ && nextTokenKind !== 41 /* MinusToken */ && nextTokenKind !== 44 /* SlashToken */ && nextTokenKind !== 14 /* RegularExpressionLiteral */ && nextTokenKind !== 28 /* CommaToken */ && nextTokenKind !== 228 /* TemplateExpression */ && nextTokenKind !== 16 /* TemplateHead */ && nextTokenKind !== 15 /* NoSubstitutionTemplateLiteral */ && nextTokenKind !== 25 /* DotToken */ ; } function isSemicolonInsertionContext(context) { return positionIsASICandidate(context.currentTokenSpan.end, context.currentTokenParent, context.sourceFile); @@ -133752,7 +136724,7 @@ ${options.prefix}` : "\n" : options.prefix return map2; } function getRuleBucketIndex(row, column) { - Debug.assert(row <= 162 /* LastKeyword */ && column <= 162 /* LastKeyword */ , "Must compute formatting context from tokens"); + Debug.assert(row <= 165 /* LastKeyword */ && column <= 165 /* LastKeyword */ , "Must compute formatting context from tokens"); return row * mapRowLength + column; } function addRule(rules, rule2, specificTokens, constructionState, rulesBucketIndex) { @@ -133782,7 +136754,7 @@ ${options.prefix}` : "\n" : options.prefix init_ts_formatting(); maskBitSize = 5; mask = 31; - mapRowLength = 163; + mapRowLength = 166; RulesPosition = ((RulesPosition2)=>{ RulesPosition2[RulesPosition2["StopRulesSpecific"] = 0] = "StopRulesSpecific"; RulesPosition2[RulesPosition2["StopRulesAny"] = maskBitSize * 1] = "StopRulesAny"; @@ -133821,11 +136793,11 @@ ${options.prefix}` : "\n" : options.prefix return formatSpan(span, sourceFile, formatContext, 2 /* FormatOnEnter */ ); } function formatOnSemicolon(position, sourceFile, formatContext) { - const semicolon = findImmediatelyPrecedingTokenOfKind(position, 26 /* SemicolonToken */ , sourceFile); + const semicolon = findImmediatelyPrecedingTokenOfKind(position, 27 /* SemicolonToken */ , sourceFile); return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, formatContext, 3 /* FormatOnSemicolon */ ); } function formatOnOpeningCurly(position, sourceFile, formatContext) { - const openingCurly = findImmediatelyPrecedingTokenOfKind(position, 18 /* OpenBraceToken */ , sourceFile); + const openingCurly = findImmediatelyPrecedingTokenOfKind(position, 19 /* OpenBraceToken */ , sourceFile); if (!openingCurly) return []; const curlyBraceRange = openingCurly.parent; const outermostNode = findOutermostNodeWithinListLevel(curlyBraceRange); @@ -133837,7 +136809,7 @@ ${options.prefix}` : "\n" : options.prefix return formatSpan(textRange, sourceFile, formatContext, 4 /* FormatOnOpeningCurlyBrace */ ); } function formatOnClosingCurly(position, sourceFile, formatContext) { - const precedingToken = findImmediatelyPrecedingTokenOfKind(position, 19 /* CloseBraceToken */ , sourceFile); + const precedingToken = findImmediatelyPrecedingTokenOfKind(position, 20 /* CloseBraceToken */ , sourceFile); return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, formatContext, 5 /* FormatOnClosingCurlyBrace */ ); } function formatDocument(sourceFile, formatContext) { @@ -133865,17 +136837,17 @@ ${options.prefix}` : "\n" : options.prefix } function isListElement(parent2, node) { switch(parent2.kind){ - case 260 /* ClassDeclaration */ : - case 261 /* InterfaceDeclaration */ : + case 263 /* ClassDeclaration */ : + case 264 /* InterfaceDeclaration */ : return rangeContainsRange(parent2.members, node); - case 264 /* ModuleDeclaration */ : + case 267 /* ModuleDeclaration */ : const body = parent2.body; - return !!body && body.kind === 265 /* ModuleBlock */ && rangeContainsRange(body.statements, node); - case 308 /* SourceFile */ : - case 238 /* Block */ : - case 265 /* ModuleBlock */ : + return !!body && body.kind === 268 /* ModuleBlock */ && rangeContainsRange(body.statements, node); + case 312 /* SourceFile */ : + case 241 /* Block */ : + case 268 /* ModuleBlock */ : return rangeContainsRange(parent2.statements, node); - case 295 /* CatchClause */ : + case 299 /* CatchClause */ : return rangeContainsRange(parent2.block.statements, node); } return false; @@ -133899,9 +136871,9 @@ ${options.prefix}` : "\n" : options.prefix return (r)=>{ while(true){ if (index >= sorted.length) return false; - const error = sorted[index]; - if (r.end <= error.start) return false; - if (startEndOverlapsWithStartEnd(r.pos, r.end, error.start, error.start + error.length)) return true; + const error2 = sorted[index]; + if (r.end <= error2.start) return false; + if (startEndOverlapsWithStartEnd(r.pos, r.end, error2.start, error2.start + error2.length)) return true; index++; } }; @@ -133950,8 +136922,8 @@ ${options.prefix}` : "\n" : options.prefix const enclosingNode = findEnclosingNode(originalRange, sourceFile); return getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, (scanner2)=>formatSpanWorker(originalRange, enclosingNode, SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options), getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile), scanner2, formatContext, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile)); } - function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, { options: options , getRules: getRules , host: host }, requestKind, rangeContainsError, sourceFile) { - var _a2; + function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, { options: options, getRules: getRules, host: host }, requestKind, rangeContainsError, sourceFile) { + var _a; const formattingContext = new FormattingContext(sourceFile, requestKind, options); let previousRangeTriviaEnd; let previousRange; @@ -133967,18 +136939,19 @@ ${options.prefix}` : "\n" : options.prefix if (hasDecorators(enclosingNode)) undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line; processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); } - if (!formattingScanner.isOnToken()) { + const remainingTrivia = formattingScanner.getCurrentLeadingTrivia(); + if (remainingTrivia) { const indentation = SmartIndenter.nodeWillIndentChild(options, enclosingNode, /*child*/ void 0, sourceFile, /*indentByDefault*/ false) ? initialIndentation + options.indentSize : initialIndentation; - const leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); - if (leadingTrivia) { - indentTriviaItems(leadingTrivia, indentation, /*indentNextTokenOrTrivia*/ false, (item)=>processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ void 0)); - if (options.trimTrailingWhitespace !== false) trimTrailingWhitespacesForRemainingRange(leadingTrivia); - } + indentTriviaItems(remainingTrivia, indentation, /*indentNextTokenOrTrivia*/ true, (item)=>{ + processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ void 0); + insertIndentation(item.pos, indentation, /*lineAdded*/ false); + }); + if (options.trimTrailingWhitespace !== false) trimTrailingWhitespacesForRemainingRange(remainingTrivia); } - if (previousRange && formattingScanner.getStartPos() >= originalRange.end) { + if (previousRange && formattingScanner.getTokenFullStart() >= originalRange.end) { const tokenInfo = formattingScanner.isOnEOF() ? formattingScanner.readEOFTokenRange() : formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(enclosingNode).token : void 0; if (tokenInfo && tokenInfo.pos === previousRangeTriviaEnd) { - const parent2 = ((_a2 = findPrecedingToken(tokenInfo.end, sourceFile, enclosingNode)) == null ? void 0 : _a2.parent) || previousParent; + const parent2 = ((_a = findPrecedingToken(tokenInfo.end, sourceFile, enclosingNode)) == null ? void 0 : _a.parent) || previousParent; processPair(tokenInfo, sourceFile.getLineAndCharacterOfPosition(tokenInfo.pos).line, parent2, previousRange, previousRangeStartLine, previousParent, parent2, /*dynamicIndentation*/ void 0); } } @@ -134004,7 +136977,7 @@ ${options.prefix}` : "\n" : options.prefix delta: Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta2) }; else if (inheritedIndentation === -1 /* Unknown */ ) { - if (node.kind === 20 /* OpenParenToken */ && startLine === lastIndentedLine) return { + if (node.kind === 21 /* OpenParenToken */ && startLine === lastIndentedLine) return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; @@ -134027,22 +137000,22 @@ ${options.prefix}` : "\n" : options.prefix if (modifier) return modifier.kind; } switch(node.kind){ - case 260 /* ClassDeclaration */ : - return 84 /* ClassKeyword */ ; - case 261 /* InterfaceDeclaration */ : - return 118 /* InterfaceKeyword */ ; - case 259 /* FunctionDeclaration */ : - return 98 /* FunctionKeyword */ ; - case 263 /* EnumDeclaration */ : - return 263 /* EnumDeclaration */ ; - case 174 /* GetAccessor */ : - return 137 /* GetKeyword */ ; - case 175 /* SetAccessor */ : - return 151 /* SetKeyword */ ; - case 171 /* MethodDeclaration */ : - if (node.asteriskToken) return 41 /* AsteriskToken */ ; - case 169 /* PropertyDeclaration */ : - case 166 /* Parameter */ : + case 263 /* ClassDeclaration */ : + return 86 /* ClassKeyword */ ; + case 264 /* InterfaceDeclaration */ : + return 120 /* InterfaceKeyword */ ; + case 262 /* FunctionDeclaration */ : + return 100 /* FunctionKeyword */ ; + case 266 /* EnumDeclaration */ : + return 266 /* EnumDeclaration */ ; + case 177 /* GetAccessor */ : + return 139 /* GetKeyword */ ; + case 178 /* SetAccessor */ : + return 153 /* SetKeyword */ ; + case 174 /* MethodDeclaration */ : + if (node.asteriskToken) return 42 /* AsteriskToken */ ; + case 172 /* PropertyDeclaration */ : + case 169 /* Parameter */ : const name = getNameOfDeclaration(node); if (name) return name.kind; } @@ -134051,9 +137024,9 @@ ${options.prefix}` : "\n" : options.prefix return { getIndentationForComment: (kind, tokenIndentation, container)=>{ switch(kind){ - case 19 /* CloseBraceToken */ : - case 23 /* CloseBracketToken */ : - case 21 /* CloseParenToken */ : + case 20 /* CloseBraceToken */ : + case 24 /* CloseBracketToken */ : + case 22 /* CloseParenToken */ : return indentation + getDelta(container); } return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; @@ -134080,25 +137053,25 @@ ${options.prefix}` : "\n" : options.prefix }; function shouldAddDelta(line, kind, container) { switch(kind){ - case 18 /* OpenBraceToken */ : - case 19 /* CloseBraceToken */ : - case 21 /* CloseParenToken */ : - case 91 /* ElseKeyword */ : - case 115 /* WhileKeyword */ : - case 59 /* AtToken */ : + case 19 /* OpenBraceToken */ : + case 20 /* CloseBraceToken */ : + case 22 /* CloseParenToken */ : + case 93 /* ElseKeyword */ : + case 117 /* WhileKeyword */ : + case 60 /* AtToken */ : return false; - case 43 /* SlashToken */ : - case 31 /* GreaterThanToken */ : + case 44 /* SlashToken */ : + case 32 /* GreaterThanToken */ : switch(container.kind){ - case 283 /* JsxOpeningElement */ : - case 284 /* JsxClosingElement */ : - case 282 /* JsxSelfClosingElement */ : + case 286 /* JsxOpeningElement */ : + case 287 /* JsxClosingElement */ : + case 285 /* JsxSelfClosingElement */ : return false; } break; - case 22 /* OpenBracketToken */ : - case 23 /* CloseBracketToken */ : - if (container.kind !== 197 /* MappedType */ ) return false; + case 23 /* OpenBracketToken */ : + case 24 /* CloseBracketToken */ : + if (container.kind !== 200 /* MappedType */ ) return false; break; } return nodeStartLine !== line && !(hasDecorators(node) && kind === getFirstNonDecoratorTokenOfNode(node)); @@ -134116,7 +137089,7 @@ ${options.prefix}` : "\n" : options.prefix }, (nodes)=>{ processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation); }); - while(formattingScanner.isOnToken() && formattingScanner.getStartPos() < originalRange.end){ + while(formattingScanner.isOnToken() && formattingScanner.getTokenFullStart() < originalRange.end){ const tokenInfo = formattingScanner.readTokenInfo(node); if (tokenInfo.token.end > Math.min(node.end, originalRange.end)) break; consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node); @@ -134138,7 +137111,7 @@ ${options.prefix}` : "\n" : options.prefix return inheritedIndentation; } if (child.getFullWidth() === 0) return inheritedIndentation; - while(formattingScanner.isOnToken() && formattingScanner.getStartPos() < originalRange.end){ + while(formattingScanner.isOnToken() && formattingScanner.getTokenFullStart() < originalRange.end){ const tokenInfo = formattingScanner.readTokenInfo(node); if (tokenInfo.token.end > originalRange.end) return inheritedIndentation; if (tokenInfo.token.end > childStartPos) { @@ -134147,20 +137120,20 @@ ${options.prefix}` : "\n" : options.prefix } consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, node); } - if (!formattingScanner.isOnToken() || formattingScanner.getStartPos() >= originalRange.end) return inheritedIndentation; + if (!formattingScanner.isOnToken() || formattingScanner.getTokenFullStart() >= originalRange.end) return inheritedIndentation; if (isToken(child)) { const tokenInfo = formattingScanner.readTokenInfo(child); - if (child.kind !== 11 /* JsxText */ ) { + if (child.kind !== 12 /* JsxText */ ) { Debug.assert(tokenInfo.token.end === child.end, "Token end is child end"); consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } } - const effectiveParentStartLine = child.kind === 167 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + const effectiveParentStartLine = child.kind === 170 /* Decorator */ ? childStartLine : undecoratedParentStartLine; const childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); childContextNode = node; - if (isFirstListItem && parent2.kind === 206 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */ ) inheritedIndentation = childIndentation.indentation; + if (isFirstListItem && parent2.kind === 209 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */ ) inheritedIndentation = childIndentation.indentation; return inheritedIndentation; } function processChildNodes(nodes, parent2, parentStartLine, parentDynamicIndentation) { @@ -134173,7 +137146,7 @@ ${options.prefix}` : "\n" : options.prefix if (nodes.end < originalRange.pos) formattingScanner.skipToEndOf(nodes); return; } - if (listStartToken !== 0 /* Unknown */ ) while(formattingScanner.isOnToken() && formattingScanner.getStartPos() < originalRange.end){ + if (listStartToken !== 0 /* Unknown */ ) while(formattingScanner.isOnToken() && formattingScanner.getTokenFullStart() < originalRange.end){ const tokenInfo = formattingScanner.readTokenInfo(parent2); if (tokenInfo.token.end > nodes.pos) break; else if (tokenInfo.token.kind === listStartToken) { @@ -134194,9 +137167,9 @@ ${options.prefix}` : "\n" : options.prefix inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0); } const listEndToken = getCloseTokenForOpenToken(listStartToken); - if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken() && formattingScanner.getStartPos() < originalRange.end) { + if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken() && formattingScanner.getTokenFullStart() < originalRange.end) { let tokenInfo = formattingScanner.readTokenInfo(parent2); - if (tokenInfo.token.kind === 27 /* CommaToken */ ) { + if (tokenInfo.token.kind === 28 /* CommaToken */ ) { consumeTokenAndAdvanceScanner(tokenInfo, parent2, listDynamicIndentation, parent2); tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent2) : void 0; } @@ -134466,52 +137439,52 @@ ${options.prefix}` : "\n" : options.prefix } function getOpenTokenForList(node, list) { switch(node.kind){ - case 173 /* Constructor */ : - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 216 /* ArrowFunction */ : - case 176 /* CallSignature */ : - case 177 /* ConstructSignature */ : - case 181 /* FunctionType */ : - case 182 /* ConstructorType */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - if (node.typeParameters === list) return 29 /* LessThanToken */ ; - else if (node.parameters === list) return 20 /* OpenParenToken */ ; + case 176 /* Constructor */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 219 /* ArrowFunction */ : + case 179 /* CallSignature */ : + case 180 /* ConstructSignature */ : + case 184 /* FunctionType */ : + case 185 /* ConstructorType */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + if (node.typeParameters === list) return 30 /* LessThanToken */ ; + else if (node.parameters === list) return 21 /* OpenParenToken */ ; break; - case 210 /* CallExpression */ : - case 211 /* NewExpression */ : - if (node.typeArguments === list) return 29 /* LessThanToken */ ; - else if (node.arguments === list) return 20 /* OpenParenToken */ ; + case 213 /* CallExpression */ : + case 214 /* NewExpression */ : + if (node.typeArguments === list) return 30 /* LessThanToken */ ; + else if (node.arguments === list) return 21 /* OpenParenToken */ ; break; - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : - case 261 /* InterfaceDeclaration */ : - case 262 /* TypeAliasDeclaration */ : - if (node.typeParameters === list) return 29 /* LessThanToken */ ; + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 264 /* InterfaceDeclaration */ : + case 265 /* TypeAliasDeclaration */ : + if (node.typeParameters === list) return 30 /* LessThanToken */ ; break; - case 180 /* TypeReference */ : - case 212 /* TaggedTemplateExpression */ : - case 183 /* TypeQuery */ : - case 230 /* ExpressionWithTypeArguments */ : - case 202 /* ImportType */ : - if (node.typeArguments === list) return 29 /* LessThanToken */ ; + case 183 /* TypeReference */ : + case 215 /* TaggedTemplateExpression */ : + case 186 /* TypeQuery */ : + case 233 /* ExpressionWithTypeArguments */ : + case 205 /* ImportType */ : + if (node.typeArguments === list) return 30 /* LessThanToken */ ; break; - case 184 /* TypeLiteral */ : - return 18 /* OpenBraceToken */ ; + case 187 /* TypeLiteral */ : + return 19 /* OpenBraceToken */ ; } return 0 /* Unknown */ ; } function getCloseTokenForOpenToken(kind) { switch(kind){ - case 20 /* OpenParenToken */ : - return 21 /* CloseParenToken */ ; - case 29 /* LessThanToken */ : - return 31 /* GreaterThanToken */ ; - case 18 /* OpenBraceToken */ : - return 19 /* CloseBraceToken */ ; + case 21 /* OpenParenToken */ : + return 22 /* CloseParenToken */ ; + case 30 /* LessThanToken */ : + return 32 /* GreaterThanToken */ ; + case 19 /* OpenBraceToken */ : + return 20 /* CloseBraceToken */ ; } return 0 /* Unknown */ ; } @@ -134575,17 +137548,17 @@ ${options.prefix}` : "\n" : options.prefix if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && position < precedingToken.end) return 0; const lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; const currentToken = getTokenAtPosition(sourceFile, position); - const isObjectLiteral = currentToken.kind === 18 /* OpenBraceToken */ && currentToken.parent.kind === 207 /* ObjectLiteralExpression */ ; + const isObjectLiteral = currentToken.kind === 19 /* OpenBraceToken */ && currentToken.parent.kind === 210 /* ObjectLiteralExpression */ ; if (options.indentStyle === 1 /* Block */ || isObjectLiteral) return getBlockIndent(sourceFile, position, options); - if (precedingToken.kind === 27 /* CommaToken */ && precedingToken.parent.kind !== 223 /* BinaryExpression */ ) { + if (precedingToken.kind === 28 /* CommaToken */ && precedingToken.parent.kind !== 226 /* BinaryExpression */ ) { const actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1 /* Unknown */ ) return actualIndentation; } const containerList = getListByPosition(position, precedingToken.parent, sourceFile); if (containerList && !rangeContainsRange(containerList, precedingToken)) { const useTheSameBaseIndentation = [ - 215 /* FunctionExpression */ , - 216 /* ArrowFunction */ + 218 /* FunctionExpression */ , + 219 /* ArrowFunction */ ].indexOf(currentToken.parent.kind) !== -1; const indentSize = useTheSameBaseIndentation ? 0 : options.indentSize; return getActualIndentationForListStartLine(containerList, sourceFile, options) + indentSize; @@ -134599,7 +137572,7 @@ ${options.prefix}` : "\n" : options.prefix Debug.assert(commentStartLine >= 0); if (previousLine <= commentStartLine) return findFirstNonWhitespaceColumn(getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); const startPositionOfLine = getStartPositionOfLine(previousLine, sourceFile); - const { column: column , character: character } = findFirstNonWhitespaceCharacterAndColumn(startPositionOfLine, position, sourceFile, options); + const { column: column, character: character } = findFirstNonWhitespaceCharacterAndColumn(startPositionOfLine, position, sourceFile, options); if (column === 0) return column; const firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPositionOfLine + character); return firstNonWhitespaceCharacterCode === 42 /* asterisk */ ? column - 1 : column; @@ -134641,7 +137614,7 @@ ${options.prefix}` : "\n" : options.prefix } SmartIndenter2.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) { - var _a2; + var _a; let parent2 = current.parent; while(parent2){ let useActualIndentation = true; @@ -134652,7 +137625,7 @@ ${options.prefix}` : "\n" : options.prefix const containingListOrParentStart = getContainingListOrParentStart(parent2, current, sourceFile); const parentAndChildShareLine = containingListOrParentStart.line === currentStart.line || childStartsOnTheSameLineWithElseInIfStatement(parent2, current, currentStart.line, sourceFile); if (useActualIndentation) { - const firstListChild = (_a2 = getContainingList(current, sourceFile)) == null ? void 0 : _a2[0]; + const firstListChild = (_a = getContainingList(current, sourceFile)) == null ? void 0 : _a[0]; const listIndentsChild = !!firstListChild && getStartLineAndCharacterForNode(firstListChild, sourceFile).line > containingListOrParentStart.line; let actualIndentation = getActualIndentationForListItem(current, sourceFile, options, listIndentsChild); if (actualIndentation !== -1 /* Unknown */ ) return actualIndentation + indentationDelta; @@ -134678,7 +137651,7 @@ ${options.prefix}` : "\n" : options.prefix else return -1 /* Unknown */ ; } function getActualIndentationForNode(current, parent2, currentLineAndChar, parentAndChildShareLine, sourceFile, options) { - const useActualIndentation = (isDeclaration(current) || isStatementButNotDeclaration(current)) && (parent2.kind === 308 /* SourceFile */ || !parentAndChildShareLine); + const useActualIndentation = (isDeclaration(current) || isStatementButNotDeclaration(current)) && (parent2.kind === 312 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) return -1 /* Unknown */ ; return findColumnForFirstNonWhitespaceCharacterInLine(currentLineAndChar, sourceFile, options); } @@ -134691,8 +137664,8 @@ ${options.prefix}` : "\n" : options.prefix function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) { const nextToken = findNextToken(precedingToken, current, sourceFile); if (!nextToken) return 0 /* Unknown */ ; - if (nextToken.kind === 18 /* OpenBraceToken */ ) return 1 /* OpenBrace */ ; - else if (nextToken.kind === 19 /* CloseBraceToken */ ) { + if (nextToken.kind === 19 /* OpenBraceToken */ ) return 1 /* OpenBrace */ ; + else if (nextToken.kind === 20 /* CloseBraceToken */ ) { const nextTokenStartLine = getStartLineAndCharacterForNode(nextToken, sourceFile).line; return lineAtPosition === nextTokenStartLine ? 2 /* CloseBrace */ : 0 /* Unknown */ ; } @@ -134709,8 +137682,8 @@ ${options.prefix}` : "\n" : options.prefix } SmartIndenter2.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled; function childStartsOnTheSameLineWithElseInIfStatement(parent2, child, childStartLine, sourceFile) { - if (parent2.kind === 242 /* IfStatement */ && parent2.elseStatement === child) { - const elseKeyword = findChildOfKind(parent2, 91 /* ElseKeyword */ , sourceFile); + if (parent2.kind === 245 /* IfStatement */ && parent2.elseStatement === child) { + const elseKeyword = findChildOfKind(parent2, 93 /* ElseKeyword */ , sourceFile); Debug.assert(elseKeyword !== void 0); const elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; return elseKeywordStartLine === childStartLine; @@ -134754,42 +137727,42 @@ ${options.prefix}` : "\n" : options.prefix } function getListByRange(start, end, node, sourceFile) { switch(node.kind){ - case 180 /* TypeReference */ : + case 183 /* TypeReference */ : return getList(node.typeArguments); - case 207 /* ObjectLiteralExpression */ : + case 210 /* ObjectLiteralExpression */ : return getList(node.properties); - case 206 /* ArrayLiteralExpression */ : + case 209 /* ArrayLiteralExpression */ : return getList(node.elements); - case 184 /* TypeLiteral */ : + case 187 /* TypeLiteral */ : return getList(node.members); - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 216 /* ArrowFunction */ : - case 171 /* MethodDeclaration */ : - case 170 /* MethodSignature */ : - case 176 /* CallSignature */ : - case 173 /* Constructor */ : - case 182 /* ConstructorType */ : - case 177 /* ConstructSignature */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 219 /* ArrowFunction */ : + case 174 /* MethodDeclaration */ : + case 173 /* MethodSignature */ : + case 179 /* CallSignature */ : + case 176 /* Constructor */ : + case 185 /* ConstructorType */ : + case 180 /* ConstructSignature */ : return getList(node.typeParameters) || getList(node.parameters); - case 174 /* GetAccessor */ : + case 177 /* GetAccessor */ : return getList(node.parameters); - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : - case 261 /* InterfaceDeclaration */ : - case 262 /* TypeAliasDeclaration */ : - case 348 /* JSDocTemplateTag */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 264 /* InterfaceDeclaration */ : + case 265 /* TypeAliasDeclaration */ : + case 352 /* JSDocTemplateTag */ : return getList(node.typeParameters); - case 211 /* NewExpression */ : - case 210 /* CallExpression */ : + case 214 /* NewExpression */ : + case 213 /* CallExpression */ : return getList(node.typeArguments) || getList(node.arguments); - case 258 /* VariableDeclarationList */ : + case 261 /* VariableDeclarationList */ : return getList(node.declarations); - case 272 /* NamedImports */ : - case 276 /* NamedExports */ : + case 275 /* NamedImports */ : + case 279 /* NamedExports */ : return getList(node.elements); - case 203 /* ObjectBindingPattern */ : - case 204 /* ArrayBindingPattern */ : + case 206 /* ObjectBindingPattern */ : + case 207 /* ArrayBindingPattern */ : return getList(node.elements); } function getList(list) { @@ -134811,7 +137784,7 @@ ${options.prefix}` : "\n" : options.prefix return findColumnForFirstNonWhitespaceCharacterInLine(sourceFile.getLineAndCharacterOfPosition(list.pos), sourceFile, options); } function getActualIndentationForListItem(node, sourceFile, options, listIndentsChild) { - if (node.parent && node.parent.kind === 258 /* VariableDeclarationList */ ) return -1 /* Unknown */ ; + if (node.parent && node.parent.kind === 261 /* VariableDeclarationList */ ) return -1 /* Unknown */ ; const containingList = getContainingList(node, sourceFile); if (containingList) { const index = containingList.indexOf(node); @@ -134828,7 +137801,7 @@ ${options.prefix}` : "\n" : options.prefix const node = list[index]; let lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile); for(let i = index - 1; i >= 0; i--){ - if (list[i].kind === 27 /* CommaToken */ ) continue; + if (list[i].kind === 28 /* CommaToken */ ) continue; const prevEndLine = sourceFile.getLineAndCharacterOfPosition(list[i].end).line; if (prevEndLine !== lineAndCharacter.line) return findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options); lineAndCharacter = getStartLineAndCharacterForNode(list[i], sourceFile); @@ -134862,89 +137835,90 @@ ${options.prefix}` : "\n" : options.prefix function nodeWillIndentChild(settings, parent2, child, sourceFile, indentByDefault) { const childKind = child ? child.kind : 0 /* Unknown */ ; switch(parent2.kind){ - case 241 /* ExpressionStatement */ : - case 260 /* ClassDeclaration */ : - case 228 /* ClassExpression */ : - case 261 /* InterfaceDeclaration */ : - case 263 /* EnumDeclaration */ : - case 262 /* TypeAliasDeclaration */ : - case 206 /* ArrayLiteralExpression */ : - case 238 /* Block */ : - case 265 /* ModuleBlock */ : - case 207 /* ObjectLiteralExpression */ : - case 184 /* TypeLiteral */ : - case 197 /* MappedType */ : - case 186 /* TupleType */ : - case 266 /* CaseBlock */ : - case 293 /* DefaultClause */ : - case 292 /* CaseClause */ : - case 214 /* ParenthesizedExpression */ : - case 208 /* PropertyAccessExpression */ : - case 210 /* CallExpression */ : - case 211 /* NewExpression */ : - case 240 /* VariableStatement */ : - case 274 /* ExportAssignment */ : - case 250 /* ReturnStatement */ : - case 224 /* ConditionalExpression */ : - case 204 /* ArrayBindingPattern */ : - case 203 /* ObjectBindingPattern */ : - case 283 /* JsxOpeningElement */ : - case 286 /* JsxOpeningFragment */ : - case 282 /* JsxSelfClosingElement */ : - case 291 /* JsxExpression */ : - case 170 /* MethodSignature */ : - case 176 /* CallSignature */ : - case 177 /* ConstructSignature */ : - case 166 /* Parameter */ : - case 181 /* FunctionType */ : - case 182 /* ConstructorType */ : - case 193 /* ParenthesizedType */ : - case 212 /* TaggedTemplateExpression */ : - case 220 /* AwaitExpression */ : - case 276 /* NamedExports */ : - case 272 /* NamedImports */ : - case 278 /* ExportSpecifier */ : - case 273 /* ImportSpecifier */ : - case 169 /* PropertyDeclaration */ : + case 244 /* ExpressionStatement */ : + case 263 /* ClassDeclaration */ : + case 231 /* ClassExpression */ : + case 264 /* InterfaceDeclaration */ : + case 266 /* EnumDeclaration */ : + case 265 /* TypeAliasDeclaration */ : + case 209 /* ArrayLiteralExpression */ : + case 241 /* Block */ : + case 268 /* ModuleBlock */ : + case 210 /* ObjectLiteralExpression */ : + case 187 /* TypeLiteral */ : + case 200 /* MappedType */ : + case 189 /* TupleType */ : + case 217 /* ParenthesizedExpression */ : + case 211 /* PropertyAccessExpression */ : + case 213 /* CallExpression */ : + case 214 /* NewExpression */ : + case 243 /* VariableStatement */ : + case 277 /* ExportAssignment */ : + case 253 /* ReturnStatement */ : + case 227 /* ConditionalExpression */ : + case 207 /* ArrayBindingPattern */ : + case 206 /* ObjectBindingPattern */ : + case 286 /* JsxOpeningElement */ : + case 289 /* JsxOpeningFragment */ : + case 285 /* JsxSelfClosingElement */ : + case 294 /* JsxExpression */ : + case 173 /* MethodSignature */ : + case 179 /* CallSignature */ : + case 180 /* ConstructSignature */ : + case 169 /* Parameter */ : + case 184 /* FunctionType */ : + case 185 /* ConstructorType */ : + case 196 /* ParenthesizedType */ : + case 215 /* TaggedTemplateExpression */ : + case 223 /* AwaitExpression */ : + case 279 /* NamedExports */ : + case 275 /* NamedImports */ : + case 281 /* ExportSpecifier */ : + case 276 /* ImportSpecifier */ : + case 172 /* PropertyDeclaration */ : + case 296 /* CaseClause */ : + case 297 /* DefaultClause */ : return true; - case 257 /* VariableDeclaration */ : - case 299 /* PropertyAssignment */ : - case 223 /* BinaryExpression */ : - if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 207 /* ObjectLiteralExpression */ ) return rangeIsOnOneLine(sourceFile, child); - if (parent2.kind === 223 /* BinaryExpression */ && sourceFile && child && childKind === 281 /* JsxElement */ ) { + case 269 /* CaseBlock */ : + return settings.indentSwitchCase ?? true; + case 260 /* VariableDeclaration */ : + case 303 /* PropertyAssignment */ : + case 226 /* BinaryExpression */ : + if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 210 /* ObjectLiteralExpression */ ) return rangeIsOnOneLine(sourceFile, child); + if (parent2.kind === 226 /* BinaryExpression */ && sourceFile && child && childKind === 284 /* JsxElement */ ) { const parentStartLine = sourceFile.getLineAndCharacterOfPosition(skipTrivia(sourceFile.text, parent2.pos)).line; const childStartLine = sourceFile.getLineAndCharacterOfPosition(skipTrivia(sourceFile.text, child.pos)).line; return parentStartLine !== childStartLine; } - if (parent2.kind !== 223 /* BinaryExpression */ ) return true; + if (parent2.kind !== 226 /* BinaryExpression */ ) return true; break; - case 243 /* DoStatement */ : - case 244 /* WhileStatement */ : - case 246 /* ForInStatement */ : - case 247 /* ForOfStatement */ : - case 245 /* ForStatement */ : - case 242 /* IfStatement */ : - case 259 /* FunctionDeclaration */ : - case 215 /* FunctionExpression */ : - case 171 /* MethodDeclaration */ : - case 173 /* Constructor */ : - case 174 /* GetAccessor */ : - case 175 /* SetAccessor */ : - return childKind !== 238 /* Block */ ; - case 216 /* ArrowFunction */ : - if (sourceFile && childKind === 214 /* ParenthesizedExpression */ ) return rangeIsOnOneLine(sourceFile, child); - return childKind !== 238 /* Block */ ; - case 275 /* ExportDeclaration */ : - return childKind !== 276 /* NamedExports */ ; - case 269 /* ImportDeclaration */ : - return childKind !== 270 /* ImportClause */ || !!child.namedBindings && child.namedBindings.kind !== 272 /* NamedImports */ ; - case 281 /* JsxElement */ : - return childKind !== 284 /* JsxClosingElement */ ; - case 285 /* JsxFragment */ : - return childKind !== 287 /* JsxClosingFragment */ ; - case 190 /* IntersectionType */ : - case 189 /* UnionType */ : - if (childKind === 184 /* TypeLiteral */ || childKind === 186 /* TupleType */ ) return false; + case 246 /* DoStatement */ : + case 247 /* WhileStatement */ : + case 249 /* ForInStatement */ : + case 250 /* ForOfStatement */ : + case 248 /* ForStatement */ : + case 245 /* IfStatement */ : + case 262 /* FunctionDeclaration */ : + case 218 /* FunctionExpression */ : + case 174 /* MethodDeclaration */ : + case 176 /* Constructor */ : + case 177 /* GetAccessor */ : + case 178 /* SetAccessor */ : + return childKind !== 241 /* Block */ ; + case 219 /* ArrowFunction */ : + if (sourceFile && childKind === 217 /* ParenthesizedExpression */ ) return rangeIsOnOneLine(sourceFile, child); + return childKind !== 241 /* Block */ ; + case 278 /* ExportDeclaration */ : + return childKind !== 279 /* NamedExports */ ; + case 272 /* ImportDeclaration */ : + return childKind !== 273 /* ImportClause */ || !!child.namedBindings && child.namedBindings.kind !== 275 /* NamedImports */ ; + case 284 /* JsxElement */ : + return childKind !== 287 /* JsxClosingElement */ ; + case 288 /* JsxFragment */ : + return childKind !== 290 /* JsxClosingFragment */ ; + case 193 /* IntersectionType */ : + case 192 /* UnionType */ : + if (childKind === 187 /* TypeLiteral */ || childKind === 189 /* TupleType */ ) return false; break; } return indentByDefault; @@ -134952,11 +137926,11 @@ ${options.prefix}` : "\n" : options.prefix SmartIndenter2.nodeWillIndentChild = nodeWillIndentChild; function isControlFlowEndingStatement(kind, parent2) { switch(kind){ - case 250 /* ReturnStatement */ : - case 254 /* ThrowStatement */ : - case 248 /* ContinueStatement */ : - case 249 /* BreakStatement */ : - return parent2.kind !== 238 /* Block */ ; + case 253 /* ReturnStatement */ : + case 257 /* ThrowStatement */ : + case 251 /* ContinueStatement */ : + case 252 /* BreakStatement */ : + return parent2.kind !== 241 /* Block */ ; default: return false; } @@ -135054,13 +138028,13 @@ ${options.prefix}` : "\n" : options.prefix }); // src/deprecatedCompat/deprecate.ts function getTypeScriptVersion() { - return typeScriptVersion2 != null ? typeScriptVersion2 : typeScriptVersion2 = new Version(version); + return typeScriptVersion2 ?? (typeScriptVersion2 = new Version(version)); } - function formatDeprecationMessage(name, error, errorAfter, since, message) { - let deprecationMessage = error ? "DeprecationError: " : "DeprecationWarning: "; + function formatDeprecationMessage(name, error2, errorAfter, since, message) { + let deprecationMessage = error2 ? "DeprecationError: " : "DeprecationWarning: "; deprecationMessage += `'${name}' `; deprecationMessage += since ? `has been deprecated since v${since}` : "is deprecated"; - deprecationMessage += error ? " and can no longer be used." : errorAfter ? ` and will no longer be usable after v${errorAfter}.` : "."; + deprecationMessage += error2 ? " and can no longer be used." : errorAfter ? ` and will no longer be usable after v${errorAfter}.` : "."; deprecationMessage += message ? ` ${formatStringFromArgs(message, [ name ], 0)}` : ""; @@ -135082,14 +138056,13 @@ ${options.prefix}` : "\n" : options.prefix }; } function createDeprecation(name, options = {}) { - var _a2, _b; - const version2 = typeof options.typeScriptVersion === "string" ? new Version(options.typeScriptVersion) : (_a2 = options.typeScriptVersion) != null ? _a2 : getTypeScriptVersion(); + const version2 = typeof options.typeScriptVersion === "string" ? new Version(options.typeScriptVersion) : options.typeScriptVersion ?? getTypeScriptVersion(); const errorAfter = typeof options.errorAfter === "string" ? new Version(options.errorAfter) : options.errorAfter; const warnAfter = typeof options.warnAfter === "string" ? new Version(options.warnAfter) : options.warnAfter; - const since = typeof options.since === "string" ? new Version(options.since) : (_b = options.since) != null ? _b : warnAfter; - const error = options.error || errorAfter && version2.compareTo(errorAfter) >= 0; + const since = typeof options.since === "string" ? new Version(options.since) : options.since ?? warnAfter; + const error2 = options.error || errorAfter && version2.compareTo(errorAfter) >= 0; const warn = !warnAfter || version2.compareTo(warnAfter) >= 0; - return error ? createErrorDeprecation(name, errorAfter, since, options.message) : warn ? createWarningDeprecation(name, errorAfter, since, options.message) : noop; + return error2 ? createErrorDeprecation(name, errorAfter, since, options.message) : warn ? createWarningDeprecation(name, errorAfter, since, options.message) : noop; } function wrapFunction(deprecation, func) { return function() { @@ -135098,8 +138071,7 @@ ${options.prefix}` : "\n" : options.prefix }; } function deprecate(func, options) { - var _a2; - const deprecation = createDeprecation((_a2 = options == null ? void 0 : options.name) != null ? _a2 : Debug.getFunctionName(func), options); + const deprecation = createDeprecation((options == null ? void 0 : options.name) ?? Debug.getFunctionName(func), options); return wrapFunction(deprecation, func); } var enableDeprecationWarnings, typeScriptVersion2; @@ -135166,8 +138138,8 @@ ${options.prefix}` : "\n" : options.prefix init_ts5(); init_deprecate(); addObjectAllocatorPatcher((objectAllocator2)=>{ - const Identifier73 = objectAllocator2.getIdentifierConstructor(); - if (!hasProperty(Identifier73.prototype, "originalKeywordKind")) Object.defineProperty(Identifier73.prototype, "originalKeywordKind", { + const Identifier78 = objectAllocator2.getIdentifierConstructor(); + if (!hasProperty(Identifier78.prototype, "originalKeywordKind")) Object.defineProperty(Identifier78.prototype, "originalKeywordKind", { get: deprecate(function() { return identifierToKeywordKind(this); }, { @@ -135178,9 +138150,9 @@ ${options.prefix}` : "\n" : options.prefix message: "Use 'identifierToKeywordKind(identifier)' instead." }) }); - if (!hasProperty(Identifier73.prototype, "isInJSDocNamespace")) Object.defineProperty(Identifier73.prototype, "isInJSDocNamespace", { + if (!hasProperty(Identifier78.prototype, "isInJSDocNamespace")) Object.defineProperty(Identifier78.prototype, "isInJSDocNamespace", { get: deprecate(function() { - return this.flags & 2048 /* IdentifierIsInJSDocNamespace */ ? true : void 0; + return this.flags & 4096 /* IdentifierIsInJSDocNamespace */ ? true : void 0; }, { name: "isInJSDocNamespace", since: "5.0", @@ -135202,8 +138174,8 @@ ${options.prefix}` : "\n" : options.prefix } }); // src/typescript/_namespaces/ts.ts - var ts_exports3 = {}; - __export(ts_exports3, { + var ts_exports2 = {}; + __export(ts_exports2, { ANONYMOUS: ()=>ANONYMOUS, AccessFlags: ()=>AccessFlags, AssertionLevel: ()=>AssertionLevel, @@ -135227,6 +138199,7 @@ ${options.prefix}` : "\n" : options.prefix CompletionTriggerKind: ()=>CompletionTriggerKind, Completions: ()=>ts_Completions_exports, ConfigFileProgramReloadLevel: ()=>ConfigFileProgramReloadLevel, + ContainerFlags: ()=>ContainerFlags, ContextFlags: ()=>ContextFlags, CoreServicesShimHostAdapter: ()=>CoreServicesShimHostAdapter, Debug: ()=>Debug, @@ -135256,9 +138229,12 @@ ${options.prefix}` : "\n" : options.prefix GetLiteralTextFlags: ()=>GetLiteralTextFlags, GoToDefinition: ()=>ts_GoToDefinition_exports, HighlightSpanKind: ()=>HighlightSpanKind, + IdentifierNameMap: ()=>IdentifierNameMap, + IdentifierNameMultiMap: ()=>IdentifierNameMultiMap, ImportKind: ()=>ImportKind, ImportsNotUsedAsValues: ()=>ImportsNotUsedAsValues, IndentStyle: ()=>IndentStyle, + IndexFlags: ()=>IndexFlags, IndexKind: ()=>IndexKind, InferenceFlags: ()=>InferenceFlags, InferencePriority: ()=>InferencePriority, @@ -135359,6 +138335,7 @@ ${options.prefix}` : "\n" : options.prefix WatchLogLevel: ()=>WatchLogLevel, WatchType: ()=>WatchType, accessPrivateIdentifier: ()=>accessPrivateIdentifier, + addDisposableResourceHelper: ()=>addDisposableResourceHelper, addEmitFlags: ()=>addEmitFlags, addEmitHelper: ()=>addEmitHelper, addEmitHelpers: ()=>addEmitHelpers, @@ -135424,6 +138401,8 @@ ${options.prefix}` : "\n" : options.prefix canJsonReportNoInputFiles: ()=>canJsonReportNoInputFiles, canProduceDiagnostics: ()=>canProduceDiagnostics, canUsePropertyAccess: ()=>canUsePropertyAccess, + canWatchAffectingLocation: ()=>canWatchAffectingLocation, + canWatchAtTypes: ()=>canWatchAtTypes, canWatchDirectoryOrFile: ()=>canWatchDirectoryOrFile, cartesianProduct: ()=>cartesianProduct, cast: ()=>cast, @@ -135436,6 +138415,9 @@ ${options.prefix}` : "\n" : options.prefix changesAffectingProgramStructure: ()=>changesAffectingProgramStructure, childIsDecorated: ()=>childIsDecorated, classElementOrClassElementParameterIsDecorated: ()=>classElementOrClassElementParameterIsDecorated, + classHasClassThisAssignment: ()=>classHasClassThisAssignment, + classHasDeclaredOrExplicitlyAssignedName: ()=>classHasDeclaredOrExplicitlyAssignedName, + classHasExplicitlyAssignedName: ()=>classHasExplicitlyAssignedName, classOrConstructorParameterIsDecorated: ()=>classOrConstructorParameterIsDecorated, classPrivateFieldGetHelper: ()=>classPrivateFieldGetHelper, classPrivateFieldInHelper: ()=>classPrivateFieldInHelper, @@ -135505,8 +138487,8 @@ ${options.prefix}` : "\n" : options.prefix convertCompilerOptionsFromJson: ()=>convertCompilerOptionsFromJson, convertJsonOption: ()=>convertJsonOption, convertToBase64: ()=>convertToBase64, + convertToJson: ()=>convertToJson, convertToObject: ()=>convertToObject, - convertToObjectWorker: ()=>convertToObjectWorker, convertToOptionsWithAbsolutePaths: ()=>convertToOptionsWithAbsolutePaths, convertToRelativePath: ()=>convertToRelativePath, convertToTSConfig: ()=>convertToTSConfig, @@ -135533,6 +138515,8 @@ ${options.prefix}` : "\n" : options.prefix createCacheWithRedirects: ()=>createCacheWithRedirects, createCacheableExportInfoMap: ()=>createCacheableExportInfoMap, createCachedDirectoryStructureHost: ()=>createCachedDirectoryStructureHost, + createClassNamedEvaluationHelperBlock: ()=>createClassNamedEvaluationHelperBlock, + createClassThisAssignmentBlock: ()=>createClassThisAssignmentBlock, createClassifier: ()=>createClassifier, createCommentDirectivesMap: ()=>createCommentDirectivesMap, createCompilerDiagnostic: ()=>createCompilerDiagnostic, @@ -135583,6 +138567,7 @@ ${options.prefix}` : "\n" : options.prefix createMemberAccessForPropertyName: ()=>createMemberAccessForPropertyName, createModeAwareCache: ()=>createModeAwareCache, createModeAwareCacheKey: ()=>createModeAwareCacheKey, + createModuleNotFoundChain: ()=>createModuleNotFoundChain, createModuleResolutionCache: ()=>createModuleResolutionCache, createModuleResolutionLoader: ()=>createModuleResolutionLoader, createModuleSpecifierResolutionHost: ()=>createModuleSpecifierResolutionHost, @@ -135639,7 +138624,6 @@ ${options.prefix}` : "\n" : options.prefix createTypeChecker: ()=>createTypeChecker, createTypeReferenceDirectiveResolutionCache: ()=>createTypeReferenceDirectiveResolutionCache, createTypeReferenceResolutionLoader: ()=>createTypeReferenceResolutionLoader, - createUnderscoreEscapedMultiMap: ()=>createUnderscoreEscapedMultiMap, createUnparsedSourceFile: ()=>createUnparsedSourceFile, createWatchCompilerHost: ()=>createWatchCompilerHost2, createWatchCompilerHostOfConfigFile: ()=>createWatchCompilerHostOfConfigFile, @@ -135665,6 +138649,7 @@ ${options.prefix}` : "\n" : options.prefix displayPart: ()=>displayPart, displayPartsToString: ()=>displayPartsToString, disposeEmitNodes: ()=>disposeEmitNodes, + disposeResourcesHelper: ()=>disposeResourcesHelper, documentSpansEqual: ()=>documentSpansEqual, dumpTracingLegend: ()=>dumpTracingLegend, elementAt: ()=>elementAt, @@ -135712,11 +138697,13 @@ ${options.prefix}` : "\n" : options.prefix extendsHelper: ()=>extendsHelper, extensionFromPath: ()=>extensionFromPath, extensionIsTS: ()=>extensionIsTS, + extensionsNotSupportingExtensionlessResolution: ()=>extensionsNotSupportingExtensionlessResolution, externalHelpersModuleNameText: ()=>externalHelpersModuleNameText, factory: ()=>factory, fileExtensionIs: ()=>fileExtensionIs, fileExtensionIsOneOf: ()=>fileExtensionIsOneOf, fileIncludeReasonToDiagnostics: ()=>fileIncludeReasonToDiagnostics, + fileShouldUseJavaScriptRequire: ()=>fileShouldUseJavaScriptRequire, filter: ()=>filter, filterMutate: ()=>filterMutate, filterSemanticDiagnostics: ()=>filterSemanticDiagnostics, @@ -135740,7 +138727,7 @@ ${options.prefix}` : "\n" : options.prefix findPackageJsons: ()=>findPackageJsons, findPrecedingMatchingToken: ()=>findPrecedingMatchingToken, findPrecedingToken: ()=>findPrecedingToken, - findSuperStatementIndex: ()=>findSuperStatementIndex, + findSuperStatementIndexPath: ()=>findSuperStatementIndexPath, findTokenOnLeftOfPosition: ()=>findTokenOnLeftOfPosition, findUseStrictPrologue: ()=>findUseStrictPrologue, first: ()=>first, @@ -135772,10 +138759,12 @@ ${options.prefix}` : "\n" : options.prefix forEachKey: ()=>forEachKey, forEachLeadingCommentRange: ()=>forEachLeadingCommentRange, forEachNameInAccessChainWalkingLeft: ()=>forEachNameInAccessChainWalkingLeft, + forEachPropertyAssignment: ()=>forEachPropertyAssignment, forEachResolvedProjectReference: ()=>forEachResolvedProjectReference, forEachReturnStatement: ()=>forEachReturnStatement, forEachRight: ()=>forEachRight, forEachTrailingCommentRange: ()=>forEachTrailingCommentRange, + forEachTsConfigPropArray: ()=>forEachTsConfigPropArray, forEachUnique: ()=>forEachUnique, forEachYieldExpression: ()=>forEachYieldExpression, forSomeAncestorDirectory: ()=>forSomeAncestorDirectory, @@ -135813,6 +138802,7 @@ ${options.prefix}` : "\n" : options.prefix getAreDeclarationMapsEnabled: ()=>getAreDeclarationMapsEnabled, getAssignedExpandoInitializer: ()=>getAssignedExpandoInitializer, getAssignedName: ()=>getAssignedName, + getAssignedNameOfIdentifier: ()=>getAssignedNameOfIdentifier, getAssignmentDeclarationKind: ()=>getAssignmentDeclarationKind, getAssignmentDeclarationPropertyAccessKind: ()=>getAssignmentDeclarationPropertyAccessKind, getAssignmentTargetKind: ()=>getAssignmentTargetKind, @@ -135840,8 +138830,10 @@ ${options.prefix}` : "\n" : options.prefix getConditions: ()=>getConditions, getConfigFileParsingDiagnostics: ()=>getConfigFileParsingDiagnostics, getConstantValue: ()=>getConstantValue, + getContainerFlags: ()=>getContainerFlags, getContainerNode: ()=>getContainerNode, getContainingClass: ()=>getContainingClass, + getContainingClassExcludingClassDecorators: ()=>getContainingClassExcludingClassDecorators, getContainingClassStaticBlock: ()=>getContainingClassStaticBlock, getContainingFunction: ()=>getContainingFunction, getContainingFunctionDeclaration: ()=>getContainingFunctionDeclaration, @@ -135870,6 +138862,8 @@ ${options.prefix}` : "\n" : options.prefix getDiagnosticText: ()=>getDiagnosticText, getDiagnosticsWithinSpan: ()=>getDiagnosticsWithinSpan, getDirectoryPath: ()=>getDirectoryPath, + getDirectoryToWatchFailedLookupLocation: ()=>getDirectoryToWatchFailedLookupLocation, + getDirectoryToWatchFailedLookupLocationFromTypeRoot: ()=>getDirectoryToWatchFailedLookupLocationFromTypeRoot, getDocumentPositionMapper: ()=>getDocumentPositionMapper, getESModuleInterop: ()=>getESModuleInterop, getEditsForFileRename: ()=>getEditsForFileRename, @@ -135897,7 +138891,9 @@ ${options.prefix}` : "\n" : options.prefix getEmitModuleKind: ()=>getEmitModuleKind, getEmitModuleResolutionKind: ()=>getEmitModuleResolutionKind, getEmitScriptTarget: ()=>getEmitScriptTarget, + getEmitStandardClassFields: ()=>getEmitStandardClassFields, getEnclosingBlockScopeContainer: ()=>getEnclosingBlockScopeContainer, + getEnclosingContainer: ()=>getEnclosingContainer, getEncodedSemanticClassifications: ()=>getEncodedSemanticClassifications, getEncodedSyntacticClassifications: ()=>getEncodedSyntacticClassifications, getEndLinePosition: ()=>getEndLinePosition, @@ -135907,6 +138903,8 @@ ${options.prefix}` : "\n" : options.prefix getErrorSpanForNode: ()=>getErrorSpanForNode, getErrorSummaryText: ()=>getErrorSummaryText, getEscapedTextOfIdentifierOrLiteral: ()=>getEscapedTextOfIdentifierOrLiteral, + getEscapedTextOfJsxAttributeName: ()=>getEscapedTextOfJsxAttributeName, + getEscapedTextOfJsxNamespacedName: ()=>getEscapedTextOfJsxNamespacedName, getExpandoInitializer: ()=>getExpandoInitializer, getExportAssignmentExpression: ()=>getExportAssignmentExpression, getExportInfoMap: ()=>getExportInfoMap, @@ -135946,6 +138944,7 @@ ${options.prefix}` : "\n" : options.prefix getImportNeedsImportStarHelper: ()=>getImportNeedsImportStarHelper, getIndentSize: ()=>getIndentSize, getIndentString: ()=>getIndentString, + getInferredLibraryNameResolveFrom: ()=>getInferredLibraryNameResolveFrom, getInitializedVariables: ()=>getInitializedVariables, getInitializerOfBinaryExpression: ()=>getInitializerOfBinaryExpression, getInitializerOfBindingOrAssignmentElement: ()=>getInitializerOfBindingOrAssignmentElement, @@ -136066,6 +139065,7 @@ ${options.prefix}` : "\n" : options.prefix getOperatorAssociativity: ()=>getOperatorAssociativity, getOperatorPrecedence: ()=>getOperatorPrecedence, getOptionFromName: ()=>getOptionFromName, + getOptionsForLibraryResolution: ()=>getOptionsForLibraryResolution, getOptionsNameMap: ()=>getOptionsNameMap, getOrCreateEmitNode: ()=>getOrCreateEmitNode, getOrCreateExternalHelpersModuleNameIfNeeded: ()=>getOrCreateExternalHelpersModuleNameIfNeeded, @@ -136108,10 +139108,10 @@ ${options.prefix}` : "\n" : options.prefix getProperties: ()=>getProperties, getProperty: ()=>getProperty, getPropertyArrayElementValue: ()=>getPropertyArrayElementValue, - getPropertyAssignment: ()=>getPropertyAssignment, getPropertyAssignmentAliasLikeExpression: ()=>getPropertyAssignmentAliasLikeExpression, getPropertyNameForPropertyNameNode: ()=>getPropertyNameForPropertyNameNode, getPropertyNameForUniqueESSymbol: ()=>getPropertyNameForUniqueESSymbol, + getPropertyNameFromType: ()=>getPropertyNameFromType, getPropertyNameOfBindingOrAssignmentElement: ()=>getPropertyNameOfBindingOrAssignmentElement, getPropertySymbolFromBindingElement: ()=>getPropertySymbolFromBindingElement, getPropertySymbolsFromContextualType: ()=>getPropertySymbolsFromContextualType, @@ -136140,7 +139140,9 @@ ${options.prefix}` : "\n" : options.prefix getRestParameterElementType: ()=>getRestParameterElementType, getRightMostAssignedExpression: ()=>getRightMostAssignedExpression, getRootDeclaration: ()=>getRootDeclaration, + getRootDirectoryOfResolutionCache: ()=>getRootDirectoryOfResolutionCache, getRootLength: ()=>getRootLength, + getRootPathSplitLength: ()=>getRootPathSplitLength, getScriptKind: ()=>getScriptKind, getScriptKindFromFileName: ()=>getScriptKindFromFileName, getScriptTargetFeatures: ()=>getScriptTargetFeatures, @@ -136197,6 +139199,8 @@ ${options.prefix}` : "\n" : options.prefix getTextOfConstantValue: ()=>getTextOfConstantValue, getTextOfIdentifierOrLiteral: ()=>getTextOfIdentifierOrLiteral, getTextOfJSDocComment: ()=>getTextOfJSDocComment, + getTextOfJsxAttributeName: ()=>getTextOfJsxAttributeName, + getTextOfJsxNamespacedName: ()=>getTextOfJsxNamespacedName, getTextOfNode: ()=>getTextOfNode, getTextOfNodeFromSourceText: ()=>getTextOfNodeFromSourceText, getTextOfPropertyName: ()=>getTextOfPropertyName, @@ -136213,7 +139217,6 @@ ${options.prefix}` : "\n" : options.prefix getTransformers: ()=>getTransformers, getTsBuildInfoEmitOutputFilePath: ()=>getTsBuildInfoEmitOutputFilePath, getTsConfigObjectLiteralExpression: ()=>getTsConfigObjectLiteralExpression, - getTsConfigPropArray: ()=>getTsConfigPropArray, getTsConfigPropArrayElementValue: ()=>getTsConfigPropArrayElementValue, getTypeAnnotationNode: ()=>getTypeAnnotationNode, getTypeArgumentOrTypeParameterList: ()=>getTypeArgumentOrTypeParameterList, @@ -136289,6 +139292,8 @@ ${options.prefix}` : "\n" : options.prefix indexOfNode: ()=>indexOfNode, indicesOf: ()=>indicesOf, inferredTypesContainingFile: ()=>inferredTypesContainingFile, + injectClassNamedEvaluationHelperBlockIfMissing: ()=>injectClassNamedEvaluationHelperBlockIfMissing, + injectClassThisAssignmentIfMissing: ()=>injectClassThisAssignmentIfMissing, insertImports: ()=>insertImports, insertLeadingStatement: ()=>insertLeadingStatement, insertSorted: ()=>insertSorted, @@ -136297,6 +139302,7 @@ ${options.prefix}` : "\n" : options.prefix insertStatementsAfterCustomPrologue: ()=>insertStatementsAfterCustomPrologue, insertStatementsAfterStandardPrologue: ()=>insertStatementsAfterStandardPrologue, intersperse: ()=>intersperse, + intrinsicTagNameToString: ()=>intrinsicTagNameToString, introducesArgumentsExoticObject: ()=>introducesArgumentsExoticObject, inverseJsxOptionMap: ()=>inverseJsxOptionMap, isAbstractConstructorSymbol: ()=>isAbstractConstructorSymbol, @@ -136390,8 +139396,10 @@ ${options.prefix}` : "\n" : options.prefix isClassExpression: ()=>isClassExpression, isClassLike: ()=>isClassLike, isClassMemberModifier: ()=>isClassMemberModifier, + isClassNamedEvaluationHelperBlock: ()=>isClassNamedEvaluationHelperBlock, isClassOrTypeElement: ()=>isClassOrTypeElement, isClassStaticBlockDeclaration: ()=>isClassStaticBlockDeclaration, + isClassThisAssignmentBlock: ()=>isClassThisAssignmentBlock, isCollapsedRange: ()=>isCollapsedRange, isColonToken: ()=>isColonToken, isCommaExpression: ()=>isCommaExpression, @@ -136437,6 +139445,7 @@ ${options.prefix}` : "\n" : options.prefix isDiagnosticWithLocation: ()=>isDiagnosticWithLocation, isDiskPathRoot: ()=>isDiskPathRoot, isDoStatement: ()=>isDoStatement, + isDocumentRegistryEntry: ()=>isDocumentRegistryEntry, isDotDotDotToken: ()=>isDotDotDotToken, isDottedName: ()=>isDottedName, isDynamicName: ()=>isDynamicName, @@ -136453,7 +139462,6 @@ ${options.prefix}` : "\n" : options.prefix isEmptyObjectLiteral: ()=>isEmptyObjectLiteral, isEmptyStatement: ()=>isEmptyStatement, isEmptyStringLiteral: ()=>isEmptyStringLiteral, - isEndOfDeclarationMarker: ()=>isEndOfDeclarationMarker, isEntityName: ()=>isEntityName, isEntityNameExpression: ()=>isEntityNameExpression, isEnumConst: ()=>isEnumConst, @@ -136488,6 +139496,7 @@ ${options.prefix}` : "\n" : options.prefix isExternalModuleReference: ()=>isExternalModuleReference, isExternalModuleSymbol: ()=>isExternalModuleSymbol, isExternalOrCommonJsModule: ()=>isExternalOrCommonJsModule, + isFileLevelReservedGeneratedIdentifier: ()=>isFileLevelReservedGeneratedIdentifier, isFileLevelUniqueName: ()=>isFileLevelUniqueName, isFileProbablyExternalModule: ()=>isFileProbablyExternalModule, isFirstDeclarationOfSymbolParameter: ()=>isFirstDeclarationOfSymbolParameter, @@ -136558,6 +139567,7 @@ ${options.prefix}` : "\n" : options.prefix isInString: ()=>isInString, isInTemplateString: ()=>isInTemplateString, isInTopLevelContext: ()=>isInTopLevelContext, + isInTypeQuery: ()=>isInTypeQuery, isIncrementalCompilation: ()=>isIncrementalCompilation, isIndexSignatureDeclaration: ()=>isIndexSignatureDeclaration, isIndexedAccessTypeNode: ()=>isIndexedAccessTypeNode, @@ -136636,6 +139646,7 @@ ${options.prefix}` : "\n" : options.prefix isJsonSourceFile: ()=>isJsonSourceFile, isJsxAttribute: ()=>isJsxAttribute, isJsxAttributeLike: ()=>isJsxAttributeLike, + isJsxAttributeName: ()=>isJsxAttributeName, isJsxAttributes: ()=>isJsxAttributes, isJsxChild: ()=>isJsxChild, isJsxClosingElement: ()=>isJsxClosingElement, @@ -136643,6 +139654,7 @@ ${options.prefix}` : "\n" : options.prefix isJsxElement: ()=>isJsxElement, isJsxExpression: ()=>isJsxExpression, isJsxFragment: ()=>isJsxFragment, + isJsxNamespacedName: ()=>isJsxNamespacedName, isJsxOpeningElement: ()=>isJsxOpeningElement, isJsxOpeningFragment: ()=>isJsxOpeningFragment, isJsxOpeningLikeElement: ()=>isJsxOpeningLikeElement, @@ -136653,6 +139665,7 @@ ${options.prefix}` : "\n" : options.prefix isJsxText: ()=>isJsxText, isJumpStatementTarget: ()=>isJumpStatementTarget, isKeyword: ()=>isKeyword, + isKeywordOrPunctuation: ()=>isKeywordOrPunctuation, isKnownSymbol: ()=>isKnownSymbol, isLabelName: ()=>isLabelName, isLabelOfLabeledStatement: ()=>isLabelOfLabeledStatement, @@ -136681,7 +139694,6 @@ ${options.prefix}` : "\n" : options.prefix isLogicalOrCoalescingBinaryOperator: ()=>isLogicalOrCoalescingBinaryOperator, isMappedTypeNode: ()=>isMappedTypeNode, isMemberName: ()=>isMemberName, - isMergeDeclarationMarker: ()=>isMergeDeclarationMarker, isMetaProperty: ()=>isMetaProperty, isMethodDeclaration: ()=>isMethodDeclaration, isMethodOrAccessor: ()=>isMethodOrAccessor, @@ -136933,6 +139945,7 @@ ${options.prefix}` : "\n" : options.prefix isTypeQueryNode: ()=>isTypeQueryNode, isTypeReferenceNode: ()=>isTypeReferenceNode, isTypeReferenceType: ()=>isTypeReferenceType, + isTypeUsableAsPropertyName: ()=>isTypeUsableAsPropertyName, isUMDExportSymbol: ()=>isUMDExportSymbol, isUnaryExpression: ()=>isUnaryExpression, isUnaryExpressionWithWrite: ()=>isUnaryExpressionWithWrite, @@ -136947,7 +139960,9 @@ ${options.prefix}` : "\n" : options.prefix isValidESSymbolDeclaration: ()=>isValidESSymbolDeclaration, isValidTypeOnlyAliasUseSite: ()=>isValidTypeOnlyAliasUseSite, isValueSignatureDeclaration: ()=>isValueSignatureDeclaration, + isVarAwaitUsing: ()=>isVarAwaitUsing, isVarConst: ()=>isVarConst, + isVarUsing: ()=>isVarUsing, isVariableDeclaration: ()=>isVariableDeclaration, isVariableDeclarationInVariableStatement: ()=>isVariableDeclarationInVariableStatement, isVariableDeclarationInitializedToBareOrAccessedRequire: ()=>isVariableDeclarationInitializedToBareOrAccessedRequire, @@ -137049,7 +140064,6 @@ ${options.prefix}` : "\n" : options.prefix nodeToDisplayParts: ()=>nodeToDisplayParts, noop: ()=>noop, noopFileWatcher: ()=>noopFileWatcher, - noopPush: ()=>noopPush, normalizePath: ()=>normalizePath, normalizeSlashes: ()=>normalizeSlashes, not: ()=>not, @@ -137172,6 +140186,7 @@ ${options.prefix}` : "\n" : options.prefix resolutionExtensionIsTSOrJson: ()=>resolutionExtensionIsTSOrJson, resolveConfigFileProjectName: ()=>resolveConfigFileProjectName, resolveJSModule: ()=>resolveJSModule, + resolveLibrary: ()=>resolveLibrary, resolveModuleName: ()=>resolveModuleName, resolveModuleNameFromCache: ()=>resolveModuleNameFromCache, resolvePackageNameToPackageJson: ()=>resolvePackageNameToPackageJson, @@ -137359,6 +140374,7 @@ ${options.prefix}` : "\n" : options.prefix transformJsx: ()=>transformJsx, transformLegacyDecorators: ()=>transformLegacyDecorators, transformModule: ()=>transformModule, + transformNamedEvaluation: ()=>transformNamedEvaluation, transformNodeModule: ()=>transformNodeModule, transformNodes: ()=>transformNodes, transformSystemModule: ()=>transformSystemModule, @@ -137479,7 +140495,7 @@ ${options.prefix}` : "\n" : options.prefix } } }; - module2.exports = ts_exports3; + module2.exports = ts_exports2; } }); return require_typescript(); @@ -137489,7 +140505,7 @@ if (0, $1b3769ee38aa2ff9$exports) $1b3769ee38aa2ff9$exports = $1b3769ee38aa2ff9$ var $364920da4f638603$exports = {}; -$364920da4f638603$exports = JSON.parse('{"lib.d.ts":"/*! *****************************************************************************\\nCopyright (c) Microsoft Corporation. All rights reserved.\\nLicensed under the Apache License, Version 2.0 (the \\"License\\"); you may not use\\nthis file except in compliance with the License. You may obtain a copy of the\\nLicense at http://www.apache.org/licenses/LICENSE-2.0\\n\\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\\nMERCHANTABLITY OR NON-INFRINGEMENT.\\n\\nSee the Apache Version 2.0 License for specific language governing permissions\\nand limitations under the License.\\n***************************************************************************** */\\n\\n\\n/// \\n\\n/// \\n/// \\n/// \\n/// \\n","lib.decorators.d.ts":"/*! *****************************************************************************\\nCopyright (c) Microsoft Corporation. All rights reserved.\\nLicensed under the Apache License, Version 2.0 (the \\"License\\"); you may not use\\nthis file except in compliance with the License. You may obtain a copy of the\\nLicense at http://www.apache.org/licenses/LICENSE-2.0\\n\\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\\nMERCHANTABLITY OR NON-INFRINGEMENT.\\n\\nSee the Apache Version 2.0 License for specific language governing permissions\\nand limitations under the License.\\n***************************************************************************** */\\n\\n\\n/// \\n\\n/**\\n * The decorator context types provided to class element decorators.\\n */\\ntype ClassMemberDecoratorContext =\\n | ClassMethodDecoratorContext\\n | ClassGetterDecoratorContext\\n | ClassSetterDecoratorContext\\n | ClassFieldDecoratorContext\\n | ClassAccessorDecoratorContext\\n ;\\n\\n/**\\n * The decorator context types provided to any decorator.\\n */\\ntype DecoratorContext =\\n | ClassDecoratorContext\\n | ClassMemberDecoratorContext\\n ;\\n\\n/**\\n * Context provided to a class decorator.\\n * @template Class The type of the decorated class associated with this context.\\n */\\ninterface ClassDecoratorContext<\\n Class extends abstract new (...args: any) => any = abstract new (...args: any) => any,\\n> {\\n /** The kind of element that was decorated. */\\n readonly kind: \\"class\\";\\n\\n /** The name of the decorated class. */\\n readonly name: string | undefined;\\n\\n /**\\n * Adds a callback to be invoked after the class definition has been finalized.\\n *\\n * @example\\n * ```ts\\n * function customElement(name: string): ClassDecoratorFunction {\\n * return (target, context) => {\\n * context.addInitializer(function () {\\n * customElements.define(name, this);\\n * });\\n * }\\n * }\\n *\\n * @customElement(\\"my-element\\")\\n * class MyElement {}\\n * ```\\n */\\n addInitializer(initializer: (this: Class) => void): void;\\n}\\n\\n/**\\n * Context provided to a class method decorator.\\n * @template This The type on which the class element will be defined. For a static class element, this will be\\n * the type of the constructor. For a non-static class element, this will be the type of the instance.\\n * @template Value The type of the decorated class method.\\n */\\ninterface ClassMethodDecoratorContext<\\n This = unknown,\\n Value extends (this: This, ...args: any) => any = (this: This, ...args: any) => any,\\n> {\\n /** The kind of class element that was decorated. */\\n readonly kind: \\"method\\";\\n\\n /** The name of the decorated class element. */\\n readonly name: string | symbol;\\n\\n /** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */\\n readonly static: boolean;\\n\\n /** A value indicating whether the class element has a private name. */\\n readonly private: boolean;\\n\\n /** An object that can be used to access the current value of the class element at runtime. */\\n readonly access: {\\n /**\\n * Determines whether an object has a property with the same name as the decorated element.\\n */\\n has(object: This): boolean;\\n /**\\n * Gets the current value of the method from the provided object.\\n *\\n * @example\\n * let fn = context.access.get(instance);\\n */\\n get(object: This): Value;\\n };\\n\\n /**\\n * Adds a callback to be invoked either before static initializers are run (when\\n * decorating a `static` element), or before instance initializers are run (when\\n * decorating a non-`static` element).\\n *\\n * @example\\n * ```ts\\n * const bound: ClassMethodDecoratorFunction = (value, context) {\\n * if (context.private) throw new TypeError(\\"Not supported on private methods.\\");\\n * context.addInitializer(function () {\\n * this[context.name] = this[context.name].bind(this);\\n * });\\n * }\\n *\\n * class C {\\n * message = \\"Hello\\";\\n *\\n * @bound\\n * m() {\\n * console.log(this.message);\\n * }\\n * }\\n * ```\\n */\\n addInitializer(initializer: (this: This) => void): void;\\n}\\n\\n/**\\n * Context provided to a class getter decorator.\\n * @template This The type on which the class element will be defined. For a static class element, this will be\\n * the type of the constructor. For a non-static class element, this will be the type of the instance.\\n * @template Value The property type of the decorated class getter.\\n */\\ninterface ClassGetterDecoratorContext<\\n This = unknown,\\n Value = unknown,\\n> {\\n /** The kind of class element that was decorated. */\\n readonly kind: \\"getter\\";\\n\\n /** The name of the decorated class element. */\\n readonly name: string | symbol;\\n\\n /** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */\\n readonly static: boolean;\\n\\n /** A value indicating whether the class element has a private name. */\\n readonly private: boolean;\\n\\n /** An object that can be used to access the current value of the class element at runtime. */\\n readonly access: {\\n /**\\n * Determines whether an object has a property with the same name as the decorated element.\\n */\\n has(object: This): boolean;\\n /**\\n * Invokes the getter on the provided object.\\n *\\n * @example\\n * let value = context.access.get(instance);\\n */\\n get(object: This): Value;\\n };\\n\\n /**\\n * Adds a callback to be invoked either before static initializers are run (when\\n * decorating a `static` element), or before instance initializers are run (when\\n * decorating a non-`static` element).\\n */\\n addInitializer(initializer: (this: This) => void): void;\\n}\\n\\n/**\\n * Context provided to a class setter decorator.\\n * @template This The type on which the class element will be defined. For a static class element, this will be\\n * the type of the constructor. For a non-static class element, this will be the type of the instance.\\n * @template Value The type of the decorated class setter.\\n */\\ninterface ClassSetterDecoratorContext<\\n This = unknown,\\n Value = unknown,\\n> {\\n /** The kind of class element that was decorated. */\\n readonly kind: \\"setter\\";\\n\\n /** The name of the decorated class element. */\\n readonly name: string | symbol;\\n\\n /** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */\\n readonly static: boolean;\\n\\n /** A value indicating whether the class element has a private name. */\\n readonly private: boolean;\\n\\n /** An object that can be used to access the current value of the class element at runtime. */\\n readonly access: {\\n /**\\n * Determines whether an object has a property with the same name as the decorated element.\\n */\\n has(object: This): boolean;\\n /**\\n * Invokes the setter on the provided object.\\n *\\n * @example\\n * context.access.set(instance, value);\\n */\\n set(object: This, value: Value): void;\\n };\\n\\n /**\\n * Adds a callback to be invoked either before static initializers are run (when\\n * decorating a `static` element), or before instance initializers are run (when\\n * decorating a non-`static` element).\\n */\\n addInitializer(initializer: (this: This) => void): void;\\n}\\n\\n/**\\n * Context provided to a class `accessor` field decorator.\\n * @template This The type on which the class element will be defined. For a static class element, this will be\\n * the type of the constructor. For a non-static class element, this will be the type of the instance.\\n * @template Value The type of decorated class field.\\n */\\ninterface ClassAccessorDecoratorContext<\\n This = unknown,\\n Value = unknown,\\n> {\\n /** The kind of class element that was decorated. */\\n readonly kind: \\"accessor\\";\\n\\n /** The name of the decorated class element. */\\n readonly name: string | symbol;\\n\\n /** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */\\n readonly static: boolean;\\n\\n /** A value indicating whether the class element has a private name. */\\n readonly private: boolean;\\n\\n /** An object that can be used to access the current value of the class element at runtime. */\\n readonly access: {\\n /**\\n * Determines whether an object has a property with the same name as the decorated element.\\n */\\n has(object: This): boolean;\\n\\n /**\\n * Invokes the getter on the provided object.\\n *\\n * @example\\n * let value = context.access.get(instance);\\n */\\n get(object: This): Value;\\n\\n /**\\n * Invokes the setter on the provided object.\\n *\\n * @example\\n * context.access.set(instance, value);\\n */\\n set(object: This, value: Value): void;\\n };\\n\\n /**\\n * Adds a callback to be invoked either before static initializers are run (when\\n * decorating a `static` element), or before instance initializers are run (when\\n * decorating a non-`static` element).\\n */\\n addInitializer(initializer: (this: This) => void): void;\\n}\\n\\n/**\\n * Describes the target provided to class `accessor` field decorators.\\n * @template This The `this` type to which the target applies.\\n * @template Value The property type for the class `accessor` field.\\n */\\ninterface ClassAccessorDecoratorTarget {\\n /**\\n * Invokes the getter that was defined prior to decorator application.\\n *\\n * @example\\n * let value = target.get.call(instance);\\n */\\n get(this: This): Value;\\n\\n /**\\n * Invokes the setter that was defined prior to decorator application.\\n *\\n * @example\\n * target.set.call(instance, value);\\n */\\n set(this: This, value: Value): void;\\n}\\n\\n/**\\n * Describes the allowed return value from a class `accessor` field decorator.\\n * @template This The `this` type to which the target applies.\\n * @template Value The property type for the class `accessor` field.\\n */\\ninterface ClassAccessorDecoratorResult {\\n /**\\n * An optional replacement getter function. If not provided, the existing getter function is used instead.\\n */\\n get?(this: This): Value;\\n\\n /**\\n * An optional replacement setter function. If not provided, the existing setter function is used instead.\\n */\\n set?(this: This, value: Value): void;\\n\\n /**\\n * An optional initializer mutator that is invoked when the underlying field initializer is evaluated.\\n * @param value The incoming initializer value.\\n * @returns The replacement initializer value.\\n */\\n init?(this: This, value: Value): Value;\\n}\\n\\n/**\\n * Context provided to a class field decorator.\\n * @template This The type on which the class element will be defined. For a static class element, this will be\\n * the type of the constructor. For a non-static class element, this will be the type of the instance.\\n * @template Value The type of the decorated class field.\\n */\\ninterface ClassFieldDecoratorContext<\\n This = unknown,\\n Value = unknown,\\n> {\\n /** The kind of class element that was decorated. */\\n readonly kind: \\"field\\";\\n\\n /** The name of the decorated class element. */\\n readonly name: string | symbol;\\n\\n /** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */\\n readonly static: boolean;\\n\\n /** A value indicating whether the class element has a private name. */\\n readonly private: boolean;\\n\\n /** An object that can be used to access the current value of the class element at runtime. */\\n readonly access: {\\n /**\\n * Determines whether an object has a property with the same name as the decorated element.\\n */\\n has(object: This): boolean;\\n\\n /**\\n * Gets the value of the field on the provided object.\\n */\\n get(object: This): Value;\\n\\n /**\\n * Sets the value of the field on the provided object.\\n */\\n set(object: This, value: Value): void;\\n };\\n\\n /**\\n * Adds a callback to be invoked either before static initializers are run (when\\n * decorating a `static` element), or before instance initializers are run (when\\n * decorating a non-`static` element).\\n */\\n addInitializer(initializer: (this: This) => void): void;\\n}\\n","lib.decorators.legacy.d.ts":"/*! *****************************************************************************\\nCopyright (c) Microsoft Corporation. All rights reserved.\\nLicensed under the Apache License, Version 2.0 (the \\"License\\"); you may not use\\nthis file except in compliance with the License. You may obtain a copy of the\\nLicense at http://www.apache.org/licenses/LICENSE-2.0\\n\\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\\nMERCHANTABLITY OR NON-INFRINGEMENT.\\n\\nSee the Apache Version 2.0 License for specific language governing permissions\\nand limitations under the License.\\n***************************************************************************** */\\n\\n\\n/// \\n\\ndeclare type ClassDecorator = (target: TFunction) => TFunction | void;\\ndeclare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;\\ndeclare type MethodDecorator = (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void;\\ndeclare type ParameterDecorator = (target: Object, propertyKey: string | symbol | undefined, parameterIndex: number) => void;\\n","lib.dom.d.ts":"/*! *****************************************************************************\\nCopyright (c) Microsoft Corporation. All rights reserved.\\nLicensed under the Apache License, Version 2.0 (the \\"License\\"); you may not use\\nthis file except in compliance with the License. You may obtain a copy of the\\nLicense at http://www.apache.org/licenses/LICENSE-2.0\\n\\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\\nMERCHANTABLITY OR NON-INFRINGEMENT.\\n\\nSee the Apache Version 2.0 License for specific language governing permissions\\nand limitations under the License.\\n***************************************************************************** */\\n\\n\\n/// \\n\\n/////////////////////////////\\n/// Window APIs\\n/////////////////////////////\\n\\ninterface AddEventListenerOptions extends EventListenerOptions {\\n once?: boolean;\\n passive?: boolean;\\n signal?: AbortSignal;\\n}\\n\\ninterface AesCbcParams extends Algorithm {\\n iv: BufferSource;\\n}\\n\\ninterface AesCtrParams extends Algorithm {\\n counter: BufferSource;\\n length: number;\\n}\\n\\ninterface AesDerivedKeyParams extends Algorithm {\\n length: number;\\n}\\n\\ninterface AesGcmParams extends Algorithm {\\n additionalData?: BufferSource;\\n iv: BufferSource;\\n tagLength?: number;\\n}\\n\\ninterface AesKeyAlgorithm extends KeyAlgorithm {\\n length: number;\\n}\\n\\ninterface AesKeyGenParams extends Algorithm {\\n length: number;\\n}\\n\\ninterface Algorithm {\\n name: string;\\n}\\n\\ninterface AnalyserOptions extends AudioNodeOptions {\\n fftSize?: number;\\n maxDecibels?: number;\\n minDecibels?: number;\\n smoothingTimeConstant?: number;\\n}\\n\\ninterface AnimationEventInit extends EventInit {\\n animationName?: string;\\n elapsedTime?: number;\\n pseudoElement?: string;\\n}\\n\\ninterface AnimationPlaybackEventInit extends EventInit {\\n currentTime?: CSSNumberish | null;\\n timelineTime?: CSSNumberish | null;\\n}\\n\\ninterface AssignedNodesOptions {\\n flatten?: boolean;\\n}\\n\\ninterface AudioBufferOptions {\\n length: number;\\n numberOfChannels?: number;\\n sampleRate: number;\\n}\\n\\ninterface AudioBufferSourceOptions {\\n buffer?: AudioBuffer | null;\\n detune?: number;\\n loop?: boolean;\\n loopEnd?: number;\\n loopStart?: number;\\n playbackRate?: number;\\n}\\n\\ninterface AudioConfiguration {\\n bitrate?: number;\\n channels?: string;\\n contentType: string;\\n samplerate?: number;\\n spatialRendering?: boolean;\\n}\\n\\ninterface AudioContextOptions {\\n latencyHint?: AudioContextLatencyCategory | number;\\n sampleRate?: number;\\n}\\n\\ninterface AudioNodeOptions {\\n channelCount?: number;\\n channelCountMode?: ChannelCountMode;\\n channelInterpretation?: ChannelInterpretation;\\n}\\n\\ninterface AudioProcessingEventInit extends EventInit {\\n inputBuffer: AudioBuffer;\\n outputBuffer: AudioBuffer;\\n playbackTime: number;\\n}\\n\\ninterface AudioTimestamp {\\n contextTime?: number;\\n performanceTime?: DOMHighResTimeStamp;\\n}\\n\\ninterface AudioWorkletNodeOptions extends AudioNodeOptions {\\n numberOfInputs?: number;\\n numberOfOutputs?: number;\\n outputChannelCount?: number[];\\n parameterData?: Record;\\n processorOptions?: any;\\n}\\n\\ninterface AuthenticationExtensionsClientInputs {\\n appid?: string;\\n credProps?: boolean;\\n hmacCreateSecret?: boolean;\\n}\\n\\ninterface AuthenticationExtensionsClientOutputs {\\n appid?: boolean;\\n credProps?: CredentialPropertiesOutput;\\n hmacCreateSecret?: boolean;\\n}\\n\\ninterface AuthenticatorSelectionCriteria {\\n authenticatorAttachment?: AuthenticatorAttachment;\\n requireResidentKey?: boolean;\\n residentKey?: ResidentKeyRequirement;\\n userVerification?: UserVerificationRequirement;\\n}\\n\\ninterface BiquadFilterOptions extends AudioNodeOptions {\\n Q?: number;\\n detune?: number;\\n frequency?: number;\\n gain?: number;\\n type?: BiquadFilterType;\\n}\\n\\ninterface BlobEventInit {\\n data: Blob;\\n timecode?: DOMHighResTimeStamp;\\n}\\n\\ninterface BlobPropertyBag {\\n endings?: EndingType;\\n type?: string;\\n}\\n\\ninterface CSSStyleSheetInit {\\n baseURL?: string;\\n disabled?: boolean;\\n media?: MediaList | string;\\n}\\n\\ninterface CacheQueryOptions {\\n ignoreMethod?: boolean;\\n ignoreSearch?: boolean;\\n ignoreVary?: boolean;\\n}\\n\\ninterface CanvasRenderingContext2DSettings {\\n alpha?: boolean;\\n colorSpace?: PredefinedColorSpace;\\n desynchronized?: boolean;\\n willReadFrequently?: boolean;\\n}\\n\\ninterface ChannelMergerOptions extends AudioNodeOptions {\\n numberOfInputs?: number;\\n}\\n\\ninterface ChannelSplitterOptions extends AudioNodeOptions {\\n numberOfOutputs?: number;\\n}\\n\\ninterface CheckVisibilityOptions {\\n checkOpacity?: boolean;\\n checkVisibilityCSS?: boolean;\\n}\\n\\ninterface ClientQueryOptions {\\n includeUncontrolled?: boolean;\\n type?: ClientTypes;\\n}\\n\\ninterface ClipboardEventInit extends EventInit {\\n clipboardData?: DataTransfer | null;\\n}\\n\\ninterface ClipboardItemOptions {\\n presentationStyle?: PresentationStyle;\\n}\\n\\ninterface CloseEventInit extends EventInit {\\n code?: number;\\n reason?: string;\\n wasClean?: boolean;\\n}\\n\\ninterface CompositionEventInit extends UIEventInit {\\n data?: string;\\n}\\n\\ninterface ComputedEffectTiming extends EffectTiming {\\n activeDuration?: CSSNumberish;\\n currentIteration?: number | null;\\n endTime?: CSSNumberish;\\n localTime?: CSSNumberish | null;\\n progress?: number | null;\\n startTime?: CSSNumberish;\\n}\\n\\ninterface ComputedKeyframe {\\n composite: CompositeOperationOrAuto;\\n computedOffset: number;\\n easing: string;\\n offset: number | null;\\n [property: string]: string | number | null | undefined;\\n}\\n\\ninterface ConstantSourceOptions {\\n offset?: number;\\n}\\n\\ninterface ConstrainBooleanParameters {\\n exact?: boolean;\\n ideal?: boolean;\\n}\\n\\ninterface ConstrainDOMStringParameters {\\n exact?: string | string[];\\n ideal?: string | string[];\\n}\\n\\ninterface ConstrainDoubleRange extends DoubleRange {\\n exact?: number;\\n ideal?: number;\\n}\\n\\ninterface ConstrainULongRange extends ULongRange {\\n exact?: number;\\n ideal?: number;\\n}\\n\\ninterface ConvolverOptions extends AudioNodeOptions {\\n buffer?: AudioBuffer | null;\\n disableNormalization?: boolean;\\n}\\n\\ninterface CredentialCreationOptions {\\n publicKey?: PublicKeyCredentialCreationOptions;\\n signal?: AbortSignal;\\n}\\n\\ninterface CredentialPropertiesOutput {\\n rk?: boolean;\\n}\\n\\ninterface CredentialRequestOptions {\\n mediation?: CredentialMediationRequirement;\\n publicKey?: PublicKeyCredentialRequestOptions;\\n signal?: AbortSignal;\\n}\\n\\ninterface CryptoKeyPair {\\n privateKey: CryptoKey;\\n publicKey: CryptoKey;\\n}\\n\\ninterface CustomEventInit extends EventInit {\\n detail?: T;\\n}\\n\\ninterface DOMMatrix2DInit {\\n a?: number;\\n b?: number;\\n c?: number;\\n d?: number;\\n e?: number;\\n f?: number;\\n m11?: number;\\n m12?: number;\\n m21?: number;\\n m22?: number;\\n m41?: number;\\n m42?: number;\\n}\\n\\ninterface DOMMatrixInit extends DOMMatrix2DInit {\\n is2D?: boolean;\\n m13?: number;\\n m14?: number;\\n m23?: number;\\n m24?: number;\\n m31?: number;\\n m32?: number;\\n m33?: number;\\n m34?: number;\\n m43?: number;\\n m44?: number;\\n}\\n\\ninterface DOMPointInit {\\n w?: number;\\n x?: number;\\n y?: number;\\n z?: number;\\n}\\n\\ninterface DOMQuadInit {\\n p1?: DOMPointInit;\\n p2?: DOMPointInit;\\n p3?: DOMPointInit;\\n p4?: DOMPointInit;\\n}\\n\\ninterface DOMRectInit {\\n height?: number;\\n width?: number;\\n x?: number;\\n y?: number;\\n}\\n\\ninterface DelayOptions extends AudioNodeOptions {\\n delayTime?: number;\\n maxDelayTime?: number;\\n}\\n\\ninterface DeviceMotionEventAccelerationInit {\\n x?: number | null;\\n y?: number | null;\\n z?: number | null;\\n}\\n\\ninterface DeviceMotionEventInit extends EventInit {\\n acceleration?: DeviceMotionEventAccelerationInit;\\n accelerationIncludingGravity?: DeviceMotionEventAccelerationInit;\\n interval?: number;\\n rotationRate?: DeviceMotionEventRotationRateInit;\\n}\\n\\ninterface DeviceMotionEventRotationRateInit {\\n alpha?: number | null;\\n beta?: number | null;\\n gamma?: number | null;\\n}\\n\\ninterface DeviceOrientationEventInit extends EventInit {\\n absolute?: boolean;\\n alpha?: number | null;\\n beta?: number | null;\\n gamma?: number | null;\\n}\\n\\ninterface DisplayMediaStreamOptions {\\n audio?: boolean | MediaTrackConstraints;\\n video?: boolean | MediaTrackConstraints;\\n}\\n\\ninterface DocumentTimelineOptions {\\n originTime?: DOMHighResTimeStamp;\\n}\\n\\ninterface DoubleRange {\\n max?: number;\\n min?: number;\\n}\\n\\ninterface DragEventInit extends MouseEventInit {\\n dataTransfer?: DataTransfer | null;\\n}\\n\\ninterface DynamicsCompressorOptions extends AudioNodeOptions {\\n attack?: number;\\n knee?: number;\\n ratio?: number;\\n release?: number;\\n threshold?: number;\\n}\\n\\ninterface EcKeyAlgorithm extends KeyAlgorithm {\\n namedCurve: NamedCurve;\\n}\\n\\ninterface EcKeyGenParams extends Algorithm {\\n namedCurve: NamedCurve;\\n}\\n\\ninterface EcKeyImportParams extends Algorithm {\\n namedCurve: NamedCurve;\\n}\\n\\ninterface EcdhKeyDeriveParams extends Algorithm {\\n public: CryptoKey;\\n}\\n\\ninterface EcdsaParams extends Algorithm {\\n hash: HashAlgorithmIdentifier;\\n}\\n\\ninterface EffectTiming {\\n delay?: number;\\n direction?: PlaybackDirection;\\n duration?: number | string;\\n easing?: string;\\n endDelay?: number;\\n fill?: FillMode;\\n iterationStart?: number;\\n iterations?: number;\\n playbackRate?: number;\\n}\\n\\ninterface ElementCreationOptions {\\n is?: string;\\n}\\n\\ninterface ElementDefinitionOptions {\\n extends?: string;\\n}\\n\\ninterface ErrorEventInit extends EventInit {\\n colno?: number;\\n error?: any;\\n filename?: string;\\n lineno?: number;\\n message?: string;\\n}\\n\\ninterface EventInit {\\n bubbles?: boolean;\\n cancelable?: boolean;\\n composed?: boolean;\\n}\\n\\ninterface EventListenerOptions {\\n capture?: boolean;\\n}\\n\\ninterface EventModifierInit extends UIEventInit {\\n altKey?: boolean;\\n ctrlKey?: boolean;\\n metaKey?: boolean;\\n modifierAltGraph?: boolean;\\n modifierCapsLock?: boolean;\\n modifierFn?: boolean;\\n modifierFnLock?: boolean;\\n modifierHyper?: boolean;\\n modifierNumLock?: boolean;\\n modifierScrollLock?: boolean;\\n modifierSuper?: boolean;\\n modifierSymbol?: boolean;\\n modifierSymbolLock?: boolean;\\n shiftKey?: boolean;\\n}\\n\\ninterface EventSourceInit {\\n withCredentials?: boolean;\\n}\\n\\ninterface FilePropertyBag extends BlobPropertyBag {\\n lastModified?: number;\\n}\\n\\ninterface FileSystemFlags {\\n create?: boolean;\\n exclusive?: boolean;\\n}\\n\\ninterface FileSystemGetDirectoryOptions {\\n create?: boolean;\\n}\\n\\ninterface FileSystemGetFileOptions {\\n create?: boolean;\\n}\\n\\ninterface FileSystemRemoveOptions {\\n recursive?: boolean;\\n}\\n\\ninterface FocusEventInit extends UIEventInit {\\n relatedTarget?: EventTarget | null;\\n}\\n\\ninterface FocusOptions {\\n preventScroll?: boolean;\\n}\\n\\ninterface FontFaceDescriptors {\\n ascentOverride?: string;\\n descentOverride?: string;\\n display?: FontDisplay;\\n featureSettings?: string;\\n lineGapOverride?: string;\\n stretch?: string;\\n style?: string;\\n unicodeRange?: string;\\n variant?: string;\\n weight?: string;\\n}\\n\\ninterface FontFaceSetLoadEventInit extends EventInit {\\n fontfaces?: FontFace[];\\n}\\n\\ninterface FormDataEventInit extends EventInit {\\n formData: FormData;\\n}\\n\\ninterface FullscreenOptions {\\n navigationUI?: FullscreenNavigationUI;\\n}\\n\\ninterface GainOptions extends AudioNodeOptions {\\n gain?: number;\\n}\\n\\ninterface GamepadEventInit extends EventInit {\\n gamepad: Gamepad;\\n}\\n\\ninterface GetAnimationsOptions {\\n subtree?: boolean;\\n}\\n\\ninterface GetNotificationOptions {\\n tag?: string;\\n}\\n\\ninterface GetRootNodeOptions {\\n composed?: boolean;\\n}\\n\\ninterface HashChangeEventInit extends EventInit {\\n newURL?: string;\\n oldURL?: string;\\n}\\n\\ninterface HkdfParams extends Algorithm {\\n hash: HashAlgorithmIdentifier;\\n info: BufferSource;\\n salt: BufferSource;\\n}\\n\\ninterface HmacImportParams extends Algorithm {\\n hash: HashAlgorithmIdentifier;\\n length?: number;\\n}\\n\\ninterface HmacKeyAlgorithm extends KeyAlgorithm {\\n hash: KeyAlgorithm;\\n length: number;\\n}\\n\\ninterface HmacKeyGenParams extends Algorithm {\\n hash: HashAlgorithmIdentifier;\\n length?: number;\\n}\\n\\ninterface IDBDatabaseInfo {\\n name?: string;\\n version?: number;\\n}\\n\\ninterface IDBIndexParameters {\\n multiEntry?: boolean;\\n unique?: boolean;\\n}\\n\\ninterface IDBObjectStoreParameters {\\n autoIncrement?: boolean;\\n keyPath?: string | string[] | null;\\n}\\n\\ninterface IDBTransactionOptions {\\n durability?: IDBTransactionDurability;\\n}\\n\\ninterface IDBVersionChangeEventInit extends EventInit {\\n newVersion?: number | null;\\n oldVersion?: number;\\n}\\n\\ninterface IIRFilterOptions extends AudioNodeOptions {\\n feedback: number[];\\n feedforward: number[];\\n}\\n\\ninterface IdleRequestOptions {\\n timeout?: number;\\n}\\n\\ninterface ImageBitmapOptions {\\n colorSpaceConversion?: ColorSpaceConversion;\\n imageOrientation?: ImageOrientation;\\n premultiplyAlpha?: PremultiplyAlpha;\\n resizeHeight?: number;\\n resizeQuality?: ResizeQuality;\\n resizeWidth?: number;\\n}\\n\\ninterface ImageBitmapRenderingContextSettings {\\n alpha?: boolean;\\n}\\n\\ninterface ImageDataSettings {\\n colorSpace?: PredefinedColorSpace;\\n}\\n\\ninterface ImageEncodeOptions {\\n quality?: number;\\n type?: string;\\n}\\n\\ninterface ImportMeta {\\n url: string;\\n}\\n\\ninterface InputEventInit extends UIEventInit {\\n data?: string | null;\\n dataTransfer?: DataTransfer | null;\\n inputType?: string;\\n isComposing?: boolean;\\n targetRanges?: StaticRange[];\\n}\\n\\ninterface IntersectionObserverEntryInit {\\n boundingClientRect: DOMRectInit;\\n intersectionRatio: number;\\n intersectionRect: DOMRectInit;\\n isIntersecting: boolean;\\n rootBounds: DOMRectInit | null;\\n target: Element;\\n time: DOMHighResTimeStamp;\\n}\\n\\ninterface IntersectionObserverInit {\\n root?: Element | Document | null;\\n rootMargin?: string;\\n threshold?: number | number[];\\n}\\n\\ninterface JsonWebKey {\\n alg?: string;\\n crv?: string;\\n d?: string;\\n dp?: string;\\n dq?: string;\\n e?: string;\\n ext?: boolean;\\n k?: string;\\n key_ops?: string[];\\n kty?: string;\\n n?: string;\\n oth?: RsaOtherPrimesInfo[];\\n p?: string;\\n q?: string;\\n qi?: string;\\n use?: string;\\n x?: string;\\n y?: string;\\n}\\n\\ninterface KeyAlgorithm {\\n name: string;\\n}\\n\\ninterface KeyboardEventInit extends EventModifierInit {\\n /** @deprecated */\\n charCode?: number;\\n code?: string;\\n isComposing?: boolean;\\n key?: string;\\n /** @deprecated */\\n keyCode?: number;\\n location?: number;\\n repeat?: boolean;\\n}\\n\\ninterface Keyframe {\\n composite?: CompositeOperationOrAuto;\\n easing?: string;\\n offset?: number | null;\\n [property: string]: string | number | null | undefined;\\n}\\n\\ninterface KeyframeAnimationOptions extends KeyframeEffectOptions {\\n id?: string;\\n}\\n\\ninterface KeyframeEffectOptions extends EffectTiming {\\n composite?: CompositeOperation;\\n iterationComposite?: IterationCompositeOperation;\\n pseudoElement?: string | null;\\n}\\n\\ninterface LockInfo {\\n clientId?: string;\\n mode?: LockMode;\\n name?: string;\\n}\\n\\ninterface LockManagerSnapshot {\\n held?: LockInfo[];\\n pending?: LockInfo[];\\n}\\n\\ninterface LockOptions {\\n ifAvailable?: boolean;\\n mode?: LockMode;\\n signal?: AbortSignal;\\n steal?: boolean;\\n}\\n\\ninterface MIDIConnectionEventInit extends EventInit {\\n port?: MIDIPort;\\n}\\n\\ninterface MIDIMessageEventInit extends EventInit {\\n data?: Uint8Array;\\n}\\n\\ninterface MIDIOptions {\\n software?: boolean;\\n sysex?: boolean;\\n}\\n\\ninterface MediaCapabilitiesDecodingInfo extends MediaCapabilitiesInfo {\\n configuration?: MediaDecodingConfiguration;\\n}\\n\\ninterface MediaCapabilitiesEncodingInfo extends MediaCapabilitiesInfo {\\n configuration?: MediaEncodingConfiguration;\\n}\\n\\ninterface MediaCapabilitiesInfo {\\n powerEfficient: boolean;\\n smooth: boolean;\\n supported: boolean;\\n}\\n\\ninterface MediaConfiguration {\\n audio?: AudioConfiguration;\\n video?: VideoConfiguration;\\n}\\n\\ninterface MediaDecodingConfiguration extends MediaConfiguration {\\n type: MediaDecodingType;\\n}\\n\\ninterface MediaElementAudioSourceOptions {\\n mediaElement: HTMLMediaElement;\\n}\\n\\ninterface MediaEncodingConfiguration extends MediaConfiguration {\\n type: MediaEncodingType;\\n}\\n\\ninterface MediaEncryptedEventInit extends EventInit {\\n initData?: ArrayBuffer | null;\\n initDataType?: string;\\n}\\n\\ninterface MediaImage {\\n sizes?: string;\\n src: string;\\n type?: string;\\n}\\n\\ninterface MediaKeyMessageEventInit extends EventInit {\\n message: ArrayBuffer;\\n messageType: MediaKeyMessageType;\\n}\\n\\ninterface MediaKeySystemConfiguration {\\n audioCapabilities?: MediaKeySystemMediaCapability[];\\n distinctiveIdentifier?: MediaKeysRequirement;\\n initDataTypes?: string[];\\n label?: string;\\n persistentState?: MediaKeysRequirement;\\n sessionTypes?: string[];\\n videoCapabilities?: MediaKeySystemMediaCapability[];\\n}\\n\\ninterface MediaKeySystemMediaCapability {\\n contentType?: string;\\n encryptionScheme?: string | null;\\n robustness?: string;\\n}\\n\\ninterface MediaMetadataInit {\\n album?: string;\\n artist?: string;\\n artwork?: MediaImage[];\\n title?: string;\\n}\\n\\ninterface MediaPositionState {\\n duration?: number;\\n playbackRate?: number;\\n position?: number;\\n}\\n\\ninterface MediaQueryListEventInit extends EventInit {\\n matches?: boolean;\\n media?: string;\\n}\\n\\ninterface MediaRecorderOptions {\\n audioBitsPerSecond?: number;\\n bitsPerSecond?: number;\\n mimeType?: string;\\n videoBitsPerSecond?: number;\\n}\\n\\ninterface MediaSessionActionDetails {\\n action: MediaSessionAction;\\n fastSeek?: boolean;\\n seekOffset?: number;\\n seekTime?: number;\\n}\\n\\ninterface MediaStreamAudioSourceOptions {\\n mediaStream: MediaStream;\\n}\\n\\ninterface MediaStreamConstraints {\\n audio?: boolean | MediaTrackConstraints;\\n peerIdentity?: string;\\n preferCurrentTab?: boolean;\\n video?: boolean | MediaTrackConstraints;\\n}\\n\\ninterface MediaStreamTrackEventInit extends EventInit {\\n track: MediaStreamTrack;\\n}\\n\\ninterface MediaTrackCapabilities {\\n aspectRatio?: DoubleRange;\\n autoGainControl?: boolean[];\\n channelCount?: ULongRange;\\n deviceId?: string;\\n displaySurface?: string;\\n echoCancellation?: boolean[];\\n facingMode?: string[];\\n frameRate?: DoubleRange;\\n groupId?: string;\\n height?: ULongRange;\\n noiseSuppression?: boolean[];\\n sampleRate?: ULongRange;\\n sampleSize?: ULongRange;\\n width?: ULongRange;\\n}\\n\\ninterface MediaTrackConstraintSet {\\n aspectRatio?: ConstrainDouble;\\n autoGainControl?: ConstrainBoolean;\\n channelCount?: ConstrainULong;\\n deviceId?: ConstrainDOMString;\\n displaySurface?: ConstrainDOMString;\\n echoCancellation?: ConstrainBoolean;\\n facingMode?: ConstrainDOMString;\\n frameRate?: ConstrainDouble;\\n groupId?: ConstrainDOMString;\\n height?: ConstrainULong;\\n noiseSuppression?: ConstrainBoolean;\\n sampleRate?: ConstrainULong;\\n sampleSize?: ConstrainULong;\\n width?: ConstrainULong;\\n}\\n\\ninterface MediaTrackConstraints extends MediaTrackConstraintSet {\\n advanced?: MediaTrackConstraintSet[];\\n}\\n\\ninterface MediaTrackSettings {\\n aspectRatio?: number;\\n autoGainControl?: boolean;\\n channelCount?: number;\\n deviceId?: string;\\n displaySurface?: string;\\n echoCancellation?: boolean;\\n facingMode?: string;\\n frameRate?: number;\\n groupId?: string;\\n height?: number;\\n noiseSuppression?: boolean;\\n sampleRate?: number;\\n sampleSize?: number;\\n width?: number;\\n}\\n\\ninterface MediaTrackSupportedConstraints {\\n aspectRatio?: boolean;\\n autoGainControl?: boolean;\\n channelCount?: boolean;\\n deviceId?: boolean;\\n displaySurface?: boolean;\\n echoCancellation?: boolean;\\n facingMode?: boolean;\\n frameRate?: boolean;\\n groupId?: boolean;\\n height?: boolean;\\n noiseSuppression?: boolean;\\n sampleRate?: boolean;\\n sampleSize?: boolean;\\n width?: boolean;\\n}\\n\\ninterface MessageEventInit extends EventInit {\\n data?: T;\\n lastEventId?: string;\\n origin?: string;\\n ports?: MessagePort[];\\n source?: MessageEventSource | null;\\n}\\n\\ninterface MouseEventInit extends EventModifierInit {\\n button?: number;\\n buttons?: number;\\n clientX?: number;\\n clientY?: number;\\n movementX?: number;\\n movementY?: number;\\n relatedTarget?: EventTarget | null;\\n screenX?: number;\\n screenY?: number;\\n}\\n\\ninterface MultiCacheQueryOptions extends CacheQueryOptions {\\n cacheName?: string;\\n}\\n\\ninterface MutationObserverInit {\\n /** Set to a list of attribute local names (without namespace) if not all attribute mutations need to be observed and attributes is true or omitted. */\\n attributeFilter?: string[];\\n /** Set to true if attributes is true or omitted and target\'s attribute value before the mutation needs to be recorded. */\\n attributeOldValue?: boolean;\\n /** Set to true if mutations to target\'s attributes are to be observed. Can be omitted if attributeOldValue or attributeFilter is specified. */\\n attributes?: boolean;\\n /** Set to true if mutations to target\'s data are to be observed. Can be omitted if characterDataOldValue is specified. */\\n characterData?: boolean;\\n /** Set to true if characterData is set to true or omitted and target\'s data before the mutation needs to be recorded. */\\n characterDataOldValue?: boolean;\\n /** Set to true if mutations to target\'s children are to be observed. */\\n childList?: boolean;\\n /** Set to true if mutations to not just target, but also target\'s descendants are to be observed. */\\n subtree?: boolean;\\n}\\n\\ninterface NavigationPreloadState {\\n enabled?: boolean;\\n headerValue?: string;\\n}\\n\\ninterface NotificationAction {\\n action: string;\\n icon?: string;\\n title: string;\\n}\\n\\ninterface NotificationOptions {\\n actions?: NotificationAction[];\\n badge?: string;\\n body?: string;\\n data?: any;\\n dir?: NotificationDirection;\\n icon?: string;\\n image?: string;\\n lang?: string;\\n renotify?: boolean;\\n requireInteraction?: boolean;\\n silent?: boolean;\\n tag?: string;\\n timestamp?: EpochTimeStamp;\\n vibrate?: VibratePattern;\\n}\\n\\ninterface OfflineAudioCompletionEventInit extends EventInit {\\n renderedBuffer: AudioBuffer;\\n}\\n\\ninterface OfflineAudioContextOptions {\\n length: number;\\n numberOfChannels?: number;\\n sampleRate: number;\\n}\\n\\ninterface OptionalEffectTiming {\\n delay?: number;\\n direction?: PlaybackDirection;\\n duration?: number | string;\\n easing?: string;\\n endDelay?: number;\\n fill?: FillMode;\\n iterationStart?: number;\\n iterations?: number;\\n playbackRate?: number;\\n}\\n\\ninterface OscillatorOptions extends AudioNodeOptions {\\n detune?: number;\\n frequency?: number;\\n periodicWave?: PeriodicWave;\\n type?: OscillatorType;\\n}\\n\\ninterface PageTransitionEventInit extends EventInit {\\n persisted?: boolean;\\n}\\n\\ninterface PannerOptions extends AudioNodeOptions {\\n coneInnerAngle?: number;\\n coneOuterAngle?: number;\\n coneOuterGain?: number;\\n distanceModel?: DistanceModelType;\\n maxDistance?: number;\\n orientationX?: number;\\n orientationY?: number;\\n orientationZ?: number;\\n panningModel?: PanningModelType;\\n positionX?: number;\\n positionY?: number;\\n positionZ?: number;\\n refDistance?: number;\\n rolloffFactor?: number;\\n}\\n\\ninterface PaymentCurrencyAmount {\\n currency: string;\\n value: string;\\n}\\n\\ninterface PaymentDetailsBase {\\n displayItems?: PaymentItem[];\\n modifiers?: PaymentDetailsModifier[];\\n}\\n\\ninterface PaymentDetailsInit extends PaymentDetailsBase {\\n id?: string;\\n total: PaymentItem;\\n}\\n\\ninterface PaymentDetailsModifier {\\n additionalDisplayItems?: PaymentItem[];\\n data?: any;\\n supportedMethods: string;\\n total?: PaymentItem;\\n}\\n\\ninterface PaymentDetailsUpdate extends PaymentDetailsBase {\\n paymentMethodErrors?: any;\\n total?: PaymentItem;\\n}\\n\\ninterface PaymentItem {\\n amount: PaymentCurrencyAmount;\\n label: string;\\n pending?: boolean;\\n}\\n\\ninterface PaymentMethodChangeEventInit extends PaymentRequestUpdateEventInit {\\n methodDetails?: any;\\n methodName?: string;\\n}\\n\\ninterface PaymentMethodData {\\n data?: any;\\n supportedMethods: string;\\n}\\n\\ninterface PaymentRequestUpdateEventInit extends EventInit {\\n}\\n\\ninterface PaymentValidationErrors {\\n error?: string;\\n paymentMethod?: any;\\n}\\n\\ninterface Pbkdf2Params extends Algorithm {\\n hash: HashAlgorithmIdentifier;\\n iterations: number;\\n salt: BufferSource;\\n}\\n\\ninterface PerformanceMarkOptions {\\n detail?: any;\\n startTime?: DOMHighResTimeStamp;\\n}\\n\\ninterface PerformanceMeasureOptions {\\n detail?: any;\\n duration?: DOMHighResTimeStamp;\\n end?: string | DOMHighResTimeStamp;\\n start?: string | DOMHighResTimeStamp;\\n}\\n\\ninterface PerformanceObserverInit {\\n buffered?: boolean;\\n entryTypes?: string[];\\n type?: string;\\n}\\n\\ninterface PeriodicWaveConstraints {\\n disableNormalization?: boolean;\\n}\\n\\ninterface PeriodicWaveOptions extends PeriodicWaveConstraints {\\n imag?: number[] | Float32Array;\\n real?: number[] | Float32Array;\\n}\\n\\ninterface PermissionDescriptor {\\n name: PermissionName;\\n}\\n\\ninterface PictureInPictureEventInit extends EventInit {\\n pictureInPictureWindow: PictureInPictureWindow;\\n}\\n\\ninterface PointerEventInit extends MouseEventInit {\\n coalescedEvents?: PointerEvent[];\\n height?: number;\\n isPrimary?: boolean;\\n pointerId?: number;\\n pointerType?: string;\\n predictedEvents?: PointerEvent[];\\n pressure?: number;\\n tangentialPressure?: number;\\n tiltX?: number;\\n tiltY?: number;\\n twist?: number;\\n width?: number;\\n}\\n\\ninterface PopStateEventInit extends EventInit {\\n state?: any;\\n}\\n\\ninterface PositionOptions {\\n enableHighAccuracy?: boolean;\\n maximumAge?: number;\\n timeout?: number;\\n}\\n\\ninterface ProgressEventInit extends EventInit {\\n lengthComputable?: boolean;\\n loaded?: number;\\n total?: number;\\n}\\n\\ninterface PromiseRejectionEventInit extends EventInit {\\n promise: Promise;\\n reason?: any;\\n}\\n\\ninterface PropertyIndexedKeyframes {\\n composite?: CompositeOperationOrAuto | CompositeOperationOrAuto[];\\n easing?: string | string[];\\n offset?: number | (number | null)[];\\n [property: string]: string | string[] | number | null | (number | null)[] | undefined;\\n}\\n\\ninterface PublicKeyCredentialCreationOptions {\\n attestation?: AttestationConveyancePreference;\\n authenticatorSelection?: AuthenticatorSelectionCriteria;\\n challenge: BufferSource;\\n excludeCredentials?: PublicKeyCredentialDescriptor[];\\n extensions?: AuthenticationExtensionsClientInputs;\\n pubKeyCredParams: PublicKeyCredentialParameters[];\\n rp: PublicKeyCredentialRpEntity;\\n timeout?: number;\\n user: PublicKeyCredentialUserEntity;\\n}\\n\\ninterface PublicKeyCredentialDescriptor {\\n id: BufferSource;\\n transports?: AuthenticatorTransport[];\\n type: PublicKeyCredentialType;\\n}\\n\\ninterface PublicKeyCredentialEntity {\\n name: string;\\n}\\n\\ninterface PublicKeyCredentialParameters {\\n alg: COSEAlgorithmIdentifier;\\n type: PublicKeyCredentialType;\\n}\\n\\ninterface PublicKeyCredentialRequestOptions {\\n allowCredentials?: PublicKeyCredentialDescriptor[];\\n challenge: BufferSource;\\n extensions?: AuthenticationExtensionsClientInputs;\\n rpId?: string;\\n timeout?: number;\\n userVerification?: UserVerificationRequirement;\\n}\\n\\ninterface PublicKeyCredentialRpEntity extends PublicKeyCredentialEntity {\\n id?: string;\\n}\\n\\ninterface PublicKeyCredentialUserEntity extends PublicKeyCredentialEntity {\\n displayName: string;\\n id: BufferSource;\\n}\\n\\ninterface PushSubscriptionJSON {\\n endpoint?: string;\\n expirationTime?: EpochTimeStamp | null;\\n keys?: Record;\\n}\\n\\ninterface PushSubscriptionOptionsInit {\\n applicationServerKey?: BufferSource | string | null;\\n userVisibleOnly?: boolean;\\n}\\n\\ninterface QueuingStrategy {\\n highWaterMark?: number;\\n size?: QueuingStrategySize;\\n}\\n\\ninterface QueuingStrategyInit {\\n /**\\n * Creates a new ByteLengthQueuingStrategy with the provided high water mark.\\n *\\n * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw.\\n */\\n highWaterMark: number;\\n}\\n\\ninterface RTCAnswerOptions extends RTCOfferAnswerOptions {\\n}\\n\\ninterface RTCCertificateExpiration {\\n expires?: number;\\n}\\n\\ninterface RTCConfiguration {\\n bundlePolicy?: RTCBundlePolicy;\\n certificates?: RTCCertificate[];\\n iceCandidatePoolSize?: number;\\n iceServers?: RTCIceServer[];\\n iceTransportPolicy?: RTCIceTransportPolicy;\\n rtcpMuxPolicy?: RTCRtcpMuxPolicy;\\n}\\n\\ninterface RTCDTMFToneChangeEventInit extends EventInit {\\n tone?: string;\\n}\\n\\ninterface RTCDataChannelEventInit extends EventInit {\\n channel: RTCDataChannel;\\n}\\n\\ninterface RTCDataChannelInit {\\n id?: number;\\n maxPacketLifeTime?: number;\\n maxRetransmits?: number;\\n negotiated?: boolean;\\n ordered?: boolean;\\n protocol?: string;\\n}\\n\\ninterface RTCDtlsFingerprint {\\n algorithm?: string;\\n value?: string;\\n}\\n\\ninterface RTCEncodedAudioFrameMetadata {\\n contributingSources?: number[];\\n synchronizationSource?: number;\\n}\\n\\ninterface RTCEncodedVideoFrameMetadata {\\n contributingSources?: number[];\\n dependencies?: number[];\\n frameId?: number;\\n height?: number;\\n spatialIndex?: number;\\n synchronizationSource?: number;\\n temporalIndex?: number;\\n width?: number;\\n}\\n\\ninterface RTCErrorEventInit extends EventInit {\\n error: RTCError;\\n}\\n\\ninterface RTCErrorInit {\\n errorDetail: RTCErrorDetailType;\\n httpRequestStatusCode?: number;\\n receivedAlert?: number;\\n sctpCauseCode?: number;\\n sdpLineNumber?: number;\\n sentAlert?: number;\\n}\\n\\ninterface RTCIceCandidateInit {\\n candidate?: string;\\n sdpMLineIndex?: number | null;\\n sdpMid?: string | null;\\n usernameFragment?: string | null;\\n}\\n\\ninterface RTCIceCandidatePairStats extends RTCStats {\\n availableIncomingBitrate?: number;\\n availableOutgoingBitrate?: number;\\n bytesReceived?: number;\\n bytesSent?: number;\\n currentRoundTripTime?: number;\\n lastPacketReceivedTimestamp?: DOMHighResTimeStamp;\\n lastPacketSentTimestamp?: DOMHighResTimeStamp;\\n localCandidateId: string;\\n nominated?: boolean;\\n remoteCandidateId: string;\\n requestsReceived?: number;\\n requestsSent?: number;\\n responsesReceived?: number;\\n responsesSent?: number;\\n state: RTCStatsIceCandidatePairState;\\n totalRoundTripTime?: number;\\n transportId: string;\\n}\\n\\ninterface RTCIceServer {\\n credential?: string;\\n urls: string | string[];\\n username?: string;\\n}\\n\\ninterface RTCInboundRtpStreamStats extends RTCReceivedRtpStreamStats {\\n audioLevel?: number;\\n bytesReceived?: number;\\n concealedSamples?: number;\\n concealmentEvents?: number;\\n decoderImplementation?: string;\\n estimatedPlayoutTimestamp?: DOMHighResTimeStamp;\\n fecPacketsDiscarded?: number;\\n fecPacketsReceived?: number;\\n firCount?: number;\\n frameHeight?: number;\\n frameWidth?: number;\\n framesDecoded?: number;\\n framesDropped?: number;\\n framesPerSecond?: number;\\n framesReceived?: number;\\n headerBytesReceived?: number;\\n insertedSamplesForDeceleration?: number;\\n jitterBufferDelay?: number;\\n jitterBufferEmittedCount?: number;\\n keyFramesDecoded?: number;\\n kind: string;\\n lastPacketReceivedTimestamp?: DOMHighResTimeStamp;\\n nackCount?: number;\\n packetsDiscarded?: number;\\n pliCount?: number;\\n qpSum?: number;\\n remoteId?: string;\\n removedSamplesForAcceleration?: number;\\n silentConcealedSamples?: number;\\n totalAudioEnergy?: number;\\n totalDecodeTime?: number;\\n totalInterFrameDelay?: number;\\n totalProcessingDelay?: number;\\n totalSamplesDuration?: number;\\n totalSamplesReceived?: number;\\n totalSquaredInterFrameDelay?: number;\\n}\\n\\ninterface RTCLocalSessionDescriptionInit {\\n sdp?: string;\\n type?: RTCSdpType;\\n}\\n\\ninterface RTCOfferAnswerOptions {\\n}\\n\\ninterface RTCOfferOptions extends RTCOfferAnswerOptions {\\n iceRestart?: boolean;\\n offerToReceiveAudio?: boolean;\\n offerToReceiveVideo?: boolean;\\n}\\n\\ninterface RTCOutboundRtpStreamStats extends RTCSentRtpStreamStats {\\n firCount?: number;\\n frameHeight?: number;\\n frameWidth?: number;\\n framesEncoded?: number;\\n framesPerSecond?: number;\\n framesSent?: number;\\n headerBytesSent?: number;\\n hugeFramesSent?: number;\\n keyFramesEncoded?: number;\\n mediaSourceId?: string;\\n nackCount?: number;\\n pliCount?: number;\\n qpSum?: number;\\n qualityLimitationResolutionChanges?: number;\\n remoteId?: string;\\n retransmittedBytesSent?: number;\\n retransmittedPacketsSent?: number;\\n rid?: string;\\n targetBitrate?: number;\\n totalEncodeTime?: number;\\n totalEncodedBytesTarget?: number;\\n totalPacketSendDelay?: number;\\n}\\n\\ninterface RTCPeerConnectionIceErrorEventInit extends EventInit {\\n address?: string | null;\\n errorCode: number;\\n errorText?: string;\\n port?: number | null;\\n url?: string;\\n}\\n\\ninterface RTCPeerConnectionIceEventInit extends EventInit {\\n candidate?: RTCIceCandidate | null;\\n url?: string | null;\\n}\\n\\ninterface RTCReceivedRtpStreamStats extends RTCRtpStreamStats {\\n jitter?: number;\\n packetsLost?: number;\\n packetsReceived?: number;\\n}\\n\\ninterface RTCRtcpParameters {\\n cname?: string;\\n reducedSize?: boolean;\\n}\\n\\ninterface RTCRtpCapabilities {\\n codecs: RTCRtpCodecCapability[];\\n headerExtensions: RTCRtpHeaderExtensionCapability[];\\n}\\n\\ninterface RTCRtpCodecCapability {\\n channels?: number;\\n clockRate: number;\\n mimeType: string;\\n sdpFmtpLine?: string;\\n}\\n\\ninterface RTCRtpCodecParameters {\\n channels?: number;\\n clockRate: number;\\n mimeType: string;\\n payloadType: number;\\n sdpFmtpLine?: string;\\n}\\n\\ninterface RTCRtpCodingParameters {\\n rid?: string;\\n}\\n\\ninterface RTCRtpContributingSource {\\n audioLevel?: number;\\n rtpTimestamp: number;\\n source: number;\\n timestamp: DOMHighResTimeStamp;\\n}\\n\\ninterface RTCRtpEncodingParameters extends RTCRtpCodingParameters {\\n active?: boolean;\\n maxBitrate?: number;\\n maxFramerate?: number;\\n networkPriority?: RTCPriorityType;\\n priority?: RTCPriorityType;\\n scaleResolutionDownBy?: number;\\n}\\n\\ninterface RTCRtpHeaderExtensionCapability {\\n uri?: string;\\n}\\n\\ninterface RTCRtpHeaderExtensionParameters {\\n encrypted?: boolean;\\n id: number;\\n uri: string;\\n}\\n\\ninterface RTCRtpParameters {\\n codecs: RTCRtpCodecParameters[];\\n headerExtensions: RTCRtpHeaderExtensionParameters[];\\n rtcp: RTCRtcpParameters;\\n}\\n\\ninterface RTCRtpReceiveParameters extends RTCRtpParameters {\\n}\\n\\ninterface RTCRtpSendParameters extends RTCRtpParameters {\\n degradationPreference?: RTCDegradationPreference;\\n encodings: RTCRtpEncodingParameters[];\\n transactionId: string;\\n}\\n\\ninterface RTCRtpStreamStats extends RTCStats {\\n codecId?: string;\\n kind: string;\\n ssrc: number;\\n transportId?: string;\\n}\\n\\ninterface RTCRtpSynchronizationSource extends RTCRtpContributingSource {\\n}\\n\\ninterface RTCRtpTransceiverInit {\\n direction?: RTCRtpTransceiverDirection;\\n sendEncodings?: RTCRtpEncodingParameters[];\\n streams?: MediaStream[];\\n}\\n\\ninterface RTCSentRtpStreamStats extends RTCRtpStreamStats {\\n bytesSent?: number;\\n packetsSent?: number;\\n}\\n\\ninterface RTCSessionDescriptionInit {\\n sdp?: string;\\n type: RTCSdpType;\\n}\\n\\ninterface RTCStats {\\n id: string;\\n timestamp: DOMHighResTimeStamp;\\n type: RTCStatsType;\\n}\\n\\ninterface RTCTrackEventInit extends EventInit {\\n receiver: RTCRtpReceiver;\\n streams?: MediaStream[];\\n track: MediaStreamTrack;\\n transceiver: RTCRtpTransceiver;\\n}\\n\\ninterface RTCTransportStats extends RTCStats {\\n bytesReceived?: number;\\n bytesSent?: number;\\n dtlsCipher?: string;\\n dtlsState: RTCDtlsTransportState;\\n localCertificateId?: string;\\n remoteCertificateId?: string;\\n selectedCandidatePairId?: string;\\n srtpCipher?: string;\\n tlsVersion?: string;\\n}\\n\\ninterface ReadableStreamGetReaderOptions {\\n /**\\n * Creates a ReadableStreamBYOBReader and locks the stream to the new reader.\\n *\\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle \\"bring your own buffer\\" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation.\\n */\\n mode?: ReadableStreamReaderMode;\\n}\\n\\ninterface ReadableStreamReadDoneResult {\\n done: true;\\n value?: T;\\n}\\n\\ninterface ReadableStreamReadValueResult {\\n done: false;\\n value: T;\\n}\\n\\ninterface ReadableWritablePair {\\n readable: ReadableStream;\\n /**\\n * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use.\\n *\\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\\n */\\n writable: WritableStream;\\n}\\n\\ninterface RegistrationOptions {\\n scope?: string;\\n type?: WorkerType;\\n updateViaCache?: ServiceWorkerUpdateViaCache;\\n}\\n\\ninterface RequestInit {\\n /** A BodyInit object or null to set request\'s body. */\\n body?: BodyInit | null;\\n /** A string indicating how the request will interact with the browser\'s cache to set request\'s cache. */\\n cache?: RequestCache;\\n /** A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request\'s credentials. */\\n credentials?: RequestCredentials;\\n /** A Headers object, an object literal, or an array of two-item arrays to set request\'s headers. */\\n headers?: HeadersInit;\\n /** A cryptographic hash of the resource to be fetched by request. Sets request\'s integrity. */\\n integrity?: string;\\n /** A boolean to set request\'s keepalive. */\\n keepalive?: boolean;\\n /** A string to set request\'s method. */\\n method?: string;\\n /** A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request\'s mode. */\\n mode?: RequestMode;\\n /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request\'s redirect. */\\n redirect?: RequestRedirect;\\n /** A string whose value is a same-origin URL, \\"about:client\\", or the empty string, to set request\'s referrer. */\\n referrer?: string;\\n /** A referrer policy to set request\'s referrerPolicy. */\\n referrerPolicy?: ReferrerPolicy;\\n /** An AbortSignal to set request\'s signal. */\\n signal?: AbortSignal | null;\\n /** Can only be null. Used to disassociate request from any Window. */\\n window?: null;\\n}\\n\\ninterface ResizeObserverOptions {\\n box?: ResizeObserverBoxOptions;\\n}\\n\\ninterface ResponseInit {\\n headers?: HeadersInit;\\n status?: number;\\n statusText?: string;\\n}\\n\\ninterface RsaHashedImportParams extends Algorithm {\\n hash: HashAlgorithmIdentifier;\\n}\\n\\ninterface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm {\\n hash: KeyAlgorithm;\\n}\\n\\ninterface RsaHashedKeyGenParams extends RsaKeyGenParams {\\n hash: HashAlgorithmIdentifier;\\n}\\n\\ninterface RsaKeyAlgorithm extends KeyAlgorithm {\\n modulusLength: number;\\n publicExponent: BigInteger;\\n}\\n\\ninterface RsaKeyGenParams extends Algorithm {\\n modulusLength: number;\\n publicExponent: BigInteger;\\n}\\n\\ninterface RsaOaepParams extends Algorithm {\\n label?: BufferSource;\\n}\\n\\ninterface RsaOtherPrimesInfo {\\n d?: string;\\n r?: string;\\n t?: string;\\n}\\n\\ninterface RsaPssParams extends Algorithm {\\n saltLength: number;\\n}\\n\\ninterface SVGBoundingBoxOptions {\\n clipped?: boolean;\\n fill?: boolean;\\n markers?: boolean;\\n stroke?: boolean;\\n}\\n\\ninterface ScrollIntoViewOptions extends ScrollOptions {\\n block?: ScrollLogicalPosition;\\n inline?: ScrollLogicalPosition;\\n}\\n\\ninterface ScrollOptions {\\n behavior?: ScrollBehavior;\\n}\\n\\ninterface ScrollToOptions extends ScrollOptions {\\n left?: number;\\n top?: number;\\n}\\n\\ninterface SecurityPolicyViolationEventInit extends EventInit {\\n blockedURI?: string;\\n columnNumber?: number;\\n disposition: SecurityPolicyViolationEventDisposition;\\n documentURI: string;\\n effectiveDirective: string;\\n lineNumber?: number;\\n originalPolicy: string;\\n referrer?: string;\\n sample?: string;\\n sourceFile?: string;\\n statusCode: number;\\n violatedDirective: string;\\n}\\n\\ninterface ShadowRootInit {\\n delegatesFocus?: boolean;\\n mode: ShadowRootMode;\\n slotAssignment?: SlotAssignmentMode;\\n}\\n\\ninterface ShareData {\\n files?: File[];\\n text?: string;\\n title?: string;\\n url?: string;\\n}\\n\\ninterface SpeechSynthesisErrorEventInit extends SpeechSynthesisEventInit {\\n error: SpeechSynthesisErrorCode;\\n}\\n\\ninterface SpeechSynthesisEventInit extends EventInit {\\n charIndex?: number;\\n charLength?: number;\\n elapsedTime?: number;\\n name?: string;\\n utterance: SpeechSynthesisUtterance;\\n}\\n\\ninterface StaticRangeInit {\\n endContainer: Node;\\n endOffset: number;\\n startContainer: Node;\\n startOffset: number;\\n}\\n\\ninterface StereoPannerOptions extends AudioNodeOptions {\\n pan?: number;\\n}\\n\\ninterface StorageEstimate {\\n quota?: number;\\n usage?: number;\\n}\\n\\ninterface StorageEventInit extends EventInit {\\n key?: string | null;\\n newValue?: string | null;\\n oldValue?: string | null;\\n storageArea?: Storage | null;\\n url?: string;\\n}\\n\\ninterface StreamPipeOptions {\\n preventAbort?: boolean;\\n preventCancel?: boolean;\\n /**\\n * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered.\\n *\\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\\n *\\n * Errors and closures of the source and destination streams propagate as follows:\\n *\\n * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source\'s error, or with any error that occurs during aborting the destination.\\n *\\n * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination\'s error, or with any error that occurs during canceling the source.\\n *\\n * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error.\\n *\\n * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source.\\n *\\n * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set.\\n */\\n preventClose?: boolean;\\n signal?: AbortSignal;\\n}\\n\\ninterface StructuredSerializeOptions {\\n transfer?: Transferable[];\\n}\\n\\ninterface SubmitEventInit extends EventInit {\\n submitter?: HTMLElement | null;\\n}\\n\\ninterface TextDecodeOptions {\\n stream?: boolean;\\n}\\n\\ninterface TextDecoderOptions {\\n fatal?: boolean;\\n ignoreBOM?: boolean;\\n}\\n\\ninterface TextEncoderEncodeIntoResult {\\n read?: number;\\n written?: number;\\n}\\n\\ninterface TouchEventInit extends EventModifierInit {\\n changedTouches?: Touch[];\\n targetTouches?: Touch[];\\n touches?: Touch[];\\n}\\n\\ninterface TouchInit {\\n altitudeAngle?: number;\\n azimuthAngle?: number;\\n clientX?: number;\\n clientY?: number;\\n force?: number;\\n identifier: number;\\n pageX?: number;\\n pageY?: number;\\n radiusX?: number;\\n radiusY?: number;\\n rotationAngle?: number;\\n screenX?: number;\\n screenY?: number;\\n target: EventTarget;\\n touchType?: TouchType;\\n}\\n\\ninterface TrackEventInit extends EventInit {\\n track?: TextTrack | null;\\n}\\n\\ninterface Transformer {\\n flush?: TransformerFlushCallback;\\n readableType?: undefined;\\n start?: TransformerStartCallback;\\n transform?: TransformerTransformCallback;\\n writableType?: undefined;\\n}\\n\\ninterface TransitionEventInit extends EventInit {\\n elapsedTime?: number;\\n propertyName?: string;\\n pseudoElement?: string;\\n}\\n\\ninterface UIEventInit extends EventInit {\\n detail?: number;\\n view?: Window | null;\\n /** @deprecated */\\n which?: number;\\n}\\n\\ninterface ULongRange {\\n max?: number;\\n min?: number;\\n}\\n\\ninterface UnderlyingByteSource {\\n autoAllocateChunkSize?: number;\\n cancel?: UnderlyingSourceCancelCallback;\\n pull?: (controller: ReadableByteStreamController) => void | PromiseLike;\\n start?: (controller: ReadableByteStreamController) => any;\\n type: \\"bytes\\";\\n}\\n\\ninterface UnderlyingDefaultSource {\\n cancel?: UnderlyingSourceCancelCallback;\\n pull?: (controller: ReadableStreamDefaultController) => void | PromiseLike;\\n start?: (controller: ReadableStreamDefaultController) => any;\\n type?: undefined;\\n}\\n\\ninterface UnderlyingSink {\\n abort?: UnderlyingSinkAbortCallback;\\n close?: UnderlyingSinkCloseCallback;\\n start?: UnderlyingSinkStartCallback;\\n type?: undefined;\\n write?: UnderlyingSinkWriteCallback;\\n}\\n\\ninterface UnderlyingSource {\\n autoAllocateChunkSize?: number;\\n cancel?: UnderlyingSourceCancelCallback;\\n pull?: UnderlyingSourcePullCallback;\\n start?: UnderlyingSourceStartCallback;\\n type?: ReadableStreamType;\\n}\\n\\ninterface ValidityStateFlags {\\n badInput?: boolean;\\n customError?: boolean;\\n patternMismatch?: boolean;\\n rangeOverflow?: boolean;\\n rangeUnderflow?: boolean;\\n stepMismatch?: boolean;\\n tooLong?: boolean;\\n tooShort?: boolean;\\n typeMismatch?: boolean;\\n valueMissing?: boolean;\\n}\\n\\ninterface VideoColorSpaceInit {\\n fullRange?: boolean | null;\\n matrix?: VideoMatrixCoefficients | null;\\n primaries?: VideoColorPrimaries | null;\\n transfer?: VideoTransferCharacteristics | null;\\n}\\n\\ninterface VideoConfiguration {\\n bitrate: number;\\n colorGamut?: ColorGamut;\\n contentType: string;\\n framerate: number;\\n hdrMetadataType?: HdrMetadataType;\\n height: number;\\n scalabilityMode?: string;\\n transferFunction?: TransferFunction;\\n width: number;\\n}\\n\\ninterface VideoFrameCallbackMetadata {\\n captureTime?: DOMHighResTimeStamp;\\n expectedDisplayTime: DOMHighResTimeStamp;\\n height: number;\\n mediaTime: number;\\n presentationTime: DOMHighResTimeStamp;\\n presentedFrames: number;\\n processingDuration?: number;\\n receiveTime?: DOMHighResTimeStamp;\\n rtpTimestamp?: number;\\n width: number;\\n}\\n\\ninterface WaveShaperOptions extends AudioNodeOptions {\\n curve?: number[] | Float32Array;\\n oversample?: OverSampleType;\\n}\\n\\ninterface WebGLContextAttributes {\\n alpha?: boolean;\\n antialias?: boolean;\\n depth?: boolean;\\n desynchronized?: boolean;\\n failIfMajorPerformanceCaveat?: boolean;\\n powerPreference?: WebGLPowerPreference;\\n premultipliedAlpha?: boolean;\\n preserveDrawingBuffer?: boolean;\\n stencil?: boolean;\\n}\\n\\ninterface WebGLContextEventInit extends EventInit {\\n statusMessage?: string;\\n}\\n\\ninterface WheelEventInit extends MouseEventInit {\\n deltaMode?: number;\\n deltaX?: number;\\n deltaY?: number;\\n deltaZ?: number;\\n}\\n\\ninterface WindowPostMessageOptions extends StructuredSerializeOptions {\\n targetOrigin?: string;\\n}\\n\\ninterface WorkerOptions {\\n credentials?: RequestCredentials;\\n name?: string;\\n type?: WorkerType;\\n}\\n\\ninterface WorkletOptions {\\n credentials?: RequestCredentials;\\n}\\n\\ntype NodeFilter = ((node: Node) => number) | { acceptNode(node: Node): number; };\\n\\ndeclare var NodeFilter: {\\n readonly FILTER_ACCEPT: 1;\\n readonly FILTER_REJECT: 2;\\n readonly FILTER_SKIP: 3;\\n readonly SHOW_ALL: 0xFFFFFFFF;\\n readonly SHOW_ELEMENT: 0x1;\\n readonly SHOW_ATTRIBUTE: 0x2;\\n readonly SHOW_TEXT: 0x4;\\n readonly SHOW_CDATA_SECTION: 0x8;\\n readonly SHOW_ENTITY_REFERENCE: 0x10;\\n readonly SHOW_ENTITY: 0x20;\\n readonly SHOW_PROCESSING_INSTRUCTION: 0x40;\\n readonly SHOW_COMMENT: 0x80;\\n readonly SHOW_DOCUMENT: 0x100;\\n readonly SHOW_DOCUMENT_TYPE: 0x200;\\n readonly SHOW_DOCUMENT_FRAGMENT: 0x400;\\n readonly SHOW_NOTATION: 0x800;\\n};\\n\\ntype XPathNSResolver = ((prefix: string | null) => string | null) | { lookupNamespaceURI(prefix: string | null): string | null; };\\n\\n/** The ANGLE_instanced_arrays extension is part of the WebGL API and allows to draw the same object, or groups of similar objects multiple times, if they share the same vertex data, primitive count and type. */\\ninterface ANGLE_instanced_arrays {\\n drawArraysInstancedANGLE(mode: GLenum, first: GLint, count: GLsizei, primcount: GLsizei): void;\\n drawElementsInstancedANGLE(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, primcount: GLsizei): void;\\n vertexAttribDivisorANGLE(index: GLuint, divisor: GLuint): void;\\n readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: 0x88FE;\\n}\\n\\ninterface ARIAMixin {\\n ariaAtomic: string | null;\\n ariaAutoComplete: string | null;\\n ariaBusy: string | null;\\n ariaChecked: string | null;\\n ariaColCount: string | null;\\n ariaColIndex: string | null;\\n ariaColSpan: string | null;\\n ariaCurrent: string | null;\\n ariaDisabled: string | null;\\n ariaExpanded: string | null;\\n ariaHasPopup: string | null;\\n ariaHidden: string | null;\\n ariaInvalid: string | null;\\n ariaKeyShortcuts: string | null;\\n ariaLabel: string | null;\\n ariaLevel: string | null;\\n ariaLive: string | null;\\n ariaModal: string | null;\\n ariaMultiLine: string | null;\\n ariaMultiSelectable: string | null;\\n ariaOrientation: string | null;\\n ariaPlaceholder: string | null;\\n ariaPosInSet: string | null;\\n ariaPressed: string | null;\\n ariaReadOnly: string | null;\\n ariaRequired: string | null;\\n ariaRoleDescription: string | null;\\n ariaRowCount: string | null;\\n ariaRowIndex: string | null;\\n ariaRowSpan: string | null;\\n ariaSelected: string | null;\\n ariaSetSize: string | null;\\n ariaSort: string | null;\\n ariaValueMax: string | null;\\n ariaValueMin: string | null;\\n ariaValueNow: string | null;\\n ariaValueText: string | null;\\n role: string | null;\\n}\\n\\n/** A controller object that allows you to abort one or more DOM requests as and when desired. */\\ninterface AbortController {\\n /** Returns the AbortSignal object associated with this object. */\\n readonly signal: AbortSignal;\\n /** Invoking this method will set this object\'s AbortSignal\'s aborted flag and signal to any observers that the associated activity is to be aborted. */\\n abort(reason?: any): void;\\n}\\n\\ndeclare var AbortController: {\\n prototype: AbortController;\\n new(): AbortController;\\n};\\n\\ninterface AbortSignalEventMap {\\n \\"abort\\": Event;\\n}\\n\\n/** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */\\ninterface AbortSignal extends EventTarget {\\n /** Returns true if this AbortSignal\'s AbortController has signaled to abort, and false otherwise. */\\n readonly aborted: boolean;\\n onabort: ((this: AbortSignal, ev: Event) => any) | null;\\n readonly reason: any;\\n throwIfAborted(): void;\\n addEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\\n removeEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\\n}\\n\\ndeclare var AbortSignal: {\\n prototype: AbortSignal;\\n new(): AbortSignal;\\n abort(reason?: any): AbortSignal;\\n timeout(milliseconds: number): AbortSignal;\\n};\\n\\ninterface AbstractRange {\\n /** Returns true if range is collapsed, and false otherwise. */\\n readonly collapsed: boolean;\\n /** Returns range\'s end node. */\\n readonly endContainer: Node;\\n /** Returns range\'s end offset. */\\n readonly endOffset: number;\\n /** Returns range\'s start node. */\\n readonly startContainer: Node;\\n /** Returns range\'s start offset. */\\n readonly startOffset: number;\\n}\\n\\ndeclare var AbstractRange: {\\n prototype: AbstractRange;\\n new(): AbstractRange;\\n};\\n\\ninterface AbstractWorkerEventMap {\\n \\"error\\": ErrorEvent;\\n}\\n\\ninterface AbstractWorker {\\n onerror: ((this: AbstractWorker, ev: ErrorEvent) => any) | null;\\n addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\\n removeEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\\n}\\n\\n/** A node able to provide real-time frequency and time-domain analysis information. It is an AudioNode that passes the audio stream unchanged from the input to the output, but allows you to take the generated data, process it, and create audio visualizations. */\\ninterface AnalyserNode extends AudioNode {\\n fftSize: number;\\n readonly frequencyBinCount: number;\\n maxDecibels: number;\\n minDecibels: number;\\n smoothingTimeConstant: number;\\n getByteFrequencyData(array: Uint8Array): void;\\n getByteTimeDomainData(array: Uint8Array): void;\\n getFloatFrequencyData(array: Float32Array): void;\\n getFloatTimeDomainData(array: Float32Array): void;\\n}\\n\\ndeclare var AnalyserNode: {\\n prototype: AnalyserNode;\\n new(context: BaseAudioContext, options?: AnalyserOptions): AnalyserNode;\\n};\\n\\ninterface Animatable {\\n animate(keyframes: Keyframe[] | PropertyIndexedKeyframes | null, options?: number | KeyframeAnimationOptions): Animation;\\n getAnimations(options?: GetAnimationsOptions): Animation[];\\n}\\n\\ninterface AnimationEventMap {\\n \\"cancel\\": AnimationPlaybackEvent;\\n \\"finish\\": AnimationPlaybackEvent;\\n \\"remove\\": Event;\\n}\\n\\ninterface Animation extends EventTarget {\\n currentTime: CSSNumberish | null;\\n effect: AnimationEffect | null;\\n readonly finished: Promise;\\n id: string;\\n oncancel: ((this: Animation, ev: AnimationPlaybackEvent) => any) | null;\\n onfinish: ((this: Animation, ev: AnimationPlaybackEvent) => any) | null;\\n onremove: ((this: Animation, ev: Event) => any) | null;\\n readonly pending: boolean;\\n readonly playState: AnimationPlayState;\\n playbackRate: number;\\n readonly ready: Promise;\\n readonly replaceState: AnimationReplaceState;\\n startTime: CSSNumberish | null;\\n timeline: AnimationTimeline | null;\\n cancel(): void;\\n commitStyles(): void;\\n finish(): void;\\n pause(): void;\\n persist(): void;\\n play(): void;\\n reverse(): void;\\n updatePlaybackRate(playbackRate: number): void;\\n addEventListener(type: K, listener: (this: Animation, ev: AnimationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\\n removeEventListener(type: K, listener: (this: Animation, ev: AnimationEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\\n}\\n\\ndeclare var Animation: {\\n prototype: Animation;\\n new(effect?: AnimationEffect | null, timeline?: AnimationTimeline | null): Animation;\\n};\\n\\ninterface AnimationEffect {\\n getComputedTiming(): ComputedEffectTiming;\\n getTiming(): EffectTiming;\\n updateTiming(timing?: OptionalEffectTiming): void;\\n}\\n\\ndeclare var AnimationEffect: {\\n prototype: AnimationEffect;\\n new(): AnimationEffect;\\n};\\n\\n/** Events providing information related to animations. */\\ninterface AnimationEvent extends Event {\\n readonly animationName: string;\\n readonly elapsedTime: number;\\n readonly pseudoElement: string;\\n}\\n\\ndeclare var AnimationEvent: {\\n prototype: AnimationEvent;\\n new(type: string, animationEventInitDict?: AnimationEventInit): AnimationEvent;\\n};\\n\\ninterface AnimationFrameProvider {\\n cancelAnimationFrame(handle: number): void;\\n requestAnimationFrame(callback: FrameRequestCallback): number;\\n}\\n\\ninterface AnimationPlaybackEvent extends Event {\\n readonly currentTime: CSSNumberish | null;\\n readonly timelineTime: CSSNumberish | null;\\n}\\n\\ndeclare var AnimationPlaybackEvent: {\\n prototype: AnimationPlaybackEvent;\\n new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent;\\n};\\n\\ninterface AnimationTimeline {\\n readonly currentTime: number | null;\\n}\\n\\ndeclare var AnimationTimeline: {\\n prototype: AnimationTimeline;\\n new(): AnimationTimeline;\\n};\\n\\n/** A DOM element\'s attribute as an object. In most DOM methods, you will probably directly retrieve the attribute as a string (e.g., Element.getAttribute(), but certain functions (e.g., Element.getAttributeNode()) or means of iterating give Attr types. */\\ninterface Attr extends Node {\\n readonly localName: string;\\n readonly name: string;\\n readonly namespaceURI: string | null;\\n readonly ownerDocument: Document;\\n readonly ownerElement: Element | null;\\n readonly prefix: string | null;\\n /** @deprecated */\\n readonly specified: boolean;\\n value: string;\\n}\\n\\ndeclare var Attr: {\\n prototype: Attr;\\n new(): Attr;\\n};\\n\\n/** A short audio asset residing in memory, created from an audio file using the AudioContext.decodeAudioData() method, or from raw data using AudioContext.createBuffer(). Once put into an AudioBuffer, the audio can then be played by being passed into an AudioBufferSourceNode. */\\ninterface AudioBuffer {\\n readonly duration: number;\\n readonly length: number;\\n readonly numberOfChannels: number;\\n readonly sampleRate: number;\\n copyFromChannel(destination: Float32Array, channelNumber: number, bufferOffset?: number): void;\\n copyToChannel(source: Float32Array, channelNumber: number, bufferOffset?: number): void;\\n getChannelData(channel: number): Float32Array;\\n}\\n\\ndeclare var AudioBuffer: {\\n prototype: AudioBuffer;\\n new(options: AudioBufferOptions): AudioBuffer;\\n};\\n\\n/** An AudioScheduledSourceNode which represents an audio source consisting of in-memory audio data, stored in an AudioBuffer. It\'s especially useful for playing back audio which has particularly stringent timing accuracy requirements, such as for sounds that must match a specific rhythm and can be kept in memory rather than being played from disk or the network. */\\ninterface AudioBufferSourceNode extends AudioScheduledSourceNode {\\n buffer: AudioBuffer | null;\\n readonly detune: AudioParam;\\n loop: boolean;\\n loopEnd: number;\\n loopStart: number;\\n readonly playbackRate: AudioParam;\\n start(when?: number, offset?: number, duration?: number): void;\\n addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\\n removeEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\\n}\\n\\ndeclare var AudioBufferSourceNode: {\\n prototype: AudioBufferSourceNode;\\n new(context: BaseAudioContext, options?: AudioBufferSourceOptions): AudioBufferSourceNode;\\n};\\n\\n/** An audio-processing graph built from audio modules linked together, each represented by an AudioNode. */\\ninterface AudioContext extends BaseAudioContext {\\n readonly baseLatency: number;\\n readonly outputLatency: number;\\n close(): Promise;\\n createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode;\\n createMediaStreamDestination(): MediaStreamAudioDestinationNode;\\n createMediaStreamSource(mediaStream: MediaStream): MediaStreamAudioSourceNode;\\n getOutputTimestamp(): AudioTimestamp;\\n resume(): Promise;\\n suspend(): Promise;\\n addEventListener(type: K, listener: (this: AudioContext, ev: BaseAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\\n removeEventListener(type: K, listener: (this: AudioContext, ev: BaseAudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\\n}\\n\\ndeclare var AudioContext: {\\n prototype: AudioContext;\\n new(contextOptions?: AudioContextOptions): AudioContext;\\n};\\n\\n/** AudioDestinationNode has no output (as it is the output, no more AudioNode can be linked after it in the audio graph) and one input. The number of channels in the input must be between 0 and the maxChannelCount value or an exception is raised. */\\ninterface AudioDestinationNode extends AudioNode {\\n readonly maxChannelCount: number;\\n}\\n\\ndeclare var AudioDestinationNode: {\\n prototype: AudioDestinationNode;\\n new(): AudioDestinationNode;\\n};\\n\\n/** The position and orientation of the unique person listening to the audio scene, and is used in audio spatialization. All PannerNodes spatialize in relation to the AudioListener stored in the BaseAudioContext.listener attribute. */\\ninterface AudioListener {\\n readonly forwardX: AudioParam;\\n readonly forwardY: AudioParam;\\n readonly forwardZ: AudioParam;\\n readonly positionX: AudioParam;\\n readonly positionY: AudioParam;\\n readonly positionZ: AudioParam;\\n readonly upX: AudioParam;\\n readonly upY: AudioParam;\\n readonly upZ: AudioParam;\\n /** @deprecated */\\n setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void;\\n /** @deprecated */\\n setPosition(x: number, y: number, z: number): void;\\n}\\n\\ndeclare var AudioListener: {\\n prototype: AudioListener;\\n new(): AudioListener;\\n};\\n\\n/** A generic interface for representing an audio processing module. Examples include: */\\ninterface AudioNode extends EventTarget {\\n channelCount: number;\\n channelCountMode: ChannelCountMode;\\n channelInterpretation: ChannelInterpretation;\\n readonly context: BaseAudioContext;\\n readonly numberOfInputs: number;\\n readonly numberOfOutputs: number;\\n connect(destinationNode: AudioNode, output?: number, input?: number): AudioNode;\\n connect(destinationParam: AudioParam, output?: number): void;\\n disconnect(): void;\\n disconnect(output: number): void;\\n disconnect(destinationNode: AudioNode): void;\\n disconnect(destinationNode: AudioNode, output: number): void;\\n disconnect(destinationNode: AudioNode, output: number, input: number): void;\\n disconnect(destinationParam: AudioParam): void;\\n disconnect(destinationParam: AudioParam, output: number): void;\\n}\\n\\ndeclare var AudioNode: {\\n prototype: AudioNode;\\n new(): AudioNode;\\n};\\n\\n/** The Web Audio API\'s AudioParam interface represents an audio-related parameter, usually a parameter of an AudioNode (such as GainNode.gain). */\\ninterface AudioParam {\\n automationRate: AutomationRate;\\n readonly defaultValue: number;\\n readonly maxValue: number;\\n readonly minValue: number;\\n value: number;\\n cancelAndHoldAtTime(cancelTime: number): AudioParam;\\n cancelScheduledValues(cancelTime: number): AudioParam;\\n exponentialRampToValueAtTime(value: number, endTime: number): AudioParam;\\n linearRampToValueAtTime(value: number, endTime: number): AudioParam;\\n setTargetAtTime(target: number, startTime: number, timeConstant: number): AudioParam;\\n setValueAtTime(value: number, startTime: number): AudioParam;\\n setValueCurveAtTime(values: number[] | Float32Array, startTime: number, duration: number): AudioParam;\\n}\\n\\ndeclare var AudioParam: {\\n prototype: AudioParam;\\n new(): AudioParam;\\n};\\n\\ninterface AudioParamMap {\\n forEach(callbackfn: (value: AudioParam, key: string, parent: AudioParamMap) => void, thisArg?: any): void;\\n}\\n\\ndeclare var AudioParamMap: {\\n prototype: AudioParamMap;\\n new(): AudioParamMap;\\n};\\n\\n/**\\n * The Web Audio API events that occur when a ScriptProcessorNode input buffer is ready to be processed.\\n * @deprecated As of the August 29 2014 Web Audio API spec publication, this feature has been marked as deprecated, and is soon to be replaced by AudioWorklet.\\n */\\ninterface AudioProcessingEvent extends Event {\\n /** @deprecated */\\n readonly inputBuffer: AudioBuffer;\\n /** @deprecated */\\n readonly outputBuffer: AudioBuffer;\\n /** @deprecated */\\n readonly playbackTime: number;\\n}\\n\\n/** @deprecated */\\ndeclare var AudioProcessingEvent: {\\n prototype: AudioProcessingEvent;\\n new(type: string, eventInitDict: AudioProcessingEventInit): AudioProcessingEvent;\\n};\\n\\ninterface AudioScheduledSourceNodeEventMap {\\n \\"ended\\": Event;\\n}\\n\\ninterface AudioScheduledSourceNode extends AudioNode {\\n onended: ((this: AudioScheduledSourceNode, ev: Event) => any) | null;\\n start(when?: number): void;\\n stop(when?: number): void;\\n addEventListener(type: K, listener: (this: AudioScheduledSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\\n removeEventListener(type: K, listener: (this: AudioScheduledSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\\n}\\n\\ndeclare var AudioScheduledSourceNode: {\\n prototype: AudioScheduledSourceNode;\\n new(): AudioScheduledSourceNode;\\n};\\n\\n/** Available only in secure contexts. */\\ninterface AudioWorklet extends Worklet {\\n}\\n\\ndeclare var AudioWorklet: {\\n prototype: AudioWorklet;\\n new(): AudioWorklet;\\n};\\n\\ninterface AudioWorkletNodeEventMap {\\n \\"processorerror\\": Event;\\n}\\n\\n/** Available only in secure contexts. */\\ninterface AudioWorkletNode extends AudioNode {\\n onprocessorerror: ((this: AudioWorkletNode, ev: Event) => any) | null;\\n readonly parameters: AudioParamMap;\\n readonly port: MessagePort;\\n addEventListener(type: K, listener: (this: AudioWorkletNode, ev: AudioWorkletNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\\n removeEventListener(type: K, listener: (this: AudioWorkletNode, ev: AudioWorkletNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\\n}\\n\\ndeclare var AudioWorkletNode: {\\n prototype: AudioWorkletNode;\\n new(context: BaseAudioContext, name: string, options?: AudioWorkletNodeOptions): AudioWorkletNode;\\n};\\n\\n/** Available only in secure contexts. */\\ninterface AuthenticatorAssertionResponse extends AuthenticatorResponse {\\n readonly authenticatorData: ArrayBuffer;\\n readonly signature: ArrayBuffer;\\n readonly userHandle: ArrayBuffer | null;\\n}\\n\\ndeclare var AuthenticatorAssertionResponse: {\\n prototype: AuthenticatorAssertionResponse;\\n new(): AuthenticatorAssertionResponse;\\n};\\n\\n/** Available only in secure contexts. */\\ninterface AuthenticatorAttestationResponse extends AuthenticatorResponse {\\n readonly attestationObject: ArrayBuffer;\\n getAuthenticatorData(): ArrayBuffer;\\n getPublicKey(): ArrayBuffer | null;\\n getPublicKeyAlgorithm(): COSEAlgorithmIdentifier;\\n getTransports(): string[];\\n}\\n\\ndeclare var AuthenticatorAttestationResponse: {\\n prototype: AuthenticatorAttestationResponse;\\n new(): AuthenticatorAttestationResponse;\\n};\\n\\n/** Available only in secure contexts. */\\ninterface AuthenticatorResponse {\\n readonly clientDataJSON: ArrayBuffer;\\n}\\n\\ndeclare var AuthenticatorResponse: {\\n prototype: AuthenticatorResponse;\\n new(): AuthenticatorResponse;\\n};\\n\\ninterface BarProp {\\n readonly visible: boolean;\\n}\\n\\ndeclare var BarProp: {\\n prototype: BarProp;\\n new(): BarProp;\\n};\\n\\ninterface BaseAudioContextEventMap {\\n \\"statechange\\": Event;\\n}\\n\\ninterface BaseAudioContext extends EventTarget {\\n /** Available only in secure contexts. */\\n readonly audioWorklet: AudioWorklet;\\n readonly currentTime: number;\\n readonly destination: AudioDestinationNode;\\n readonly listener: AudioListener;\\n onstatechange: ((this: BaseAudioContext, ev: Event) => any) | null;\\n readonly sampleRate: number;\\n readonly state: AudioContextState;\\n createAnalyser(): AnalyserNode;\\n createBiquadFilter(): BiquadFilterNode;\\n createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer;\\n createBufferSource(): AudioBufferSourceNode;\\n createChannelMerger(numberOfInputs?: number): ChannelMergerNode;\\n createChannelSplitter(numberOfOutputs?: number): ChannelSplitterNode;\\n createConstantSource(): ConstantSourceNode;\\n createConvolver(): ConvolverNode;\\n createDelay(maxDelayTime?: number): DelayNode;\\n createDynamicsCompressor(): DynamicsCompressorNode;\\n createGain(): GainNode;\\n createIIRFilter(feedforward: number[], feedback: number[]): IIRFilterNode;\\n createOscillator(): OscillatorNode;\\n createPanner(): PannerNode;\\n createPeriodicWave(real: number[] | Float32Array, imag: number[] | Float32Array, constraints?: PeriodicWaveConstraints): PeriodicWave;\\n /** @deprecated */\\n createScriptProcessor(bufferSize?: number, numberOfInputChannels?: number, numberOfOutputChannels?: number): ScriptProcessorNode;\\n createStereoPanner(): StereoPannerNode;\\n createWaveShaper(): WaveShaperNode;\\n decodeAudioData(audioData: ArrayBuffer, successCallback?: DecodeSuccessCallback | null, errorCallback?: DecodeErrorCallback | null): Promise;\\n addEventListener(type: K, listener: (this: BaseAudioContext, ev: BaseAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\\n removeEventListener(type: K, listener: (this: BaseAudioContext, ev: BaseAudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\\n}\\n\\ndeclare var BaseAudioContext: {\\n prototype: BaseAudioContext;\\n new(): BaseAudioContext;\\n};\\n\\n/** The beforeunload event is fired when the window, the document and its resources are about to be unloaded. */\\ninterface BeforeUnloadEvent extends Event {\\n returnValue: any;\\n}\\n\\ndeclare var BeforeUnloadEvent: {\\n prototype: BeforeUnloadEvent;\\n new(): BeforeUnloadEvent;\\n};\\n\\n/** A simple low-order filter, and is created using the AudioContext.createBiquadFilter() method. It is an AudioNode that can represent different kinds of filters, tone control devices, and graphic equalizers. */\\ninterface BiquadFilterNode extends AudioNode {\\n readonly Q: AudioParam;\\n readonly detune: AudioParam;\\n readonly frequency: AudioParam;\\n readonly gain: AudioParam;\\n type: BiquadFilterType;\\n getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void;\\n}\\n\\ndeclare var BiquadFilterNode: {\\n prototype: BiquadFilterNode;\\n new(context: BaseAudioContext, options?: BiquadFilterOptions): BiquadFilterNode;\\n};\\n\\n/** A file-like object of immutable, raw data. Blobs represent data that isn\'t necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user\'s system. */\\ninterface Blob {\\n readonly size: number;\\n readonly type: string;\\n arrayBuffer(): Promise;\\n slice(start?: number, end?: number, contentType?: string): Blob;\\n stream(): ReadableStream;\\n text(): Promise;\\n}\\n\\ndeclare var Blob: {\\n prototype: Blob;\\n new(blobParts?: BlobPart[], options?: BlobPropertyBag): Blob;\\n};\\n\\ninterface BlobEvent extends Event {\\n readonly data: Blob;\\n readonly timecode: DOMHighResTimeStamp;\\n}\\n\\ndeclare var BlobEvent: {\\n prototype: BlobEvent;\\n new(type: string, eventInitDict: BlobEventInit): BlobEvent;\\n};\\n\\ninterface Body {\\n readonly body: ReadableStream | null;\\n readonly bodyUsed: boolean;\\n arrayBuffer(): Promise;\\n blob(): Promise;\\n formData(): Promise;\\n json(): Promise;\\n text(): Promise;\\n}\\n\\ninterface BroadcastChannelEventMap {\\n \\"message\\": MessageEvent;\\n \\"messageerror\\": MessageEvent;\\n}\\n\\ninterface BroadcastChannel extends EventTarget {\\n /** Returns the channel name (as passed to the constructor). */\\n readonly name: string;\\n onmessage: ((this: BroadcastChannel, ev: MessageEvent) => any) | null;\\n onmessageerror: ((this: BroadcastChannel, ev: MessageEvent) => any) | null;\\n /** Closes the BroadcastChannel object, opening it up to garbage collection. */\\n close(): void;\\n /** Sends the given message to other BroadcastChannel objects set up for this channel. Messages can be structured objects, e.g. nested objects and arrays. */\\n postMessage(message: any): void;\\n addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\\n removeEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\\n}\\n\\ndeclare var BroadcastChannel: {\\n prototype: BroadcastChannel;\\n new(name: string): BroadcastChannel;\\n};\\n\\n/** This Streams API interface provides\xa0a built-in byte length queuing strategy that can be used when constructing streams. */\\ninterface ByteLengthQueuingStrategy extends QueuingStrategy {\\n readonly highWaterMark: number;\\n readonly size: QueuingStrategySize;\\n}\\n\\ndeclare var ByteLengthQueuingStrategy: {\\n prototype: ByteLengthQueuingStrategy;\\n new(init: QueuingStrategyInit): ByteLengthQueuingStrategy;\\n};\\n\\n/** A CDATA section that can be used within XML to include extended portions of unescaped text. The symbols < and & don’t need escaping as they normally do when inside a CDATA section. */\\ninterface CDATASection extends Text {\\n}\\n\\ndeclare var CDATASection: {\\n prototype: CDATASection;\\n new(): CDATASection;\\n};\\n\\ninterface CSSAnimation extends Animation {\\n readonly animationName: string;\\n addEventListener(type: K, listener: (this: CSSAnimation, ev: AnimationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\\n removeEventListener(type: K, listener: (this: CSSAnimation, ev: AnimationEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\\n}\\n\\ndeclare var CSSAnimation: {\\n prototype: CSSAnimation;\\n new(): CSSAnimation;\\n};\\n\\n/** A single condition CSS at-rule, which consists of a condition and a statement block. It is a child of CSSGroupingRule. */\\ninterface CSSConditionRule extends CSSGroupingRule {\\n readonly conditionText: string;\\n}\\n\\ndeclare var CSSConditionRule: {\\n prototype: CSSConditionRule;\\n new(): CSSConditionRule;\\n};\\n\\ninterface CSSContainerRule extends CSSConditionRule {\\n}\\n\\ndeclare var CSSContainerRule: {\\n prototype: CSSContainerRule;\\n new(): CSSContainerRule;\\n};\\n\\ninterface CSSCounterStyleRule extends CSSRule {\\n additiveSymbols: string;\\n fallback: string;\\n name: string;\\n negative: string;\\n pad: string;\\n prefix: string;\\n range: string;\\n speakAs: string;\\n suffix: string;\\n symbols: string;\\n system: string;\\n}\\n\\ndeclare var CSSCounterStyleRule: {\\n prototype: CSSCounterStyleRule;\\n new(): CSSCounterStyleRule;\\n};\\n\\ninterface CSSFontFaceRule extends CSSRule {\\n readonly style: CSSStyleDeclaration;\\n}\\n\\ndeclare var CSSFontFaceRule: {\\n prototype: CSSFontFaceRule;\\n new(): CSSFontFaceRule;\\n};\\n\\ninterface CSSFontFeatureValuesRule extends CSSRule {\\n fontFamily: string;\\n}\\n\\ndeclare var CSSFontFeatureValuesRule: {\\n prototype: CSSFontFeatureValuesRule;\\n new(): CSSFontFeatureValuesRule;\\n};\\n\\ninterface CSSFontPaletteValuesRule extends CSSRule {\\n readonly basePalette: string;\\n readonly fontFamily: string;\\n readonly name: string;\\n readonly overrideColors: string;\\n}\\n\\ndeclare var CSSFontPaletteValuesRule: {\\n prototype: CSSFontPaletteValuesRule;\\n new(): CSSFontPaletteValuesRule;\\n};\\n\\n/** Any CSS at-rule that contains other rules nested within it. */\\ninterface CSSGroupingRule extends CSSRule {\\n readonly cssRules: CSSRuleList;\\n deleteRule(index: number): void;\\n insertRule(rule: string, index?: number): number;\\n}\\n\\ndeclare var CSSGroupingRule: {\\n prototype: CSSGroupingRule;\\n new(): CSSGroupingRule;\\n};\\n\\ninterface CSSImportRule extends CSSRule {\\n readonly href: string;\\n readonly layerName: string | null;\\n readonly media: MediaList;\\n readonly styleSheet: CSSStyleSheet;\\n}\\n\\ndeclare var CSSImportRule: {\\n prototype: CSSImportRule;\\n new(): CSSImportRule;\\n};\\n\\n/** An object representing a set of style for a given keyframe. It corresponds to the contains of a single keyframe of a @keyframes at-rule. It implements the CSSRule interface with a type value of 8 (CSSRule.KEYFRAME_RULE). */\\ninterface CSSKeyframeRule extends CSSRule {\\n keyText: string;\\n readonly style: CSSStyleDeclaration;\\n}\\n\\ndeclare var CSSKeyframeRule: {\\n prototype: CSSKeyframeRule;\\n new(): CSSKeyframeRule;\\n};\\n\\n/** An object representing a complete set of keyframes for a CSS animation. It corresponds to the contains of a whole @keyframes at-rule. It implements the CSSRule interface with a type value of 7 (CSSRule.KEYFRAMES_RULE). */\\ninterface CSSKeyframesRule extends CSSRule {\\n readonly cssRules: CSSRuleList;\\n name: string;\\n appendRule(rule: string): void;\\n deleteRule(select: string): void;\\n findRule(select: string): CSSKeyframeRule | null;\\n [index: number]: CSSKeyframeRule;\\n}\\n\\ndeclare var CSSKeyframesRule: {\\n prototype: CSSKeyframesRule;\\n new(): CSSKeyframesRule;\\n};\\n\\ninterface CSSLayerBlockRule extends CSSGroupingRule {\\n readonly name: string;\\n}\\n\\ndeclare var CSSLayerBlockRule: {\\n prototype: CSSLayerBlockRule;\\n new(): CSSLayerBlockRule;\\n};\\n\\ninterface CSSLayerStatementRule extends CSSRule {\\n readonly nameList: ReadonlyArray;\\n}\\n\\ndeclare var CSSLayerStatementRule: {\\n prototype: CSSLayerStatementRule;\\n new(): CSSLayerStatementRule;\\n};\\n\\n/** A single CSS @media rule. It implements the CSSConditionRule interface, and therefore the CSSGroupingRule and the CSSRule interface with a type value of 4 (CSSRule.MEDIA_RULE). */\\ninterface CSSMediaRule extends CSSConditionRule {\\n readonly media: MediaList;\\n}\\n\\ndeclare var CSSMediaRule: {\\n prototype: CSSMediaRule;\\n new(): CSSMediaRule;\\n};\\n\\n/** An object representing a single CSS @namespace at-rule. It implements the CSSRule interface, with a type value of 10 (CSSRule.NAMESPACE_RULE). */\\ninterface CSSNamespaceRule extends CSSRule {\\n readonly namespaceURI: string;\\n readonly prefix: string;\\n}\\n\\ndeclare var CSSNamespaceRule: {\\n prototype: CSSNamespaceRule;\\n new(): CSSNamespaceRule;\\n};\\n\\n/** CSSPageRule is an interface representing a single CSS @page rule. It implements the CSSRule interface with a type value of 6 (CSSRule.PAGE_RULE). */\\ninterface CSSPageRule extends CSSGroupingRule {\\n selectorText: string;\\n readonly style: CSSStyleDeclaration;\\n}\\n\\ndeclare var CSSPageRule: {\\n prototype: CSSPageRule;\\n new(): CSSPageRule;\\n};\\n\\n/** A single CSS rule. There are several types of rules, listed in the Type constants section below. */\\ninterface CSSRule {\\n cssText: string;\\n readonly parentRule: CSSRule | null;\\n readonly parentStyleSheet: CSSStyleSheet | null;\\n /** @deprecated */\\n readonly type: number;\\n readonly STYLE_RULE: 1;\\n readonly CHARSET_RULE: 2;\\n readonly IMPORT_RULE: 3;\\n readonly MEDIA_RULE: 4;\\n readonly FONT_FACE_RULE: 5;\\n readonly PAGE_RULE: 6;\\n readonly NAMESPACE_RULE: 10;\\n readonly KEYFRAMES_RULE: 7;\\n readonly KEYFRAME_RULE: 8;\\n readonly SUPPORTS_RULE: 12;\\n}\\n\\ndeclare var CSSRule: {\\n prototype: CSSRule;\\n new(): CSSRule;\\n readonly STYLE_RULE: 1;\\n readonly CHARSET_RULE: 2;\\n readonly IMPORT_RULE: 3;\\n readonly MEDIA_RULE: 4;\\n readonly FONT_FACE_RULE: 5;\\n readonly PAGE_RULE: 6;\\n readonly NAMESPACE_RULE: 10;\\n readonly KEYFRAMES_RULE: 7;\\n readonly KEYFRAME_RULE: 8;\\n readonly SUPPORTS_RULE: 12;\\n};\\n\\n/** A CSSRuleList is an (indirect-modify only) array-like object containing an ordered collection of CSSRule objects. */\\ninterface CSSRuleList {\\n readonly length: number;\\n item(index: number): CSSRule | null;\\n [index: number]: CSSRule;\\n}\\n\\ndeclare var CSSRuleList: {\\n prototype: CSSRuleList;\\n new(): CSSRuleList;\\n};\\n\\n/** An object that is a CSS declaration block, and exposes style information and various style-related methods and properties. */\\ninterface CSSStyleDeclaration {\\n accentColor: string;\\n alignContent: string;\\n alignItems: string;\\n alignSelf: string;\\n alignmentBaseline: string;\\n all: string;\\n animation: string;\\n animationDelay: string;\\n animationDirection: string;\\n animationDuration: string;\\n animationFillMode: string;\\n animationIterationCount: string;\\n animationName: string;\\n animationPlayState: string;\\n animationTimingFunction: string;\\n appearance: string;\\n aspectRatio: string;\\n backdropFilter: string;\\n backfaceVisibility: string;\\n background: string;\\n backgroundAttachment: string;\\n backgroundBlendMode: string;\\n backgroundClip: string;\\n backgroundColor: string;\\n backgroundImage: string;\\n backgroundOrigin: string;\\n backgroundPosition: string;\\n backgroundPositionX: string;\\n backgroundPositionY: string;\\n backgroundRepeat: string;\\n backgroundSize: string;\\n baselineShift: string;\\n blockSize: string;\\n border: string;\\n borderBlock: string;\\n borderBlockColor: string;\\n borderBlockEnd: string;\\n borderBlockEndColor: string;\\n borderBlockEndStyle: string;\\n borderBlockEndWidth: string;\\n borderBlockStart: string;\\n borderBlockStartColor: string;\\n borderBlockStartStyle: string;\\n borderBlockStartWidth: string;\\n borderBlockStyle: string;\\n borderBlockWidth: string;\\n borderBottom: string;\\n borderBottomColor: string;\\n borderBottomLeftRadius: string;\\n borderBottomRightRadius: string;\\n borderBottomStyle: string;\\n borderBottomWidth: string;\\n borderCollapse: string;\\n borderColor: string;\\n borderEndEndRadius: string;\\n borderEndStartRadius: string;\\n borderImage: string;\\n borderImageOutset: string;\\n borderImageRepeat: string;\\n borderImageSlice: string;\\n borderImageSource: string;\\n borderImageWidth: string;\\n borderInline: string;\\n borderInlineColor: string;\\n borderInlineEnd: string;\\n borderInlineEndColor: string;\\n borderInlineEndStyle: string;\\n borderInlineEndWidth: string;\\n borderInlineStart: string;\\n borderInlineStartColor: string;\\n borderInlineStartStyle: string;\\n borderInlineStartWidth: string;\\n borderInlineStyle: string;\\n borderInlineWidth: string;\\n borderLeft: string;\\n borderLeftColor: string;\\n borderLeftStyle: string;\\n borderLeftWidth: string;\\n borderRadius: string;\\n borderRight: string;\\n borderRightColor: string;\\n borderRightStyle: string;\\n borderRightWidth: string;\\n borderSpacing: string;\\n borderStartEndRadius: string;\\n borderStartStartRadius: string;\\n borderStyle: string;\\n borderTop: string;\\n borderTopColor: string;\\n borderTopLeftRadius: string;\\n borderTopRightRadius: string;\\n borderTopStyle: string;\\n borderTopWidth: string;\\n borderWidth: string;\\n bottom: string;\\n boxShadow: string;\\n boxSizing: string;\\n breakAfter: string;\\n breakBefore: string;\\n breakInside: string;\\n captionSide: string;\\n caretColor: string;\\n clear: string;\\n /** @deprecated */\\n clip: string;\\n clipPath: string;\\n clipRule: string;\\n color: string;\\n colorInterpolation: string;\\n colorInterpolationFilters: string;\\n colorScheme: string;\\n columnCount: string;\\n columnFill: string;\\n columnGap: string;\\n columnRule: string;\\n columnRuleColor: string;\\n columnRuleStyle: string;\\n columnRuleWidth: string;\\n columnSpan: string;\\n columnWidth: string;\\n columns: string;\\n contain: string;\\n containIntrinsicBlockSize: string;\\n containIntrinsicHeight: string;\\n containIntrinsicInlineSize: string;\\n containIntrinsicSize: string;\\n containIntrinsicWidth: string;\\n container: string;\\n containerName: string;\\n containerType: string;\\n content: string;\\n contentVisibility: string;\\n counterIncrement: string;\\n counterReset: string;\\n counterSet: string;\\n cssFloat: string;\\n cssText: string;\\n cursor: string;\\n direction: string;\\n display: string;\\n dominantBaseline: string;\\n emptyCells: string;\\n fill: string;\\n fillOpacity: string;\\n fillRule: string;\\n filter: string;\\n flex: string;\\n flexBasis: string;\\n flexDirection: string;\\n flexFlow: string;\\n flexGrow: string;\\n flexShrink: string;\\n flexWrap: string;\\n float: string;\\n floodColor: string;\\n floodOpacity: string;\\n font: string;\\n fontFamily: string;\\n fontFeatureSettings: string;\\n fontKerning: string;\\n fontOpticalSizing: string;\\n fontPalette: string;\\n fontSize: string;\\n fontSizeAdjust: string;\\n fontStretch: string;\\n fontStyle: string;\\n fontSynthesis: string;\\n fontVariant: string;\\n fontVariantAlternates: string;\\n fontVariantCaps: string;\\n fontVariantEastAsian: string;\\n fontVariantLigatures: string;\\n fontVariantNumeric: string;\\n fontVariantPosition: string;\\n fontVariationSettings: string;\\n fontWeight: string;\\n gap: string;\\n grid: string;\\n gridArea: string;\\n gridAutoColumns: string;\\n gridAutoFlow: string;\\n gridAutoRows: string;\\n gridColumn: string;\\n gridColumnEnd: string;\\n /** @deprecated This is a legacy alias of `columnGap`. */\\n gridColumnGap: string;\\n gridColumnStart: string;\\n /** @deprecated This is a legacy alias of `gap`. */\\n gridGap: string;\\n gridRow: string;\\n gridRowEnd: string;\\n /** @deprecated This is a legacy alias of `rowGap`. */\\n gridRowGap: string;\\n gridRowStart: string;\\n gridTemplate: string;\\n gridTemplateAreas: string;\\n gridTemplateColumns: string;\\n gridTemplateRows: string;\\n height: string;\\n hyphenateCharacter: string;\\n hyphens: string;\\n /** @deprecated */\\n imageOrientation: string;\\n imageRendering: string;\\n inlineSize: string;\\n inset: string;\\n insetBlock: string;\\n insetBlockEnd: string;\\n insetBlockStart: string;\\n insetInline: string;\\n insetInlineEnd: string;\\n insetInlineStart: string;\\n isolation: string;\\n justifyContent: string;\\n justifyItems: string;\\n justifySelf: string;\\n left: string;\\n readonly length: number;\\n letterSpacing: string;\\n lightingColor: string;\\n lineBreak: string;\\n lineHeight: string;\\n listStyle: string;\\n listStyleImage: string;\\n listStylePosition: string;\\n listStyleType: string;\\n margin: string;\\n marginBlock: string;\\n marginBlockEnd: string;\\n marginBlockStart: string;\\n marginBottom: string;\\n marginInline: string;\\n marginInlineEnd: string;\\n marginInlineStart: string;\\n marginLeft: string;\\n marginRight: string;\\n marginTop: string;\\n marker: string;\\n markerEnd: string;\\n markerMid: string;\\n markerStart: string;\\n mask: string;\\n maskClip: string;\\n maskComposite: string;\\n maskImage: string;\\n maskMode: string;\\n maskOrigin: string;\\n maskPosition: string;\\n maskRepeat: string;\\n maskSize: string;\\n maskType: string;\\n mathStyle: string;\\n maxBlockSize: string;\\n maxHeight: string;\\n maxInlineSize: string;\\n maxWidth: string;\\n minBlockSize: string;\\n minHeight: string;\\n minInlineSize: string;\\n minWidth: string;\\n mixBlendMode: string;\\n objectFit: string;\\n objectPosition: string;\\n offset: string;\\n offsetDistance: string;\\n offsetPath: string;\\n offsetRotate: string;\\n opacity: string;\\n order: string;\\n orphans: string;\\n outline: string;\\n outlineColor: string;\\n outlineOffset: string;\\n outlineStyle: string;\\n outlineWidth: string;\\n overflow: string;\\n overflowAnchor: string;\\n overflowClipMargin: string;\\n overflowWrap: string;\\n overflowX: string;\\n overflowY: string;\\n overscrollBehavior: string;\\n overscrollBehaviorBlock: string;\\n overscrollBehaviorInline: string;\\n overscrollBehaviorX: string;\\n overscrollBehaviorY: string;\\n padding: string;\\n paddingBlock: string;\\n paddingBlockEnd: string;\\n paddingBlockStart: string;\\n paddingBottom: string;\\n paddingInline: string;\\n paddingInlineEnd: string;\\n paddingInlineStart: string;\\n paddingLeft: string;\\n paddingRight: string;\\n paddingTop: string;\\n pageBreakAfter: string;\\n pageBreakBefore: string;\\n pageBreakInside: string;\\n paintOrder: string;\\n readonly parentRule: CSSRule | null;\\n perspective: string;\\n perspectiveOrigin: string;\\n placeContent: string;\\n placeItems: string;\\n placeSelf: string;\\n pointerEvents: string;\\n position: string;\\n printColorAdjust: string;\\n quotes: string;\\n resize: string;\\n right: string;\\n rotate: string;\\n rowGap: string;\\n rubyPosition: string;\\n scale: string;\\n scrollBehavior: string;\\n scrollMargin: string;\\n scrollMarginBlock: string;\\n scrollMarginBlockEnd: string;\\n scrollMarginBlockStart: string;\\n scrollMarginBottom: string;\\n scrollMarginInline: string;\\n scrollMarginInlineEnd: string;\\n scrollMarginInlineStart: string;\\n scrollMarginLeft: string;\\n scrollMarginRight: string;\\n scrollMarginTop: string;\\n scrollPadding: string;\\n scrollPaddingBlock: string;\\n scrollPaddingBlockEnd: string;\\n scrollPaddingBlockStart: string;\\n scrollPaddingBottom: string;\\n scrollPaddingInline: string;\\n scrollPaddingInlineEnd: string;\\n scrollPaddingInlineStart: string;\\n scrollPaddingLeft: string;\\n scrollPaddingRight: string;\\n scrollPaddingTop: string;\\n scrollSnapAlign: string;\\n scrollSnapStop: string;\\n scrollSnapType: string;\\n scrollbarGutter: string;\\n shapeImageThreshold: string;\\n shapeMargin: string;\\n shapeOutside: string;\\n shapeRendering: string;\\n stopColor: string;\\n stopOpacity: string;\\n stroke: string;\\n strokeDasharray: string;\\n strokeDashoffset: string;\\n strokeLinecap: string;\\n strokeLinejoin: string;\\n strokeMiterlimit: string;\\n strokeOpacity: string;\\n strokeWidth: string;\\n tabSize: string;\\n tableLayout: string;\\n textAlign: string;\\n textAlignLast: string;\\n textAnchor: string;\\n textCombineUpright: string;\\n textDecoration: string;\\n textDecorationColor: string;\\n textDecorationLine: string;\\n textDecorationSkipInk: string;\\n textDecorationStyle: string;\\n textDecorationThickness: string;\\n textEmphasis: string;\\n textEmphasisColor: string;\\n textEmphasisPosition: string;\\n textEmphasisStyle: string;\\n textIndent: string;\\n textOrientation: string;\\n textOverflow: string;\\n textRendering: string;\\n textShadow: string;\\n textTransform: string;\\n textUnderlineOffset: string;\\n textUnderlinePosition: string;\\n top: string;\\n touchAction: string;\\n transform: string;\\n transformBox: string;\\n transformOrigin: string;\\n transformStyle: string;\\n transition: string;\\n transitionDelay: string;\\n transitionDuration: string;\\n transitionProperty: string;\\n transitionTimingFunction: string;\\n translate: string;\\n unicodeBidi: string;\\n userSelect: string;\\n verticalAlign: string;\\n visibility: string;\\n /** @deprecated This is a legacy alias of `alignContent`. */\\n webkitAlignContent: string;\\n /** @deprecated This is a legacy alias of `alignItems`. */\\n webkitAlignItems: string;\\n /** @deprecated This is a legacy alias of `alignSelf`. */\\n webkitAlignSelf: string;\\n /** @deprecated This is a legacy alias of `animation`. */\\n webkitAnimation: string;\\n /** @deprecated This is a legacy alias of `animationDelay`. */\\n webkitAnimationDelay: string;\\n /** @deprecated This is a legacy alias of `animationDirection`. */\\n webkitAnimationDirection: string;\\n /** @deprecated This is a legacy alias of `animationDuration`. */\\n webkitAnimationDuration: string;\\n /** @deprecated This is a legacy alias of `animationFillMode`. */\\n webkitAnimationFillMode: string;\\n /** @deprecated This is a legacy alias of `animationIterationCount`. */\\n webkitAnimationIterationCount: string;\\n /** @deprecated This is a legacy alias of `animationName`. */\\n webkitAnimationName: string;\\n /** @deprecated This is a legacy alias of `animationPlayState`. */\\n webkitAnimationPlayState: string;\\n /** @deprecated This is a legacy alias of `animationTimingFunction`. */\\n webkitAnimationTimingFunction: string;\\n /** @deprecated This is a legacy alias of `appearance`. */\\n webkitAppearance: string;\\n /** @deprecated This is a legacy alias of `backfaceVisibility`. */\\n webkitBackfaceVisibility: string;\\n /** @deprecated This is a legacy alias of `backgroundClip`. */\\n webkitBackgroundClip: string;\\n /** @deprecated This is a legacy alias of `backgroundOrigin`. */\\n webkitBackgroundOrigin: string;\\n /** @deprecated This is a legacy alias of `backgroundSize`. */\\n webkitBackgroundSize: string;\\n /** @deprecated This is a legacy alias of `borderBottomLeftRadius`. */\\n webkitBorderBottomLeftRadius: string;\\n /** @deprecated This is a legacy alias of `borderBottomRightRadius`. */\\n webkitBorderBottomRightRadius: string;\\n /** @deprecated This is a legacy alias of `borderRadius`. */\\n webkitBorderRadius: string;\\n /** @deprecated This is a legacy alias of `borderTopLeftRadius`. */\\n webkitBorderTopLeftRadius: string;\\n /** @deprecated This is a legacy alias of `borderTopRightRadius`. */\\n webkitBorderTopRightRadius: string;\\n /** @deprecated This is a legacy alias of `boxAlign`. */\\n webkitBoxAlign: string;\\n /** @deprecated This is a legacy alias of `boxFlex`. */\\n webkitBoxFlex: string;\\n /** @deprecated This is a legacy alias of `boxOrdinalGroup`. */\\n webkitBoxOrdinalGroup: string;\\n /** @deprecated This is a legacy alias of `boxOrient`. */\\n webkitBoxOrient: string;\\n /** @deprecated This is a legacy alias of `boxPack`. */\\n webkitBoxPack: string;\\n /** @deprecated This is a legacy alias of `boxShadow`. */\\n webkitBoxShadow: string;\\n /** @deprecated This is a legacy alias of `boxSizing`. */\\n webkitBoxSizing: string;\\n /** @deprecated This is a legacy alias of `filter`. */\\n webkitFilter: string;\\n /** @deprecated This is a legacy alias of `flex`. */\\n webkitFlex: string;\\n /** @deprecated This is a legacy alias of `flexBasis`. */\\n webkitFlexBasis: string;\\n /** @deprecated This is a legacy alias of `flexDirection`. */\\n webkitFlexDirection: string;\\n /** @deprecated This is a legacy alias of `flexFlow`. */\\n webkitFlexFlow: string;\\n /** @deprecated This is a legacy alias of `flexGrow`. */\\n webkitFlexGrow: string;\\n /** @deprecated This is a legacy alias of `flexShrink`. */\\n webkitFlexShrink: string;\\n /** @deprecated This is a legacy alias of `flexWrap`. */\\n webkitFlexWrap: string;\\n /** @deprecated This is a legacy alias of `justifyContent`. */\\n webkitJustifyContent: string;\\n webkitLineClamp: string;\\n /** @deprecated This is a legacy alias of `mask`. */\\n webkitMask: string;\\n /** @deprecated This is a legacy alias of `maskBorder`. */\\n webkitMaskBoxImage: string;\\n /** @deprecated This is a legacy alias of `maskBorderOutset`. */\\n webkitMaskBoxImageOutset: string;\\n /** @deprecated This is a legacy alias of `maskBorderRepeat`. */\\n webkitMaskBoxImageRepeat: string;\\n /** @deprecated This is a legacy alias of `maskBorderSlice`. */\\n webkitMaskBoxImageSlice: string;\\n /** @deprecated This is a legacy alias of `maskBorderSource`. */\\n webkitMaskBoxImageSource: string;\\n /** @deprecated This is a legacy alias of `maskBorderWidth`. */\\n webkitMaskBoxImageWidth: string;\\n /** @deprecated This is a legacy alias of `maskClip`. */\\n webkitMaskClip: string;\\n webkitMaskComposite: string;\\n /** @deprecated This is a legacy alias of `maskImage`. */\\n webkitMaskImage: string;\\n /** @deprecated This is a legacy alias of `maskOrigin`. */\\n webkitMaskOrigin: string;\\n /** @deprecated This is a legacy alias of `maskPosition`. */\\n webkitMaskPosition: string;\\n /** @deprecated This is a legacy alias of `maskRepeat`. */\\n webkitMaskRepeat: string;\\n /** @deprecated This is a legacy alias of `maskSize`. */\\n webkitMaskSize: string;\\n /** @deprecated This is a legacy alias of `order`. */\\n webkitOrder: string;\\n /** @deprecated This is a legacy alias of `perspective`. */\\n webkitPerspective: string;\\n /** @deprecated This is a legacy alias of `perspectiveOrigin`. */\\n webkitPerspectiveOrigin: string;\\n webkitTextFillColor: string;\\n /** @deprecated This is a legacy alias of `textSizeAdjust`. */\\n webkitTextSizeAdjust: string;\\n webkitTextStroke: string;\\n webkitTextStrokeColor: string;\\n webkitTextStrokeWidth: string;\\n /** @deprecated This is a legacy alias of `transform`. */\\n webkitTransform: string;\\n /** @deprecated This is a legacy alias of `transformOrigin`. */\\n webkitTransformOrigin: string;\\n /** @deprecated This is a legacy alias of `transformStyle`. */\\n webkitTransformStyle: string;\\n /** @deprecated This is a legacy alias of `transition`. */\\n webkitTransition: string;\\n /** @deprecated This is a legacy alias of `transitionDelay`. */\\n webkitTransitionDelay: string;\\n /** @deprecated This is a legacy alias of `transitionDuration`. */\\n webkitTransitionDuration: string;\\n /** @deprecated This is a legacy alias of `transitionProperty`. */\\n webkitTransitionProperty: string;\\n /** @deprecated This is a legacy alias of `transitionTimingFunction`. */\\n webkitTransitionTimingFunction: string;\\n /** @deprecated This is a legacy alias of `userSelect`. */\\n webkitUserSelect: string;\\n whiteSpace: string;\\n widows: string;\\n width: string;\\n willChange: string;\\n wordBreak: string;\\n wordSpacing: string;\\n /** @deprecated */\\n wordWrap: string;\\n writingMode: string;\\n zIndex: string;\\n getPropertyPriority(property: string): string;\\n getPropertyValue(property: string): string;\\n item(index: number): string;\\n removeProperty(property: string): string;\\n setProperty(property: string, value: string | null, priority?: string): void;\\n [index: number]: string;\\n}\\n\\ndeclare var CSSStyleDeclaration: {\\n prototype: CSSStyleDeclaration;\\n new(): CSSStyleDeclaration;\\n};\\n\\n/** CSSStyleRule represents a single CSS style rule. It implements the CSSRule interface with a type value of 1 (CSSRule.STYLE_RULE). */\\ninterface CSSStyleRule extends CSSRule {\\n selectorText: string;\\n readonly style: CSSStyleDeclaration;\\n}\\n\\ndeclare var CSSStyleRule: {\\n prototype: CSSStyleRule;\\n new(): CSSStyleRule;\\n};\\n\\n/** A single CSS style sheet. It inherits properties and methods from its parent, StyleSheet. */\\ninterface CSSStyleSheet extends StyleSheet {\\n readonly cssRules: CSSRuleList;\\n readonly ownerRule: CSSRule | null;\\n /** @deprecated */\\n readonly rules: CSSRuleList;\\n /** @deprecated */\\n addRule(selector?: string, style?: string, index?: number): number;\\n deleteRule(index: number): void;\\n insertRule(rule: string, index?: number): number;\\n /** @deprecated */\\n removeRule(index?: number): void;\\n replace(text: string): Promise;\\n replaceSync(text: string): void;\\n}\\n\\ndeclare var CSSStyleSheet: {\\n prototype: CSSStyleSheet;\\n new(options?: CSSStyleSheetInit): CSSStyleSheet;\\n};\\n\\n/** An object representing a single CSS @supports at-rule. It implements the CSSConditionRule interface, and therefore the CSSRule and CSSGroupingRule interfaces with a type value of 12 (CSSRule.SUPPORTS_RULE). */\\ninterface CSSSupportsRule extends CSSConditionRule {\\n}\\n\\ndeclare var CSSSupportsRule: {\\n prototype: CSSSupportsRule;\\n new(): CSSSupportsRule;\\n};\\n\\ninterface CSSTransition extends Animation {\\n readonly transitionProperty: string;\\n addEventListener(type: K, listener: (this: CSSTransition, ev: AnimationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\\n removeEventListener(type: K, listener: (this: CSSTransition, ev: AnimationEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\\n}\\n\\ndeclare var CSSTransition: {\\n prototype: CSSTransition;\\n new(): CSSTransition;\\n};\\n\\n/**\\n * Provides a storage mechanism for Request / Response object pairs that are cached, for example as part of the ServiceWorker life cycle. Note that the Cache interface is exposed to windowed scopes as well as workers. You don\'t have to use it in conjunction with service workers, even though it is defined in the service worker spec.\\n * Available only in secure contexts.\\n */\\ninterface Cache {\\n add(request: RequestInfo | URL): Promise;\\n addAll(requests: RequestInfo[]): Promise;\\n delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise;\\n keys(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>;\\n match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise;\\n matchAll(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>;\\n put(request: RequestInfo | URL, response: Response): Promise;\\n}\\n\\ndeclare var Cache: {\\n prototype: Cache;\\n new(): Cache;\\n};\\n\\n/**\\n * The storage for Cache objects.\\n * Available only in secure contexts.\\n */\\ninterface CacheStorage {\\n delete(cacheName: string): Promise;\\n has(cacheName: string): Promise;\\n keys(): Promise;\\n match(request: RequestInfo | URL, options?: MultiCacheQueryOptions): Promise;\\n open(cacheName: string): Promise;\\n}\\n\\ndeclare var CacheStorage: {\\n prototype: CacheStorage;\\n new(): CacheStorage;\\n};\\n\\ninterface CanvasCaptureMediaStreamTrack extends MediaStreamTrack {\\n readonly canvas: HTMLCanvasElement;\\n requestFrame(): void;\\n addEventListener(type: K, listener: (this: CanvasCaptureMediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\\n removeEventListener(type: K, listener: (this: CanvasCaptureMediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\\n}\\n\\ndeclare var CanvasCaptureMediaStreamTrack: {\\n prototype: CanvasCaptureMediaStreamTrack;\\n new(): CanvasCaptureMediaStreamTrack;\\n};\\n\\ninterface CanvasCompositing {\\n globalAlpha: number;\\n globalCompositeOperation: GlobalCompositeOperation;\\n}\\n\\ninterface CanvasDrawImage {\\n drawImage(image: CanvasImageSource, dx: number, dy: number): void;\\n drawImage(image: CanvasImageSource, dx: number, dy: number, dw: number, dh: number): void;\\n drawImage(image: CanvasImageSource, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void;\\n}\\n\\ninterface CanvasDrawPath {\\n beginPath(): void;\\n clip(fillRule?: CanvasFillRule): void;\\n clip(path: Path2D, fillRule?: CanvasFillRule): void;\\n fill(fillRule?: CanvasFillRule): void;\\n fill(path: Path2D, fillRule?: CanvasFillRule): void;\\n isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean;\\n isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean;\\n isPointInStroke(x: number, y: number): boolean;\\n isPointInStroke(path: Path2D, x: number, y: number): boolean;\\n stroke(): void;\\n stroke(path: Path2D): void;\\n}\\n\\ninterface CanvasFillStrokeStyles {\\n fillStyle: string | CanvasGradient | CanvasPattern;\\n strokeStyle: string | CanvasGradient | CanvasPattern;\\n createConicGradient(startAngle: number, x: number, y: number): CanvasGradient;\\n createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient;\\n createPattern(image: CanvasImageSource, repetition: string | null): CanvasPattern | null;\\n createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient;\\n}\\n\\ninterface CanvasFilters {\\n filter: string;\\n}\\n\\n/** An opaque object describing a gradient. It is returned by the methods CanvasRenderingContext2D.createLinearGradient() or CanvasRenderingContext2D.createRadialGradient(). */\\ninterface CanvasGradient {\\n /**\\n * Adds a color stop with the given color to the gradient at the given offset. 0.0 is the offset at one end of the gradient, 1.0 is the offset at the other end.\\n *\\n * Throws an \\"IndexSizeError\\" DOMException if the offset is out of range. Throws a \\"SyntaxError\\" DOMException if the color cannot be parsed.\\n */\\n addColorStop(offset: number, color: string): void;\\n}\\n\\ndeclare var CanvasGradient: {\\n prototype: CanvasGradient;\\n new(): CanvasGradient;\\n};\\n\\ninterface CanvasImageData {\\n createImageData(sw: number, sh: number, settings?: ImageDataSettings): ImageData;\\n createImageData(imagedata: ImageData): ImageData;\\n getImageData(sx: number, sy: number, sw: number, sh: number, settings?: ImageDataSettings): ImageData;\\n putImageData(imagedata: ImageData, dx: number, dy: number): void;\\n putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth: number, dirtyHeight: number): void;\\n}\\n\\ninterface CanvasImageSmoothing {\\n imageSmoothingEnabled: boolean;\\n imageSmoothingQuality: ImageSmoothingQuality;\\n}\\n\\ninterface CanvasPath {\\n arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void;\\n arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void;\\n bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void;\\n closePath(): void;\\n ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void;\\n lineTo(x: number, y: number): void;\\n moveTo(x: number, y: number): void;\\n quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void;\\n rect(x: number, y: number, w: number, h: number): void;\\n roundRect(x: number, y: number, w: number, h: number, radii?: number | DOMPointInit | (number | DOMPointInit)[]): void;\\n}\\n\\ninterface CanvasPathDrawingStyles {\\n lineCap: CanvasLineCap;\\n lineDashOffset: number;\\n lineJoin: CanvasLineJoin;\\n lineWidth: number;\\n miterLimit: number;\\n getLineDash(): number[];\\n setLineDash(segments: number[]): void;\\n}\\n\\n/** An opaque object describing a pattern, based on an image, a canvas, or a video, created by the CanvasRenderingContext2D.createPattern() method. */\\ninterface CanvasPattern {\\n /** Sets the transformation matrix that will be used when rendering the pattern during a fill or stroke painting operation. */\\n setTransform(transform?: DOMMatrix2DInit): void;\\n}\\n\\ndeclare var CanvasPattern: {\\n prototype: CanvasPattern;\\n new(): CanvasPattern;\\n};\\n\\ninterface CanvasRect {\\n clearRect(x: number, y: number, w: number, h: number): void;\\n fillRect(x: number, y: number, w: number, h: number): void;\\n strokeRect(x: number, y: number, w: number, h: number): void;\\n}\\n\\n/** The CanvasRenderingContext2D interface, part of the Canvas API, provides the 2D rendering context for the drawing surface of a element. It is used for drawing shapes, text, images, and other objects. */\\ninterface CanvasRenderingContext2D extends CanvasCompositing, CanvasDrawImage, CanvasDrawPath, CanvasFillStrokeStyles, CanvasFilters, CanvasImageData, CanvasImageSmoothing, CanvasPath, CanvasPathDrawingStyles, CanvasRect, CanvasShadowStyles, CanvasState, CanvasText, CanvasTextDrawingStyles, CanvasTransform, CanvasUserInterface {\\n readonly canvas: HTMLCanvasElement;\\n getContextAttributes(): CanvasRenderingContext2DSettings;\\n}\\n\\ndeclare var CanvasRenderingContext2D: {\\n prototype: CanvasRenderingContext2D;\\n new(): CanvasRenderingContext2D;\\n};\\n\\ninterface CanvasShadowStyles {\\n shadowBlur: number;\\n shadowColor: string;\\n shadowOffsetX: number;\\n shadowOffsetY: number;\\n}\\n\\ninterface CanvasState {\\n restore(): void;\\n save(): void;\\n}\\n\\ninterface CanvasText {\\n fillText(text: string, x: number, y: number, maxWidth?: number): void;\\n measureText(text: string): TextMetrics;\\n strokeText(text: string, x: number, y: number, maxWidth?: number): void;\\n}\\n\\ninterface CanvasTextDrawingStyles {\\n direction: CanvasDirection;\\n font: string;\\n fontKerning: CanvasFontKerning;\\n textAlign: CanvasTextAlign;\\n textBaseline: CanvasTextBaseline;\\n}\\n\\ninterface CanvasTransform {\\n getTransform(): DOMMatrix;\\n resetTransform(): void;\\n rotate(angle: number): void;\\n scale(x: number, y: number): void;\\n setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void;\\n setTransform(transform?: DOMMatrix2DInit): void;\\n transform(a: number, b: number, c: number, d: number, e: number, f: number): void;\\n translate(x: number, y: number): void;\\n}\\n\\ninterface CanvasUserInterface {\\n drawFocusIfNeeded(element: Element): void;\\n drawFocusIfNeeded(path: Path2D, element: Element): void;\\n}\\n\\n/** The ChannelMergerNode interface, often used in conjunction with its opposite, ChannelSplitterNode, reunites different mono inputs into a single output. Each input is used to fill a channel of the output. This is useful for accessing each channels separately, e.g. for performing channel mixing where gain must be separately controlled on each channel. */\\ninterface ChannelMergerNode extends AudioNode {\\n}\\n\\ndeclare var ChannelMergerNode: {\\n prototype: ChannelMergerNode;\\n new(context: BaseAudioContext, options?: ChannelMergerOptions): ChannelMergerNode;\\n};\\n\\n/** The ChannelSplitterNode interface, often used in conjunction with its opposite, ChannelMergerNode, separates the different channels of an audio source into a set of mono outputs. This is useful for accessing each channel separately, e.g. for performing channel mixing where gain must be separately controlled on each channel. */\\ninterface ChannelSplitterNode extends AudioNode {\\n}\\n\\ndeclare var ChannelSplitterNode: {\\n prototype: ChannelSplitterNode;\\n new(context: BaseAudioContext, options?: ChannelSplitterOptions): ChannelSplitterNode;\\n};\\n\\n/** The CharacterData abstract interface represents a Node object that contains characters. This is an abstract interface, meaning there aren\'t any object of type CharacterData: it is implemented by other interfaces, like Text, Comment, or ProcessingInstruction which aren\'t abstract. */\\ninterface CharacterData extends Node, ChildNode, NonDocumentTypeChildNode {\\n data: string;\\n readonly length: number;\\n readonly ownerDocument: Document;\\n appendData(data: string): void;\\n deleteData(offset: number, count: number): void;\\n insertData(offset: number, data: string): void;\\n replaceData(offset: number, count: number, data: string): void;\\n substringData(offset: number, count: number): string;\\n}\\n\\ndeclare var CharacterData: {\\n prototype: CharacterData;\\n new(): CharacterData;\\n};\\n\\ninterface ChildNode extends Node {\\n /**\\n * Inserts nodes just after node, while replacing strings in nodes with equivalent Text nodes.\\n *\\n * Throws a \\"HierarchyRequestError\\" DOMException if the constraints of the node tree are violated.\\n */\\n after(...nodes: (Node | string)[]): void;\\n /**\\n * Inserts nodes just before node, while replacing strings in nodes with equivalent Text nodes.\\n *\\n * Throws a \\"HierarchyRequestError\\" DOMException if the constraints of the node tree are violated.\\n */\\n before(...nodes: (Node | string)[]): void;\\n /** Removes node. */\\n remove(): void;\\n /**\\n * Replaces node with nodes, while replacing strings in nodes with equivalent Text nodes.\\n *\\n * Throws a \\"HierarchyRequestError\\" DOMException if the constraints of the node tree are violated.\\n */\\n replaceWith(...nodes: (Node | string)[]): void;\\n}\\n\\n/** @deprecated */\\ninterface ClientRect extends DOMRect {\\n}\\n\\n/** Available only in secure contexts. */\\ninterface Clipboard extends EventTarget {\\n read(): Promise;\\n readText(): Promise;\\n write(data: ClipboardItems): Promise;\\n writeText(data: string): Promise;\\n}\\n\\ndeclare var Clipboard: {\\n prototype: Clipboard;\\n new(): Clipboard;\\n};\\n\\n/** Events providing information related to modification of the clipboard, that is cut, copy, and paste events. */\\ninterface ClipboardEvent extends Event {\\n readonly clipboardData: DataTransfer | null;\\n}\\n\\ndeclare var ClipboardEvent: {\\n prototype: ClipboardEvent;\\n new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent;\\n};\\n\\n/** Available only in secure contexts. */\\ninterface ClipboardItem {\\n readonly presentationStyle: PresentationStyle;\\n readonly types: ReadonlyArray;\\n getType(type: string): Promise;\\n}\\n\\ndeclare var ClipboardItem: {\\n prototype: ClipboardItem;\\n new(items: Record>, options?: ClipboardItemOptions): ClipboardItem;\\n};\\n\\n/** A CloseEvent is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object\'s onclose attribute. */\\ninterface CloseEvent extends Event {\\n /** Returns the WebSocket connection close code provided by the server. */\\n readonly code: number;\\n /** Returns the WebSocket connection close reason provided by the server. */\\n readonly reason: string;\\n /** Returns true if the connection closed cleanly; false otherwise. */\\n readonly wasClean: boolean;\\n}\\n\\ndeclare var CloseEvent: {\\n prototype: CloseEvent;\\n new(type: string, eventInitDict?: CloseEventInit): CloseEvent;\\n};\\n\\n/** Textual notations within markup; although it is generally not visually shown, such comments are available to be read in the source view. */\\ninterface Comment extends CharacterData {\\n}\\n\\ndeclare var Comment: {\\n prototype: Comment;\\n new(data?: string): Comment;\\n};\\n\\n/** The DOM CompositionEvent represents events that occur due to the user indirectly entering text. */\\ninterface CompositionEvent extends UIEvent {\\n readonly data: string;\\n /** @deprecated */\\n initCompositionEvent(typeArg: string, bubblesArg?: boolean, cancelableArg?: boolean, viewArg?: WindowProxy | null, dataArg?: string): void;\\n}\\n\\ndeclare var CompositionEvent: {\\n prototype: CompositionEvent;\\n new(type: string, eventInitDict?: CompositionEventInit): CompositionEvent;\\n};\\n\\ninterface ConstantSourceNode extends AudioScheduledSourceNode {\\n readonly offset: AudioParam;\\n addEventListener(type: K, listener: (this: ConstantSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\\n removeEventListener(type: K, listener: (this: ConstantSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\\n}\\n\\ndeclare var ConstantSourceNode: {\\n prototype: ConstantSourceNode;\\n new(context: BaseAudioContext, options?: ConstantSourceOptions): ConstantSourceNode;\\n};\\n\\n/** An AudioNode that performs a Linear Convolution on a given AudioBuffer, often used to achieve a reverb effect. A ConvolverNode always has exactly one input and one output. */\\ninterface ConvolverNode extends AudioNode {\\n buffer: AudioBuffer | null;\\n normalize: boolean;\\n}\\n\\ndeclare var ConvolverNode: {\\n prototype: ConvolverNode;\\n new(context: BaseAudioContext, options?: ConvolverOptions): ConvolverNode;\\n};\\n\\n/** This Streams API interface provides\xa0a built-in byte length queuing strategy that can be used when constructing streams. */\\ninterface CountQueuingStrategy extends QueuingStrategy {\\n readonly highWaterMark: number;\\n readonly size: QueuingStrategySize;\\n}\\n\\ndeclare var CountQueuingStrategy: {\\n prototype: CountQueuingStrategy;\\n new(init: QueuingStrategyInit): CountQueuingStrategy;\\n};\\n\\n/** Available only in secure contexts. */\\ninterface Credential {\\n readonly id: string;\\n readonly type: string;\\n}\\n\\ndeclare var Credential: {\\n prototype: Credential;\\n new(): Credential;\\n};\\n\\n/** Available only in secure contexts. */\\ninterface CredentialsContainer {\\n create(options?: CredentialCreationOptions): Promise;\\n get(options?: CredentialRequestOptions): Promise;\\n preventSilentAccess(): Promise;\\n store(credential: Credential): Promise;\\n}\\n\\ndeclare var CredentialsContainer: {\\n prototype: CredentialsContainer;\\n new(): CredentialsContainer;\\n};\\n\\n/** Basic cryptography features available in the current context. It allows access to a cryptographically strong random number generator and to cryptographic primitives. */\\ninterface Crypto {\\n /** Available only in secure contexts. */\\n readonly subtle: SubtleCrypto;\\n getRandomValues(array: T): T;\\n /** Available only in secure contexts. */\\n randomUUID(): `${string}-${string}-${string}-${string}-${string}`;\\n}\\n\\ndeclare var Crypto: {\\n prototype: Crypto;\\n new(): Crypto;\\n};\\n\\n/**\\n * The CryptoKey dictionary of the Web Crypto API represents a cryptographic key.\\n * Available only in secure contexts.\\n */\\ninterface CryptoKey {\\n readonly algorithm: KeyAlgorithm;\\n readonly extractable: boolean;\\n readonly type: KeyType;\\n readonly usages: KeyUsage[];\\n}\\n\\ndeclare var CryptoKey: {\\n prototype: CryptoKey;\\n new(): CryptoKey;\\n};\\n\\ninterface CustomElementRegistry {\\n define(name: string, constructor: CustomElementConstructor, options?: ElementDefinitionOptions): void;\\n get(name: string): CustomElementConstructor | undefined;\\n upgrade(root: Node): void;\\n whenDefined(name: string): Promise;\\n}\\n\\ndeclare var CustomElementRegistry: {\\n prototype: CustomElementRegistry;\\n new(): CustomElementRegistry;\\n};\\n\\ninterface CustomEvent extends Event {\\n /** Returns any custom data event was created with. Typically used for synthetic events. */\\n readonly detail: T;\\n /** @deprecated */\\n initCustomEvent(type: string, bubbles?: boolean, cancelable?: boolean, detail?: T): void;\\n}\\n\\ndeclare var CustomEvent: {\\n prototype: CustomEvent;\\n new(type: string, eventInitDict?: CustomEventInit): CustomEvent;\\n};\\n\\n/** An abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API. */\\ninterface DOMException extends Error {\\n /** @deprecated */\\n readonly code: number;\\n readonly message: string;\\n readonly name: string;\\n readonly INDEX_SIZE_ERR: 1;\\n readonly DOMSTRING_SIZE_ERR: 2;\\n readonly HIERARCHY_REQUEST_ERR: 3;\\n readonly WRONG_DOCUMENT_ERR: 4;\\n readonly INVALID_CHARACTER_ERR: 5;\\n readonly NO_DATA_ALLOWED_ERR: 6;\\n readonly NO_MODIFICATION_ALLOWED_ERR: 7;\\n readonly NOT_FOUND_ERR: 8;\\n readonly NOT_SUPPORTED_ERR: 9;\\n readonly INUSE_ATTRIBUTE_ERR: 10;\\n readonly INVALID_STATE_ERR: 11;\\n readonly SYNTAX_ERR: 12;\\n readonly INVALID_MODIFICATION_ERR: 13;\\n readonly NAMESPACE_ERR: 14;\\n readonly INVALID_ACCESS_ERR: 15;\\n readonly VALIDATION_ERR: 16;\\n readonly TYPE_MISMATCH_ERR: 17;\\n readonly SECURITY_ERR: 18;\\n readonly NETWORK_ERR: 19;\\n readonly ABORT_ERR: 20;\\n readonly URL_MISMATCH_ERR: 21;\\n readonly QUOTA_EXCEEDED_ERR: 22;\\n readonly TIMEOUT_ERR: 23;\\n readonly INVALID_NODE_TYPE_ERR: 24;\\n readonly DATA_CLONE_ERR: 25;\\n}\\n\\ndeclare var DOMException: {\\n prototype: DOMException;\\n new(message?: string, name?: string): DOMException;\\n readonly INDEX_SIZE_ERR: 1;\\n readonly DOMSTRING_SIZE_ERR: 2;\\n readonly HIERARCHY_REQUEST_ERR: 3;\\n readonly WRONG_DOCUMENT_ERR: 4;\\n readonly INVALID_CHARACTER_ERR: 5;\\n readonly NO_DATA_ALLOWED_ERR: 6;\\n readonly NO_MODIFICATION_ALLOWED_ERR: 7;\\n readonly NOT_FOUND_ERR: 8;\\n readonly NOT_SUPPORTED_ERR: 9;\\n readonly INUSE_ATTRIBUTE_ERR: 10;\\n readonly INVALID_STATE_ERR: 11;\\n readonly SYNTAX_ERR: 12;\\n readonly INVALID_MODIFICATION_ERR: 13;\\n readonly NAMESPACE_ERR: 14;\\n readonly INVALID_ACCESS_ERR: 15;\\n readonly VALIDATION_ERR: 16;\\n readonly TYPE_MISMATCH_ERR: 17;\\n readonly SECURITY_ERR: 18;\\n readonly NETWORK_ERR: 19;\\n readonly ABORT_ERR: 20;\\n readonly URL_MISMATCH_ERR: 21;\\n readonly QUOTA_EXCEEDED_ERR: 22;\\n readonly TIMEOUT_ERR: 23;\\n readonly INVALID_NODE_TYPE_ERR: 24;\\n readonly DATA_CLONE_ERR: 25;\\n};\\n\\n/** An object providing methods which are not dependent on any particular document. Such an object is returned by the Document.implementation property. */\\ninterface DOMImplementation {\\n createDocument(namespace: string | null, qualifiedName: string | null, doctype?: DocumentType | null): XMLDocument;\\n createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType;\\n createHTMLDocument(title?: string): Document;\\n /** @deprecated */\\n hasFeature(...args: any[]): true;\\n}\\n\\ndeclare var DOMImplementation: {\\n prototype: DOMImplementation;\\n new(): DOMImplementation;\\n};\\n\\ninterface DOMMatrix extends DOMMatrixReadOnly {\\n a: number;\\n b: number;\\n c: number;\\n d: number;\\n e: number;\\n f: number;\\n m11: number;\\n m12: number;\\n m13: number;\\n m14: number;\\n m21: number;\\n m22: number;\\n m23: number;\\n m24: number;\\n m31: number;\\n m32: number;\\n m33: number;\\n m34: number;\\n m41: number;\\n m42: number;\\n m43: number;\\n m44: number;\\n invertSelf(): DOMMatrix;\\n multiplySelf(other?: DOMMatrixInit): DOMMatrix;\\n preMultiplySelf(other?: DOMMatrixInit): DOMMatrix;\\n rotateAxisAngleSelf(x?: number, y?: number, z?: number, angle?: number): DOMMatrix;\\n rotateFromVectorSelf(x?: number, y?: number): DOMMatrix;\\n rotateSelf(rotX?: number, rotY?: number, rotZ?: number): DOMMatrix;\\n scale3dSelf(scale?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;\\n scaleSelf(scaleX?: number, scaleY?: number, scaleZ?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;\\n setMatrixValue(transformList: string): DOMMatrix;\\n skewXSelf(sx?: number): DOMMatrix;\\n skewYSelf(sy?: number): DOMMatrix;\\n translateSelf(tx?: number, ty?: number, tz?: number): DOMMatrix;\\n}\\n\\ndeclare var DOMMatrix: {\\n prototype: DOMMatrix;\\n new(init?: string | number[]): DOMMatrix;\\n fromFloat32Array(array32: Float32Array): DOMMatrix;\\n fromFloat64Array(array64: Float64Array): DOMMatrix;\\n fromMatrix(other?: DOMMatrixInit): DOMMatrix;\\n};\\n\\ntype SVGMatrix = DOMMatrix;\\ndeclare var SVGMatrix: typeof DOMMatrix;\\n\\ntype WebKitCSSMatrix = DOMMatrix;\\ndeclare var WebKitCSSMatrix: typeof DOMMatrix;\\n\\ninterface DOMMatrixReadOnly {\\n readonly a: number;\\n readonly b: number;\\n readonly c: number;\\n readonly d: number;\\n readonly e: number;\\n readonly f: number;\\n readonly is2D: boolean;\\n readonly isIdentity: boolean;\\n readonly m11: number;\\n readonly m12: number;\\n readonly m13: number;\\n readonly m14: number;\\n readonly m21: number;\\n readonly m22: number;\\n readonly m23: number;\\n readonly m24: number;\\n readonly m31: number;\\n readonly m32: number;\\n readonly m33: number;\\n readonly m34: number;\\n readonly m41: number;\\n readonly m42: number;\\n readonly m43: number;\\n readonly m44: number;\\n flipX(): DOMMatrix;\\n flipY(): DOMMatrix;\\n inverse(): DOMMatrix;\\n multiply(other?: DOMMatrixInit): DOMMatrix;\\n rotate(rotX?: number, rotY?: number, rotZ?: number): DOMMatrix;\\n rotateAxisAngle(x?: number, y?: number, z?: number, angle?: number): DOMMatrix;\\n rotateFromVector(x?: number, y?: number): DOMMatrix;\\n scale(scaleX?: number, scaleY?: number, scaleZ?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;\\n scale3d(scale?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;\\n /** @deprecated */\\n scaleNonUniform(scaleX?: number, scaleY?: number): DOMMatrix;\\n skewX(sx?: number): DOMMatrix;\\n skewY(sy?: number): DOMMatrix;\\n toFloat32Array(): Float32Array;\\n toFloat64Array(): Float64Array;\\n toJSON(): any;\\n transformPoint(point?: DOMPointInit): DOMPoint;\\n translate(tx?: number, ty?: number, tz?: number): DOMMatrix;\\n toString(): string;\\n}\\n\\ndeclare var DOMMatrixReadOnly: {\\n prototype: DOMMatrixReadOnly;\\n new(init?: string | number[]): DOMMatrixReadOnly;\\n fromFloat32Array(array32: Float32Array): DOMMatrixReadOnly;\\n fromFloat64Array(array64: Float64Array): DOMMatrixReadOnly;\\n fromMatrix(other?: DOMMatrixInit): DOMMatrixReadOnly;\\n toString(): string;\\n};\\n\\n/** Provides the ability to parse XML or HTML source code from a string into a DOM Document. */\\ninterface DOMParser {\\n /**\\n * Parses string using either the HTML or XML parser, according to type, and returns the resulting Document. type can be \\"text/html\\" (which will invoke the HTML parser), or any of \\"text/xml\\", \\"application/xml\\", \\"application/xhtml+xml\\", or \\"image/svg+xml\\" (which will invoke the XML parser).\\n *\\n * For the XML parser, if string cannot be parsed, then the returned Document will contain elements describing the resulting error.\\n *\\n * Note that script elements are not evaluated during parsing, and the resulting document\'s encoding will always be UTF-8.\\n *\\n * Values other than the above for type will cause a TypeError exception to be thrown.\\n */\\n parseFromString(string: string, type: DOMParserSupportedType): Document;\\n}\\n\\ndeclare var DOMParser: {\\n prototype: DOMParser;\\n new(): DOMParser;\\n};\\n\\ninterface DOMPoint extends DOMPointReadOnly {\\n w: number;\\n x: number;\\n y: number;\\n z: number;\\n}\\n\\ndeclare var DOMPoint: {\\n prototype: DOMPoint;\\n new(x?: number, y?: number, z?: number, w?: number): DOMPoint;\\n fromPoint(other?: DOMPointInit): DOMPoint;\\n};\\n\\ntype SVGPoint = DOMPoint;\\ndeclare var SVGPoint: typeof DOMPoint;\\n\\ninterface DOMPointReadOnly {\\n readonly w: number;\\n readonly x: number;\\n readonly y: number;\\n readonly z: number;\\n matrixTransform(matrix?: DOMMatrixInit): DOMPoint;\\n toJSON(): any;\\n}\\n\\ndeclare var DOMPointReadOnly: {\\n prototype: DOMPointReadOnly;\\n new(x?: number, y?: number, z?: number, w?: number): DOMPointReadOnly;\\n fromPoint(other?: DOMPointInit): DOMPointReadOnly;\\n};\\n\\ninterface DOMQuad {\\n readonly p1: DOMPoint;\\n readonly p2: DOMPoint;\\n readonly p3: DOMPoint;\\n readonly p4: DOMPoint;\\n getBounds(): DOMRect;\\n toJSON(): any;\\n}\\n\\ndeclare var DOMQuad: {\\n prototype: DOMQuad;\\n new(p1?: DOMPointInit, p2?: DOMPointInit, p3?: DOMPointInit, p4?: DOMPointInit): DOMQuad;\\n fromQuad(other?: DOMQuadInit): DOMQuad;\\n fromRect(other?: DOMRectInit): DOMQuad;\\n};\\n\\ninterface DOMRect extends DOMRectReadOnly {\\n height: number;\\n width: number;\\n x: number;\\n y: number;\\n}\\n\\ndeclare var DOMRect: {\\n prototype: DOMRect;\\n new(x?: number, y?: number, width?: number, height?: number): DOMRect;\\n fromRect(other?: DOMRectInit): DOMRect;\\n};\\n\\ntype SVGRect = DOMRect;\\ndeclare var SVGRect: typeof DOMRect;\\n\\ninterface DOMRectList {\\n readonly length: number;\\n item(index: number): DOMRect | null;\\n [index: number]: DOMRect;\\n}\\n\\ndeclare var DOMRectList: {\\n prototype: DOMRectList;\\n new(): DOMRectList;\\n};\\n\\ninterface DOMRectReadOnly {\\n readonly bottom: number;\\n readonly height: number;\\n readonly left: number;\\n readonly right: number;\\n readonly top: number;\\n readonly width: number;\\n readonly x: number;\\n readonly y: number;\\n toJSON(): any;\\n}\\n\\ndeclare var DOMRectReadOnly: {\\n prototype: DOMRectReadOnly;\\n new(x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly;\\n fromRect(other?: DOMRectInit): DOMRectReadOnly;\\n};\\n\\n/** A type returned by some APIs which contains a list of DOMString (strings). */\\ninterface DOMStringList {\\n /** Returns the number of strings in strings. */\\n readonly length: number;\\n /** Returns true if strings contains string, and false otherwise. */\\n contains(string: string): boolean;\\n /** Returns the string with index index from strings. */\\n item(index: number): string | null;\\n [index: number]: string;\\n}\\n\\ndeclare var DOMStringList: {\\n prototype: DOMStringList;\\n new(): DOMStringList;\\n};\\n\\n/** Used by the dataset\xa0HTML\xa0attribute to represent data for custom attributes added to elements. */\\ninterface DOMStringMap {\\n [name: string]: string | undefined;\\n}\\n\\ndeclare var DOMStringMap: {\\n prototype: DOMStringMap;\\n new(): DOMStringMap;\\n};\\n\\n/** A set of space-separated tokens. Such a set is returned by Element.classList, HTMLLinkElement.relList, HTMLAnchorElement.relList, HTMLAreaElement.relList, HTMLIframeElement.sandbox, or HTMLOutputElement.htmlFor. It is indexed beginning with 0 as with JavaScript Array objects. DOMTokenList is always case-sensitive. */\\ninterface DOMTokenList {\\n /** Returns the number of tokens. */\\n readonly length: number;\\n /**\\n * Returns the associated set as string.\\n *\\n * Can be set, to change the associated attribute.\\n */\\n value: string;\\n toString(): string;\\n /**\\n * Adds all arguments passed, except those already present.\\n *\\n * Throws a \\"SyntaxError\\" DOMException if one of the arguments is the empty string.\\n *\\n * Throws an \\"InvalidCharacterError\\" DOMException if one of the arguments contains any ASCII whitespace.\\n */\\n add(...tokens: string[]): void;\\n /** Returns true if token is present, and false otherwise. */\\n contains(token: string): boolean;\\n /** Returns the token with index index. */\\n item(index: number): string | null;\\n /**\\n * Removes arguments passed, if they are present.\\n *\\n * Throws a \\"SyntaxError\\" DOMException if one of the arguments is the empty string.\\n *\\n * Throws an \\"InvalidCharacterError\\" DOMException if one of the arguments contains any ASCII whitespace.\\n */\\n remove(...tokens: string[]): void;\\n /**\\n * Replaces token with newToken.\\n *\\n * Returns true if token was replaced with newToken, and false otherwise.\\n *\\n * Throws a \\"SyntaxError\\" DOMException if one of the arguments is the empty string.\\n *\\n * Throws an \\"InvalidCharacterError\\" DOMException if one of the arguments contains any ASCII whitespace.\\n */\\n replace(token: string, newToken: string): boolean;\\n /**\\n * Returns true if token is in the associated attribute\'s supported tokens. Returns false otherwise.\\n *\\n * Throws a TypeError if the associated attribute has no supported tokens defined.\\n */\\n supports(token: string): boolean;\\n /**\\n * If force is not given, \\"toggles\\" token, removing it if it\'s present and adding it if it\'s not present. If force is true, adds token (same as add()). If force is false, removes token (same as remove()).\\n *\\n * Returns true if token is now present, and false otherwise.\\n *\\n * Throws a \\"SyntaxError\\" DOMException if token is empty.\\n *\\n * Throws an \\"InvalidCharacterError\\" DOMException if token contains any spaces.\\n */\\n toggle(token: string, force?: boolean): boolean;\\n forEach(callbackfn: (value: string, key: number, parent: DOMTokenList) => void, thisArg?: any): void;\\n [index: number]: string;\\n}\\n\\ndeclare var DOMTokenList: {\\n prototype: DOMTokenList;\\n new(): DOMTokenList;\\n};\\n\\n/** Used to hold the data that is being dragged during a drag and drop operation. It may hold one or more data items, each of one or more data types. For more information about drag and drop, see HTML Drag and Drop API. */\\ninterface DataTransfer {\\n /**\\n * Returns the kind of operation that is currently selected. If the kind of operation isn\'t one of those that is allowed by the effectAllowed attribute, then the operation will fail.\\n *\\n * Can be set, to change the selected operation.\\n *\\n * The possible values are \\"none\\", \\"copy\\", \\"link\\", and \\"move\\".\\n */\\n dropEffect: \\"none\\" | \\"copy\\" | \\"link\\" | \\"move\\";\\n /**\\n * Returns the kinds of operations that are to be allowed.\\n *\\n * Can be set (during the dragstart event), to change the allowed operations.\\n *\\n * The possible values are \\"none\\", \\"copy\\", \\"copyLink\\", \\"copyMove\\", \\"link\\", \\"linkMove\\", \\"move\\", \\"all\\", and \\"uninitialized\\",\\n */\\n effectAllowed: \\"none\\" | \\"copy\\" | \\"copyLink\\" | \\"copyMove\\" | \\"link\\" | \\"linkMove\\" | \\"move\\" | \\"all\\" | \\"uninitialized\\";\\n /** Returns a FileList of the files being dragged, if any. */\\n readonly files: FileList;\\n /** Returns a DataTransferItemList object, with the drag data. */\\n readonly items: DataTransferItemList;\\n /** Returns a frozen array listing the formats that were set in the dragstart event. In addition, if any files are being dragged, then one of the types will be the string \\"Files\\". */\\n readonly types: ReadonlyArray;\\n /** Removes the data of the specified formats. Removes all data if the argument is omitted. */\\n clearData(format?: string): void;\\n /** Returns the specified data. If there is no such data, returns the empty string. */\\n getData(format: string): string;\\n /** Adds the specified data. */\\n setData(format: string, data: string): void;\\n /** Uses the given element to update the drag feedback, replacing any previously specified feedback. */\\n setDragImage(image: Element, x: number, y: number): void;\\n}\\n\\ndeclare var DataTransfer: {\\n prototype: DataTransfer;\\n new(): DataTransfer;\\n};\\n\\n/** One drag data item. During a drag operation, each drag event has a dataTransfer property which contains a list of drag data items. Each item in the list is a DataTransferItem object. */\\ninterface DataTransferItem {\\n /** Returns the drag data item kind, one of: \\"string\\", \\"file\\". */\\n readonly kind: string;\\n /** Returns the drag data item type string. */\\n readonly type: string;\\n /** Returns a File object, if the drag data item kind is File. */\\n getAsFile(): File | null;\\n /** Invokes the callback with the string data as the argument, if the drag data item kind is text. */\\n getAsString(callback: FunctionStringCallback | null): void;\\n webkitGetAsEntry(): FileSystemEntry | null;\\n}\\n\\ndeclare var DataTransferItem: {\\n prototype: DataTransferItem;\\n new(): DataTransferItem;\\n};\\n\\n/** A list of DataTransferItem objects representing items being dragged. During a drag operation, each DragEvent has a dataTransfer property and that property is a DataTransferItemList. */\\ninterface DataTransferItemList {\\n /** Returns the number of items in the drag data store. */\\n readonly length: number;\\n /** Adds a new entry for the given data to the drag data store. If the data is plain text then a type string has to be provided also. */\\n add(data: string, type: string): DataTransferItem | null;\\n add(data: File): DataTransferItem | null;\\n /** Removes all the entries in the drag data store. */\\n clear(): void;\\n /** Removes the indexth entry in the drag data store. */\\n remove(index: number): void;\\n [index: number]: DataTransferItem;\\n}\\n\\ndeclare var DataTransferItemList: {\\n prototype: DataTransferItemList;\\n new(): DataTransferItemList;\\n};\\n\\n/** A delay-line; an AudioNode audio-processing module that causes a delay between the arrival of an input data and its propagation to the output. */\\ninterface DelayNode extends AudioNode {\\n readonly delayTime: AudioParam;\\n}\\n\\ndeclare var DelayNode: {\\n prototype: DelayNode;\\n new(context: BaseAudioContext, options?: DelayOptions): DelayNode;\\n};\\n\\n/**\\n * The DeviceMotionEvent provides web developers with information about the speed of changes for the device\'s position and orientation.\\n * Available only in secure contexts.\\n */\\ninterface DeviceMotionEvent extends Event {\\n readonly acceleration: DeviceMotionEventAcceleration | null;\\n readonly accelerationIncludingGravity: DeviceMotionEventAcceleration | null;\\n readonly interval: number;\\n readonly rotationRate: DeviceMotionEventRotationRate | null;\\n}\\n\\ndeclare var DeviceMotionEvent: {\\n prototype: DeviceMotionEvent;\\n new(type: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent;\\n};\\n\\n/** Available only in secure contexts. */\\ninterface DeviceMotionEventAcceleration {\\n readonly x: number | null;\\n readonly y: number | null;\\n readonly z: number | null;\\n}\\n\\n/** Available only in secure contexts. */\\ninterface DeviceMotionEventRotationRate {\\n readonly alpha: number | null;\\n readonly beta: number | null;\\n readonly gamma: number | null;\\n}\\n\\n/**\\n * The DeviceOrientationEvent provides web developers with information from the physical orientation of the device running the web page.\\n * Available only in secure contexts.\\n */\\ninterface DeviceOrientationEvent extends Event {\\n readonly absolute: boolean;\\n readonly alpha: number | null;\\n readonly beta: number | null;\\n readonly gamma: number | null;\\n}\\n\\ndeclare var DeviceOrientationEvent: {\\n prototype: DeviceOrientationEvent;\\n new(type: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent;\\n};\\n\\ninterface DocumentEventMap extends GlobalEventHandlersEventMap {\\n \\"DOMContentLoaded\\": Event;\\n \\"fullscreenchange\\": Event;\\n \\"fullscreenerror\\": Event;\\n \\"pointerlockchange\\": Event;\\n \\"pointerlockerror\\": Event;\\n \\"readystatechange\\": Event;\\n \\"visibilitychange\\": Event;\\n}\\n\\n/** Any web page loaded in the browser and serves as an entry point into the web page\'s content, which is the DOM tree. */\\ninterface Document extends Node, DocumentOrShadowRoot, FontFaceSource, GlobalEventHandlers, NonElementParentNode, ParentNode, XPathEvaluatorBase {\\n /** Sets or gets the URL for the current document. */\\n readonly URL: string;\\n /**\\n * Sets or gets the color of all active links in the document.\\n * @deprecated\\n */\\n alinkColor: string;\\n /**\\n * Returns a reference to the collection of elements contained by the object.\\n * @deprecated\\n */\\n readonly all: HTMLAllCollection;\\n /**\\n * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order.\\n * @deprecated\\n */\\n readonly anchors: HTMLCollectionOf;\\n /**\\n * Retrieves a collection of all applet objects in the document.\\n * @deprecated\\n */\\n readonly applets: HTMLCollection;\\n /**\\n * Deprecated. Sets or retrieves a value that indicates the background color behind the object.\\n * @deprecated\\n */\\n bgColor: string;\\n /** Specifies the beginning and end of the document body. */\\n body: HTMLElement;\\n /** Returns document\'s encoding. */\\n readonly characterSet: string;\\n /**\\n * Gets or sets the character set used to encode the object.\\n * @deprecated This is a legacy alias of `characterSet`.\\n */\\n readonly charset: string;\\n /** Gets a value that indicates whether standards-compliant mode is switched on for the object. */\\n readonly compatMode: string;\\n /** Returns document\'s content type. */\\n readonly contentType: string;\\n /**\\n * Returns the HTTP cookies that apply to the Document. If there are no cookies or cookies can\'t be applied to this resource, the empty string will be returned.\\n *\\n * Can be set, to add a new cookie to the element\'s set of HTTP cookies.\\n *\\n * If the contents are sandboxed into a unique origin (e.g. in an iframe with the sandbox attribute), a \\"SecurityError\\" DOMException will be thrown on getting and setting.\\n */\\n cookie: string;\\n /**\\n * Returns the script element, or the SVG script element, that is currently executing, as long as the element represents a classic script. In the case of reentrant script execution, returns the one that most recently started executing amongst those that have not yet finished executing.\\n *\\n * Returns null if the Document is not currently executing a script or SVG script element (e.g., because the running script is an event handler, or a timeout), or if the currently executing script or SVG script element represents a module script.\\n */\\n readonly currentScript: HTMLOrSVGScriptElement | null;\\n /** Returns the Window object of the active document. */\\n readonly defaultView: (WindowProxy & typeof globalThis) | null;\\n /** Sets or gets a value that indicates whether the document can be edited. */\\n designMode: string;\\n /** Sets or retrieves a value that indicates the reading order of the object. */\\n dir: string;\\n /** Gets an object representing the document type declaration associated with the current document. */\\n readonly doctype: DocumentType | null;\\n /** Gets a reference to the root node of the document. */\\n readonly documentElement: HTMLElement;\\n /** Returns document\'s URL. */\\n readonly documentURI: string;\\n /**\\n * Sets or gets the security domain of the document.\\n * @deprecated\\n */\\n domain: string;\\n /** Retrieves a collection of all embed objects in the document. */\\n readonly embeds: HTMLCollectionOf;\\n /**\\n * Sets or gets the foreground (text) color of the document.\\n * @deprecated\\n */\\n fgColor: string;\\n /** Retrieves a collection, in source order, of all form objects in the document. */\\n readonly forms: HTMLCollectionOf;\\n /** @deprecated */\\n readonly fullscreen: boolean;\\n /** Returns true if document has the ability to display elements fullscreen and fullscreen is supported, or false otherwise. */\\n readonly fullscreenEnabled: boolean;\\n /** Returns the head element. */\\n readonly head: HTMLHeadElement;\\n readonly hidden: boolean;\\n /** Retrieves a collection, in source order, of img objects in the document. */\\n readonly images: HTMLCollectionOf;\\n /** Gets the implementation object of the current document. */\\n readonly implementation: DOMImplementation;\\n /**\\n * Returns the character encoding used to create the webpage that is loaded into the document object.\\n * @deprecated This is a legacy alias of `characterSet`.\\n */\\n readonly inputEncoding: string;\\n /** Gets the date that the page was last modified, if the page supplies one. */\\n readonly lastModified: string;\\n /**\\n * Sets or gets the color of the document links.\\n * @deprecated\\n */\\n linkColor: string;\\n /** Retrieves a collection of all a objects that specify the href property and all area objects in the document. */\\n readonly links: HTMLCollectionOf;\\n /** Contains information about the current URL. */\\n get location(): Location;\\n set location(href: string | Location);\\n onfullscreenchange: ((this: Document, ev: Event) => any) | null;\\n onfullscreenerror: ((this: Document, ev: Event) => any) | null;\\n onpointerlockchange: ((this: Document, ev: Event) => any) | null;\\n onpointerlockerror: ((this: Document, ev: Event) => any) | null;\\n /**\\n * Fires when the state of the object has changed.\\n * @param ev The event\\n */\\n onreadystatechange: ((this: Document, ev: Event) => any) | null;\\n onvisibilitychange: ((this: Document, ev: Event) => any) | null;\\n readonly ownerDocument: null;\\n readonly pictureInPictureEnabled: boolean;\\n /** Return an HTMLCollection of the embed elements in the Document. */\\n readonly plugins: HTMLCollectionOf;\\n /** Retrieves a value that indicates the current state of the object. */\\n readonly readyState: DocumentReadyState;\\n /** Gets the URL of the location that referred the user to the current page. */\\n readonly referrer: string;\\n /** @deprecated */\\n readonly rootElement: SVGSVGElement | null;\\n /** Retrieves a collection of all script objects in the document. */\\n readonly scripts: HTMLCollectionOf;\\n readonly scrollingElement: Element | null;\\n readonly timeline: DocumentTimeline;\\n /** Contains the title of the document. */\\n title: string;\\n readonly visibilityState: DocumentVisibilityState;\\n /**\\n * Sets or gets the color of the links that the user has visited.\\n * @deprecated\\n */\\n vlinkColor: string;\\n /**\\n * Moves node from another document and returns it.\\n *\\n * If node is a document, throws a \\"NotSupportedError\\" DOMException or, if node is a shadow root, throws a \\"HierarchyRequestError\\" DOMException.\\n */\\n adoptNode(node: T): T;\\n /** @deprecated */\\n captureEvents(): void;\\n /** @deprecated */\\n caretRangeFromPoint(x: number, y: number): Range | null;\\n /** @deprecated */\\n clear(): void;\\n /** Closes an output stream and forces the sent data to display. */\\n close(): void;\\n /**\\n * Creates an attribute object with a specified name.\\n * @param name String that sets the attribute object\'s name.\\n */\\n createAttribute(localName: string): Attr;\\n createAttributeNS(namespace: string | null, qualifiedName: string): Attr;\\n /** Returns a CDATASection node whose data is data. */\\n createCDATASection(data: string): CDATASection;\\n /**\\n * Creates a comment object with the specified data.\\n * @param data Sets the comment object\'s data.\\n */\\n createComment(data: string): Comment;\\n /** Creates a new document. */\\n createDocumentFragment(): DocumentFragment;\\n /**\\n * Creates an instance of the element for the specified tag.\\n * @param tagName The name of an element.\\n */\\n createElement(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K];\\n /** @deprecated */\\n createElement(tagName: K, options?: ElementCreationOptions): HTMLElementDeprecatedTagNameMap[K];\\n createElement(tagName: string, options?: ElementCreationOptions): HTMLElement;\\n /**\\n * Returns an element with namespace namespace. Its namespace prefix will be everything before \\":\\" (U+003E) in qualifiedName or null. Its local name will be everything after \\":\\" (U+003E) in qualifiedName or qualifiedName.\\n *\\n * If localName does not match the Name production an \\"InvalidCharacterError\\" DOMException will be thrown.\\n *\\n * If one of the following conditions is true a \\"NamespaceError\\" DOMException will be thrown:\\n *\\n * localName does not match the QName production.\\n * Namespace prefix is not null and namespace is the empty string.\\n * Namespace prefix is \\"xml\\" and namespace is not the XML namespace.\\n * qualifiedName or namespace prefix is \\"xmlns\\" and namespace is not the XMLNS namespace.\\n * namespace is the XMLNS namespace and neither qualifiedName nor namespace prefix is \\"xmlns\\".\\n *\\n * When supplied, options\'s is can be used to create a customized built-in element.\\n */\\n createElementNS(namespaceURI: \\"http://www.w3.org/1999/xhtml\\", qualifiedName: string): HTMLElement;\\n createElementNS(namespaceURI: \\"http://www.w3.org/2000/svg\\", qualifiedName: K): SVGElementTagNameMap[K];\\n createElementNS(namespaceURI: \\"http://www.w3.org/2000/svg\\", qualifiedName: string): SVGElement;\\n createElementNS(namespaceURI: \\"http://www.w3.org/1998/Math/MathML\\", qualifiedName: K): MathMLElementTagNameMap[K];\\n createElementNS(namespaceURI: \\"http://www.w3.org/1998/Math/MathML\\", qualifiedName: string): MathMLElement;\\n createElementNS(namespaceURI: string | null, qualifiedName: string, options?: ElementCreationOptions): Element;\\n createElementNS(namespace: string | null, qualifiedName: string, options?: string | ElementCreationOptions): Element;\\n createEvent(eventInterface: \\"AnimationEvent\\"): AnimationEvent;\\n createEvent(eventInterface: \\"AnimationPlaybackEvent\\"): AnimationPlaybackEvent;\\n createEvent(eventInterface: \\"AudioProcessingEvent\\"): AudioProcessingEvent;\\n createEvent(eventInterface: \\"BeforeUnloadEvent\\"): BeforeUnloadEvent;\\n createEvent(eventInterface: \\"BlobEvent\\"): BlobEvent;\\n createEvent(eventInterface: \\"ClipboardEvent\\"): ClipboardEvent;\\n createEvent(eventInterface: \\"CloseEvent\\"): CloseEvent;\\n createEvent(eventInterface: \\"CompositionEvent\\"): CompositionEvent;\\n createEvent(eventInterface: \\"CustomEvent\\"): CustomEvent;\\n createEvent(eventInterface: \\"DeviceMotionEvent\\"): DeviceMotionEvent;\\n createEvent(eventInterface: \\"DeviceOrientationEvent\\"): DeviceOrientationEvent;\\n createEvent(eventInterface: \\"DragEvent\\"): DragEvent;\\n createEvent(eventInterface: \\"ErrorEvent\\"): ErrorEvent;\\n createEvent(eventInterface: \\"Event\\"): Event;\\n createEvent(eventInterface: \\"Events\\"): Event;\\n createEvent(eventInterface: \\"FocusEvent\\"): FocusEvent;\\n createEvent(eventInterface: \\"FontFaceSetLoadEvent\\"): FontFaceSetLoadEvent;\\n createEvent(eventInterface: \\"FormDataEvent\\"): FormDataEvent;\\n createEvent(eventInterface: \\"GamepadEvent\\"): GamepadEvent;\\n createEvent(eventInterface: \\"HashChangeEvent\\"): HashChangeEvent;\\n createEvent(eventInterface: \\"IDBVersionChangeEvent\\"): IDBVersionChangeEvent;\\n createEvent(eventInterface: \\"InputEvent\\"): InputEvent;\\n createEvent(eventInterface: \\"KeyboardEvent\\"): KeyboardEvent;\\n createEvent(eventInterface: \\"MIDIConnectionEvent\\"): MIDIConnectionEvent;\\n createEvent(eventInterface: \\"MIDIMessageEvent\\"): MIDIMessageEvent;\\n createEvent(eventInterface: \\"MediaEncryptedEvent\\"): MediaEncryptedEvent;\\n createEvent(eventInterface: \\"MediaKeyMessageEvent\\"): MediaKeyMessageEvent;\\n createEvent(eventInterface: \\"MediaQueryListEvent\\"): MediaQueryListEvent;\\n createEvent(eventInterface: \\"MediaStreamTrackEvent\\"): MediaStreamTrackEvent;\\n createEvent(eventInterface: \\"MessageEvent\\"): MessageEvent;\\n createEvent(eventInterface: \\"MouseEvent\\"): MouseEvent;\\n createEvent(eventInterface: \\"MouseEvents\\"): MouseEvent;\\n createEvent(eventInterface: \\"MutationEvent\\"): MutationEvent;\\n createEvent(eventInterface: \\"MutationEvents\\"): MutationEvent;\\n createEvent(eventInterface: \\"OfflineAudioCompletionEvent\\"): OfflineAudioCompletionEvent;\\n createEvent(eventInterface: \\"PageTransitionEvent\\"): PageTransitionEvent;\\n createEvent(eventInterface: \\"PaymentMethodChangeEvent\\"): PaymentMethodChangeEvent;\\n createEvent(eventInterface: \\"PaymentRequestUpdateEvent\\"): PaymentRequestUpdateEvent;\\n createEvent(eventInterface: \\"PictureInPictureEvent\\"): PictureInPictureEvent;\\n createEvent(eventInterface: \\"PointerEvent\\"): PointerEvent;\\n createEvent(eventInterface: \\"PopStateEvent\\"): PopStateEvent;\\n createEvent(eventInterface: \\"ProgressEvent\\"): ProgressEvent;\\n createEvent(eventInterface: \\"PromiseRejectionEvent\\"): PromiseRejectionEvent;\\n createEvent(eventInterface: \\"RTCDTMFToneChangeEvent\\"): RTCDTMFToneChangeEvent;\\n createEvent(eventInterface: \\"RTCDataChannelEvent\\"): RTCDataChannelEvent;\\n createEvent(eventInterface: \\"RTCErrorEvent\\"): RTCErrorEvent;\\n createEvent(eventInterface: \\"RTCPeerConnectionIceErrorEvent\\"): RTCPeerConnectionIceErrorEvent;\\n createEvent(eventInterface: \\"RTCPeerConnectionIceEvent\\"): RTCPeerConnectionIceEvent;\\n createEvent(eventInterface: \\"RTCTrackEvent\\"): RTCTrackEvent;\\n createEvent(eventInterface: \\"SecurityPolicyViolationEvent\\"): SecurityPolicyViolationEvent;\\n createEvent(eventInterface: \\"SpeechSynthesisErrorEvent\\"): SpeechSynthesisErrorEvent;\\n createEvent(eventInterface: \\"SpeechSynthesisEvent\\"): SpeechSynthesisEvent;\\n createEvent(eventInterface: \\"StorageEvent\\"): StorageEvent;\\n createEvent(eventInterface: \\"SubmitEvent\\"): SubmitEvent;\\n createEvent(eventInterface: \\"TouchEvent\\"): TouchEvent;\\n createEvent(eventInterface: \\"TrackEvent\\"): TrackEvent;\\n createEvent(eventInterface: \\"TransitionEvent\\"): TransitionEvent;\\n createEvent(eventInterface: \\"UIEvent\\"): UIEvent;\\n createEvent(eventInterface: \\"UIEvents\\"): UIEvent;\\n createEvent(eventInterface: \\"WebGLContextEvent\\"): WebGLContextEvent;\\n createEvent(eventInterface: \\"WheelEvent\\"): WheelEvent;\\n createEvent(eventInterface: string): Event;\\n /**\\n * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.\\n * @param root The root element or node to start traversing on.\\n * @param whatToShow The type of nodes or elements to appear in the node list\\n * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter.\\n */\\n createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter | null): NodeIterator;\\n /** Returns a ProcessingInstruction node whose target is target and data is data. If target does not match the Name production an \\"InvalidCharacterError\\" DOMException will be thrown. If data contains \\"?>\\" an \\"InvalidCharacterError\\" DOMException will be thrown. */\\n createProcessingInstruction(target: string, data: string): ProcessingInstruction;\\n /** Returns an empty range object that has both of its boundary points positioned at the beginning of the document. */\\n createRange(): Range;\\n /**\\n * Creates a text string from the specified value.\\n * @param data String that specifies the nodeValue property of the text node.\\n */\\n createTextNode(data: string): Text;\\n /**\\n * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document.\\n * @param root The root element or node to start traversing on.\\n * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow.\\n * @param filter A custom NodeFilter function to use.\\n */\\n createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter | null): TreeWalker;\\n /**\\n * Executes a command on the current document, current selection, or the given range.\\n * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script.\\n * @param showUI Display the user interface, defaults to false.\\n * @param value Value to assign.\\n * @deprecated\\n */\\n execCommand(commandId: string, showUI?: boolean, value?: string): boolean;\\n /** Stops document\'s fullscreen element from being displayed fullscreen and resolves promise when done. */\\n exitFullscreen(): Promise;\\n exitPictureInPicture(): Promise;\\n exitPointerLock(): void;\\n /**\\n * Returns a reference to the first object with the specified value of the ID attribute.\\n * @param elementId String that specifies the ID value.\\n */\\n getElementById(elementId: string): HTMLElement | null;\\n /** Returns a HTMLCollection of the elements in the object on which the method was invoked (a document or an element) that have all the classes given by classNames. The classNames argument is interpreted as a space-separated list of classes. */\\n getElementsByClassName(classNames: string): HTMLCollectionOf;\\n /**\\n * Gets a collection of objects based on the value of the NAME or ID attribute.\\n * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute.\\n */\\n getElementsByName(elementName: string): NodeListOf;\\n /**\\n * Retrieves a collection of objects based on the specified element name.\\n * @param name Specifies the name of an element.\\n */\\n getElementsByTagName(qualifiedName: K): HTMLCollectionOf;\\n getElementsByTagName(qualifiedName: K): HTMLCollectionOf;\\n getElementsByTagName(qualifiedName: K): HTMLCollectionOf;\\n /** @deprecated */\\n getElementsByTagName(qualifiedName: K): HTMLCollectionOf;\\n getElementsByTagName(qualifiedName: string): HTMLCollectionOf;\\n /**\\n * If namespace and localName are \\"*\\" returns a HTMLCollection of all descendant elements.\\n *\\n * If only namespace is \\"*\\" returns a HTMLCollection of all descendant elements whose local name is localName.\\n *\\n * If only localName is \\"*\\" returns a HTMLCollection of all descendant elements whose namespace is namespace.\\n *\\n * Otherwise, returns a HTMLCollection of all descendant elements whose namespace is namespace and local name is localName.\\n */\\n getElementsByTagNameNS(namespaceURI: \\"http://www.w3.org/1999/xhtml\\", localName: string): HTMLCollectionOf;\\n getElementsByTagNameNS(namespaceURI: \\"http://www.w3.org/2000/svg\\", localName: string): HTMLCollectionOf;\\n getElementsByTagNameNS(namespaceURI: \\"http://www.w3.org/1998/Math/MathML\\", localName: string): HTMLCollectionOf;\\n getElementsByTagNameNS(namespace: string | null, localName: string): HTMLCollectionOf;\\n /** Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. */\\n getSelection(): Selection | null;\\n /** Gets a value indicating whether the object currently has focus. */\\n hasFocus(): boolean;\\n hasStorageAccess(): Promise;\\n /**\\n * Returns a copy of node. If deep is true, the copy also includes the node\'s descendants.\\n *\\n * If node is a document or a shadow root, throws a \\"NotSupportedError\\" DOMException.\\n */\\n importNode(node: T, deep?: boolean): T;\\n /**\\n * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method.\\n * @param url Specifies a MIME type for the document.\\n * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element.\\n * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, \\"fullscreen=yes, toolbar=yes\\"). The following values are supported.\\n * @param replace Specifies whether the existing entry for the document is replaced in the history list.\\n */\\n open(unused1?: string, unused2?: string): Document;\\n open(url: string | URL, name: string, features: string): WindowProxy | null;\\n /**\\n * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document.\\n * @param commandId Specifies a command identifier.\\n * @deprecated\\n */\\n queryCommandEnabled(commandId: string): boolean;\\n /**\\n * Returns a Boolean value that indicates whether the specified command is in the indeterminate state.\\n * @param commandId String that specifies a command identifier.\\n * @deprecated\\n */\\n queryCommandIndeterm(commandId: string): boolean;\\n /**\\n * Returns a Boolean value that indicates the current state of the command.\\n * @param commandId String that specifies a command identifier.\\n * @deprecated\\n */\\n queryCommandState(commandId: string): boolean;\\n /**\\n * Returns a Boolean value that indicates whether the current command is supported on the current range.\\n * @param commandId Specifies a command identifier.\\n * @deprecated\\n */\\n queryCommandSupported(commandId: string): boolean;\\n /**\\n * Returns the current value of the document, range, or current selection for the given command.\\n * @param commandId String that specifies a command identifier.\\n * @deprecated\\n */\\n queryCommandValue(commandId: string): string;\\n /** @deprecated */\\n releaseEvents(): void;\\n requestStorageAccess(): Promise;\\n /**\\n * Writes one or more HTML expressions to a document in the specified window.\\n * @param content Specifies the text and HTML tags to write.\\n */\\n write(...text: string[]): void;\\n /**\\n * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window.\\n * @param content The text and HTML tags to write.\\n */\\n writeln(...text: string[]): void;\\n addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\\n removeEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\\n}\\n\\ndeclare var Document: {\\n prototype: Document;\\n new(): Document;\\n};\\n\\n/** A minimal document object that has no parent. It is used as a lightweight version of Document that stores a segment of a document structure comprised of nodes just like a standard document. The key difference is that because the document fragment isn\'t part of the active document tree structure, changes made to the fragment don\'t affect the document, cause reflow, or incur any performance impact that can occur when changes are made. */\\ninterface DocumentFragment extends Node, NonElementParentNode, ParentNode {\\n readonly ownerDocument: Document;\\n getElementById(elementId: string): HTMLElement | null;\\n}\\n\\ndeclare var DocumentFragment: {\\n prototype: DocumentFragment;\\n new(): DocumentFragment;\\n};\\n\\ninterface DocumentOrShadowRoot {\\n /**\\n * Returns the deepest element in the document through which or to which key events are being routed. This is, roughly speaking, the focused element in the document.\\n *\\n * For the purposes of this API, when a child browsing context is focused, its container is focused in the parent browsing context. For example, if the user moves the focus to a text control in an iframe, the iframe is the element returned by the activeElement API in the iframe\'s node document.\\n *\\n * Similarly, when the focused element is in a different node tree than documentOrShadowRoot, the element returned will be the host that\'s located in the same node tree as documentOrShadowRoot if documentOrShadowRoot is a shadow-including inclusive ancestor of the focused element, and null if not.\\n */\\n readonly activeElement: Element | null;\\n adoptedStyleSheets: CSSStyleSheet[];\\n /** Returns document\'s fullscreen element. */\\n readonly fullscreenElement: Element | null;\\n readonly pictureInPictureElement: Element | null;\\n readonly pointerLockElement: Element | null;\\n /** Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. */\\n readonly styleSheets: StyleSheetList;\\n /**\\n * Returns the element for the specified x coordinate and the specified y coordinate.\\n * @param x The x-offset\\n * @param y The y-offset\\n */\\n elementFromPoint(x: number, y: number): Element | null;\\n elementsFromPoint(x: number, y: number): Element[];\\n getAnimations(): Animation[];\\n}\\n\\ninterface DocumentTimeline extends AnimationTimeline {\\n}\\n\\ndeclare var DocumentTimeline: {\\n prototype: DocumentTimeline;\\n new(options?: DocumentTimelineOptions): DocumentTimeline;\\n};\\n\\n/** A Node containing a doctype. */\\ninterface DocumentType extends Node, ChildNode {\\n readonly name: string;\\n readonly ownerDocument: Document;\\n readonly publicId: string;\\n readonly systemId: string;\\n}\\n\\ndeclare var DocumentType: {\\n prototype: DocumentType;\\n new(): DocumentType;\\n};\\n\\n/** A DOM event that represents a drag and drop interaction. The user initiates a drag by placing a pointer device (such as a mouse) on the touch surface and then dragging the pointer to a new location (such as another DOM element). Applications are free to interpret a drag and drop interaction in an application-specific way. */\\ninterface DragEvent extends MouseEvent {\\n /** Returns the DataTransfer object for the event. */\\n readonly dataTransfer: DataTransfer | null;\\n}\\n\\ndeclare var DragEvent: {\\n prototype: DragEvent;\\n new(type: string, eventInitDict?: DragEventInit): DragEvent;\\n};\\n\\n/** Inherits properties from its parent, AudioNode. */\\ninterface DynamicsCompressorNode extends AudioNode {\\n readonly attack: AudioParam;\\n readonly knee: AudioParam;\\n readonly ratio: AudioParam;\\n readonly reduction: number;\\n readonly release: AudioParam;\\n readonly threshold: AudioParam;\\n}\\n\\ndeclare var DynamicsCompressorNode: {\\n prototype: DynamicsCompressorNode;\\n new(context: BaseAudioContext, options?: DynamicsCompressorOptions): DynamicsCompressorNode;\\n};\\n\\ninterface EXT_blend_minmax {\\n readonly MIN_EXT: 0x8007;\\n readonly MAX_EXT: 0x8008;\\n}\\n\\ninterface EXT_color_buffer_float {\\n}\\n\\ninterface EXT_color_buffer_half_float {\\n readonly RGBA16F_EXT: 0x881A;\\n readonly RGB16F_EXT: 0x881B;\\n readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: 0x8211;\\n readonly UNSIGNED_NORMALIZED_EXT: 0x8C17;\\n}\\n\\ninterface EXT_float_blend {\\n}\\n\\n/** The EXT_frag_depth extension is part of the WebGL API and enables to set a depth value of a fragment from within the fragment shader. */\\ninterface EXT_frag_depth {\\n}\\n\\ninterface EXT_sRGB {\\n readonly SRGB_EXT: 0x8C40;\\n readonly SRGB_ALPHA_EXT: 0x8C42;\\n readonly SRGB8_ALPHA8_EXT: 0x8C43;\\n readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: 0x8210;\\n}\\n\\ninterface EXT_shader_texture_lod {\\n}\\n\\ninterface EXT_texture_compression_bptc {\\n readonly COMPRESSED_RGBA_BPTC_UNORM_EXT: 0x8E8C;\\n readonly COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT: 0x8E8D;\\n readonly COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT: 0x8E8E;\\n readonly COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT: 0x8E8F;\\n}\\n\\ninterface EXT_texture_compression_rgtc {\\n readonly COMPRESSED_RED_RGTC1_EXT: 0x8DBB;\\n readonly COMPRESSED_SIGNED_RED_RGTC1_EXT: 0x8DBC;\\n readonly COMPRESSED_RED_GREEN_RGTC2_EXT: 0x8DBD;\\n readonly COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT: 0x8DBE;\\n}\\n\\n/** The EXT_texture_filter_anisotropic extension is part of the WebGL API and exposes two constants for anisotropic filtering (AF). */\\ninterface EXT_texture_filter_anisotropic {\\n readonly TEXTURE_MAX_ANISOTROPY_EXT: 0x84FE;\\n readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: 0x84FF;\\n}\\n\\ninterface EXT_texture_norm16 {\\n readonly R16_EXT: 0x822A;\\n readonly RG16_EXT: 0x822C;\\n readonly RGB16_EXT: 0x8054;\\n readonly RGBA16_EXT: 0x805B;\\n readonly R16_SNORM_EXT: 0x8F98;\\n readonly RG16_SNORM_EXT: 0x8F99;\\n readonly RGB16_SNORM_EXT: 0x8F9A;\\n readonly RGBA16_SNORM_EXT: 0x8F9B;\\n}\\n\\ninterface ElementEventMap {\\n \\"fullscreenchange\\": Event;\\n \\"fullscreenerror\\": Event;\\n}\\n\\n/** Element is the most general base class from which all objects in a Document inherit. It only has methods and properties common to all kinds of elements. More specific classes inherit from Element. */\\ninterface Element extends Node, ARIAMixin, Animatable, ChildNode, InnerHTML, NonDocumentTypeChildNode, ParentNode, Slottable {\\n readonly attributes: NamedNodeMap;\\n /** Allows for manipulation of element\'s class content attribute as a set of whitespace-separated tokens through a DOMTokenList object. */\\n readonly classList: DOMTokenList;\\n /** Returns the value of element\'s class content attribute. Can be set to change it. */\\n className: string;\\n readonly clientHeight: number;\\n readonly clientLeft: number;\\n readonly clientTop: number;\\n readonly clientWidth: number;\\n /** Returns the value of element\'s id content attribute. Can be set to change it. */\\n id: string;\\n /** Returns the local name. */\\n readonly localName: string;\\n /** Returns the namespace. */\\n readonly namespaceURI: string | null;\\n onfullscreenchange: ((this: Element, ev: Event) => any) | null;\\n onfullscreenerror: ((this: Element, ev: Event) => any) | null;\\n outerHTML: string;\\n readonly ownerDocument: Document;\\n readonly part: DOMTokenList;\\n /** Returns the namespace prefix. */\\n readonly prefix: string | null;\\n readonly scrollHeight: number;\\n scrollLeft: number;\\n scrollTop: number;\\n readonly scrollWidth: number;\\n /** Returns element\'s shadow root, if any, and if shadow root\'s mode is \\"open\\", and null otherwise. */\\n readonly shadowRoot: ShadowRoot | null;\\n /** Returns the value of element\'s slot content attribute. Can be set to change it. */\\n slot: string;\\n /** Returns the HTML-uppercased qualified name. */\\n readonly tagName: string;\\n /** Creates a shadow root for element and returns it. */\\n attachShadow(init: ShadowRootInit): ShadowRoot;\\n checkVisibility(options?: CheckVisibilityOptions): boolean;\\n /** Returns the first (starting at element) inclusive ancestor that matches selectors, and null otherwise. */\\n closest(selector: K): HTMLElementTagNameMap[K] | null;\\n closest(selector: K): SVGElementTagNameMap[K] | null;\\n closest(selector: K): MathMLElementTagNameMap[K] | null;\\n closest(selectors: string): E | null;\\n /** Returns element\'s first attribute whose qualified name is qualifiedName, and null if there is no such attribute otherwise. */\\n getAttribute(qualifiedName: string): string | null;\\n /** Returns element\'s attribute whose namespace is namespace and local name is localName, and null if there is no such attribute otherwise. */\\n getAttributeNS(namespace: string | null, localName: string): string | null;\\n /** Returns the qualified names of all element\'s attributes. Can contain duplicates. */\\n getAttributeNames(): string[];\\n getAttributeNode(qualifiedName: string): Attr | null;\\n getAttributeNodeNS(namespace: string | null, localName: string): Attr | null;\\n getBoundingClientRect(): DOMRect;\\n getClientRects(): DOMRectList;\\n /** Returns a HTMLCollection of the elements in the object on which the method was invoked (a document or an element) that have all the classes given by classNames. The classNames argument is interpreted as a space-separated list of classes. */\\n getElementsByClassName(classNames: string): HTMLCollectionOf;\\n getElementsByTagName(qualifiedName: K): HTMLCollectionOf;\\n getElementsByTagName(qualifiedName: K): HTMLCollectionOf;\\n getElementsByTagName(qualifiedName: K): HTMLCollectionOf;\\n /** @deprecated */\\n getElementsByTagName(qualifiedName: K): HTMLCollectionOf;\\n getElementsByTagName(qualifiedName: string): HTMLCollectionOf;\\n getElementsByTagNameNS(namespaceURI: \\"http://www.w3.org/1999/xhtml\\", localName: string): HTMLCollectionOf;\\n getElementsByTagNameNS(namespaceURI: \\"http://www.w3.org/2000/svg\\", localName: string): HTMLCollectionOf;\\n getElementsByTagNameNS(namespaceURI: \\"http://www.w3.org/1998/Math/MathML\\", localName: string): HTMLCollectionOf;\\n getElementsByTagNameNS(namespace: string | null, localName: string): HTMLCollectionOf;\\n /** Returns true if element has an attribute whose qualified name is qualifiedName, and false otherwise. */\\n hasAttribute(qualifiedName: string): boolean;\\n /** Returns true if element has an attribute whose namespace is namespace and local name is localName. */\\n hasAttributeNS(namespace: string | null, localName: string): boolean;\\n /** Returns true if element has attributes, and false otherwise. */\\n hasAttributes(): boolean;\\n hasPointerCapture(pointerId: number): boolean;\\n insertAdjacentElement(where: InsertPosition, element: Element): Element | null;\\n insertAdjacentHTML(position: InsertPosition, text: string): void;\\n insertAdjacentText(where: InsertPosition, data: string): void;\\n /** Returns true if matching selectors against element\'s root yields element, and false otherwise. */\\n matches(selectors: string): boolean;\\n releasePointerCapture(pointerId: number): void;\\n /** Removes element\'s first attribute whose qualified name is qualifiedName. */\\n removeAttribute(qualifiedName: string): void;\\n /** Removes element\'s attribute whose namespace is namespace and local name is localName. */\\n removeAttributeNS(namespace: string | null, localName: string): void;\\n removeAttributeNode(attr: Attr): Attr;\\n /**\\n * Displays element fullscreen and resolves promise when done.\\n *\\n * When supplied, options\'s navigationUI member indicates whether showing navigation UI while in fullscreen is preferred or not. If set to \\"show\\", navigation simplicity is preferred over screen space, and if set to \\"hide\\", more screen space is preferred. User agents are always free to honor user preference over the application\'s. The default value \\"auto\\" indicates no application preference.\\n */\\n requestFullscreen(options?: FullscreenOptions): Promise;\\n requestPointerLock(): void;\\n scroll(options?: ScrollToOptions): void;\\n scroll(x: number, y: number): void;\\n scrollBy(options?: ScrollToOptions): void;\\n scrollBy(x: number, y: number): void;\\n scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void;\\n scrollTo(options?: ScrollToOptions): void;\\n scrollTo(x: number, y: number): void;\\n /** Sets the value of element\'s first attribute whose qualified name is qualifiedName to value. */\\n setAttribute(qualifiedName: string, value: string): void;\\n /** Sets the value of element\'s attribute whose namespace is namespace and local name is localName to value. */\\n setAttributeNS(namespace: string | null, qualifiedName: string, value: string): void;\\n setAttributeNode(attr: Attr): Attr | null;\\n setAttributeNodeNS(attr: Attr): Attr | null;\\n setPointerCapture(pointerId: number): void;\\n /**\\n * If force is not given, \\"toggles\\" qualifiedName, removing it if it is present and adding it if it is not present. If force is true, adds qualifiedName. If force is false, removes qualifiedName.\\n *\\n * Returns true if qualifiedName is now present, and false otherwise.\\n */\\n toggleAttribute(qualifiedName: string, force?: boolean): boolean;\\n /** @deprecated This is a legacy alias of `matches`. */\\n webkitMatchesSelector(selectors: string): boolean;\\n addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\\n removeEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\\n}\\n\\ndeclare var Element: {\\n prototype: Element;\\n new(): Element;\\n};\\n\\ninterface ElementCSSInlineStyle {\\n readonly style: CSSStyleDeclaration;\\n}\\n\\ninterface ElementContentEditable {\\n contentEditable: string;\\n enterKeyHint: string;\\n inputMode: string;\\n readonly isContentEditable: boolean;\\n}\\n\\ninterface ElementInternals extends ARIAMixin {\\n /** Returns the form owner of internals\'s target element. */\\n readonly form: HTMLFormElement | null;\\n /** Returns a NodeList of all the label elements that internals\'s target element is associated with. */\\n readonly labels: NodeList;\\n /** Returns the ShadowRoot for internals\'s target element, if the target element is a shadow host, or null otherwise. */\\n readonly shadowRoot: ShadowRoot | null;\\n /** Returns the error message that would be shown to the user if internals\'s target element was to be checked for validity. */\\n readonly validationMessage: string;\\n /** Returns the ValidityState object for internals\'s target element. */\\n readonly validity: ValidityState;\\n /** Returns true if internals\'s target element will be validated when the form is submitted; false otherwise. */\\n readonly willValidate: boolean;\\n /** Returns true if internals\'s target element has no validity problems; false otherwise. Fires an invalid event at the element in the latter case. */\\n checkValidity(): boolean;\\n /** Returns true if internals\'s target element has no validity problems; otherwise, returns false, fires an invalid event at the element, and (if the event isn\'t canceled) reports the problem to the user. */\\n reportValidity(): boolean;\\n /**\\n * Sets both the state and submission value of internals\'s target element to value.\\n *\\n * If value is null, the element won\'t participate in form submission.\\n */\\n setFormValue(value: File | string | FormData | null, state?: File | string | FormData | null): void;\\n /** Marks internals\'s target element as suffering from the constraints indicated by the flags argument, and sets the element\'s validation message to message. If anchor is specified, the user agent might use it to indicate problems with the constraints of internals\'s target element when the form owner is validated interactively or reportValidity() is called. */\\n setValidity(flags?: ValidityStateFlags, message?: string, anchor?: HTMLElement): void;\\n}\\n\\ndeclare var ElementInternals: {\\n prototype: ElementInternals;\\n new(): ElementInternals;\\n};\\n\\n/** Events providing information related to errors in scripts or in files. */\\ninterface ErrorEvent extends Event {\\n readonly colno: number;\\n readonly error: any;\\n readonly filename: string;\\n readonly lineno: number;\\n readonly message: string;\\n}\\n\\ndeclare var ErrorEvent: {\\n prototype: ErrorEvent;\\n new(type: string, eventInitDict?: ErrorEventInit): ErrorEvent;\\n};\\n\\n/** An event which takes place in the DOM. */\\ninterface Event {\\n /** Returns true or false depending on how event was initialized. True if event goes through its target\'s ancestors in reverse tree order, and false otherwise. */\\n readonly bubbles: boolean;\\n /** @deprecated */\\n cancelBubble: boolean;\\n /** Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. */\\n readonly cancelable: boolean;\\n /** Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. */\\n readonly composed: boolean;\\n /** Returns the object whose event listener\'s callback is currently being invoked. */\\n readonly currentTarget: EventTarget | null;\\n /** Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. */\\n readonly defaultPrevented: boolean;\\n /** Returns the event\'s phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. */\\n readonly eventPhase: number;\\n /** Returns true if event was dispatched by the user agent, and false otherwise. */\\n readonly isTrusted: boolean;\\n /** @deprecated */\\n returnValue: boolean;\\n /** @deprecated */\\n readonly srcElement: EventTarget | null;\\n /** Returns the object to which event is dispatched (its target). */\\n readonly target: EventTarget | null;\\n /** Returns the event\'s timestamp as the number of milliseconds measured relative to the time origin. */\\n readonly timeStamp: DOMHighResTimeStamp;\\n /** Returns the type of event, e.g. \\"click\\", \\"hashchange\\", or \\"submit\\". */\\n readonly type: string;\\n /** Returns the invocation target objects of event\'s path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root\'s mode is \\"closed\\" that are not reachable from event\'s currentTarget. */\\n composedPath(): EventTarget[];\\n /** @deprecated */\\n initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void;\\n /** If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. */\\n preventDefault(): void;\\n /** Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. */\\n stopImmediatePropagation(): void;\\n /** When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. */\\n stopPropagation(): void;\\n readonly NONE: 0;\\n readonly CAPTURING_PHASE: 1;\\n readonly AT_TARGET: 2;\\n readonly BUBBLING_PHASE: 3;\\n}\\n\\ndeclare var Event: {\\n prototype: Event;\\n new(type: string, eventInitDict?: EventInit): Event;\\n readonly NONE: 0;\\n readonly CAPTURING_PHASE: 1;\\n readonly AT_TARGET: 2;\\n readonly BUBBLING_PHASE: 3;\\n};\\n\\ninterface EventCounts {\\n forEach(callbackfn: (value: number, key: string, parent: EventCounts) => void, thisArg?: any): void;\\n}\\n\\ndeclare var EventCounts: {\\n prototype: EventCounts;\\n new(): EventCounts;\\n};\\n\\ninterface EventListener {\\n (evt: Event): void;\\n}\\n\\ninterface EventListenerObject {\\n handleEvent(object: Event): void;\\n}\\n\\ninterface EventSourceEventMap {\\n \\"error\\": Event;\\n \\"message\\": MessageEvent;\\n \\"open\\": Event;\\n}\\n\\ninterface EventSource extends EventTarget {\\n onerror: ((this: EventSource, ev: Event) => any) | null;\\n onmessage: ((this: EventSource, ev: MessageEvent) => any) | null;\\n onopen: ((this: EventSource, ev: Event) => any) | null;\\n /** Returns the state of this EventSource object\'s connection. It can have the values described below. */\\n readonly readyState: number;\\n /** Returns the URL providing the event stream. */\\n readonly url: string;\\n /** Returns true if the credentials mode for connection requests to the URL providing the event stream is set to \\"include\\", and false otherwise. */\\n readonly withCredentials: boolean;\\n /** Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED. */\\n close(): void;\\n readonly CONNECTING: 0;\\n readonly OPEN: 1;\\n readonly CLOSED: 2;\\n addEventListener(type: K, listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\\n addEventListener(type: string, listener: (this: EventSource, event: MessageEvent) => any, options?: boolean | AddEventListenerOptions): void;\\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\\n removeEventListener(type: K, listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\\n removeEventListener(type: string, listener: (this: EventSource, event: MessageEvent) => any, options?: boolean | EventListenerOptions): void;\\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\\n}\\n\\ndeclare var EventSource: {\\n prototype: EventSource;\\n new(url: string | URL, eventSourceInitDict?: EventSourceInit): EventSource;\\n readonly CONNECTING: 0;\\n readonly OPEN: 1;\\n readonly CLOSED: 2;\\n};\\n\\n/** EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them. */\\ninterface EventTarget {\\n /**\\n * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.\\n *\\n * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options\'s capture.\\n *\\n * When set to true, options\'s capture prevents callback from being invoked when the event\'s eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event\'s eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event\'s eventPhase attribute value is AT_TARGET.\\n *\\n * When set to true, options\'s passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in \xa7 2.8 Observing event listeners.\\n *\\n * When set to true, options\'s once indicates that the callback will only be invoked once after which the event listener will be removed.\\n *\\n * If an AbortSignal is passed for options\'s signal, then the event listener will be removed when signal is aborted.\\n *\\n * The event listener is appended to target\'s event listener list and is not appended if it has the same type, callback, and capture.\\n */\\n addEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: AddEventListenerOptions | boolean): void;\\n /** Dispatches a synthetic event event to target and returns true if either event\'s cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */\\n dispatchEvent(event: Event): boolean;\\n /** Removes the event listener in target\'s event listener list with the same type, callback, and options. */\\n removeEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void;\\n}\\n\\ndeclare var EventTarget: {\\n prototype: EventTarget;\\n new(): EventTarget;\\n};\\n\\n/** @deprecated */\\ninterface External {\\n /** @deprecated */\\n AddSearchProvider(): void;\\n /** @deprecated */\\n IsSearchProviderInstalled(): void;\\n}\\n\\n/** @deprecated */\\ndeclare var External: {\\n prototype: External;\\n new(): External;\\n};\\n\\n/** Provides information about files and allows JavaScript in a web page to access their content. */\\ninterface File extends Blob {\\n readonly lastModified: number;\\n readonly name: string;\\n readonly webkitRelativePath: string;\\n}\\n\\ndeclare var File: {\\n prototype: File;\\n new(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): File;\\n};\\n\\n/** An object of this type is returned by the files property of the HTML element; this lets you access the list of files selected with the element. It\'s also used for a list of files dropped into web content when using the drag and drop API; see the DataTransfer object for details on this usage. */\\ninterface FileList {\\n readonly length: number;\\n item(index: number): File | null;\\n [index: number]: File;\\n}\\n\\ndeclare var FileList: {\\n prototype: FileList;\\n new(): FileList;\\n};\\n\\ninterface FileReaderEventMap {\\n \\"abort\\": ProgressEvent;\\n \\"error\\": ProgressEvent;\\n \\"load\\": ProgressEvent;\\n \\"loadend\\": ProgressEvent;\\n \\"loadstart\\": ProgressEvent;\\n \\"progress\\": ProgressEvent;\\n}\\n\\n/** Lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user\'s computer, using File or Blob objects to specify the file or data to read. */\\ninterface FileReader extends EventTarget {\\n readonly error: DOMException | null;\\n onabort: ((this: FileReader, ev: ProgressEvent) => any) | null;\\n onerror: ((this: FileReader, ev: ProgressEvent) => any) | null;\\n onload: ((this: FileReader, ev: ProgressEvent) => any) | null;\\n onloadend: ((this: FileReader, ev: ProgressEvent) => any) | null;\\n onloadstart: ((this: FileReader, ev: ProgressEvent) => any) | null;\\n onprogress: ((this: FileReader, ev: ProgressEvent) => any) | null;\\n readonly readyState: typeof FileReader.EMPTY | typeof FileReader.LOADING | typeof FileReader.DONE;\\n readonly result: string | ArrayBuffer | null;\\n abort(): void;\\n readAsArrayBuffer(blob: Blob): void;\\n readAsBinaryString(blob: Blob): void;\\n readAsDataURL(blob: Blob): void;\\n readAsText(blob: Blob, encoding?: string): void;\\n readonly EMPTY: 0;\\n readonly LOADING: 1;\\n readonly DONE: 2;\\n addEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\\n removeEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\\n}\\n\\ndeclare var FileReader: {\\n prototype: FileReader;\\n new(): FileReader;\\n readonly EMPTY: 0;\\n readonly LOADING: 1;\\n readonly DONE: 2;\\n};\\n\\ninterface FileSystem {\\n readonly name: string;\\n readonly root: FileSystemDirectoryEntry;\\n}\\n\\ndeclare var FileSystem: {\\n prototype: FileSystem;\\n new(): FileSystem;\\n};\\n\\ninterface FileSystemDirectoryEntry extends FileSystemEntry {\\n createReader(): FileSystemDirectoryReader;\\n getDirectory(path?: string | null, options?: FileSystemFlags, successCallback?: FileSystemEntryCallback, errorCallback?: ErrorCallback): void;\\n getFile(path?: string | null, options?: FileSystemFlags, successCallback?: FileSystemEntryCallback, errorCallback?: ErrorCallback): void;\\n}\\n\\ndeclare var FileSystemDirectoryEntry: {\\n prototype: FileSystemDirectoryEntry;\\n new(): FileSystemDirectoryEntry;\\n};\\n\\n/** Available only in secure contexts. */\\ninterface FileSystemDirectoryHandle extends FileSystemHandle {\\n readonly kind: \\"directory\\";\\n getDirectoryHandle(name: string, options?: FileSystemGetDirectoryOptions): Promise;\\n getFileHandle(name: string, options?: FileSystemGetFileOptions): Promise;\\n removeEntry(name: string, options?: FileSystemRemoveOptions): Promise;\\n resolve(possibleDescendant: FileSystemHandle): Promise;\\n}\\n\\ndeclare var FileSystemDirectoryHandle: {\\n prototype: FileSystemDirectoryHandle;\\n new(): FileSystemDirectoryHandle;\\n};\\n\\ninterface FileSystemDirectoryReader {\\n readEntries(successCallback: FileSystemEntriesCallback, errorCallback?: ErrorCallback): void;\\n}\\n\\ndeclare var FileSystemDirectoryReader: {\\n prototype: FileSystemDirectoryReader;\\n new(): FileSystemDirectoryReader;\\n};\\n\\ninterface FileSystemEntry {\\n readonly filesystem: FileSystem;\\n readonly fullPath: string;\\n readonly isDirectory: boolean;\\n readonly isFile: boolean;\\n readonly name: string;\\n getParent(successCallback?: FileSystemEntryCallback, errorCallback?: ErrorCallback): void;\\n}\\n\\ndeclare var FileSystemEntry: {\\n prototype: FileSystemEntry;\\n new(): FileSystemEntry;\\n};\\n\\ninterface FileSystemFileEntry extends FileSystemEntry {\\n file(successCallback: FileCallback, errorCallback?: ErrorCallback): void;\\n}\\n\\ndeclare var FileSystemFileEntry: {\\n prototype: FileSystemFileEntry;\\n new(): FileSystemFileEntry;\\n};\\n\\n/** Available only in secure contexts. */\\ninterface FileSystemFileHandle extends FileSystemHandle {\\n readonly kind: \\"file\\";\\n getFile(): Promise;\\n}\\n\\ndeclare var FileSystemFileHandle: {\\n prototype: FileSystemFileHandle;\\n new(): FileSystemFileHandle;\\n};\\n\\n/** Available only in secure contexts. */\\ninterface FileSystemHandle {\\n readonly kind: FileSystemHandleKind;\\n readonly name: string;\\n isSameEntry(other: FileSystemHandle): Promise;\\n}\\n\\ndeclare var FileSystemHandle: {\\n prototype: FileSystemHandle;\\n new(): FileSystemHandle;\\n};\\n\\n/** Focus-related events like focus, blur, focusin, or focusout. */\\ninterface FocusEvent extends UIEvent {\\n readonly relatedTarget: EventTarget | null;\\n}\\n\\ndeclare var FocusEvent: {\\n prototype: FocusEvent;\\n new(type: string, eventInitDict?: FocusEventInit): FocusEvent;\\n};\\n\\ninterface FontFace {\\n ascentOverride: string;\\n descentOverride: string;\\n display: FontDisplay;\\n family: string;\\n featureSettings: string;\\n lineGapOverride: string;\\n readonly loaded: Promise;\\n readonly status: FontFaceLoadStatus;\\n stretch: string;\\n style: string;\\n unicodeRange: string;\\n variant: string;\\n weight: string;\\n load(): Promise;\\n}\\n\\ndeclare var FontFace: {\\n prototype: FontFace;\\n new(family: string, source: string | BinaryData, descriptors?: FontFaceDescriptors): FontFace;\\n};\\n\\ninterface FontFaceSetEventMap {\\n \\"loading\\": Event;\\n \\"loadingdone\\": Event;\\n \\"loadingerror\\": Event;\\n}\\n\\ninterface FontFaceSet extends EventTarget {\\n onloading: ((this: FontFaceSet, ev: Event) => any) | null;\\n onloadingdone: ((this: FontFaceSet, ev: Event) => any) | null;\\n onloadingerror: ((this: FontFaceSet, ev: Event) => any) | null;\\n readonly ready: Promise;\\n readonly status: FontFaceSetLoadStatus;\\n check(font: string, text?: string): boolean;\\n load(font: string, text?: string): Promise;\\n forEach(callbackfn: (value: FontFace, key: FontFace, parent: FontFaceSet) => void, thisArg?: any): void;\\n addEventListener(type: K, listener: (this: FontFaceSet, ev: FontFaceSetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\\n removeEventListener(type: K, listener: (this: FontFaceSet, ev: FontFaceSetEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\\n}\\n\\ndeclare var FontFaceSet: {\\n prototype: FontFaceSet;\\n new(initialFaces: FontFace[]): FontFaceSet;\\n};\\n\\ninterface FontFaceSetLoadEvent extends Event {\\n readonly fontfaces: ReadonlyArray;\\n}\\n\\ndeclare var FontFaceSetLoadEvent: {\\n prototype: FontFaceSetLoadEvent;\\n new(type: string, eventInitDict?: FontFaceSetLoadEventInit): FontFaceSetLoadEvent;\\n};\\n\\ninterface FontFaceSource {\\n readonly fonts: FontFaceSet;\\n}\\n\\n/** Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to \\"multipart/form-data\\". */\\ninterface FormData {\\n append(name: string, value: string | Blob, fileName?: string): void;\\n delete(name: string): void;\\n get(name: string): FormDataEntryValue | null;\\n getAll(name: string): FormDataEntryValue[];\\n has(name: string): boolean;\\n set(name: string, value: string | Blob, fileName?: string): void;\\n forEach(callbackfn: (value: FormDataEntryValue, key: string, parent: FormData) => void, thisArg?: any): void;\\n}\\n\\ndeclare var FormData: {\\n prototype: FormData;\\n new(form?: HTMLFormElement): FormData;\\n};\\n\\ninterface FormDataEvent extends Event {\\n /** Returns a FormData object representing names and values of elements associated to the target form. Operations on the FormData object will affect form data to be submitted. */\\n readonly formData: FormData;\\n}\\n\\ndeclare var FormDataEvent: {\\n prototype: FormDataEvent;\\n new(type: string, eventInitDict: FormDataEventInit): FormDataEvent;\\n};\\n\\n/** A change in volume. It is an AudioNode audio-processing module that causes a given gain to be applied to the input data before its propagation to the output. A GainNode always has exactly one input and one output, both with the same number of channels. */\\ninterface GainNode extends AudioNode {\\n readonly gain: AudioParam;\\n}\\n\\ndeclare var GainNode: {\\n prototype: GainNode;\\n new(context: BaseAudioContext, options?: GainOptions): GainNode;\\n};\\n\\n/**\\n * This Gamepad API interface defines an individual gamepad or other controller, allowing access to information such as button presses, axis positions, and id.\\n * Available only in secure contexts.\\n */\\ninterface Gamepad {\\n readonly axes: ReadonlyArray;\\n readonly buttons: ReadonlyArray;\\n readonly connected: boolean;\\n readonly hapticActuators: ReadonlyArray;\\n readonly id: string;\\n readonly index: number;\\n readonly mapping: GamepadMappingType;\\n readonly timestamp: DOMHighResTimeStamp;\\n}\\n\\ndeclare var Gamepad: {\\n prototype: Gamepad;\\n new(): Gamepad;\\n};\\n\\n/**\\n * An individual button of a gamepad or other controller, allowing access to the current state of different types of buttons available on the control device.\\n * Available only in secure contexts.\\n */\\ninterface GamepadButton {\\n readonly pressed: boolean;\\n readonly touched: boolean;\\n readonly value: number;\\n}\\n\\ndeclare var GamepadButton: {\\n prototype: GamepadButton;\\n new(): GamepadButton;\\n};\\n\\n/**\\n * This Gamepad API interface contains references to gamepads connected to the system, which is what the gamepad events Window.gamepadconnected and Window.gamepaddisconnected are fired in response to.\\n * Available only in secure contexts.\\n */\\ninterface GamepadEvent extends Event {\\n readonly gamepad: Gamepad;\\n}\\n\\ndeclare var GamepadEvent: {\\n prototype: GamepadEvent;\\n new(type: string, eventInitDict: GamepadEventInit): GamepadEvent;\\n};\\n\\n/** This Gamepad API interface represents hardware in the controller designed to provide haptic feedback to the user (if available), most commonly vibration hardware. */\\ninterface GamepadHapticActuator {\\n readonly type: GamepadHapticActuatorType;\\n}\\n\\ndeclare var GamepadHapticActuator: {\\n prototype: GamepadHapticActuator;\\n new(): GamepadHapticActuator;\\n};\\n\\ninterface GenericTransformStream {\\n readonly readable: ReadableStream;\\n readonly writable: WritableStream;\\n}\\n\\n/** An object able to programmatically obtain the position of the device. It gives Web content access to the location of the device. This allows a Web site or app to offer customized results based on the user\'s location. */\\ninterface Geolocation {\\n clearWatch(watchId: number): void;\\n getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback | null, options?: PositionOptions): void;\\n watchPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback | null, options?: PositionOptions): number;\\n}\\n\\ndeclare var Geolocation: {\\n prototype: Geolocation;\\n new(): Geolocation;\\n};\\n\\n/** Available only in secure contexts. */\\ninterface GeolocationCoordinates {\\n readonly accuracy: number;\\n readonly altitude: number | null;\\n readonly altitudeAccuracy: number | null;\\n readonly heading: number | null;\\n readonly latitude: number;\\n readonly longitude: number;\\n readonly speed: number | null;\\n}\\n\\ndeclare var GeolocationCoordinates: {\\n prototype: GeolocationCoordinates;\\n new(): GeolocationCoordinates;\\n};\\n\\n/** Available only in secure contexts. */\\ninterface GeolocationPosition {\\n readonly coords: GeolocationCoordinates;\\n readonly timestamp: EpochTimeStamp;\\n}\\n\\ndeclare var GeolocationPosition: {\\n prototype: GeolocationPosition;\\n new(): GeolocationPosition;\\n};\\n\\ninterface GeolocationPositionError {\\n readonly code: number;\\n readonly message: string;\\n readonly PERMISSION_DENIED: 1;\\n readonly POSITION_UNAVAILABLE: 2;\\n readonly TIMEOUT: 3;\\n}\\n\\ndeclare var GeolocationPositionError: {\\n prototype: GeolocationPositionError;\\n new(): GeolocationPositionError;\\n readonly PERMISSION_DENIED: 1;\\n readonly POSITION_UNAVAILABLE: 2;\\n readonly TIMEOUT: 3;\\n};\\n\\ninterface GlobalEventHandlersEventMap {\\n \\"abort\\": UIEvent;\\n \\"animationcancel\\": AnimationEvent;\\n \\"animationend\\": AnimationEvent;\\n \\"animationiteration\\": AnimationEvent;\\n \\"animationstart\\": AnimationEvent;\\n \\"auxclick\\": MouseEvent;\\n \\"beforeinput\\": InputEvent;\\n \\"blur\\": FocusEvent;\\n \\"cancel\\": Event;\\n \\"canplay\\": Event;\\n \\"canplaythrough\\": Event;\\n \\"change\\": Event;\\n \\"click\\": MouseEvent;\\n \\"close\\": Event;\\n \\"compositionend\\": CompositionEvent;\\n \\"compositionstart\\": CompositionEvent;\\n \\"compositionupdate\\": CompositionEvent;\\n \\"contextmenu\\": MouseEvent;\\n \\"copy\\": ClipboardEvent;\\n \\"cuechange\\": Event;\\n \\"cut\\": ClipboardEvent;\\n \\"dblclick\\": MouseEvent;\\n \\"drag\\": DragEvent;\\n \\"dragend\\": DragEvent;\\n \\"dragenter\\": DragEvent;\\n \\"dragleave\\": DragEvent;\\n \\"dragover\\": DragEvent;\\n \\"dragstart\\": DragEvent;\\n \\"drop\\": DragEvent;\\n \\"durationchange\\": Event;\\n \\"emptied\\": Event;\\n \\"ended\\": Event;\\n \\"error\\": ErrorEvent;\\n \\"focus\\": FocusEvent;\\n \\"focusin\\": FocusEvent;\\n \\"focusout\\": FocusEvent;\\n \\"formdata\\": FormDataEvent;\\n \\"gotpointercapture\\": PointerEvent;\\n \\"input\\": Event;\\n \\"invalid\\": Event;\\n \\"keydown\\": KeyboardEvent;\\n \\"keypress\\": KeyboardEvent;\\n \\"keyup\\": KeyboardEvent;\\n \\"load\\": Event;\\n \\"loadeddata\\": Event;\\n \\"loadedmetadata\\": Event;\\n \\"loadstart\\": Event;\\n \\"lostpointercapture\\": PointerEvent;\\n \\"mousedown\\": MouseEvent;\\n \\"mouseenter\\": MouseEvent;\\n \\"mouseleave\\": MouseEvent;\\n \\"mousemove\\": MouseEvent;\\n \\"mouseout\\": MouseEvent;\\n \\"mouseover\\": MouseEvent;\\n \\"mouseup\\": MouseEvent;\\n \\"paste\\": ClipboardEvent;\\n \\"pause\\": Event;\\n \\"play\\": Event;\\n \\"playing\\": Event;\\n \\"pointercancel\\": PointerEvent;\\n \\"pointerdown\\": PointerEvent;\\n \\"pointerenter\\": PointerEvent;\\n \\"pointerleave\\": PointerEvent;\\n \\"pointermove\\": PointerEvent;\\n \\"pointerout\\": PointerEvent;\\n \\"pointerover\\": PointerEvent;\\n \\"pointerup\\": PointerEvent;\\n \\"progress\\": ProgressEvent;\\n \\"ratechange\\": Event;\\n \\"reset\\": Event;\\n \\"resize\\": UIEvent;\\n \\"scroll\\": Event;\\n \\"securitypolicyviolation\\": SecurityPolicyViolationEvent;\\n \\"seeked\\": Event;\\n \\"seeking\\": Event;\\n \\"select\\": Event;\\n \\"selectionchange\\": Event;\\n \\"selectstart\\": Event;\\n \\"slotchange\\": Event;\\n \\"stalled\\": Event;\\n \\"submit\\": SubmitEvent;\\n \\"suspend\\": Event;\\n \\"timeupdate\\": Event;\\n \\"toggle\\": Event;\\n \\"touchcancel\\": TouchEvent;\\n \\"touchend\\": TouchEvent;\\n \\"touchmove\\": TouchEvent;\\n \\"touchstart\\": TouchEvent;\\n \\"transitioncancel\\": TransitionEvent;\\n \\"transitionend\\": TransitionEvent;\\n \\"transitionrun\\": TransitionEvent;\\n \\"transitionstart\\": TransitionEvent;\\n \\"volumechange\\": Event;\\n \\"waiting\\": Event;\\n \\"webkitanimationend\\": Event;\\n \\"webkitanimationiteration\\": Event;\\n \\"webkitanimationstart\\": Event;\\n \\"webkittransitionend\\": Event;\\n \\"wheel\\": WheelEvent;\\n}\\n\\ninterface GlobalEventHandlers {\\n /**\\n * Fires when the user aborts the download.\\n * @param ev The event.\\n */\\n onabort: ((this: GlobalEventHandlers, ev: UIEvent) => any) | null;\\n onanimationcancel: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null;\\n onanimationend: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null;\\n onanimationiteration: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null;\\n onanimationstart: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null;\\n onauxclick: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null;\\n onbeforeinput: ((this: GlobalEventHandlers, ev: InputEvent) => any) | null;\\n /**\\n * Fires when the object loses the input focus.\\n * @param ev The focus event.\\n */\\n onblur: ((this: GlobalEventHandlers, ev: FocusEvent) => any) | null;\\n oncancel: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /**\\n * Occurs when playback is possible, but would require further buffering.\\n * @param ev The event.\\n */\\n oncanplay: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n oncanplaythrough: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /**\\n * Fires when the contents of the object or selection have changed.\\n * @param ev The event.\\n */\\n onchange: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /**\\n * Fires when the user clicks the left mouse button on the object\\n * @param ev The mouse event.\\n */\\n onclick: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null;\\n onclose: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /**\\n * Fires when the user clicks the right mouse button in the client area, opening the context menu.\\n * @param ev The mouse event.\\n */\\n oncontextmenu: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null;\\n oncopy: ((this: GlobalEventHandlers, ev: ClipboardEvent) => any) | null;\\n oncuechange: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n oncut: ((this: GlobalEventHandlers, ev: ClipboardEvent) => any) | null;\\n /**\\n * Fires when the user double-clicks the object.\\n * @param ev The mouse event.\\n */\\n ondblclick: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null;\\n /**\\n * Fires on the source object continuously during a drag operation.\\n * @param ev The event.\\n */\\n ondrag: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null;\\n /**\\n * Fires on the source object when the user releases the mouse at the close of a drag operation.\\n * @param ev The event.\\n */\\n ondragend: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null;\\n /**\\n * Fires on the target element when the user drags the object to a valid drop target.\\n * @param ev The drag event.\\n */\\n ondragenter: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null;\\n /**\\n * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation.\\n * @param ev The drag event.\\n */\\n ondragleave: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null;\\n /**\\n * Fires on the target element continuously while the user drags the object over a valid drop target.\\n * @param ev The event.\\n */\\n ondragover: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null;\\n /**\\n * Fires on the source object when the user starts to drag a text selection or selected object.\\n * @param ev The event.\\n */\\n ondragstart: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null;\\n ondrop: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null;\\n /**\\n * Occurs when the duration attribute is updated.\\n * @param ev The event.\\n */\\n ondurationchange: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /**\\n * Occurs when the media element is reset to its initial state.\\n * @param ev The event.\\n */\\n onemptied: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /**\\n * Occurs when the end of playback is reached.\\n * @param ev The event\\n */\\n onended: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /**\\n * Fires when an error occurs during object loading.\\n * @param ev The event.\\n */\\n onerror: OnErrorEventHandler;\\n /**\\n * Fires when the object receives focus.\\n * @param ev The event.\\n */\\n onfocus: ((this: GlobalEventHandlers, ev: FocusEvent) => any) | null;\\n onformdata: ((this: GlobalEventHandlers, ev: FormDataEvent) => any) | null;\\n ongotpointercapture: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\\n oninput: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n oninvalid: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /**\\n * Fires when the user presses a key.\\n * @param ev The keyboard event\\n */\\n onkeydown: ((this: GlobalEventHandlers, ev: KeyboardEvent) => any) | null;\\n /**\\n * Fires when the user presses an alphanumeric key.\\n * @param ev The event.\\n * @deprecated\\n */\\n onkeypress: ((this: GlobalEventHandlers, ev: KeyboardEvent) => any) | null;\\n /**\\n * Fires when the user releases a key.\\n * @param ev The keyboard event\\n */\\n onkeyup: ((this: GlobalEventHandlers, ev: KeyboardEvent) => any) | null;\\n /**\\n * Fires immediately after the browser loads the object.\\n * @param ev The event.\\n */\\n onload: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /**\\n * Occurs when media data is loaded at the current playback position.\\n * @param ev The event.\\n */\\n onloadeddata: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /**\\n * Occurs when the duration and dimensions of the media have been determined.\\n * @param ev The event.\\n */\\n onloadedmetadata: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /**\\n * Occurs when Internet Explorer begins looking for media data.\\n * @param ev The event.\\n */\\n onloadstart: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n onlostpointercapture: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\\n /**\\n * Fires when the user clicks the object with either mouse button.\\n * @param ev The mouse event.\\n */\\n onmousedown: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null;\\n onmouseenter: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null;\\n onmouseleave: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null;\\n /**\\n * Fires when the user moves the mouse over the object.\\n * @param ev The mouse event.\\n */\\n onmousemove: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null;\\n /**\\n * Fires when the user moves the mouse pointer outside the boundaries of the object.\\n * @param ev The mouse event.\\n */\\n onmouseout: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null;\\n /**\\n * Fires when the user moves the mouse pointer into the object.\\n * @param ev The mouse event.\\n */\\n onmouseover: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null;\\n /**\\n * Fires when the user releases a mouse button while the mouse is over the object.\\n * @param ev The mouse event.\\n */\\n onmouseup: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null;\\n onpaste: ((this: GlobalEventHandlers, ev: ClipboardEvent) => any) | null;\\n /**\\n * Occurs when playback is paused.\\n * @param ev The event.\\n */\\n onpause: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /**\\n * Occurs when the play method is requested.\\n * @param ev The event.\\n */\\n onplay: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /**\\n * Occurs when the audio or video has started playing.\\n * @param ev The event.\\n */\\n onplaying: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n onpointercancel: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\\n onpointerdown: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\\n onpointerenter: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\\n onpointerleave: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\\n onpointermove: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\\n onpointerout: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\\n onpointerover: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\\n onpointerup: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\\n /**\\n * Occurs to indicate progress while downloading media data.\\n * @param ev The event.\\n */\\n onprogress: ((this: GlobalEventHandlers, ev: ProgressEvent) => any) | null;\\n /**\\n * Occurs when the playback rate is increased or decreased.\\n * @param ev The event.\\n */\\n onratechange: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /**\\n * Fires when the user resets a form.\\n * @param ev The event.\\n */\\n onreset: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n onresize: ((this: GlobalEventHandlers, ev: UIEvent) => any) | null;\\n /**\\n * Fires when the user repositions the scroll box in the scroll bar on the object.\\n * @param ev The event.\\n */\\n onscroll: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n onsecuritypolicyviolation: ((this: GlobalEventHandlers, ev: SecurityPolicyViolationEvent) => any) | null;\\n /**\\n * Occurs when the seek operation ends.\\n * @param ev The event.\\n */\\n onseeked: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /**\\n * Occurs when the current playback position is moved.\\n * @param ev The event.\\n */\\n onseeking: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /**\\n * Fires when the current selection changes.\\n * @param ev The event.\\n */\\n onselect: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n onselectionchange: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n onselectstart: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n onslotchange: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /**\\n * Occurs when the download has stopped.\\n * @param ev The event.\\n */\\n onstalled: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n onsubmit: ((this: GlobalEventHandlers, ev: SubmitEvent) => any) | null;\\n /**\\n * Occurs if the load operation has been intentionally halted.\\n * @param ev The event.\\n */\\n onsuspend: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /**\\n * Occurs to indicate the current playback position.\\n * @param ev The event.\\n */\\n ontimeupdate: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n ontoggle: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n ontouchcancel?: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null | undefined;\\n ontouchend?: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null | undefined;\\n ontouchmove?: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null | undefined;\\n ontouchstart?: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null | undefined;\\n ontransitioncancel: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null;\\n ontransitionend: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null;\\n ontransitionrun: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null;\\n ontransitionstart: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null;\\n /**\\n * Occurs when the volume is changed, or playback is muted or unmuted.\\n * @param ev The event.\\n */\\n onvolumechange: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /**\\n * Occurs when playback stops because the next frame of a video resource is not available.\\n * @param ev The event.\\n */\\n onwaiting: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /** @deprecated This is a legacy alias of `onanimationend`. */\\n onwebkitanimationend: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /** @deprecated This is a legacy alias of `onanimationiteration`. */\\n onwebkitanimationiteration: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /** @deprecated This is a legacy alias of `onanimationstart`. */\\n onwebkitanimationstart: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n /** @deprecated This is a legacy alias of `ontransitionend`. */\\n onwebkittransitionend: ((this: GlobalEventHandlers, ev: Event) => any) | null;\\n onwheel: ((this: GlobalEventHandlers, ev: WheelEvent) => any) | null;\\n addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\\n removeEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\\n}\\n\\ninterface HTMLAllCollection {\\n /** Returns the number of elements in the collection. */\\n readonly length: number;\\n /** Returns the item with index index from the collection (determined by tree order). */\\n item(nameOrIndex?: string): HTMLCollection | Element | null;\\n /**\\n * Returns the item with ID or name name from the collection.\\n *\\n * If there are multiple matching items, then an HTMLCollection object containing all those elements is returned.\\n *\\n * Only button, form, iframe, input, map, meta, object, select, and textarea elements can have a name for the purpose of this method; their name is given by the value of their name attribute.\\n */\\n namedItem(name: string): HTMLCollection | Element | null;\\n [index: number]: Element;\\n}\\n\\ndeclare var HTMLAllCollection: {\\n prototype: HTMLAllCollection;\\n new(): HTMLAllCollection;\\n};\\n\\n/** Hyperlink elements and provides special properties and methods (beyond those of the regular HTMLElement object interface that they inherit from) for manipulating the layout and presentation of such elements. */\\ninterface HTMLAnchorElement extends HTMLElement, HTMLHyperlinkElementUtils {\\n /**\\n * Sets or retrieves the character set used to encode the object.\\n * @deprecated\\n */\\n charset: string;\\n /**\\n * Sets or retrieves the coordinates of the object.\\n * @deprecated\\n */\\n coords: string;\\n download: string;\\n /** Sets or retrieves the language code of the object. */\\n hreflang: string;\\n /**\\n * Sets or retrieves the shape of the object.\\n * @deprecated\\n */\\n name: string;\\n ping: string;\\n referrerPolicy: string;\\n /** Sets or retrieves the relationship between the object and the destination of the link. */\\n rel: string;\\n readonly relList: DOMTokenList;\\n /**\\n * Sets or retrieves the relationship between the object and the destination of the link.\\n * @deprecated\\n */\\n rev: string;\\n /**\\n * Sets or retrieves the shape of the object.\\n * @deprecated\\n */\\n shape: string;\\n /** Sets or retrieves the window or frame at which to target content. */\\n target: string;\\n /** Retrieves or sets the text of the object as a string. */\\n text: string;\\n type: string;\\n addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\\n removeEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\\n}\\n\\ndeclare var HTMLAnchorElement: {\\n prototype: HTMLAnchorElement;\\n new(): HTMLAnchorElement;\\n};\\n\\n/** Provides special properties and methods (beyond those of the regular object HTMLElement interface it also has available to it by inheritance) for manipulating the layout and presentation of elements. */\\ninterface HTMLAreaElement extends HTMLElement, HTMLHyperlinkElementUtils {\\n /** Sets or retrieves a text alternative to the graphic. */\\n alt: string;\\n /** Sets or retrieves the coordinates of the object. */\\n coords: string;\\n download: string;\\n /**\\n * Sets or gets whether clicks in this region cause action.\\n * @deprecated\\n */\\n noHref: boolean;\\n ping: string;\\n referrerPolicy: string;\\n rel: string;\\n readonly relList: DOMTokenList;\\n /** Sets or retrieves the shape of the object. */\\n shape: string;\\n /** Sets or retrieves the window or frame at which to target content. */\\n target: string;\\n addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\\n removeEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\\n}\\n\\ndeclare var HTMLAreaElement: {\\n prototype: HTMLAreaElement;\\n new(): HTMLAreaElement;\\n};\\n\\n/** Provides access to the properties of